repo_name
string
path
string
copies
string
size
string
content
string
license
string
alexpotter1/Neutron_msm8974_d802
arch/sh/kernel/cpu/sh3/setup-sh770x.c
5062
7606
/* * SH3 Setup code for SH7706, SH7707, SH7708, SH7709 * * Copyright (C) 2007 Magnus Damm * Copyright (C) 2009 Paul Mundt * * Based on setup-sh7709.c * * Copyright (C) 2006 Paul Mundt * * 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. */ #include <linux/init.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/platform_device.h> #include <linux/serial.h> #include <linux/serial_sci.h> #include <linux/sh_timer.h> #include <cpu/serial.h> enum { UNUSED = 0, /* interrupt sources */ IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, PINT07, PINT815, DMAC, SCIF0, SCIF2, SCI, ADC_ADI, LCDC, PCC0, PCC1, TMU0, TMU1, TMU2, RTC, WDT, REF, }; static struct intc_vect vectors[] __initdata = { INTC_VECT(TMU0, 0x400), INTC_VECT(TMU1, 0x420), INTC_VECT(TMU2, 0x440), INTC_VECT(TMU2, 0x460), INTC_VECT(RTC, 0x480), INTC_VECT(RTC, 0x4a0), INTC_VECT(RTC, 0x4c0), INTC_VECT(SCI, 0x4e0), INTC_VECT(SCI, 0x500), INTC_VECT(SCI, 0x520), INTC_VECT(SCI, 0x540), INTC_VECT(WDT, 0x560), INTC_VECT(REF, 0x580), INTC_VECT(REF, 0x5a0), #if defined(CONFIG_CPU_SUBTYPE_SH7706) || \ defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) /* IRQ0->5 are handled in setup-sh3.c */ INTC_VECT(DMAC, 0x800), INTC_VECT(DMAC, 0x820), INTC_VECT(DMAC, 0x840), INTC_VECT(DMAC, 0x860), INTC_VECT(ADC_ADI, 0x980), INTC_VECT(SCIF2, 0x900), INTC_VECT(SCIF2, 0x920), INTC_VECT(SCIF2, 0x940), INTC_VECT(SCIF2, 0x960), #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) INTC_VECT(PINT07, 0x700), INTC_VECT(PINT815, 0x720), INTC_VECT(SCIF0, 0x880), INTC_VECT(SCIF0, 0x8a0), INTC_VECT(SCIF0, 0x8c0), INTC_VECT(SCIF0, 0x8e0), #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) INTC_VECT(LCDC, 0x9a0), INTC_VECT(PCC0, 0x9c0), INTC_VECT(PCC1, 0x9e0), #endif }; static struct intc_prio_reg prio_registers[] __initdata = { { 0xfffffee2, 0, 16, 4, /* IPRA */ { TMU0, TMU1, TMU2, RTC } }, { 0xfffffee4, 0, 16, 4, /* IPRB */ { WDT, REF, SCI, 0 } }, #if defined(CONFIG_CPU_SUBTYPE_SH7706) || \ defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) { 0xa4000016, 0, 16, 4, /* IPRC */ { IRQ3, IRQ2, IRQ1, IRQ0 } }, { 0xa4000018, 0, 16, 4, /* IPRD */ { 0, 0, IRQ5, IRQ4 } }, { 0xa400001a, 0, 16, 4, /* IPRE */ { DMAC, 0, SCIF2, ADC_ADI } }, #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) { 0xa4000018, 0, 16, 4, /* IPRD */ { PINT07, PINT815, } }, { 0xa400001a, 0, 16, 4, /* IPRE */ { 0, SCIF0 } }, #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) { 0xa400001c, 0, 16, 4, /* IPRF */ { 0, LCDC, PCC0, PCC1, } }, #endif }; static DECLARE_INTC_DESC(intc_desc, "sh770x", vectors, NULL, NULL, prio_registers, NULL); static struct resource rtc_resources[] = { [0] = { .start = 0xfffffec0, .end = 0xfffffec0 + 0x1e, .flags = IORESOURCE_IO, }, [1] = { .start = 20, .flags = IORESOURCE_IRQ, }, }; static struct platform_device rtc_device = { .name = "sh-rtc", .id = -1, .num_resources = ARRAY_SIZE(rtc_resources), .resource = rtc_resources, }; static struct plat_sci_port scif0_platform_data = { .mapbase = 0xfffffe80, .port_reg = 0xa4000136, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_TE | SCSCR_RE, .scbrr_algo_id = SCBRR_ALGO_2, .type = PORT_SCI, .irqs = { 23, 23, 23, 0 }, .ops = &sh770x_sci_port_ops, .regshift = 1, }; static struct platform_device scif0_device = { .name = "sh-sci", .id = 0, .dev = { .platform_data = &scif0_platform_data, }, }; #if defined(CONFIG_CPU_SUBTYPE_SH7706) || \ defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) static struct plat_sci_port scif1_platform_data = { .mapbase = 0xa4000150, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_TE | SCSCR_RE, .scbrr_algo_id = SCBRR_ALGO_2, .type = PORT_SCIF, .irqs = { 56, 56, 56, 56 }, .ops = &sh770x_sci_port_ops, .regtype = SCIx_SH3_SCIF_REGTYPE, }; static struct platform_device scif1_device = { .name = "sh-sci", .id = 1, .dev = { .platform_data = &scif1_platform_data, }, }; #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) static struct plat_sci_port scif2_platform_data = { .mapbase = 0xa4000140, .port_reg = SCIx_NOT_SUPPORTED, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_TE | SCSCR_RE, .scbrr_algo_id = SCBRR_ALGO_2, .type = PORT_IRDA, .irqs = { 52, 52, 52, 52 }, .ops = &sh770x_sci_port_ops, .regshift = 1, }; static struct platform_device scif2_device = { .name = "sh-sci", .id = 2, .dev = { .platform_data = &scif2_platform_data, }, }; #endif static struct sh_timer_config tmu0_platform_data = { .channel_offset = 0x02, .timer_bit = 0, .clockevent_rating = 200, }; static struct resource tmu0_resources[] = { [0] = { .start = 0xfffffe94, .end = 0xfffffe9f, .flags = IORESOURCE_MEM, }, [1] = { .start = 16, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu0_device = { .name = "sh_tmu", .id = 0, .dev = { .platform_data = &tmu0_platform_data, }, .resource = tmu0_resources, .num_resources = ARRAY_SIZE(tmu0_resources), }; static struct sh_timer_config tmu1_platform_data = { .channel_offset = 0xe, .timer_bit = 1, .clocksource_rating = 200, }; static struct resource tmu1_resources[] = { [0] = { .start = 0xfffffea0, .end = 0xfffffeab, .flags = IORESOURCE_MEM, }, [1] = { .start = 17, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu1_device = { .name = "sh_tmu", .id = 1, .dev = { .platform_data = &tmu1_platform_data, }, .resource = tmu1_resources, .num_resources = ARRAY_SIZE(tmu1_resources), }; static struct sh_timer_config tmu2_platform_data = { .channel_offset = 0x1a, .timer_bit = 2, }; static struct resource tmu2_resources[] = { [0] = { .start = 0xfffffeac, .end = 0xfffffebb, .flags = IORESOURCE_MEM, }, [1] = { .start = 18, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu2_device = { .name = "sh_tmu", .id = 2, .dev = { .platform_data = &tmu2_platform_data, }, .resource = tmu2_resources, .num_resources = ARRAY_SIZE(tmu2_resources), }; static struct platform_device *sh770x_devices[] __initdata = { &scif0_device, #if defined(CONFIG_CPU_SUBTYPE_SH7706) || \ defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) &scif1_device, #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) &scif2_device, #endif &tmu0_device, &tmu1_device, &tmu2_device, &rtc_device, }; static int __init sh770x_devices_setup(void) { return platform_add_devices(sh770x_devices, ARRAY_SIZE(sh770x_devices)); } arch_initcall(sh770x_devices_setup); static struct platform_device *sh770x_early_devices[] __initdata = { &scif0_device, #if defined(CONFIG_CPU_SUBTYPE_SH7706) || \ defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) &scif1_device, #endif #if defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) &scif2_device, #endif &tmu0_device, &tmu1_device, &tmu2_device, }; void __init plat_early_device_setup(void) { early_platform_add_devices(sh770x_early_devices, ARRAY_SIZE(sh770x_early_devices)); } void __init plat_irq_setup(void) { register_intc_controller(&intc_desc); #if defined(CONFIG_CPU_SUBTYPE_SH7706) || \ defined(CONFIG_CPU_SUBTYPE_SH7707) || \ defined(CONFIG_CPU_SUBTYPE_SH7709) plat_irq_setup_sh3(); #endif }
gpl-2.0
XtheOne/enrc2b-3.1.10-42105bd
arch/sh/drivers/pci/fixups-landisk.c
5062
1508
/* * arch/sh/drivers/pci/fixups-landisk.c * * PCI initialization for the I-O DATA Device, Inc. LANDISK board * * Copyright (C) 2006 kogiidena * Copyright (C) 2010 Nobuhiro Iwamatsu * * May be copied or modified under the terms of the GNU General Public * License. See linux/COPYING for more information. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pci.h> #include "pci-sh4.h" #define PCIMCR_MRSET_OFF 0xBFFFFFFF #define PCIMCR_RFSH_OFF 0xFFFFFFFB int pcibios_map_platform_irq(const struct pci_dev *pdev, u8 slot, u8 pin) { /* * slot0: pin1-4 = irq5,6,7,8 * slot1: pin1-4 = irq6,7,8,5 * slot2: pin1-4 = irq7,8,5,6 * slot3: pin1-4 = irq8,5,6,7 */ int irq = ((slot + pin - 1) & 0x3) + 5; if ((slot | (pin - 1)) > 0x3) { printk(KERN_WARNING "PCI: Bad IRQ mapping request for slot %d pin %c\n", slot, pin - 1 + 'A'); return -1; } return irq; } int pci_fixup_pcic(struct pci_channel *chan) { unsigned long bcr1, mcr; bcr1 = __raw_readl(SH7751_BCR1); bcr1 |= 0x40080000; /* Enable Bit 19 BREQEN, set PCIC to slave */ pci_write_reg(chan, bcr1, SH4_PCIBCR1); mcr = __raw_readl(SH7751_MCR); mcr = (mcr & PCIMCR_MRSET_OFF) & PCIMCR_RFSH_OFF; pci_write_reg(chan, mcr, SH4_PCIMCR); pci_write_reg(chan, 0x0c000000, SH7751_PCICONF5); pci_write_reg(chan, 0xd0000000, SH7751_PCICONF6); pci_write_reg(chan, 0x0c000000, SH4_PCILAR0); pci_write_reg(chan, 0x00000000, SH4_PCILAR1); return 0; }
gpl-2.0
MR64/android_kernel_htc_flounder
arch/sh/kernel/cpu/sh4/sq.c
8390
9697
/* * arch/sh/kernel/cpu/sh4/sq.c * * General management API for SH-4 integrated Store Queues * * Copyright (C) 2001 - 2006 Paul Mundt * Copyright (C) 2001, 2002 M. R. Brown * * 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. */ #include <linux/init.h> #include <linux/cpu.h> #include <linux/bitmap.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/mm.h> #include <linux/io.h> #include <linux/prefetch.h> #include <asm/page.h> #include <asm/cacheflush.h> #include <cpu/sq.h> struct sq_mapping; struct sq_mapping { const char *name; unsigned long sq_addr; unsigned long addr; unsigned int size; struct sq_mapping *next; }; static struct sq_mapping *sq_mapping_list; static DEFINE_SPINLOCK(sq_mapping_lock); static struct kmem_cache *sq_cache; static unsigned long *sq_bitmap; #define store_queue_barrier() \ do { \ (void)__raw_readl(P4SEG_STORE_QUE); \ __raw_writel(0, P4SEG_STORE_QUE + 0); \ __raw_writel(0, P4SEG_STORE_QUE + 8); \ } while (0); /** * sq_flush_range - Flush (prefetch) a specific SQ range * @start: the store queue address to start flushing from * @len: the length to flush * * Flushes the store queue cache from @start to @start + @len in a * linear fashion. */ void sq_flush_range(unsigned long start, unsigned int len) { unsigned long *sq = (unsigned long *)start; /* Flush the queues */ for (len >>= 5; len--; sq += 8) prefetchw(sq); /* Wait for completion */ store_queue_barrier(); } EXPORT_SYMBOL(sq_flush_range); static inline void sq_mapping_list_add(struct sq_mapping *map) { struct sq_mapping **p, *tmp; spin_lock_irq(&sq_mapping_lock); p = &sq_mapping_list; while ((tmp = *p) != NULL) p = &tmp->next; map->next = tmp; *p = map; spin_unlock_irq(&sq_mapping_lock); } static inline void sq_mapping_list_del(struct sq_mapping *map) { struct sq_mapping **p, *tmp; spin_lock_irq(&sq_mapping_lock); for (p = &sq_mapping_list; (tmp = *p); p = &tmp->next) if (tmp == map) { *p = tmp->next; break; } spin_unlock_irq(&sq_mapping_lock); } static int __sq_remap(struct sq_mapping *map, pgprot_t prot) { #if defined(CONFIG_MMU) struct vm_struct *vma; vma = __get_vm_area(map->size, VM_ALLOC, map->sq_addr, SQ_ADDRMAX); if (!vma) return -ENOMEM; vma->phys_addr = map->addr; if (ioremap_page_range((unsigned long)vma->addr, (unsigned long)vma->addr + map->size, vma->phys_addr, prot)) { vunmap(vma->addr); return -EAGAIN; } #else /* * Without an MMU (or with it turned off), this is much more * straightforward, as we can just load up each queue's QACR with * the physical address appropriately masked. */ __raw_writel(((map->addr >> 26) << 2) & 0x1c, SQ_QACR0); __raw_writel(((map->addr >> 26) << 2) & 0x1c, SQ_QACR1); #endif return 0; } /** * sq_remap - Map a physical address through the Store Queues * @phys: Physical address of mapping. * @size: Length of mapping. * @name: User invoking mapping. * @prot: Protection bits. * * Remaps the physical address @phys through the next available store queue * address of @size length. @name is logged at boot time as well as through * the sysfs interface. */ unsigned long sq_remap(unsigned long phys, unsigned int size, const char *name, pgprot_t prot) { struct sq_mapping *map; unsigned long end; unsigned int psz; int ret, page; /* Don't allow wraparound or zero size */ end = phys + size - 1; if (unlikely(!size || end < phys)) return -EINVAL; /* Don't allow anyone to remap normal memory.. */ if (unlikely(phys < virt_to_phys(high_memory))) return -EINVAL; phys &= PAGE_MASK; size = PAGE_ALIGN(end + 1) - phys; map = kmem_cache_alloc(sq_cache, GFP_KERNEL); if (unlikely(!map)) return -ENOMEM; map->addr = phys; map->size = size; map->name = name; page = bitmap_find_free_region(sq_bitmap, 0x04000000 >> PAGE_SHIFT, get_order(map->size)); if (unlikely(page < 0)) { ret = -ENOSPC; goto out; } map->sq_addr = P4SEG_STORE_QUE + (page << PAGE_SHIFT); ret = __sq_remap(map, prot); if (unlikely(ret != 0)) goto out; psz = (size + (PAGE_SIZE - 1)) >> PAGE_SHIFT; pr_info("sqremap: %15s [%4d page%s] va 0x%08lx pa 0x%08lx\n", likely(map->name) ? map->name : "???", psz, psz == 1 ? " " : "s", map->sq_addr, map->addr); sq_mapping_list_add(map); return map->sq_addr; out: kmem_cache_free(sq_cache, map); return ret; } EXPORT_SYMBOL(sq_remap); /** * sq_unmap - Unmap a Store Queue allocation * @vaddr: Pre-allocated Store Queue mapping. * * Unmaps the store queue allocation @map that was previously created by * sq_remap(). Also frees up the pte that was previously inserted into * the kernel page table and discards the UTLB translation. */ void sq_unmap(unsigned long vaddr) { struct sq_mapping **p, *map; int page; for (p = &sq_mapping_list; (map = *p); p = &map->next) if (map->sq_addr == vaddr) break; if (unlikely(!map)) { printk("%s: bad store queue address 0x%08lx\n", __func__, vaddr); return; } page = (map->sq_addr - P4SEG_STORE_QUE) >> PAGE_SHIFT; bitmap_release_region(sq_bitmap, page, get_order(map->size)); #ifdef CONFIG_MMU { /* * Tear down the VMA in the MMU case. */ struct vm_struct *vma; vma = remove_vm_area((void *)(map->sq_addr & PAGE_MASK)); if (!vma) { printk(KERN_ERR "%s: bad address 0x%08lx\n", __func__, map->sq_addr); return; } } #endif sq_mapping_list_del(map); kmem_cache_free(sq_cache, map); } EXPORT_SYMBOL(sq_unmap); /* * Needlessly complex sysfs interface. Unfortunately it doesn't seem like * there is any other easy way to add things on a per-cpu basis without * putting the directory entries somewhere stupid and having to create * links in sysfs by hand back in to the per-cpu directories. * * Some day we may want to have an additional abstraction per store * queue, but considering the kobject hell we already have to deal with, * it's simply not worth the trouble. */ static struct kobject *sq_kobject[NR_CPUS]; struct sq_sysfs_attr { struct attribute attr; ssize_t (*show)(char *buf); ssize_t (*store)(const char *buf, size_t count); }; #define to_sq_sysfs_attr(a) container_of(a, struct sq_sysfs_attr, attr) static ssize_t sq_sysfs_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct sq_sysfs_attr *sattr = to_sq_sysfs_attr(attr); if (likely(sattr->show)) return sattr->show(buf); return -EIO; } static ssize_t sq_sysfs_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t count) { struct sq_sysfs_attr *sattr = to_sq_sysfs_attr(attr); if (likely(sattr->store)) return sattr->store(buf, count); return -EIO; } static ssize_t mapping_show(char *buf) { struct sq_mapping **list, *entry; char *p = buf; for (list = &sq_mapping_list; (entry = *list); list = &entry->next) p += sprintf(p, "%08lx-%08lx [%08lx]: %s\n", entry->sq_addr, entry->sq_addr + entry->size, entry->addr, entry->name); return p - buf; } static ssize_t mapping_store(const char *buf, size_t count) { unsigned long base = 0, len = 0; sscanf(buf, "%lx %lx", &base, &len); if (!base) return -EIO; if (likely(len)) { int ret = sq_remap(base, len, "Userspace", PAGE_SHARED); if (ret < 0) return ret; } else sq_unmap(base); return count; } static struct sq_sysfs_attr mapping_attr = __ATTR(mapping, 0644, mapping_show, mapping_store); static struct attribute *sq_sysfs_attrs[] = { &mapping_attr.attr, NULL, }; static const struct sysfs_ops sq_sysfs_ops = { .show = sq_sysfs_show, .store = sq_sysfs_store, }; static struct kobj_type ktype_percpu_entry = { .sysfs_ops = &sq_sysfs_ops, .default_attrs = sq_sysfs_attrs, }; static int sq_dev_add(struct device *dev, struct subsys_interface *sif) { unsigned int cpu = dev->id; struct kobject *kobj; int error; sq_kobject[cpu] = kzalloc(sizeof(struct kobject), GFP_KERNEL); if (unlikely(!sq_kobject[cpu])) return -ENOMEM; kobj = sq_kobject[cpu]; error = kobject_init_and_add(kobj, &ktype_percpu_entry, &dev->kobj, "%s", "sq"); if (!error) kobject_uevent(kobj, KOBJ_ADD); return error; } static int sq_dev_remove(struct device *dev, struct subsys_interface *sif) { unsigned int cpu = dev->id; struct kobject *kobj = sq_kobject[cpu]; kobject_put(kobj); return 0; } static struct subsys_interface sq_interface = { .name = "sq", .subsys = &cpu_subsys, .add_dev = sq_dev_add, .remove_dev = sq_dev_remove, }; static int __init sq_api_init(void) { unsigned int nr_pages = 0x04000000 >> PAGE_SHIFT; unsigned int size = (nr_pages + (BITS_PER_LONG - 1)) / BITS_PER_LONG; int ret = -ENOMEM; printk(KERN_NOTICE "sq: Registering store queue API.\n"); sq_cache = kmem_cache_create("store_queue_cache", sizeof(struct sq_mapping), 0, 0, NULL); if (unlikely(!sq_cache)) return ret; sq_bitmap = kzalloc(size, GFP_KERNEL); if (unlikely(!sq_bitmap)) goto out; ret = subsys_interface_register(&sq_interface); if (unlikely(ret != 0)) goto out; return 0; out: kfree(sq_bitmap); kmem_cache_destroy(sq_cache); return ret; } static void __exit sq_api_exit(void) { subsys_interface_unregister(&sq_interface); kfree(sq_bitmap); kmem_cache_destroy(sq_cache); } module_init(sq_api_init); module_exit(sq_api_exit); MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>, M. R. Brown <mrbrown@0xd6.org>"); MODULE_DESCRIPTION("Simple API for SH-4 integrated Store Queues"); MODULE_LICENSE("GPL");
gpl-2.0
sub77/test_kernel_samsung_matissewifi
arch/arm/mach-gemini/devices.c
12486
2862
/* * Common devices definition for Gemini * * Copyright (C) 2008-2009 Paulius Zaleckas <paulius.zaleckas@teltonika.lt> * * 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/io.h> #include <linux/platform_device.h> #include <linux/serial_8250.h> #include <linux/mtd/physmap.h> #include <mach/irqs.h> #include <mach/hardware.h> #include <mach/global_reg.h> static struct plat_serial8250_port serial_platform_data[] = { { .membase = (void *)IO_ADDRESS(GEMINI_UART_BASE), .mapbase = GEMINI_UART_BASE, .irq = IRQ_UART, .uartclk = UART_CLK, .regshift = 2, .iotype = UPIO_MEM, .type = PORT_16550A, .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_FIXED_TYPE, }, {}, }; static struct platform_device serial_device = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = serial_platform_data, }, }; int platform_register_uart(void) { return platform_device_register(&serial_device); } static struct resource flash_resource = { .start = GEMINI_FLASH_BASE, .flags = IORESOURCE_MEM, }; static struct physmap_flash_data pflash_platform_data = {}; static struct platform_device pflash_device = { .name = "physmap-flash", .id = 0, .dev = { .platform_data = &pflash_platform_data, }, .resource = &flash_resource, .num_resources = 1, }; int platform_register_pflash(unsigned int size, struct mtd_partition *parts, unsigned int nr_parts) { unsigned int reg; reg = __raw_readl(IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_STATUS); if ((reg & FLASH_TYPE_MASK) != FLASH_TYPE_PARALLEL) return -ENXIO; if (reg & FLASH_WIDTH_16BIT) pflash_platform_data.width = 2; else pflash_platform_data.width = 1; /* enable parallel flash pins and disable others */ reg = __raw_readl(IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_MISC_CTRL); reg &= ~PFLASH_PADS_DISABLE; reg |= SFLASH_PADS_DISABLE | NAND_PADS_DISABLE; __raw_writel(reg, IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_MISC_CTRL); flash_resource.end = flash_resource.start + size - 1; pflash_platform_data.parts = parts; pflash_platform_data.nr_parts = nr_parts; return platform_device_register(&pflash_device); } static struct resource gemini_rtc_resources[] = { [0] = { .start = GEMINI_RTC_BASE, .end = GEMINI_RTC_BASE + 0x24, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_RTC, .end = IRQ_RTC, .flags = IORESOURCE_IRQ, }, }; static struct platform_device gemini_rtc_device = { .name = "rtc-gemini", .id = 0, .num_resources = ARRAY_SIZE(gemini_rtc_resources), .resource = gemini_rtc_resources, }; int __init platform_register_rtc(void) { return platform_device_register(&gemini_rtc_device); }
gpl-2.0
Zenfone2-development/android_kernel_asus_moorefield
arch/arm/mach-gemini/devices.c
12486
2862
/* * Common devices definition for Gemini * * Copyright (C) 2008-2009 Paulius Zaleckas <paulius.zaleckas@teltonika.lt> * * 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/io.h> #include <linux/platform_device.h> #include <linux/serial_8250.h> #include <linux/mtd/physmap.h> #include <mach/irqs.h> #include <mach/hardware.h> #include <mach/global_reg.h> static struct plat_serial8250_port serial_platform_data[] = { { .membase = (void *)IO_ADDRESS(GEMINI_UART_BASE), .mapbase = GEMINI_UART_BASE, .irq = IRQ_UART, .uartclk = UART_CLK, .regshift = 2, .iotype = UPIO_MEM, .type = PORT_16550A, .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_FIXED_TYPE, }, {}, }; static struct platform_device serial_device = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = serial_platform_data, }, }; int platform_register_uart(void) { return platform_device_register(&serial_device); } static struct resource flash_resource = { .start = GEMINI_FLASH_BASE, .flags = IORESOURCE_MEM, }; static struct physmap_flash_data pflash_platform_data = {}; static struct platform_device pflash_device = { .name = "physmap-flash", .id = 0, .dev = { .platform_data = &pflash_platform_data, }, .resource = &flash_resource, .num_resources = 1, }; int platform_register_pflash(unsigned int size, struct mtd_partition *parts, unsigned int nr_parts) { unsigned int reg; reg = __raw_readl(IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_STATUS); if ((reg & FLASH_TYPE_MASK) != FLASH_TYPE_PARALLEL) return -ENXIO; if (reg & FLASH_WIDTH_16BIT) pflash_platform_data.width = 2; else pflash_platform_data.width = 1; /* enable parallel flash pins and disable others */ reg = __raw_readl(IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_MISC_CTRL); reg &= ~PFLASH_PADS_DISABLE; reg |= SFLASH_PADS_DISABLE | NAND_PADS_DISABLE; __raw_writel(reg, IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_MISC_CTRL); flash_resource.end = flash_resource.start + size - 1; pflash_platform_data.parts = parts; pflash_platform_data.nr_parts = nr_parts; return platform_device_register(&pflash_device); } static struct resource gemini_rtc_resources[] = { [0] = { .start = GEMINI_RTC_BASE, .end = GEMINI_RTC_BASE + 0x24, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_RTC, .end = IRQ_RTC, .flags = IORESOURCE_IRQ, }, }; static struct platform_device gemini_rtc_device = { .name = "rtc-gemini", .id = 0, .num_resources = ARRAY_SIZE(gemini_rtc_resources), .resource = gemini_rtc_resources, }; int __init platform_register_rtc(void) { return platform_device_register(&gemini_rtc_device); }
gpl-2.0
AOSP-bacon/android_kernel_oneplus_msm8974
arch/arm/mach-gemini/devices.c
12486
2862
/* * Common devices definition for Gemini * * Copyright (C) 2008-2009 Paulius Zaleckas <paulius.zaleckas@teltonika.lt> * * 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/io.h> #include <linux/platform_device.h> #include <linux/serial_8250.h> #include <linux/mtd/physmap.h> #include <mach/irqs.h> #include <mach/hardware.h> #include <mach/global_reg.h> static struct plat_serial8250_port serial_platform_data[] = { { .membase = (void *)IO_ADDRESS(GEMINI_UART_BASE), .mapbase = GEMINI_UART_BASE, .irq = IRQ_UART, .uartclk = UART_CLK, .regshift = 2, .iotype = UPIO_MEM, .type = PORT_16550A, .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_FIXED_TYPE, }, {}, }; static struct platform_device serial_device = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = serial_platform_data, }, }; int platform_register_uart(void) { return platform_device_register(&serial_device); } static struct resource flash_resource = { .start = GEMINI_FLASH_BASE, .flags = IORESOURCE_MEM, }; static struct physmap_flash_data pflash_platform_data = {}; static struct platform_device pflash_device = { .name = "physmap-flash", .id = 0, .dev = { .platform_data = &pflash_platform_data, }, .resource = &flash_resource, .num_resources = 1, }; int platform_register_pflash(unsigned int size, struct mtd_partition *parts, unsigned int nr_parts) { unsigned int reg; reg = __raw_readl(IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_STATUS); if ((reg & FLASH_TYPE_MASK) != FLASH_TYPE_PARALLEL) return -ENXIO; if (reg & FLASH_WIDTH_16BIT) pflash_platform_data.width = 2; else pflash_platform_data.width = 1; /* enable parallel flash pins and disable others */ reg = __raw_readl(IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_MISC_CTRL); reg &= ~PFLASH_PADS_DISABLE; reg |= SFLASH_PADS_DISABLE | NAND_PADS_DISABLE; __raw_writel(reg, IO_ADDRESS(GEMINI_GLOBAL_BASE) + GLOBAL_MISC_CTRL); flash_resource.end = flash_resource.start + size - 1; pflash_platform_data.parts = parts; pflash_platform_data.nr_parts = nr_parts; return platform_device_register(&pflash_device); } static struct resource gemini_rtc_resources[] = { [0] = { .start = GEMINI_RTC_BASE, .end = GEMINI_RTC_BASE + 0x24, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_RTC, .end = IRQ_RTC, .flags = IORESOURCE_IRQ, }, }; static struct platform_device gemini_rtc_device = { .name = "rtc-gemini", .id = 0, .num_resources = ARRAY_SIZE(gemini_rtc_resources), .resource = gemini_rtc_resources, }; int __init platform_register_rtc(void) { return platform_device_register(&gemini_rtc_device); }
gpl-2.0
zoggn/kernel_tcl_msm8610
arch/arm/mach-msm/acpuclock-krait-debug.c
455
9035
/* * Copyright (c) 2012, 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. */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/kernel.h> #include <linux/io.h> #include <linux/debugfs.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/cpu.h> #include <linux/smp.h> #include <mach/msm_bus.h> #include <mach/msm-krait-l2-accessors.h> #include "acpuclock-krait.h" static struct drv_data *drv; static DEFINE_MUTEX(debug_lock); struct acg_action { bool set; bool enable; }; static int l2_acg_en_val; static struct dentry *base_dir; static struct dentry *sc_dir[MAX_SCALABLES]; static void cpu_action(void *info) { struct acg_action *action = info; u32 val; asm volatile ("mrc p15, 7, %[cpmr0], c15, c0, 5\n\t" : [cpmr0]"=r" (val)); if (action->set) { if (action->enable) val &= ~BIT(0); else val |= BIT(0); asm volatile ("mcr p15, 7, %[cpmr0], c15, c0, 5\n\t" : : [cpmr0]"r" (val)); } else { action->enable = !(val & BIT(0)); } } /* Disable auto clock-gating for a scalable. */ static void disable_acg(int sc_id) { u32 regval; if (sc_id == L2) { regval = get_l2_indirect_reg(drv->scalable[sc_id].l2cpmr_iaddr); l2_acg_en_val = regval & (0x3 << 10); regval |= (0x3 << 10); set_l2_indirect_reg(drv->scalable[sc_id].l2cpmr_iaddr, regval); } else { struct acg_action action = { .set = true, .enable = false }; smp_call_function_single(sc_id, cpu_action, &action, 1); } } /* Enable auto clock-gating for a scalable. */ static void enable_acg(int sc_id) { u32 regval; if (sc_id == L2) { regval = get_l2_indirect_reg(drv->scalable[sc_id].l2cpmr_iaddr); regval &= ~(0x3 << 10); regval |= l2_acg_en_val; set_l2_indirect_reg(drv->scalable[sc_id].l2cpmr_iaddr, regval); } else { struct acg_action action = { .set = true, .enable = true }; smp_call_function_single(sc_id, cpu_action, &action, 1); } } /* Check if auto clock-gating for a scalable. */ static bool acg_is_enabled(int sc_id) { u32 regval; if (sc_id == L2) { regval = get_l2_indirect_reg(drv->scalable[sc_id].l2cpmr_iaddr); return ((regval >> 10) & 0x3) != 0x3; } else { struct acg_action action = { .set = false }; smp_call_function_single(sc_id, cpu_action, &action, 1); return action.enable; } } /* Enable/Disable auto clock gating. */ static int acg_set(void *data, u64 val) { int ret = 0; int sc_id = (int)data; mutex_lock(&debug_lock); get_online_cpus(); if (!sc_dir[sc_id]) { ret = -ENODEV; goto out; } if (val == 0 && acg_is_enabled(sc_id)) disable_acg(sc_id); else if (val == 1) enable_acg(sc_id); out: put_online_cpus(); mutex_unlock(&debug_lock); return ret; } /* Get auto clock-gating state. */ static int acg_get(void *data, u64 *val) { int ret = 0; int sc_id = (int)data; mutex_lock(&debug_lock); get_online_cpus(); if (!sc_dir[sc_id]) { ret = -ENODEV; goto out; } *val = acg_is_enabled(sc_id); out: put_online_cpus(); mutex_unlock(&debug_lock); return ret; } DEFINE_SIMPLE_ATTRIBUTE(acgd_fops, acg_get, acg_set, "%lld\n"); /* Get the rate */ static int rate_get(void *data, u64 *val) { int sc_id = (int)data; *val = drv->scalable[sc_id].cur_speed->khz; return 0; } DEFINE_SIMPLE_ATTRIBUTE(rate_fops, rate_get, NULL, "%lld\n"); /* Get the HFPLL's L-value. */ static int hfpll_l_get(void *data, u64 *val) { int sc_id = (int)data; *val = drv->scalable[sc_id].cur_speed->pll_l_val; return 0; } DEFINE_SIMPLE_ATTRIBUTE(hfpll_l_fops, hfpll_l_get, NULL, "%lld\n"); /* Get the L2 rate vote. */ static int l2_vote_get(void *data, u64 *val) { int level, sc_id = (int)data; level = drv->scalable[sc_id].l2_vote; *val = drv->l2_freq_tbl[level].speed.khz; return 0; } DEFINE_SIMPLE_ATTRIBUTE(l2_vote_fops, l2_vote_get, NULL, "%lld\n"); /* Get the bandwidth vote. */ static int bw_vote_get(void *data, u64 *val) { struct l2_level *l; l = container_of(drv->scalable[L2].cur_speed, struct l2_level, speed); *val = drv->bus_scale->usecase[l->bw_level].vectors->ib; return 0; } DEFINE_SIMPLE_ATTRIBUTE(bw_vote_fops, bw_vote_get, NULL, "%lld\n"); /* Get the name of the currently-selected clock source. */ static int src_name_show(struct seq_file *m, void *unused) { const char *const src_names[NUM_SRC_ID] = { [PLL_0] = "PLL0", [HFPLL] = "HFPLL", [PLL_8] = "PLL8", }; int src, sc_id = (int)m->private; src = drv->scalable[sc_id].cur_speed->src; if (src > ARRAY_SIZE(src_names)) return -EINVAL; seq_printf(m, "%s\n", src_names[src]); return 0; } static int src_name_open(struct inode *inode, struct file *file) { return single_open(file, src_name_show, inode->i_private); } static const struct file_operations src_name_fops = { .open = src_name_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /* Get speed_bin ID */ static int speed_bin_get(void *data, u64 *val) { *val = drv->speed_bin; return 0; } DEFINE_SIMPLE_ATTRIBUTE(speed_bin_fops, speed_bin_get, NULL, "%lld\n"); /* Get pvs_bin ID */ static int pvs_bin_get(void *data, u64 *val) { *val = drv->pvs_bin; return 0; } DEFINE_SIMPLE_ATTRIBUTE(pvs_bin_fops, pvs_bin_get, NULL, "%lld\n"); /* Get boost_uv */ static int boost_get(void *data, u64 *val) { *val = drv->boost_uv; return 0; } DEFINE_SIMPLE_ATTRIBUTE(boost_fops, boost_get, NULL, "%lld\n"); static int acpu_table_show(struct seq_file *m, void *unused) { const struct acpu_level *level; seq_printf(m, "CPU_KHz PLL_L_Val L2_KHz VDD_Dig VDD_Mem "); seq_printf(m, "BW_Mbps VDD_Core UA_Core AVS\n"); for (level = drv->acpu_freq_tbl; level->speed.khz != 0; level++) { const struct l2_level *l2 = &drv->l2_freq_tbl[level->l2_level]; u32 bw = drv->bus_scale->usecase[l2->bw_level].vectors[0].ib; if (!level->use_for_scaling) continue; /* CPU speed information */ seq_printf(m, "%7lu %9u ", level->speed.khz, level->speed.pll_l_val); /* L2 level information */ seq_printf(m, "%7lu %7d %7d %7u ", l2->speed.khz, l2->vdd_dig, l2->vdd_mem, bw / 1000000); /* Core voltage information */ seq_printf(m, "%8d %7d %3d\n", level->vdd_core, level->ua_core, level->avsdscr_setting); } return 0; } static int acpu_table_open(struct inode *inode, struct file *file) { return single_open(file, acpu_table_show, inode->i_private); } static const struct file_operations acpu_table_fops = { .open = acpu_table_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void __cpuinit add_scalable_dir(int sc_id) { char sc_name[8]; if (sc_id == L2) snprintf(sc_name, sizeof(sc_name), "l2"); else snprintf(sc_name, sizeof(sc_name), "cpu%d", sc_id); sc_dir[sc_id] = debugfs_create_dir(sc_name, base_dir); if (!sc_dir[sc_id]) return; debugfs_create_file("auto_gating", S_IRUGO | S_IWUSR, sc_dir[sc_id], (void *)sc_id, &acgd_fops); debugfs_create_file("rate", S_IRUGO, sc_dir[sc_id], (void *)sc_id, &rate_fops); debugfs_create_file("hfpll_l", S_IRUGO, sc_dir[sc_id], (void *)sc_id, &hfpll_l_fops); debugfs_create_file("src", S_IRUGO, sc_dir[sc_id], (void *)sc_id, &src_name_fops); if (sc_id == L2) debugfs_create_file("bw_ib_vote", S_IRUGO, sc_dir[sc_id], (void *)sc_id, &bw_vote_fops); else debugfs_create_file("l2_vote", S_IRUGO, sc_dir[sc_id], (void *)sc_id, &l2_vote_fops); } static void __cpuinit remove_scalable_dir(int sc_id) { debugfs_remove_recursive(sc_dir[sc_id]); sc_dir[sc_id] = NULL; } static int __cpuinit debug_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (int)hcpu; switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_FAILED: case CPU_UP_PREPARE: add_scalable_dir(cpu); break; case CPU_UP_CANCELED: case CPU_DOWN_PREPARE: remove_scalable_dir(cpu); break; default: break; } return NOTIFY_OK; } static struct notifier_block __cpuinitdata debug_cpu_notifier = { .notifier_call = debug_cpu_callback, }; void __init acpuclk_krait_debug_init(struct drv_data *drv_data) { int cpu; drv = drv_data; base_dir = debugfs_create_dir("acpuclk", NULL); if (!base_dir) return; debugfs_create_file("speed_bin", S_IRUGO, base_dir, NULL, &speed_bin_fops); debugfs_create_file("pvs_bin", S_IRUGO, base_dir, NULL, &pvs_bin_fops); debugfs_create_file("boost_uv", S_IRUGO, base_dir, NULL, &boost_fops); debugfs_create_file("acpu_table", S_IRUGO, base_dir, NULL, &acpu_table_fops); for_each_online_cpu(cpu) add_scalable_dir(cpu); add_scalable_dir(L2); register_hotcpu_notifier(&debug_cpu_notifier); }
gpl-2.0
mayli/wrapfs-latest
lib/swiotlb.c
711
27796
/* * Dynamic DMA mapping support. * * This implementation is a fallback for platforms that do not support * I/O TLBs (aka DMA address translation hardware). * Copyright (C) 2000 Asit Mallick <Asit.K.Mallick@intel.com> * Copyright (C) 2000 Goutham Rao <goutham.rao@intel.com> * Copyright (C) 2000, 2003 Hewlett-Packard Co * David Mosberger-Tang <davidm@hpl.hp.com> * * 03/05/07 davidm Switch from PCI-DMA to generic device DMA API. * 00/12/13 davidm Rename to swiotlb.c and add mark_clean() to avoid * unnecessary i-cache flushing. * 04/07/.. ak Better overflow handling. Assorted fixes. * 05/09/10 linville Add support for syncing ranges, support syncing for * DMA_BIDIRECTIONAL mappings, miscellaneous cleanup. * 08/12/11 beckyb Add highmem support */ #include <linux/cache.h> #include <linux/dma-mapping.h> #include <linux/mm.h> #include <linux/export.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/swiotlb.h> #include <linux/pfn.h> #include <linux/types.h> #include <linux/ctype.h> #include <linux/highmem.h> #include <linux/gfp.h> #include <asm/io.h> #include <asm/dma.h> #include <asm/scatterlist.h> #include <linux/init.h> #include <linux/bootmem.h> #include <linux/iommu-helper.h> #define CREATE_TRACE_POINTS #include <trace/events/swiotlb.h> #define OFFSET(val,align) ((unsigned long) \ ( (val) & ( (align) - 1))) #define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT)) /* * Minimum IO TLB size to bother booting with. Systems with mainly * 64bit capable cards will only lightly use the swiotlb. If we can't * allocate a contiguous 1MB, we're probably in trouble anyway. */ #define IO_TLB_MIN_SLABS ((1<<20) >> IO_TLB_SHIFT) int swiotlb_force; /* * Used to do a quick range check in swiotlb_tbl_unmap_single and * swiotlb_tbl_sync_single_*, to see if the memory was in fact allocated by this * API. */ static phys_addr_t io_tlb_start, io_tlb_end; /* * The number of IO TLB blocks (in groups of 64) between io_tlb_start and * io_tlb_end. This is command line adjustable via setup_io_tlb_npages. */ static unsigned long io_tlb_nslabs; /* * When the IOMMU overflows we return a fallback buffer. This sets the size. */ static unsigned long io_tlb_overflow = 32*1024; static phys_addr_t io_tlb_overflow_buffer; /* * This is a free list describing the number of free entries available from * each index */ static unsigned int *io_tlb_list; static unsigned int io_tlb_index; /* * We need to save away the original address corresponding to a mapped entry * for the sync operations. */ #define INVALID_PHYS_ADDR (~(phys_addr_t)0) static phys_addr_t *io_tlb_orig_addr; /* * Protect the above data structures in the map and unmap calls */ static DEFINE_SPINLOCK(io_tlb_lock); static int late_alloc; static int __init setup_io_tlb_npages(char *str) { if (isdigit(*str)) { io_tlb_nslabs = simple_strtoul(str, &str, 0); /* avoid tail segment of size < IO_TLB_SEGSIZE */ io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE); } if (*str == ',') ++str; if (!strcmp(str, "force")) swiotlb_force = 1; return 0; } early_param("swiotlb", setup_io_tlb_npages); /* make io_tlb_overflow tunable too? */ unsigned long swiotlb_nr_tbl(void) { return io_tlb_nslabs; } EXPORT_SYMBOL_GPL(swiotlb_nr_tbl); /* default to 64MB */ #define IO_TLB_DEFAULT_SIZE (64UL<<20) unsigned long swiotlb_size_or_default(void) { unsigned long size; size = io_tlb_nslabs << IO_TLB_SHIFT; return size ? size : (IO_TLB_DEFAULT_SIZE); } /* Note that this doesn't work with highmem page */ static dma_addr_t swiotlb_virt_to_bus(struct device *hwdev, volatile void *address) { return phys_to_dma(hwdev, virt_to_phys(address)); } static bool no_iotlb_memory; void swiotlb_print_info(void) { unsigned long bytes = io_tlb_nslabs << IO_TLB_SHIFT; unsigned char *vstart, *vend; if (no_iotlb_memory) { pr_warn("software IO TLB: No low mem\n"); return; } vstart = phys_to_virt(io_tlb_start); vend = phys_to_virt(io_tlb_end); printk(KERN_INFO "software IO TLB [mem %#010llx-%#010llx] (%luMB) mapped at [%p-%p]\n", (unsigned long long)io_tlb_start, (unsigned long long)io_tlb_end, bytes >> 20, vstart, vend - 1); } int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose) { void *v_overflow_buffer; unsigned long i, bytes; bytes = nslabs << IO_TLB_SHIFT; io_tlb_nslabs = nslabs; io_tlb_start = __pa(tlb); io_tlb_end = io_tlb_start + bytes; /* * Get the overflow emergency buffer */ v_overflow_buffer = memblock_virt_alloc_low_nopanic( PAGE_ALIGN(io_tlb_overflow), PAGE_SIZE); if (!v_overflow_buffer) return -ENOMEM; io_tlb_overflow_buffer = __pa(v_overflow_buffer); /* * Allocate and initialize the free list array. This array is used * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE * between io_tlb_start and io_tlb_end. */ io_tlb_list = memblock_virt_alloc( PAGE_ALIGN(io_tlb_nslabs * sizeof(int)), PAGE_SIZE); io_tlb_orig_addr = memblock_virt_alloc( PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)), PAGE_SIZE); for (i = 0; i < io_tlb_nslabs; i++) { io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE); io_tlb_orig_addr[i] = INVALID_PHYS_ADDR; } io_tlb_index = 0; if (verbose) swiotlb_print_info(); return 0; } /* * Statically reserve bounce buffer space and initialize bounce buffer data * structures for the software IO TLB used to implement the DMA API. */ void __init swiotlb_init(int verbose) { size_t default_size = IO_TLB_DEFAULT_SIZE; unsigned char *vstart; unsigned long bytes; if (!io_tlb_nslabs) { io_tlb_nslabs = (default_size >> IO_TLB_SHIFT); io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE); } bytes = io_tlb_nslabs << IO_TLB_SHIFT; /* Get IO TLB memory from the low pages */ vstart = memblock_virt_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE); if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose)) return; if (io_tlb_start) memblock_free_early(io_tlb_start, PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT)); pr_warn("Cannot allocate SWIOTLB buffer"); no_iotlb_memory = true; } /* * Systems with larger DMA zones (those that don't support ISA) can * initialize the swiotlb later using the slab allocator if needed. * This should be just like above, but with some error catching. */ int swiotlb_late_init_with_default_size(size_t default_size) { unsigned long bytes, req_nslabs = io_tlb_nslabs; unsigned char *vstart = NULL; unsigned int order; int rc = 0; if (!io_tlb_nslabs) { io_tlb_nslabs = (default_size >> IO_TLB_SHIFT); io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE); } /* * Get IO TLB memory from the low pages */ order = get_order(io_tlb_nslabs << IO_TLB_SHIFT); io_tlb_nslabs = SLABS_PER_PAGE << order; bytes = io_tlb_nslabs << IO_TLB_SHIFT; while ((SLABS_PER_PAGE << order) > IO_TLB_MIN_SLABS) { vstart = (void *)__get_free_pages(GFP_DMA | __GFP_NOWARN, order); if (vstart) break; order--; } if (!vstart) { io_tlb_nslabs = req_nslabs; return -ENOMEM; } if (order != get_order(bytes)) { printk(KERN_WARNING "Warning: only able to allocate %ld MB " "for software IO TLB\n", (PAGE_SIZE << order) >> 20); io_tlb_nslabs = SLABS_PER_PAGE << order; } rc = swiotlb_late_init_with_tbl(vstart, io_tlb_nslabs); if (rc) free_pages((unsigned long)vstart, order); return rc; } int swiotlb_late_init_with_tbl(char *tlb, unsigned long nslabs) { unsigned long i, bytes; unsigned char *v_overflow_buffer; bytes = nslabs << IO_TLB_SHIFT; io_tlb_nslabs = nslabs; io_tlb_start = virt_to_phys(tlb); io_tlb_end = io_tlb_start + bytes; memset(tlb, 0, bytes); /* * Get the overflow emergency buffer */ v_overflow_buffer = (void *)__get_free_pages(GFP_DMA, get_order(io_tlb_overflow)); if (!v_overflow_buffer) goto cleanup2; io_tlb_overflow_buffer = virt_to_phys(v_overflow_buffer); /* * Allocate and initialize the free list array. This array is used * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE * between io_tlb_start and io_tlb_end. */ io_tlb_list = (unsigned int *)__get_free_pages(GFP_KERNEL, get_order(io_tlb_nslabs * sizeof(int))); if (!io_tlb_list) goto cleanup3; io_tlb_orig_addr = (phys_addr_t *) __get_free_pages(GFP_KERNEL, get_order(io_tlb_nslabs * sizeof(phys_addr_t))); if (!io_tlb_orig_addr) goto cleanup4; for (i = 0; i < io_tlb_nslabs; i++) { io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE); io_tlb_orig_addr[i] = INVALID_PHYS_ADDR; } io_tlb_index = 0; swiotlb_print_info(); late_alloc = 1; return 0; cleanup4: free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs * sizeof(int))); io_tlb_list = NULL; cleanup3: free_pages((unsigned long)v_overflow_buffer, get_order(io_tlb_overflow)); io_tlb_overflow_buffer = 0; cleanup2: io_tlb_end = 0; io_tlb_start = 0; io_tlb_nslabs = 0; return -ENOMEM; } void __init swiotlb_free(void) { if (!io_tlb_orig_addr) return; if (late_alloc) { free_pages((unsigned long)phys_to_virt(io_tlb_overflow_buffer), get_order(io_tlb_overflow)); free_pages((unsigned long)io_tlb_orig_addr, get_order(io_tlb_nslabs * sizeof(phys_addr_t))); free_pages((unsigned long)io_tlb_list, get_order(io_tlb_nslabs * sizeof(int))); free_pages((unsigned long)phys_to_virt(io_tlb_start), get_order(io_tlb_nslabs << IO_TLB_SHIFT)); } else { memblock_free_late(io_tlb_overflow_buffer, PAGE_ALIGN(io_tlb_overflow)); memblock_free_late(__pa(io_tlb_orig_addr), PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t))); memblock_free_late(__pa(io_tlb_list), PAGE_ALIGN(io_tlb_nslabs * sizeof(int))); memblock_free_late(io_tlb_start, PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT)); } io_tlb_nslabs = 0; } int is_swiotlb_buffer(phys_addr_t paddr) { return paddr >= io_tlb_start && paddr < io_tlb_end; } /* * Bounce: copy the swiotlb buffer back to the original dma location */ static void swiotlb_bounce(phys_addr_t orig_addr, phys_addr_t tlb_addr, size_t size, enum dma_data_direction dir) { unsigned long pfn = PFN_DOWN(orig_addr); unsigned char *vaddr = phys_to_virt(tlb_addr); if (PageHighMem(pfn_to_page(pfn))) { /* The buffer does not have a mapping. Map it in and copy */ unsigned int offset = orig_addr & ~PAGE_MASK; char *buffer; unsigned int sz = 0; unsigned long flags; while (size) { sz = min_t(size_t, PAGE_SIZE - offset, size); local_irq_save(flags); buffer = kmap_atomic(pfn_to_page(pfn)); if (dir == DMA_TO_DEVICE) memcpy(vaddr, buffer + offset, sz); else memcpy(buffer + offset, vaddr, sz); kunmap_atomic(buffer); local_irq_restore(flags); size -= sz; pfn++; vaddr += sz; offset = 0; } } else if (dir == DMA_TO_DEVICE) { memcpy(vaddr, phys_to_virt(orig_addr), size); } else { memcpy(phys_to_virt(orig_addr), vaddr, size); } } phys_addr_t swiotlb_tbl_map_single(struct device *hwdev, dma_addr_t tbl_dma_addr, phys_addr_t orig_addr, size_t size, enum dma_data_direction dir) { unsigned long flags; phys_addr_t tlb_addr; unsigned int nslots, stride, index, wrap; int i; unsigned long mask; unsigned long offset_slots; unsigned long max_slots; if (no_iotlb_memory) panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer"); mask = dma_get_seg_boundary(hwdev); tbl_dma_addr &= mask; offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT; /* * Carefully handle integer overflow which can occur when mask == ~0UL. */ max_slots = mask + 1 ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT); /* * For mappings greater than a page, we limit the stride (and * hence alignment) to a page size. */ nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT; if (size > PAGE_SIZE) stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT)); else stride = 1; BUG_ON(!nslots); /* * Find suitable number of IO TLB entries size that will fit this * request and allocate a buffer from that IO TLB pool. */ spin_lock_irqsave(&io_tlb_lock, flags); index = ALIGN(io_tlb_index, stride); if (index >= io_tlb_nslabs) index = 0; wrap = index; do { while (iommu_is_span_boundary(index, nslots, offset_slots, max_slots)) { index += stride; if (index >= io_tlb_nslabs) index = 0; if (index == wrap) goto not_found; } /* * If we find a slot that indicates we have 'nslots' number of * contiguous buffers, we allocate the buffers from that slot * and mark the entries as '0' indicating unavailable. */ if (io_tlb_list[index] >= nslots) { int count = 0; for (i = index; i < (int) (index + nslots); i++) io_tlb_list[i] = 0; for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--) io_tlb_list[i] = ++count; tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT); /* * Update the indices to avoid searching in the next * round. */ io_tlb_index = ((index + nslots) < io_tlb_nslabs ? (index + nslots) : 0); goto found; } index += stride; if (index >= io_tlb_nslabs) index = 0; } while (index != wrap); not_found: spin_unlock_irqrestore(&io_tlb_lock, flags); if (printk_ratelimit()) dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size); return SWIOTLB_MAP_ERROR; found: spin_unlock_irqrestore(&io_tlb_lock, flags); /* * Save away the mapping from the original address to the DMA address. * This is needed when we sync the memory. Then we sync the buffer if * needed. */ for (i = 0; i < nslots; i++) io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT); if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL) swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE); return tlb_addr; } EXPORT_SYMBOL_GPL(swiotlb_tbl_map_single); /* * Allocates bounce buffer and returns its kernel virtual address. */ phys_addr_t map_single(struct device *hwdev, phys_addr_t phys, size_t size, enum dma_data_direction dir) { dma_addr_t start_dma_addr = phys_to_dma(hwdev, io_tlb_start); return swiotlb_tbl_map_single(hwdev, start_dma_addr, phys, size, dir); } /* * dma_addr is the kernel virtual address of the bounce buffer to unmap. */ void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr, size_t size, enum dma_data_direction dir) { unsigned long flags; int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT; int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT; phys_addr_t orig_addr = io_tlb_orig_addr[index]; /* * First, sync the memory before unmapping the entry */ if (orig_addr != INVALID_PHYS_ADDR && ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL))) swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE); /* * Return the buffer to the free list by setting the corresponding * entries to indicate the number of contiguous entries available. * While returning the entries to the free list, we merge the entries * with slots below and above the pool being returned. */ spin_lock_irqsave(&io_tlb_lock, flags); { count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ? io_tlb_list[index + nslots] : 0); /* * Step 1: return the slots to the free list, merging the * slots with superceeding slots */ for (i = index + nslots - 1; i >= index; i--) { io_tlb_list[i] = ++count; io_tlb_orig_addr[i] = INVALID_PHYS_ADDR; } /* * Step 2: merge the returned slots with the preceding slots, * if available (non zero) */ for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--) io_tlb_list[i] = ++count; } spin_unlock_irqrestore(&io_tlb_lock, flags); } EXPORT_SYMBOL_GPL(swiotlb_tbl_unmap_single); void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr, size_t size, enum dma_data_direction dir, enum dma_sync_target target) { int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT; phys_addr_t orig_addr = io_tlb_orig_addr[index]; if (orig_addr == INVALID_PHYS_ADDR) return; orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1); switch (target) { case SYNC_FOR_CPU: if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)) swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE); else BUG_ON(dir != DMA_TO_DEVICE); break; case SYNC_FOR_DEVICE: if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)) swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE); else BUG_ON(dir != DMA_FROM_DEVICE); break; default: BUG(); } } EXPORT_SYMBOL_GPL(swiotlb_tbl_sync_single); void * swiotlb_alloc_coherent(struct device *hwdev, size_t size, dma_addr_t *dma_handle, gfp_t flags) { dma_addr_t dev_addr; void *ret; int order = get_order(size); u64 dma_mask = DMA_BIT_MASK(32); if (hwdev && hwdev->coherent_dma_mask) dma_mask = hwdev->coherent_dma_mask; ret = (void *)__get_free_pages(flags, order); if (ret) { dev_addr = swiotlb_virt_to_bus(hwdev, ret); if (dev_addr + size - 1 > dma_mask) { /* * The allocated memory isn't reachable by the device. */ free_pages((unsigned long) ret, order); ret = NULL; } } if (!ret) { /* * We are either out of memory or the device can't DMA to * GFP_DMA memory; fall back on map_single(), which * will grab memory from the lowest available address range. */ phys_addr_t paddr = map_single(hwdev, 0, size, DMA_FROM_DEVICE); if (paddr == SWIOTLB_MAP_ERROR) return NULL; ret = phys_to_virt(paddr); dev_addr = phys_to_dma(hwdev, paddr); /* Confirm address can be DMA'd by device */ if (dev_addr + size - 1 > dma_mask) { printk("hwdev DMA mask = 0x%016Lx, dev_addr = 0x%016Lx\n", (unsigned long long)dma_mask, (unsigned long long)dev_addr); /* DMA_TO_DEVICE to avoid memcpy in unmap_single */ swiotlb_tbl_unmap_single(hwdev, paddr, size, DMA_TO_DEVICE); return NULL; } } *dma_handle = dev_addr; memset(ret, 0, size); return ret; } EXPORT_SYMBOL(swiotlb_alloc_coherent); void swiotlb_free_coherent(struct device *hwdev, size_t size, void *vaddr, dma_addr_t dev_addr) { phys_addr_t paddr = dma_to_phys(hwdev, dev_addr); WARN_ON(irqs_disabled()); if (!is_swiotlb_buffer(paddr)) free_pages((unsigned long)vaddr, get_order(size)); else /* DMA_TO_DEVICE to avoid memcpy in swiotlb_tbl_unmap_single */ swiotlb_tbl_unmap_single(hwdev, paddr, size, DMA_TO_DEVICE); } EXPORT_SYMBOL(swiotlb_free_coherent); static void swiotlb_full(struct device *dev, size_t size, enum dma_data_direction dir, int do_panic) { /* * Ran out of IOMMU space for this operation. This is very bad. * Unfortunately the drivers cannot handle this operation properly. * unless they check for dma_mapping_error (most don't) * When the mapping is small enough return a static buffer to limit * the damage, or panic when the transfer is too big. */ printk(KERN_ERR "DMA: Out of SW-IOMMU space for %zu bytes at " "device %s\n", size, dev ? dev_name(dev) : "?"); if (size <= io_tlb_overflow || !do_panic) return; if (dir == DMA_BIDIRECTIONAL) panic("DMA: Random memory could be DMA accessed\n"); if (dir == DMA_FROM_DEVICE) panic("DMA: Random memory could be DMA written\n"); if (dir == DMA_TO_DEVICE) panic("DMA: Random memory could be DMA read\n"); } /* * Map a single buffer of the indicated size for DMA in streaming mode. The * physical address to use is returned. * * Once the device is given the dma address, the device owns this memory until * either swiotlb_unmap_page or swiotlb_dma_sync_single is performed. */ dma_addr_t swiotlb_map_page(struct device *dev, struct page *page, unsigned long offset, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { phys_addr_t map, phys = page_to_phys(page) + offset; dma_addr_t dev_addr = phys_to_dma(dev, phys); BUG_ON(dir == DMA_NONE); /* * If the address happens to be in the device's DMA window, * we can safely return the device addr and not worry about bounce * buffering it. */ if (dma_capable(dev, dev_addr, size) && !swiotlb_force) return dev_addr; trace_swiotlb_bounced(dev, dev_addr, size, swiotlb_force); /* Oh well, have to allocate and map a bounce buffer. */ map = map_single(dev, phys, size, dir); if (map == SWIOTLB_MAP_ERROR) { swiotlb_full(dev, size, dir, 1); return phys_to_dma(dev, io_tlb_overflow_buffer); } dev_addr = phys_to_dma(dev, map); /* Ensure that the address returned is DMA'ble */ if (!dma_capable(dev, dev_addr, size)) { swiotlb_tbl_unmap_single(dev, map, size, dir); return phys_to_dma(dev, io_tlb_overflow_buffer); } return dev_addr; } EXPORT_SYMBOL_GPL(swiotlb_map_page); /* * Unmap a single streaming mode DMA translation. The dma_addr and size must * match what was provided for in a previous swiotlb_map_page call. All * other usages are undefined. * * After this call, reads by the cpu to the buffer are guaranteed to see * whatever the device wrote there. */ static void unmap_single(struct device *hwdev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { phys_addr_t paddr = dma_to_phys(hwdev, dev_addr); BUG_ON(dir == DMA_NONE); if (is_swiotlb_buffer(paddr)) { swiotlb_tbl_unmap_single(hwdev, paddr, size, dir); return; } if (dir != DMA_FROM_DEVICE) return; /* * phys_to_virt doesn't work with hihgmem page but we could * call dma_mark_clean() with hihgmem page here. However, we * are fine since dma_mark_clean() is null on POWERPC. We can * make dma_mark_clean() take a physical address if necessary. */ dma_mark_clean(phys_to_virt(paddr), size); } void swiotlb_unmap_page(struct device *hwdev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { unmap_single(hwdev, dev_addr, size, dir); } EXPORT_SYMBOL_GPL(swiotlb_unmap_page); /* * Make physical memory consistent for a single streaming mode DMA translation * after a transfer. * * If you perform a swiotlb_map_page() but wish to interrogate the buffer * using the cpu, yet do not wish to teardown the dma mapping, you must * call this function before doing so. At the next point you give the dma * address back to the card, you must first perform a * swiotlb_dma_sync_for_device, and then the device again owns the buffer */ static void swiotlb_sync_single(struct device *hwdev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir, enum dma_sync_target target) { phys_addr_t paddr = dma_to_phys(hwdev, dev_addr); BUG_ON(dir == DMA_NONE); if (is_swiotlb_buffer(paddr)) { swiotlb_tbl_sync_single(hwdev, paddr, size, dir, target); return; } if (dir != DMA_FROM_DEVICE) return; dma_mark_clean(phys_to_virt(paddr), size); } void swiotlb_sync_single_for_cpu(struct device *hwdev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_CPU); } EXPORT_SYMBOL(swiotlb_sync_single_for_cpu); void swiotlb_sync_single_for_device(struct device *hwdev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { swiotlb_sync_single(hwdev, dev_addr, size, dir, SYNC_FOR_DEVICE); } EXPORT_SYMBOL(swiotlb_sync_single_for_device); /* * Map a set of buffers described by scatterlist in streaming mode for DMA. * This is the scatter-gather version of the above swiotlb_map_page * interface. Here the scatter gather list elements are each tagged with the * appropriate dma address and length. They are obtained via * sg_dma_{address,length}(SG). * * NOTE: An implementation may be able to use a smaller number of * DMA address/length pairs than there are SG table elements. * (for example via virtual mapping capabilities) * The routine returns the number of addr/length pairs actually * used, at most nents. * * Device ownership issues as mentioned above for swiotlb_map_page are the * same here. */ int swiotlb_map_sg_attrs(struct device *hwdev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, struct dma_attrs *attrs) { struct scatterlist *sg; int i; BUG_ON(dir == DMA_NONE); for_each_sg(sgl, sg, nelems, i) { phys_addr_t paddr = sg_phys(sg); dma_addr_t dev_addr = phys_to_dma(hwdev, paddr); if (swiotlb_force || !dma_capable(hwdev, dev_addr, sg->length)) { phys_addr_t map = map_single(hwdev, sg_phys(sg), sg->length, dir); if (map == SWIOTLB_MAP_ERROR) { /* Don't panic here, we expect map_sg users to do proper error handling. */ swiotlb_full(hwdev, sg->length, dir, 0); swiotlb_unmap_sg_attrs(hwdev, sgl, i, dir, attrs); sg_dma_len(sgl) = 0; return 0; } sg->dma_address = phys_to_dma(hwdev, map); } else sg->dma_address = dev_addr; sg_dma_len(sg) = sg->length; } return nelems; } EXPORT_SYMBOL(swiotlb_map_sg_attrs); int swiotlb_map_sg(struct device *hwdev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir) { return swiotlb_map_sg_attrs(hwdev, sgl, nelems, dir, NULL); } EXPORT_SYMBOL(swiotlb_map_sg); /* * Unmap a set of streaming mode DMA translations. Again, cpu read rules * concerning calls here are the same as for swiotlb_unmap_page() above. */ void swiotlb_unmap_sg_attrs(struct device *hwdev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, struct dma_attrs *attrs) { struct scatterlist *sg; int i; BUG_ON(dir == DMA_NONE); for_each_sg(sgl, sg, nelems, i) unmap_single(hwdev, sg->dma_address, sg_dma_len(sg), dir); } EXPORT_SYMBOL(swiotlb_unmap_sg_attrs); void swiotlb_unmap_sg(struct device *hwdev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir) { return swiotlb_unmap_sg_attrs(hwdev, sgl, nelems, dir, NULL); } EXPORT_SYMBOL(swiotlb_unmap_sg); /* * Make physical memory consistent for a set of streaming mode DMA translations * after a transfer. * * The same as swiotlb_sync_single_* but for a scatter-gather list, same rules * and usage. */ static void swiotlb_sync_sg(struct device *hwdev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, enum dma_sync_target target) { struct scatterlist *sg; int i; for_each_sg(sgl, sg, nelems, i) swiotlb_sync_single(hwdev, sg->dma_address, sg_dma_len(sg), dir, target); } void swiotlb_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg, int nelems, enum dma_data_direction dir) { swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_CPU); } EXPORT_SYMBOL(swiotlb_sync_sg_for_cpu); void swiotlb_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg, int nelems, enum dma_data_direction dir) { swiotlb_sync_sg(hwdev, sg, nelems, dir, SYNC_FOR_DEVICE); } EXPORT_SYMBOL(swiotlb_sync_sg_for_device); int swiotlb_dma_mapping_error(struct device *hwdev, dma_addr_t dma_addr) { return (dma_addr == phys_to_dma(hwdev, io_tlb_overflow_buffer)); } EXPORT_SYMBOL(swiotlb_dma_mapping_error); /* * Return whether the given device DMA address mask can be supported * properly. For example, if your device can only drive the low 24-bits * during bus mastering, then you would pass 0x00ffffff as the mask to * this function. */ int swiotlb_dma_supported(struct device *hwdev, u64 mask) { return phys_to_dma(hwdev, io_tlb_end - 1) <= mask; } EXPORT_SYMBOL(swiotlb_dma_supported);
gpl-2.0
dangu/linux
arch/xtensa/mm/highmem.c
1223
2345
/* * High memory support for Xtensa architecture * * 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) 2014 Cadence Design Systems Inc. */ #include <linux/export.h> #include <linux/highmem.h> #include <asm/tlbflush.h> static pte_t *kmap_pte; #if DCACHE_WAY_SIZE > PAGE_SIZE unsigned int last_pkmap_nr_arr[DCACHE_N_COLORS]; wait_queue_head_t pkmap_map_wait_arr[DCACHE_N_COLORS]; static void __init kmap_waitqueues_init(void) { unsigned int i; for (i = 0; i < ARRAY_SIZE(pkmap_map_wait_arr); ++i) init_waitqueue_head(pkmap_map_wait_arr + i); } #else static inline void kmap_waitqueues_init(void) { } #endif static inline enum fixed_addresses kmap_idx(int type, unsigned long color) { return (type + KM_TYPE_NR * smp_processor_id()) * DCACHE_N_COLORS + color; } void *kmap_atomic(struct page *page) { enum fixed_addresses idx; unsigned long vaddr; preempt_disable(); pagefault_disable(); if (!PageHighMem(page)) return page_address(page); idx = kmap_idx(kmap_atomic_idx_push(), DCACHE_ALIAS(page_to_phys(page))); vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx); #ifdef CONFIG_DEBUG_HIGHMEM BUG_ON(!pte_none(*(kmap_pte + idx))); #endif set_pte(kmap_pte + idx, mk_pte(page, PAGE_KERNEL_EXEC)); return (void *)vaddr; } EXPORT_SYMBOL(kmap_atomic); void __kunmap_atomic(void *kvaddr) { if (kvaddr >= (void *)FIXADDR_START && kvaddr < (void *)FIXADDR_TOP) { int idx = kmap_idx(kmap_atomic_idx(), DCACHE_ALIAS((unsigned long)kvaddr)); /* * Force other mappings to Oops if they'll try to access this * pte without first remap it. Keeping stale mappings around * is a bad idea also, in case the page changes cacheability * attributes or becomes a protected page in a hypervisor. */ pte_clear(&init_mm, kvaddr, kmap_pte + idx); local_flush_tlb_kernel_range((unsigned long)kvaddr, (unsigned long)kvaddr + PAGE_SIZE); kmap_atomic_idx_pop(); } pagefault_enable(); preempt_enable(); } EXPORT_SYMBOL(__kunmap_atomic); void __init kmap_init(void) { unsigned long kmap_vstart; /* cache the first kmap pte */ kmap_vstart = __fix_to_virt(FIX_KMAP_BEGIN); kmap_pte = kmap_get_fixmap_pte(kmap_vstart); kmap_waitqueues_init(); }
gpl-2.0
badscimmia/RK
sound/soc/codecs/wm9713.c
2247
42310
/* * wm9713.c -- ALSA Soc WM9713 codec support * * Copyright 2006-10 Wolfson Microelectronics PLC. * Author: Liam Girdwood <lrg@slimlogic.co.uk> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * Features:- * * o Support for AC97 Codec, Voice DAC and Aux DAC * o Support for DAPM */ #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/ac97_codec.h> #include <sound/initval.h> #include <sound/pcm_params.h> #include <sound/tlv.h> #include <sound/soc.h> #include "wm9713.h" struct wm9713_priv { u32 pll_in; /* PLL input frequency */ }; static unsigned int ac97_read(struct snd_soc_codec *codec, unsigned int reg); static int ac97_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int val); /* * WM9713 register cache * Reg 0x3c bit 15 is used by touch driver. */ static const u16 wm9713_reg[] = { 0x6174, 0x8080, 0x8080, 0x8080, 0xc880, 0xe808, 0xe808, 0x0808, 0x00da, 0x8000, 0xd600, 0xaaa0, 0xaaa0, 0xaaa0, 0x0000, 0x0000, 0x0f0f, 0x0040, 0x0000, 0x7f00, 0x0405, 0x0410, 0xbb80, 0xbb80, 0x0000, 0xbb80, 0x0000, 0x4523, 0x0000, 0x2000, 0x7eff, 0xffff, 0x0000, 0x0000, 0x0080, 0x0000, 0x0000, 0x0000, 0xfffe, 0xffff, 0x0000, 0x0000, 0x0000, 0xfffe, 0x4000, 0x0000, 0x0000, 0x0000, 0xb032, 0x3e00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0006, 0x0001, 0x0000, 0x574d, 0x4c13, 0x0000, 0x0000, 0x0000 }; /* virtual HP mixers regs */ #define HPL_MIXER 0x80 #define HPR_MIXER 0x82 #define MICB_MUX 0x82 static const char *wm9713_mic_mixer[] = {"Stereo", "Mic 1", "Mic 2", "Mute"}; static const char *wm9713_rec_mux[] = {"Stereo", "Left", "Right", "Mute"}; static const char *wm9713_rec_src[] = {"Mic 1", "Mic 2", "Line", "Mono In", "Headphone", "Speaker", "Mono Out", "Zh"}; static const char *wm9713_rec_gain[] = {"+1.5dB Steps", "+0.75dB Steps"}; static const char *wm9713_alc_select[] = {"None", "Left", "Right", "Stereo"}; static const char *wm9713_mono_pga[] = {"Vmid", "Zh", "Mono", "Inv", "Mono Vmid", "Inv Vmid"}; static const char *wm9713_spk_pga[] = {"Vmid", "Zh", "Headphone", "Speaker", "Inv", "Headphone Vmid", "Speaker Vmid", "Inv Vmid"}; static const char *wm9713_hp_pga[] = {"Vmid", "Zh", "Headphone", "Headphone Vmid"}; static const char *wm9713_out3_pga[] = {"Vmid", "Zh", "Inv 1", "Inv 1 Vmid"}; static const char *wm9713_out4_pga[] = {"Vmid", "Zh", "Inv 2", "Inv 2 Vmid"}; static const char *wm9713_dac_inv[] = {"Off", "Mono", "Speaker", "Left Headphone", "Right Headphone", "Headphone Mono", "NC", "Vmid"}; static const char *wm9713_bass[] = {"Linear Control", "Adaptive Boost"}; static const char *wm9713_ng_type[] = {"Constant Gain", "Mute"}; static const char *wm9713_mic_select[] = {"Mic 1", "Mic 2 A", "Mic 2 B"}; static const char *wm9713_micb_select[] = {"MPB", "MPA"}; static const struct soc_enum wm9713_enum[] = { SOC_ENUM_SINGLE(AC97_LINE, 3, 4, wm9713_mic_mixer), /* record mic mixer 0 */ SOC_ENUM_SINGLE(AC97_VIDEO, 14, 4, wm9713_rec_mux), /* record mux hp 1 */ SOC_ENUM_SINGLE(AC97_VIDEO, 9, 4, wm9713_rec_mux), /* record mux mono 2 */ SOC_ENUM_SINGLE(AC97_VIDEO, 3, 8, wm9713_rec_src), /* record mux left 3 */ SOC_ENUM_SINGLE(AC97_VIDEO, 0, 8, wm9713_rec_src), /* record mux right 4*/ SOC_ENUM_DOUBLE(AC97_CD, 14, 6, 2, wm9713_rec_gain), /* record step size 5 */ SOC_ENUM_SINGLE(AC97_PCI_SVID, 14, 4, wm9713_alc_select), /* alc source select 6*/ SOC_ENUM_SINGLE(AC97_REC_GAIN, 14, 4, wm9713_mono_pga), /* mono input select 7 */ SOC_ENUM_SINGLE(AC97_REC_GAIN, 11, 8, wm9713_spk_pga), /* speaker left input select 8 */ SOC_ENUM_SINGLE(AC97_REC_GAIN, 8, 8, wm9713_spk_pga), /* speaker right input select 9 */ SOC_ENUM_SINGLE(AC97_REC_GAIN, 6, 3, wm9713_hp_pga), /* headphone left input 10 */ SOC_ENUM_SINGLE(AC97_REC_GAIN, 4, 3, wm9713_hp_pga), /* headphone right input 11 */ SOC_ENUM_SINGLE(AC97_REC_GAIN, 2, 4, wm9713_out3_pga), /* out 3 source 12 */ SOC_ENUM_SINGLE(AC97_REC_GAIN, 0, 4, wm9713_out4_pga), /* out 4 source 13 */ SOC_ENUM_SINGLE(AC97_REC_GAIN_MIC, 13, 8, wm9713_dac_inv), /* dac invert 1 14 */ SOC_ENUM_SINGLE(AC97_REC_GAIN_MIC, 10, 8, wm9713_dac_inv), /* dac invert 2 15 */ SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 15, 2, wm9713_bass), /* bass control 16 */ SOC_ENUM_SINGLE(AC97_PCI_SVID, 5, 2, wm9713_ng_type), /* noise gate type 17 */ SOC_ENUM_SINGLE(AC97_3D_CONTROL, 12, 3, wm9713_mic_select), /* mic selection 18 */ SOC_ENUM_SINGLE(MICB_MUX, 0, 2, wm9713_micb_select), /* mic selection 19 */ }; static const DECLARE_TLV_DB_SCALE(out_tlv, -4650, 150, 0); static const DECLARE_TLV_DB_SCALE(main_tlv, -3450, 150, 0); static const DECLARE_TLV_DB_SCALE(misc_tlv, -1500, 300, 0); static unsigned int mic_tlv[] = { TLV_DB_RANGE_HEAD(2), 0, 2, TLV_DB_SCALE_ITEM(1200, 600, 0), 3, 3, TLV_DB_SCALE_ITEM(3000, 0, 0), }; static const struct snd_kcontrol_new wm9713_snd_ac97_controls[] = { SOC_DOUBLE_TLV("Speaker Playback Volume", AC97_MASTER, 8, 0, 31, 1, out_tlv), SOC_DOUBLE("Speaker Playback Switch", AC97_MASTER, 15, 7, 1, 1), SOC_DOUBLE_TLV("Headphone Playback Volume", AC97_HEADPHONE, 8, 0, 31, 1, out_tlv), SOC_DOUBLE("Headphone Playback Switch", AC97_HEADPHONE, 15, 7, 1, 1), SOC_DOUBLE_TLV("Line In Volume", AC97_PC_BEEP, 8, 0, 31, 1, main_tlv), SOC_DOUBLE_TLV("PCM Playback Volume", AC97_PHONE, 8, 0, 31, 1, main_tlv), SOC_SINGLE_TLV("Mic 1 Volume", AC97_MIC, 8, 31, 1, main_tlv), SOC_SINGLE_TLV("Mic 2 Volume", AC97_MIC, 0, 31, 1, main_tlv), SOC_SINGLE_TLV("Mic 1 Preamp Volume", AC97_3D_CONTROL, 10, 3, 0, mic_tlv), SOC_SINGLE_TLV("Mic 2 Preamp Volume", AC97_3D_CONTROL, 12, 3, 0, mic_tlv), SOC_SINGLE("Mic Boost (+20dB) Switch", AC97_LINE, 5, 1, 0), SOC_SINGLE("Mic Headphone Mixer Volume", AC97_LINE, 0, 7, 1), SOC_SINGLE("Capture Switch", AC97_CD, 15, 1, 1), SOC_ENUM("Capture Volume Steps", wm9713_enum[5]), SOC_DOUBLE("Capture Volume", AC97_CD, 8, 0, 31, 0), SOC_SINGLE("Capture ZC Switch", AC97_CD, 7, 1, 0), SOC_SINGLE_TLV("Capture to Headphone Volume", AC97_VIDEO, 11, 7, 1, misc_tlv), SOC_SINGLE("Capture to Mono Boost (+20dB) Switch", AC97_VIDEO, 8, 1, 0), SOC_SINGLE("Capture ADC Boost (+20dB) Switch", AC97_VIDEO, 6, 1, 0), SOC_SINGLE("ALC Target Volume", AC97_CODEC_CLASS_REV, 12, 15, 0), SOC_SINGLE("ALC Hold Time", AC97_CODEC_CLASS_REV, 8, 15, 0), SOC_SINGLE("ALC Decay Time", AC97_CODEC_CLASS_REV, 4, 15, 0), SOC_SINGLE("ALC Attack Time", AC97_CODEC_CLASS_REV, 0, 15, 0), SOC_ENUM("ALC Function", wm9713_enum[6]), SOC_SINGLE("ALC Max Volume", AC97_PCI_SVID, 11, 7, 0), SOC_SINGLE("ALC ZC Timeout", AC97_PCI_SVID, 9, 3, 0), SOC_SINGLE("ALC ZC Switch", AC97_PCI_SVID, 8, 1, 0), SOC_SINGLE("ALC NG Switch", AC97_PCI_SVID, 7, 1, 0), SOC_ENUM("ALC NG Type", wm9713_enum[17]), SOC_SINGLE("ALC NG Threshold", AC97_PCI_SVID, 0, 31, 0), SOC_DOUBLE("Speaker Playback ZC Switch", AC97_MASTER, 14, 6, 1, 0), SOC_DOUBLE("Headphone Playback ZC Switch", AC97_HEADPHONE, 14, 6, 1, 0), SOC_SINGLE("Out4 Playback Switch", AC97_MASTER_MONO, 15, 1, 1), SOC_SINGLE("Out4 Playback ZC Switch", AC97_MASTER_MONO, 14, 1, 0), SOC_SINGLE_TLV("Out4 Playback Volume", AC97_MASTER_MONO, 8, 31, 1, out_tlv), SOC_SINGLE("Out3 Playback Switch", AC97_MASTER_MONO, 7, 1, 1), SOC_SINGLE("Out3 Playback ZC Switch", AC97_MASTER_MONO, 6, 1, 0), SOC_SINGLE_TLV("Out3 Playback Volume", AC97_MASTER_MONO, 0, 31, 1, out_tlv), SOC_SINGLE_TLV("Mono Capture Volume", AC97_MASTER_TONE, 8, 31, 1, main_tlv), SOC_SINGLE("Mono Playback Switch", AC97_MASTER_TONE, 7, 1, 1), SOC_SINGLE("Mono Playback ZC Switch", AC97_MASTER_TONE, 6, 1, 0), SOC_SINGLE_TLV("Mono Playback Volume", AC97_MASTER_TONE, 0, 31, 1, out_tlv), SOC_SINGLE_TLV("Headphone Mixer Beep Playback Volume", AC97_AUX, 12, 7, 1, misc_tlv), SOC_SINGLE_TLV("Speaker Mixer Beep Playback Volume", AC97_AUX, 8, 7, 1, misc_tlv), SOC_SINGLE_TLV("Mono Mixer Beep Playback Volume", AC97_AUX, 4, 7, 1, misc_tlv), SOC_SINGLE_TLV("Voice Playback Headphone Volume", AC97_PCM, 12, 7, 1, misc_tlv), SOC_SINGLE("Voice Playback Master Volume", AC97_PCM, 8, 7, 1), SOC_SINGLE("Voice Playback Mono Volume", AC97_PCM, 4, 7, 1), SOC_SINGLE_TLV("Headphone Mixer Aux Playback Volume", AC97_REC_SEL, 12, 7, 1, misc_tlv), SOC_SINGLE_TLV("Speaker Mixer Voice Playback Volume", AC97_PCM, 8, 7, 1, misc_tlv), SOC_SINGLE_TLV("Speaker Mixer Aux Playback Volume", AC97_REC_SEL, 8, 7, 1, misc_tlv), SOC_SINGLE_TLV("Mono Mixer Voice Playback Volume", AC97_PCM, 4, 7, 1, misc_tlv), SOC_SINGLE_TLV("Mono Mixer Aux Playback Volume", AC97_REC_SEL, 4, 7, 1, misc_tlv), SOC_SINGLE("Aux Playback Headphone Volume", AC97_REC_SEL, 12, 7, 1), SOC_SINGLE("Aux Playback Master Volume", AC97_REC_SEL, 8, 7, 1), SOC_ENUM("Bass Control", wm9713_enum[16]), SOC_SINGLE("Bass Cut-off Switch", AC97_GENERAL_PURPOSE, 12, 1, 1), SOC_SINGLE("Tone Cut-off Switch", AC97_GENERAL_PURPOSE, 4, 1, 1), SOC_SINGLE("Playback Attenuate (-6dB) Switch", AC97_GENERAL_PURPOSE, 6, 1, 0), SOC_SINGLE("Bass Volume", AC97_GENERAL_PURPOSE, 8, 15, 1), SOC_SINGLE("Tone Volume", AC97_GENERAL_PURPOSE, 0, 15, 1), SOC_SINGLE("3D Upper Cut-off Switch", AC97_REC_GAIN_MIC, 5, 1, 0), SOC_SINGLE("3D Lower Cut-off Switch", AC97_REC_GAIN_MIC, 4, 1, 0), SOC_SINGLE("3D Depth", AC97_REC_GAIN_MIC, 0, 15, 1), }; static int wm9713_voice_shutdown(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; u16 status, rate; BUG_ON(event != SND_SOC_DAPM_PRE_PMD); /* Gracefully shut down the voice interface. */ status = ac97_read(codec, AC97_EXTENDED_MID) | 0x1000; rate = ac97_read(codec, AC97_HANDSET_RATE) & 0xF0FF; ac97_write(codec, AC97_HANDSET_RATE, rate | 0x0200); schedule_timeout_interruptible(msecs_to_jiffies(1)); ac97_write(codec, AC97_HANDSET_RATE, rate | 0x0F00); ac97_write(codec, AC97_EXTENDED_MID, status); return 0; } /* We have to create a fake left and right HP mixers because * the codec only has a single control that is shared by both channels. * This makes it impossible to determine the audio path using the current * register map, thus we add a new (virtual) register to help determine the * audio route within the device. */ static int mixer_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { u16 l, r, beep, tone, phone, rec, pcm, aux; l = ac97_read(w->codec, HPL_MIXER); r = ac97_read(w->codec, HPR_MIXER); beep = ac97_read(w->codec, AC97_PC_BEEP); tone = ac97_read(w->codec, AC97_MASTER_TONE); phone = ac97_read(w->codec, AC97_PHONE); rec = ac97_read(w->codec, AC97_REC_SEL); pcm = ac97_read(w->codec, AC97_PCM); aux = ac97_read(w->codec, AC97_AUX); if (event & SND_SOC_DAPM_PRE_REG) return 0; if ((l & 0x1) || (r & 0x1)) ac97_write(w->codec, AC97_PC_BEEP, beep & 0x7fff); else ac97_write(w->codec, AC97_PC_BEEP, beep | 0x8000); if ((l & 0x2) || (r & 0x2)) ac97_write(w->codec, AC97_MASTER_TONE, tone & 0x7fff); else ac97_write(w->codec, AC97_MASTER_TONE, tone | 0x8000); if ((l & 0x4) || (r & 0x4)) ac97_write(w->codec, AC97_PHONE, phone & 0x7fff); else ac97_write(w->codec, AC97_PHONE, phone | 0x8000); if ((l & 0x8) || (r & 0x8)) ac97_write(w->codec, AC97_REC_SEL, rec & 0x7fff); else ac97_write(w->codec, AC97_REC_SEL, rec | 0x8000); if ((l & 0x10) || (r & 0x10)) ac97_write(w->codec, AC97_PCM, pcm & 0x7fff); else ac97_write(w->codec, AC97_PCM, pcm | 0x8000); if ((l & 0x20) || (r & 0x20)) ac97_write(w->codec, AC97_AUX, aux & 0x7fff); else ac97_write(w->codec, AC97_AUX, aux | 0x8000); return 0; } /* Left Headphone Mixers */ static const struct snd_kcontrol_new wm9713_hpl_mixer_controls[] = { SOC_DAPM_SINGLE("Beep Playback Switch", HPL_MIXER, 5, 1, 0), SOC_DAPM_SINGLE("Voice Playback Switch", HPL_MIXER, 4, 1, 0), SOC_DAPM_SINGLE("Aux Playback Switch", HPL_MIXER, 3, 1, 0), SOC_DAPM_SINGLE("PCM Playback Switch", HPL_MIXER, 2, 1, 0), SOC_DAPM_SINGLE("MonoIn Playback Switch", HPL_MIXER, 1, 1, 0), SOC_DAPM_SINGLE("Bypass Playback Switch", HPL_MIXER, 0, 1, 0), }; /* Right Headphone Mixers */ static const struct snd_kcontrol_new wm9713_hpr_mixer_controls[] = { SOC_DAPM_SINGLE("Beep Playback Switch", HPR_MIXER, 5, 1, 0), SOC_DAPM_SINGLE("Voice Playback Switch", HPR_MIXER, 4, 1, 0), SOC_DAPM_SINGLE("Aux Playback Switch", HPR_MIXER, 3, 1, 0), SOC_DAPM_SINGLE("PCM Playback Switch", HPR_MIXER, 2, 1, 0), SOC_DAPM_SINGLE("MonoIn Playback Switch", HPR_MIXER, 1, 1, 0), SOC_DAPM_SINGLE("Bypass Playback Switch", HPR_MIXER, 0, 1, 0), }; /* headphone capture mux */ static const struct snd_kcontrol_new wm9713_hp_rec_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[1]); /* headphone mic mux */ static const struct snd_kcontrol_new wm9713_hp_mic_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[0]); /* Speaker Mixer */ static const struct snd_kcontrol_new wm9713_speaker_mixer_controls[] = { SOC_DAPM_SINGLE("Beep Playback Switch", AC97_AUX, 11, 1, 1), SOC_DAPM_SINGLE("Voice Playback Switch", AC97_PCM, 11, 1, 1), SOC_DAPM_SINGLE("Aux Playback Switch", AC97_REC_SEL, 11, 1, 1), SOC_DAPM_SINGLE("PCM Playback Switch", AC97_PHONE, 14, 1, 1), SOC_DAPM_SINGLE("MonoIn Playback Switch", AC97_MASTER_TONE, 14, 1, 1), SOC_DAPM_SINGLE("Bypass Playback Switch", AC97_PC_BEEP, 14, 1, 1), }; /* Mono Mixer */ static const struct snd_kcontrol_new wm9713_mono_mixer_controls[] = { SOC_DAPM_SINGLE("Beep Playback Switch", AC97_AUX, 7, 1, 1), SOC_DAPM_SINGLE("Voice Playback Switch", AC97_PCM, 7, 1, 1), SOC_DAPM_SINGLE("Aux Playback Switch", AC97_REC_SEL, 7, 1, 1), SOC_DAPM_SINGLE("PCM Playback Switch", AC97_PHONE, 13, 1, 1), SOC_DAPM_SINGLE("MonoIn Playback Switch", AC97_MASTER_TONE, 13, 1, 1), SOC_DAPM_SINGLE("Bypass Playback Switch", AC97_PC_BEEP, 13, 1, 1), SOC_DAPM_SINGLE("Mic 1 Sidetone Switch", AC97_LINE, 7, 1, 1), SOC_DAPM_SINGLE("Mic 2 Sidetone Switch", AC97_LINE, 6, 1, 1), }; /* mono mic mux */ static const struct snd_kcontrol_new wm9713_mono_mic_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[2]); /* mono output mux */ static const struct snd_kcontrol_new wm9713_mono_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[7]); /* speaker left output mux */ static const struct snd_kcontrol_new wm9713_hp_spkl_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[8]); /* speaker right output mux */ static const struct snd_kcontrol_new wm9713_hp_spkr_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[9]); /* headphone left output mux */ static const struct snd_kcontrol_new wm9713_hpl_out_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[10]); /* headphone right output mux */ static const struct snd_kcontrol_new wm9713_hpr_out_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[11]); /* Out3 mux */ static const struct snd_kcontrol_new wm9713_out3_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[12]); /* Out4 mux */ static const struct snd_kcontrol_new wm9713_out4_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[13]); /* DAC inv mux 1 */ static const struct snd_kcontrol_new wm9713_dac_inv1_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[14]); /* DAC inv mux 2 */ static const struct snd_kcontrol_new wm9713_dac_inv2_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[15]); /* Capture source left */ static const struct snd_kcontrol_new wm9713_rec_srcl_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[3]); /* Capture source right */ static const struct snd_kcontrol_new wm9713_rec_srcr_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[4]); /* mic source */ static const struct snd_kcontrol_new wm9713_mic_sel_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[18]); /* mic source B virtual control */ static const struct snd_kcontrol_new wm9713_micb_sel_mux_controls = SOC_DAPM_ENUM("Route", wm9713_enum[19]); static const struct snd_soc_dapm_widget wm9713_dapm_widgets[] = { SND_SOC_DAPM_MUX("Capture Headphone Mux", SND_SOC_NOPM, 0, 0, &wm9713_hp_rec_mux_controls), SND_SOC_DAPM_MUX("Sidetone Mux", SND_SOC_NOPM, 0, 0, &wm9713_hp_mic_mux_controls), SND_SOC_DAPM_MUX("Capture Mono Mux", SND_SOC_NOPM, 0, 0, &wm9713_mono_mic_mux_controls), SND_SOC_DAPM_MUX("Mono Out Mux", SND_SOC_NOPM, 0, 0, &wm9713_mono_mux_controls), SND_SOC_DAPM_MUX("Left Speaker Out Mux", SND_SOC_NOPM, 0, 0, &wm9713_hp_spkl_mux_controls), SND_SOC_DAPM_MUX("Right Speaker Out Mux", SND_SOC_NOPM, 0, 0, &wm9713_hp_spkr_mux_controls), SND_SOC_DAPM_MUX("Left Headphone Out Mux", SND_SOC_NOPM, 0, 0, &wm9713_hpl_out_mux_controls), SND_SOC_DAPM_MUX("Right Headphone Out Mux", SND_SOC_NOPM, 0, 0, &wm9713_hpr_out_mux_controls), SND_SOC_DAPM_MUX("Out 3 Mux", SND_SOC_NOPM, 0, 0, &wm9713_out3_mux_controls), SND_SOC_DAPM_MUX("Out 4 Mux", SND_SOC_NOPM, 0, 0, &wm9713_out4_mux_controls), SND_SOC_DAPM_MUX("DAC Inv Mux 1", SND_SOC_NOPM, 0, 0, &wm9713_dac_inv1_mux_controls), SND_SOC_DAPM_MUX("DAC Inv Mux 2", SND_SOC_NOPM, 0, 0, &wm9713_dac_inv2_mux_controls), SND_SOC_DAPM_MUX("Left Capture Source", SND_SOC_NOPM, 0, 0, &wm9713_rec_srcl_mux_controls), SND_SOC_DAPM_MUX("Right Capture Source", SND_SOC_NOPM, 0, 0, &wm9713_rec_srcr_mux_controls), SND_SOC_DAPM_MUX("Mic A Source", SND_SOC_NOPM, 0, 0, &wm9713_mic_sel_mux_controls), SND_SOC_DAPM_MUX("Mic B Source", SND_SOC_NOPM, 0, 0, &wm9713_micb_sel_mux_controls), SND_SOC_DAPM_MIXER_E("Left HP Mixer", AC97_EXTENDED_MID, 3, 1, &wm9713_hpl_mixer_controls[0], ARRAY_SIZE(wm9713_hpl_mixer_controls), mixer_event, SND_SOC_DAPM_POST_REG), SND_SOC_DAPM_MIXER_E("Right HP Mixer", AC97_EXTENDED_MID, 2, 1, &wm9713_hpr_mixer_controls[0], ARRAY_SIZE(wm9713_hpr_mixer_controls), mixer_event, SND_SOC_DAPM_POST_REG), SND_SOC_DAPM_MIXER("Mono Mixer", AC97_EXTENDED_MID, 0, 1, &wm9713_mono_mixer_controls[0], ARRAY_SIZE(wm9713_mono_mixer_controls)), SND_SOC_DAPM_MIXER("Speaker Mixer", AC97_EXTENDED_MID, 1, 1, &wm9713_speaker_mixer_controls[0], ARRAY_SIZE(wm9713_speaker_mixer_controls)), SND_SOC_DAPM_DAC("Left DAC", "Left HiFi Playback", AC97_EXTENDED_MID, 7, 1), SND_SOC_DAPM_DAC("Right DAC", "Right HiFi Playback", AC97_EXTENDED_MID, 6, 1), SND_SOC_DAPM_MIXER("AC97 Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("HP Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("Line Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("Capture Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_DAC_E("Voice DAC", "Voice Playback", AC97_EXTENDED_MID, 12, 1, wm9713_voice_shutdown, SND_SOC_DAPM_PRE_PMD), SND_SOC_DAPM_DAC("Aux DAC", "Aux Playback", AC97_EXTENDED_MID, 11, 1), SND_SOC_DAPM_PGA("Left ADC", AC97_EXTENDED_MID, 5, 1, NULL, 0), SND_SOC_DAPM_PGA("Right ADC", AC97_EXTENDED_MID, 4, 1, NULL, 0), SND_SOC_DAPM_ADC("Left HiFi ADC", "Left HiFi Capture", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_ADC("Right HiFi ADC", "Right HiFi Capture", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_ADC("Left Voice ADC", "Left Voice Capture", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_ADC("Right Voice ADC", "Right Voice Capture", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_PGA("Left Headphone", AC97_EXTENDED_MSTATUS, 10, 1, NULL, 0), SND_SOC_DAPM_PGA("Right Headphone", AC97_EXTENDED_MSTATUS, 9, 1, NULL, 0), SND_SOC_DAPM_PGA("Left Speaker", AC97_EXTENDED_MSTATUS, 8, 1, NULL, 0), SND_SOC_DAPM_PGA("Right Speaker", AC97_EXTENDED_MSTATUS, 7, 1, NULL, 0), SND_SOC_DAPM_PGA("Out 3", AC97_EXTENDED_MSTATUS, 11, 1, NULL, 0), SND_SOC_DAPM_PGA("Out 4", AC97_EXTENDED_MSTATUS, 12, 1, NULL, 0), SND_SOC_DAPM_PGA("Mono Out", AC97_EXTENDED_MSTATUS, 13, 1, NULL, 0), SND_SOC_DAPM_PGA("Left Line In", AC97_EXTENDED_MSTATUS, 6, 1, NULL, 0), SND_SOC_DAPM_PGA("Right Line In", AC97_EXTENDED_MSTATUS, 5, 1, NULL, 0), SND_SOC_DAPM_PGA("Mono In", AC97_EXTENDED_MSTATUS, 4, 1, NULL, 0), SND_SOC_DAPM_PGA("Mic A PGA", AC97_EXTENDED_MSTATUS, 3, 1, NULL, 0), SND_SOC_DAPM_PGA("Mic B PGA", AC97_EXTENDED_MSTATUS, 2, 1, NULL, 0), SND_SOC_DAPM_PGA("Mic A Pre Amp", AC97_EXTENDED_MSTATUS, 1, 1, NULL, 0), SND_SOC_DAPM_PGA("Mic B Pre Amp", AC97_EXTENDED_MSTATUS, 0, 1, NULL, 0), SND_SOC_DAPM_MICBIAS("Mic Bias", AC97_EXTENDED_MSTATUS, 14, 1), SND_SOC_DAPM_OUTPUT("MONO"), SND_SOC_DAPM_OUTPUT("HPL"), SND_SOC_DAPM_OUTPUT("HPR"), SND_SOC_DAPM_OUTPUT("SPKL"), SND_SOC_DAPM_OUTPUT("SPKR"), SND_SOC_DAPM_OUTPUT("OUT3"), SND_SOC_DAPM_OUTPUT("OUT4"), SND_SOC_DAPM_INPUT("LINEL"), SND_SOC_DAPM_INPUT("LINER"), SND_SOC_DAPM_INPUT("MONOIN"), SND_SOC_DAPM_INPUT("PCBEEP"), SND_SOC_DAPM_INPUT("MIC1"), SND_SOC_DAPM_INPUT("MIC2A"), SND_SOC_DAPM_INPUT("MIC2B"), SND_SOC_DAPM_VMID("VMID"), }; static const struct snd_soc_dapm_route wm9713_audio_map[] = { /* left HP mixer */ {"Left HP Mixer", "Beep Playback Switch", "PCBEEP"}, {"Left HP Mixer", "Voice Playback Switch", "Voice DAC"}, {"Left HP Mixer", "Aux Playback Switch", "Aux DAC"}, {"Left HP Mixer", "Bypass Playback Switch", "Left Line In"}, {"Left HP Mixer", "PCM Playback Switch", "Left DAC"}, {"Left HP Mixer", "MonoIn Playback Switch", "Mono In"}, {"Left HP Mixer", NULL, "Capture Headphone Mux"}, /* right HP mixer */ {"Right HP Mixer", "Beep Playback Switch", "PCBEEP"}, {"Right HP Mixer", "Voice Playback Switch", "Voice DAC"}, {"Right HP Mixer", "Aux Playback Switch", "Aux DAC"}, {"Right HP Mixer", "Bypass Playback Switch", "Right Line In"}, {"Right HP Mixer", "PCM Playback Switch", "Right DAC"}, {"Right HP Mixer", "MonoIn Playback Switch", "Mono In"}, {"Right HP Mixer", NULL, "Capture Headphone Mux"}, /* virtual mixer - mixes left & right channels for spk and mono */ {"AC97 Mixer", NULL, "Left DAC"}, {"AC97 Mixer", NULL, "Right DAC"}, {"Line Mixer", NULL, "Right Line In"}, {"Line Mixer", NULL, "Left Line In"}, {"HP Mixer", NULL, "Left HP Mixer"}, {"HP Mixer", NULL, "Right HP Mixer"}, {"Capture Mixer", NULL, "Left Capture Source"}, {"Capture Mixer", NULL, "Right Capture Source"}, /* speaker mixer */ {"Speaker Mixer", "Beep Playback Switch", "PCBEEP"}, {"Speaker Mixer", "Voice Playback Switch", "Voice DAC"}, {"Speaker Mixer", "Aux Playback Switch", "Aux DAC"}, {"Speaker Mixer", "Bypass Playback Switch", "Line Mixer"}, {"Speaker Mixer", "PCM Playback Switch", "AC97 Mixer"}, {"Speaker Mixer", "MonoIn Playback Switch", "Mono In"}, /* mono mixer */ {"Mono Mixer", "Beep Playback Switch", "PCBEEP"}, {"Mono Mixer", "Voice Playback Switch", "Voice DAC"}, {"Mono Mixer", "Aux Playback Switch", "Aux DAC"}, {"Mono Mixer", "Bypass Playback Switch", "Line Mixer"}, {"Mono Mixer", "PCM Playback Switch", "AC97 Mixer"}, {"Mono Mixer", "Mic 1 Sidetone Switch", "Mic A PGA"}, {"Mono Mixer", "Mic 2 Sidetone Switch", "Mic B PGA"}, {"Mono Mixer", NULL, "Capture Mono Mux"}, /* DAC inv mux 1 */ {"DAC Inv Mux 1", "Mono", "Mono Mixer"}, {"DAC Inv Mux 1", "Speaker", "Speaker Mixer"}, {"DAC Inv Mux 1", "Left Headphone", "Left HP Mixer"}, {"DAC Inv Mux 1", "Right Headphone", "Right HP Mixer"}, {"DAC Inv Mux 1", "Headphone Mono", "HP Mixer"}, /* DAC inv mux 2 */ {"DAC Inv Mux 2", "Mono", "Mono Mixer"}, {"DAC Inv Mux 2", "Speaker", "Speaker Mixer"}, {"DAC Inv Mux 2", "Left Headphone", "Left HP Mixer"}, {"DAC Inv Mux 2", "Right Headphone", "Right HP Mixer"}, {"DAC Inv Mux 2", "Headphone Mono", "HP Mixer"}, /* headphone left mux */ {"Left Headphone Out Mux", "Headphone", "Left HP Mixer"}, /* headphone right mux */ {"Right Headphone Out Mux", "Headphone", "Right HP Mixer"}, /* speaker left mux */ {"Left Speaker Out Mux", "Headphone", "Left HP Mixer"}, {"Left Speaker Out Mux", "Speaker", "Speaker Mixer"}, {"Left Speaker Out Mux", "Inv", "DAC Inv Mux 1"}, /* speaker right mux */ {"Right Speaker Out Mux", "Headphone", "Right HP Mixer"}, {"Right Speaker Out Mux", "Speaker", "Speaker Mixer"}, {"Right Speaker Out Mux", "Inv", "DAC Inv Mux 2"}, /* mono mux */ {"Mono Out Mux", "Mono", "Mono Mixer"}, {"Mono Out Mux", "Inv", "DAC Inv Mux 1"}, /* out 3 mux */ {"Out 3 Mux", "Inv 1", "DAC Inv Mux 1"}, /* out 4 mux */ {"Out 4 Mux", "Inv 2", "DAC Inv Mux 2"}, /* output pga */ {"HPL", NULL, "Left Headphone"}, {"Left Headphone", NULL, "Left Headphone Out Mux"}, {"HPR", NULL, "Right Headphone"}, {"Right Headphone", NULL, "Right Headphone Out Mux"}, {"OUT3", NULL, "Out 3"}, {"Out 3", NULL, "Out 3 Mux"}, {"OUT4", NULL, "Out 4"}, {"Out 4", NULL, "Out 4 Mux"}, {"SPKL", NULL, "Left Speaker"}, {"Left Speaker", NULL, "Left Speaker Out Mux"}, {"SPKR", NULL, "Right Speaker"}, {"Right Speaker", NULL, "Right Speaker Out Mux"}, {"MONO", NULL, "Mono Out"}, {"Mono Out", NULL, "Mono Out Mux"}, /* input pga */ {"Left Line In", NULL, "LINEL"}, {"Right Line In", NULL, "LINER"}, {"Mono In", NULL, "MONOIN"}, {"Mic A PGA", NULL, "Mic A Pre Amp"}, {"Mic B PGA", NULL, "Mic B Pre Amp"}, /* left capture select */ {"Left Capture Source", "Mic 1", "Mic A Pre Amp"}, {"Left Capture Source", "Mic 2", "Mic B Pre Amp"}, {"Left Capture Source", "Line", "LINEL"}, {"Left Capture Source", "Mono In", "MONOIN"}, {"Left Capture Source", "Headphone", "Left HP Mixer"}, {"Left Capture Source", "Speaker", "Speaker Mixer"}, {"Left Capture Source", "Mono Out", "Mono Mixer"}, /* right capture select */ {"Right Capture Source", "Mic 1", "Mic A Pre Amp"}, {"Right Capture Source", "Mic 2", "Mic B Pre Amp"}, {"Right Capture Source", "Line", "LINER"}, {"Right Capture Source", "Mono In", "MONOIN"}, {"Right Capture Source", "Headphone", "Right HP Mixer"}, {"Right Capture Source", "Speaker", "Speaker Mixer"}, {"Right Capture Source", "Mono Out", "Mono Mixer"}, /* left ADC */ {"Left ADC", NULL, "Left Capture Source"}, {"Left Voice ADC", NULL, "Left ADC"}, {"Left HiFi ADC", NULL, "Left ADC"}, /* right ADC */ {"Right ADC", NULL, "Right Capture Source"}, {"Right Voice ADC", NULL, "Right ADC"}, {"Right HiFi ADC", NULL, "Right ADC"}, /* mic */ {"Mic A Pre Amp", NULL, "Mic A Source"}, {"Mic A Source", "Mic 1", "MIC1"}, {"Mic A Source", "Mic 2 A", "MIC2A"}, {"Mic A Source", "Mic 2 B", "Mic B Source"}, {"Mic B Pre Amp", "MPB", "Mic B Source"}, {"Mic B Source", NULL, "MIC2B"}, /* headphone capture */ {"Capture Headphone Mux", "Stereo", "Capture Mixer"}, {"Capture Headphone Mux", "Left", "Left Capture Source"}, {"Capture Headphone Mux", "Right", "Right Capture Source"}, /* mono capture */ {"Capture Mono Mux", "Stereo", "Capture Mixer"}, {"Capture Mono Mux", "Left", "Left Capture Source"}, {"Capture Mono Mux", "Right", "Right Capture Source"}, }; static unsigned int ac97_read(struct snd_soc_codec *codec, unsigned int reg) { u16 *cache = codec->reg_cache; if (reg == AC97_RESET || reg == AC97_GPIO_STATUS || reg == AC97_VENDOR_ID1 || reg == AC97_VENDOR_ID2 || reg == AC97_CD) return soc_ac97_ops.read(codec->ac97, reg); else { reg = reg >> 1; if (reg >= (ARRAY_SIZE(wm9713_reg))) return -EIO; return cache[reg]; } } static int ac97_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int val) { u16 *cache = codec->reg_cache; if (reg < 0x7c) soc_ac97_ops.write(codec->ac97, reg, val); reg = reg >> 1; if (reg < (ARRAY_SIZE(wm9713_reg))) cache[reg] = val; return 0; } /* PLL divisors */ struct _pll_div { u32 divsel:1; u32 divctl:1; u32 lf:1; u32 n:4; u32 k:24; }; /* The size in bits of the PLL divide multiplied by 10 * to allow rounding later */ #define FIXED_PLL_SIZE ((1 << 22) * 10) static void pll_factors(struct _pll_div *pll_div, unsigned int source) { u64 Kpart; unsigned int K, Ndiv, Nmod, target; /* The the PLL output is always 98.304MHz. */ target = 98304000; /* If the input frequency is over 14.4MHz then scale it down. */ if (source > 14400000) { source >>= 1; pll_div->divsel = 1; if (source > 14400000) { source >>= 1; pll_div->divctl = 1; } else pll_div->divctl = 0; } else { pll_div->divsel = 0; pll_div->divctl = 0; } /* Low frequency sources require an additional divide in the * loop. */ if (source < 8192000) { pll_div->lf = 1; target >>= 2; } else pll_div->lf = 0; Ndiv = target / source; if ((Ndiv < 5) || (Ndiv > 12)) printk(KERN_WARNING "WM9713 PLL N value %u out of recommended range!\n", Ndiv); pll_div->n = Ndiv; Nmod = target % source; Kpart = FIXED_PLL_SIZE * (long long)Nmod; do_div(Kpart, source); K = Kpart & 0xFFFFFFFF; /* Check if we need to round */ if ((K % 10) >= 5) K += 5; /* Move down to proper range now rounding is done */ K /= 10; pll_div->k = K; } /** * Please note that changing the PLL input frequency may require * resynchronisation with the AC97 controller. */ static int wm9713_set_pll(struct snd_soc_codec *codec, int pll_id, unsigned int freq_in, unsigned int freq_out) { struct wm9713_priv *wm9713 = snd_soc_codec_get_drvdata(codec); u16 reg, reg2; struct _pll_div pll_div; /* turn PLL off ? */ if (freq_in == 0) { /* disable PLL power and select ext source */ reg = ac97_read(codec, AC97_HANDSET_RATE); ac97_write(codec, AC97_HANDSET_RATE, reg | 0x0080); reg = ac97_read(codec, AC97_EXTENDED_MID); ac97_write(codec, AC97_EXTENDED_MID, reg | 0x0200); wm9713->pll_in = 0; return 0; } pll_factors(&pll_div, freq_in); if (pll_div.k == 0) { reg = (pll_div.n << 12) | (pll_div.lf << 11) | (pll_div.divsel << 9) | (pll_div.divctl << 8); ac97_write(codec, AC97_LINE1_LEVEL, reg); } else { /* write the fractional k to the reg 0x46 pages */ reg2 = (pll_div.n << 12) | (pll_div.lf << 11) | (1 << 10) | (pll_div.divsel << 9) | (pll_div.divctl << 8); /* K [21:20] */ reg = reg2 | (0x5 << 4) | (pll_div.k >> 20); ac97_write(codec, AC97_LINE1_LEVEL, reg); /* K [19:16] */ reg = reg2 | (0x4 << 4) | ((pll_div.k >> 16) & 0xf); ac97_write(codec, AC97_LINE1_LEVEL, reg); /* K [15:12] */ reg = reg2 | (0x3 << 4) | ((pll_div.k >> 12) & 0xf); ac97_write(codec, AC97_LINE1_LEVEL, reg); /* K [11:8] */ reg = reg2 | (0x2 << 4) | ((pll_div.k >> 8) & 0xf); ac97_write(codec, AC97_LINE1_LEVEL, reg); /* K [7:4] */ reg = reg2 | (0x1 << 4) | ((pll_div.k >> 4) & 0xf); ac97_write(codec, AC97_LINE1_LEVEL, reg); reg = reg2 | (0x0 << 4) | (pll_div.k & 0xf); /* K [3:0] */ ac97_write(codec, AC97_LINE1_LEVEL, reg); } /* turn PLL on and select as source */ reg = ac97_read(codec, AC97_EXTENDED_MID); ac97_write(codec, AC97_EXTENDED_MID, reg & 0xfdff); reg = ac97_read(codec, AC97_HANDSET_RATE); ac97_write(codec, AC97_HANDSET_RATE, reg & 0xff7f); wm9713->pll_in = freq_in; /* wait 10ms AC97 link frames for the link to stabilise */ schedule_timeout_interruptible(msecs_to_jiffies(10)); return 0; } static int wm9713_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id, int source, unsigned int freq_in, unsigned int freq_out) { struct snd_soc_codec *codec = codec_dai->codec; return wm9713_set_pll(codec, pll_id, freq_in, freq_out); } /* * Tristate the PCM DAI lines, tristate can be disabled by calling * wm9713_set_dai_fmt() */ static int wm9713_set_dai_tristate(struct snd_soc_dai *codec_dai, int tristate) { struct snd_soc_codec *codec = codec_dai->codec; u16 reg = ac97_read(codec, AC97_CENTER_LFE_MASTER) & 0x9fff; if (tristate) ac97_write(codec, AC97_CENTER_LFE_MASTER, reg); return 0; } /* * Configure WM9713 clock dividers. * Voice DAC needs 256 FS */ static int wm9713_set_dai_clkdiv(struct snd_soc_dai *codec_dai, int div_id, int div) { struct snd_soc_codec *codec = codec_dai->codec; u16 reg; switch (div_id) { case WM9713_PCMCLK_DIV: reg = ac97_read(codec, AC97_HANDSET_RATE) & 0xf0ff; ac97_write(codec, AC97_HANDSET_RATE, reg | div); break; case WM9713_CLKA_MULT: reg = ac97_read(codec, AC97_HANDSET_RATE) & 0xfffd; ac97_write(codec, AC97_HANDSET_RATE, reg | div); break; case WM9713_CLKB_MULT: reg = ac97_read(codec, AC97_HANDSET_RATE) & 0xfffb; ac97_write(codec, AC97_HANDSET_RATE, reg | div); break; case WM9713_HIFI_DIV: reg = ac97_read(codec, AC97_HANDSET_RATE) & 0x8fff; ac97_write(codec, AC97_HANDSET_RATE, reg | div); break; case WM9713_PCMBCLK_DIV: reg = ac97_read(codec, AC97_CENTER_LFE_MASTER) & 0xf1ff; ac97_write(codec, AC97_CENTER_LFE_MASTER, reg | div); break; case WM9713_PCMCLK_PLL_DIV: reg = ac97_read(codec, AC97_LINE1_LEVEL) & 0xff80; ac97_write(codec, AC97_LINE1_LEVEL, reg | 0x60 | div); break; case WM9713_HIFI_PLL_DIV: reg = ac97_read(codec, AC97_LINE1_LEVEL) & 0xff80; ac97_write(codec, AC97_LINE1_LEVEL, reg | 0x70 | div); break; default: return -EINVAL; } return 0; } static int wm9713_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; u16 gpio = ac97_read(codec, AC97_GPIO_CFG) & 0xffc5; u16 reg = 0x8000; /* clock masters */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: reg |= 0x4000; gpio |= 0x0010; break; case SND_SOC_DAIFMT_CBM_CFS: reg |= 0x6000; gpio |= 0x0018; break; case SND_SOC_DAIFMT_CBS_CFS: reg |= 0x2000; gpio |= 0x001a; break; case SND_SOC_DAIFMT_CBS_CFM: gpio |= 0x0012; break; } /* clock inversion */ switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_IB_IF: reg |= 0x00c0; break; case SND_SOC_DAIFMT_IB_NF: reg |= 0x0080; break; case SND_SOC_DAIFMT_NB_IF: reg |= 0x0040; break; } /* DAI format */ switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: reg |= 0x0002; break; case SND_SOC_DAIFMT_RIGHT_J: break; case SND_SOC_DAIFMT_LEFT_J: reg |= 0x0001; break; case SND_SOC_DAIFMT_DSP_A: reg |= 0x0003; break; case SND_SOC_DAIFMT_DSP_B: reg |= 0x0043; break; } ac97_write(codec, AC97_GPIO_CFG, gpio); ac97_write(codec, AC97_CENTER_LFE_MASTER, reg); return 0; } static int wm9713_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; u16 reg = ac97_read(codec, AC97_CENTER_LFE_MASTER) & 0xfff3; switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: break; case SNDRV_PCM_FORMAT_S20_3LE: reg |= 0x0004; break; case SNDRV_PCM_FORMAT_S24_LE: reg |= 0x0008; break; case SNDRV_PCM_FORMAT_S32_LE: reg |= 0x000c; break; } /* enable PCM interface in master mode */ ac97_write(codec, AC97_CENTER_LFE_MASTER, reg); return 0; } static int ac97_hifi_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct snd_pcm_runtime *runtime = substream->runtime; int reg; u16 vra; vra = ac97_read(codec, AC97_EXTENDED_STATUS); ac97_write(codec, AC97_EXTENDED_STATUS, vra | 0x1); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) reg = AC97_PCM_FRONT_DAC_RATE; else reg = AC97_PCM_LR_ADC_RATE; return ac97_write(codec, reg, runtime->rate); } static int ac97_aux_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct snd_pcm_runtime *runtime = substream->runtime; u16 vra, xsle; vra = ac97_read(codec, AC97_EXTENDED_STATUS); ac97_write(codec, AC97_EXTENDED_STATUS, vra | 0x1); xsle = ac97_read(codec, AC97_PCI_SID); ac97_write(codec, AC97_PCI_SID, xsle | 0x8000); if (substream->stream != SNDRV_PCM_STREAM_PLAYBACK) return -ENODEV; return ac97_write(codec, AC97_PCM_SURR_DAC_RATE, runtime->rate); } #define WM9713_RATES (SNDRV_PCM_RATE_8000 | \ SNDRV_PCM_RATE_11025 | \ SNDRV_PCM_RATE_22050 | \ SNDRV_PCM_RATE_44100 | \ SNDRV_PCM_RATE_48000) #define WM9713_PCM_RATES (SNDRV_PCM_RATE_8000 | \ SNDRV_PCM_RATE_11025 | \ SNDRV_PCM_RATE_16000 | \ SNDRV_PCM_RATE_22050 | \ SNDRV_PCM_RATE_44100 | \ SNDRV_PCM_RATE_48000) #define WM9713_PCM_FORMATS \ (SNDRV_PCM_FORMAT_S16_LE | SNDRV_PCM_FORMAT_S20_3LE | \ SNDRV_PCM_FORMAT_S24_LE) static const struct snd_soc_dai_ops wm9713_dai_ops_hifi = { .prepare = ac97_hifi_prepare, .set_clkdiv = wm9713_set_dai_clkdiv, .set_pll = wm9713_set_dai_pll, }; static const struct snd_soc_dai_ops wm9713_dai_ops_aux = { .prepare = ac97_aux_prepare, .set_clkdiv = wm9713_set_dai_clkdiv, .set_pll = wm9713_set_dai_pll, }; static const struct snd_soc_dai_ops wm9713_dai_ops_voice = { .hw_params = wm9713_pcm_hw_params, .set_clkdiv = wm9713_set_dai_clkdiv, .set_pll = wm9713_set_dai_pll, .set_fmt = wm9713_set_dai_fmt, .set_tristate = wm9713_set_dai_tristate, }; static struct snd_soc_dai_driver wm9713_dai[] = { { .name = "wm9713-hifi", .ac97_control = 1, .playback = { .stream_name = "HiFi Playback", .channels_min = 1, .channels_max = 2, .rates = WM9713_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .capture = { .stream_name = "HiFi Capture", .channels_min = 1, .channels_max = 2, .rates = WM9713_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .ops = &wm9713_dai_ops_hifi, }, { .name = "wm9713-aux", .playback = { .stream_name = "Aux Playback", .channels_min = 1, .channels_max = 1, .rates = WM9713_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .ops = &wm9713_dai_ops_aux, }, { .name = "wm9713-voice", .playback = { .stream_name = "Voice Playback", .channels_min = 1, .channels_max = 1, .rates = WM9713_PCM_RATES, .formats = WM9713_PCM_FORMATS,}, .capture = { .stream_name = "Voice Capture", .channels_min = 1, .channels_max = 2, .rates = WM9713_PCM_RATES, .formats = WM9713_PCM_FORMATS,}, .ops = &wm9713_dai_ops_voice, .symmetric_rates = 1, }, }; int wm9713_reset(struct snd_soc_codec *codec, int try_warm) { if (try_warm && soc_ac97_ops.warm_reset) { soc_ac97_ops.warm_reset(codec->ac97); if (ac97_read(codec, 0) == wm9713_reg[0]) return 1; } soc_ac97_ops.reset(codec->ac97); if (soc_ac97_ops.warm_reset) soc_ac97_ops.warm_reset(codec->ac97); if (ac97_read(codec, 0) != wm9713_reg[0]) return -EIO; return 0; } EXPORT_SYMBOL_GPL(wm9713_reset); static int wm9713_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { u16 reg; switch (level) { case SND_SOC_BIAS_ON: /* enable thermal shutdown */ reg = ac97_read(codec, AC97_EXTENDED_MID) & 0x1bff; ac97_write(codec, AC97_EXTENDED_MID, reg); break; case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: /* enable master bias and vmid */ reg = ac97_read(codec, AC97_EXTENDED_MID) & 0x3bff; ac97_write(codec, AC97_EXTENDED_MID, reg); ac97_write(codec, AC97_POWERDOWN, 0x0000); break; case SND_SOC_BIAS_OFF: /* disable everything including AC link */ ac97_write(codec, AC97_EXTENDED_MID, 0xffff); ac97_write(codec, AC97_EXTENDED_MSTATUS, 0xffff); ac97_write(codec, AC97_POWERDOWN, 0xffff); break; } codec->dapm.bias_level = level; return 0; } static int wm9713_soc_suspend(struct snd_soc_codec *codec) { u16 reg; /* Disable everything except touchpanel - that will be handled * by the touch driver and left disabled if touch is not in * use. */ reg = ac97_read(codec, AC97_EXTENDED_MID); ac97_write(codec, AC97_EXTENDED_MID, reg | 0x7fff); ac97_write(codec, AC97_EXTENDED_MSTATUS, 0xffff); ac97_write(codec, AC97_POWERDOWN, 0x6f00); ac97_write(codec, AC97_POWERDOWN, 0xffff); return 0; } static int wm9713_soc_resume(struct snd_soc_codec *codec) { struct wm9713_priv *wm9713 = snd_soc_codec_get_drvdata(codec); int i, ret; u16 *cache = codec->reg_cache; ret = wm9713_reset(codec, 1); if (ret < 0) { printk(KERN_ERR "could not reset AC97 codec\n"); return ret; } wm9713_set_bias_level(codec, SND_SOC_BIAS_STANDBY); /* do we need to re-start the PLL ? */ if (wm9713->pll_in) wm9713_set_pll(codec, 0, wm9713->pll_in, 0); /* only synchronise the codec if warm reset failed */ if (ret == 0) { for (i = 2; i < ARRAY_SIZE(wm9713_reg) << 1; i += 2) { if (i == AC97_POWERDOWN || i == AC97_EXTENDED_MID || i == AC97_EXTENDED_MSTATUS || i > 0x66) continue; soc_ac97_ops.write(codec->ac97, i, cache[i>>1]); } } return ret; } static int wm9713_soc_probe(struct snd_soc_codec *codec) { struct wm9713_priv *wm9713; int ret = 0, reg; wm9713 = kzalloc(sizeof(struct wm9713_priv), GFP_KERNEL); if (wm9713 == NULL) return -ENOMEM; snd_soc_codec_set_drvdata(codec, wm9713); ret = snd_soc_new_ac97_codec(codec, &soc_ac97_ops, 0); if (ret < 0) goto codec_err; /* do a cold reset for the controller and then try * a warm reset followed by an optional cold reset for codec */ wm9713_reset(codec, 0); ret = wm9713_reset(codec, 1); if (ret < 0) { printk(KERN_ERR "Failed to reset WM9713: AC97 link error\n"); goto reset_err; } wm9713_set_bias_level(codec, SND_SOC_BIAS_STANDBY); /* unmute the adc - move to kcontrol */ reg = ac97_read(codec, AC97_CD) & 0x7fff; ac97_write(codec, AC97_CD, reg); snd_soc_add_codec_controls(codec, wm9713_snd_ac97_controls, ARRAY_SIZE(wm9713_snd_ac97_controls)); return 0; reset_err: snd_soc_free_ac97_codec(codec); codec_err: kfree(wm9713); return ret; } static int wm9713_soc_remove(struct snd_soc_codec *codec) { struct wm9713_priv *wm9713 = snd_soc_codec_get_drvdata(codec); snd_soc_free_ac97_codec(codec); kfree(wm9713); return 0; } static struct snd_soc_codec_driver soc_codec_dev_wm9713 = { .probe = wm9713_soc_probe, .remove = wm9713_soc_remove, .suspend = wm9713_soc_suspend, .resume = wm9713_soc_resume, .read = ac97_read, .write = ac97_write, .set_bias_level = wm9713_set_bias_level, .reg_cache_size = ARRAY_SIZE(wm9713_reg), .reg_word_size = sizeof(u16), .reg_cache_step = 2, .reg_cache_default = wm9713_reg, .dapm_widgets = wm9713_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(wm9713_dapm_widgets), .dapm_routes = wm9713_audio_map, .num_dapm_routes = ARRAY_SIZE(wm9713_audio_map), }; static int wm9713_probe(struct platform_device *pdev) { return snd_soc_register_codec(&pdev->dev, &soc_codec_dev_wm9713, wm9713_dai, ARRAY_SIZE(wm9713_dai)); } static int wm9713_remove(struct platform_device *pdev) { snd_soc_unregister_codec(&pdev->dev); return 0; } static struct platform_driver wm9713_codec_driver = { .driver = { .name = "wm9713-codec", .owner = THIS_MODULE, }, .probe = wm9713_probe, .remove = wm9713_remove, }; module_platform_driver(wm9713_codec_driver); MODULE_DESCRIPTION("ASoC WM9713/WM9714 driver"); MODULE_AUTHOR("Liam Girdwood"); MODULE_LICENSE("GPL");
gpl-2.0
hexianren/linux-3.7-Panda
arch/sparc/kernel/nmi.c
2503
6314
/* Pseudo NMI support on sparc64 systems. * * Copyright (C) 2009 David S. Miller <davem@davemloft.net> * * The NMI watchdog support and infrastructure is based almost * entirely upon the x86 NMI support code. */ #include <linux/kernel.h> #include <linux/param.h> #include <linux/init.h> #include <linux/percpu.h> #include <linux/nmi.h> #include <linux/export.h> #include <linux/kprobes.h> #include <linux/kernel_stat.h> #include <linux/reboot.h> #include <linux/slab.h> #include <linux/kdebug.h> #include <linux/delay.h> #include <linux/smp.h> #include <asm/perf_event.h> #include <asm/ptrace.h> #include <asm/pcr.h> #include "kstack.h" /* We don't have a real NMI on sparc64, but we can fake one * up using profiling counter overflow interrupts and interrupt * levels. * * The profile overflow interrupts at level 15, so we use * level 14 as our IRQ off level. */ static int panic_on_timeout; /* nmi_active: * >0: the NMI watchdog is active, but can be disabled * <0: the NMI watchdog has not been set up, and cannot be enabled * 0: the NMI watchdog is disabled, but can be enabled */ atomic_t nmi_active = ATOMIC_INIT(0); /* oprofile uses this */ EXPORT_SYMBOL(nmi_active); static unsigned int nmi_hz = HZ; static DEFINE_PER_CPU(short, wd_enabled); static int endflag __initdata; static DEFINE_PER_CPU(unsigned int, last_irq_sum); static DEFINE_PER_CPU(long, alert_counter); static DEFINE_PER_CPU(int, nmi_touch); void touch_nmi_watchdog(void) { if (atomic_read(&nmi_active)) { int cpu; for_each_present_cpu(cpu) { if (per_cpu(nmi_touch, cpu) != 1) per_cpu(nmi_touch, cpu) = 1; } } touch_softlockup_watchdog(); } EXPORT_SYMBOL(touch_nmi_watchdog); static void die_nmi(const char *str, struct pt_regs *regs, int do_panic) { if (notify_die(DIE_NMIWATCHDOG, str, regs, 0, pt_regs_trap_type(regs), SIGINT) == NOTIFY_STOP) return; console_verbose(); bust_spinlocks(1); printk(KERN_EMERG "%s", str); printk(" on CPU%d, ip %08lx, registers:\n", smp_processor_id(), regs->tpc); show_regs(regs); dump_stack(); bust_spinlocks(0); if (do_panic || panic_on_oops) panic("Non maskable interrupt"); nmi_exit(); local_irq_enable(); do_exit(SIGBUS); } notrace __kprobes void perfctr_irq(int irq, struct pt_regs *regs) { unsigned int sum, touched = 0; void *orig_sp; clear_softint(1 << irq); local_cpu_data().__nmi_count++; nmi_enter(); orig_sp = set_hardirq_stack(); if (notify_die(DIE_NMI, "nmi", regs, 0, pt_regs_trap_type(regs), SIGINT) == NOTIFY_STOP) touched = 1; else pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_disable); sum = local_cpu_data().irq0_irqs; if (__get_cpu_var(nmi_touch)) { __get_cpu_var(nmi_touch) = 0; touched = 1; } if (!touched && __get_cpu_var(last_irq_sum) == sum) { __this_cpu_inc(alert_counter); if (__this_cpu_read(alert_counter) == 30 * nmi_hz) die_nmi("BUG: NMI Watchdog detected LOCKUP", regs, panic_on_timeout); } else { __get_cpu_var(last_irq_sum) = sum; __this_cpu_write(alert_counter, 0); } if (__get_cpu_var(wd_enabled)) { pcr_ops->write_pic(0, pcr_ops->nmi_picl_value(nmi_hz)); pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_enable); } restore_hardirq_stack(orig_sp); nmi_exit(); } static inline unsigned int get_nmi_count(int cpu) { return cpu_data(cpu).__nmi_count; } static __init void nmi_cpu_busy(void *data) { local_irq_enable_in_hardirq(); while (endflag == 0) mb(); } static void report_broken_nmi(int cpu, int *prev_nmi_count) { printk(KERN_CONT "\n"); printk(KERN_WARNING "WARNING: CPU#%d: NMI appears to be stuck (%d->%d)!\n", cpu, prev_nmi_count[cpu], get_nmi_count(cpu)); printk(KERN_WARNING "Please report this to bugzilla.kernel.org,\n"); printk(KERN_WARNING "and attach the output of the 'dmesg' command.\n"); per_cpu(wd_enabled, cpu) = 0; atomic_dec(&nmi_active); } void stop_nmi_watchdog(void *unused) { pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_disable); __get_cpu_var(wd_enabled) = 0; atomic_dec(&nmi_active); } static int __init check_nmi_watchdog(void) { unsigned int *prev_nmi_count; int cpu, err; if (!atomic_read(&nmi_active)) return 0; prev_nmi_count = kmalloc(nr_cpu_ids * sizeof(unsigned int), GFP_KERNEL); if (!prev_nmi_count) { err = -ENOMEM; goto error; } printk(KERN_INFO "Testing NMI watchdog ... "); smp_call_function(nmi_cpu_busy, (void *)&endflag, 0); for_each_possible_cpu(cpu) prev_nmi_count[cpu] = get_nmi_count(cpu); local_irq_enable(); mdelay((20 * 1000) / nmi_hz); /* wait 20 ticks */ for_each_online_cpu(cpu) { if (!per_cpu(wd_enabled, cpu)) continue; if (get_nmi_count(cpu) - prev_nmi_count[cpu] <= 5) report_broken_nmi(cpu, prev_nmi_count); } endflag = 1; if (!atomic_read(&nmi_active)) { kfree(prev_nmi_count); atomic_set(&nmi_active, -1); err = -ENODEV; goto error; } printk("OK.\n"); nmi_hz = 1; kfree(prev_nmi_count); return 0; error: on_each_cpu(stop_nmi_watchdog, NULL, 1); return err; } void start_nmi_watchdog(void *unused) { __get_cpu_var(wd_enabled) = 1; atomic_inc(&nmi_active); pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_disable); pcr_ops->write_pic(0, pcr_ops->nmi_picl_value(nmi_hz)); pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_enable); } static void nmi_adjust_hz_one(void *unused) { if (!__get_cpu_var(wd_enabled)) return; pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_disable); pcr_ops->write_pic(0, pcr_ops->nmi_picl_value(nmi_hz)); pcr_ops->write_pcr(0, pcr_ops->pcr_nmi_enable); } void nmi_adjust_hz(unsigned int new_hz) { nmi_hz = new_hz; on_each_cpu(nmi_adjust_hz_one, NULL, 1); } EXPORT_SYMBOL_GPL(nmi_adjust_hz); static int nmi_shutdown(struct notifier_block *nb, unsigned long cmd, void *p) { on_each_cpu(stop_nmi_watchdog, NULL, 1); return 0; } static struct notifier_block nmi_reboot_notifier = { .notifier_call = nmi_shutdown, }; int __init nmi_init(void) { int err; on_each_cpu(start_nmi_watchdog, NULL, 1); err = check_nmi_watchdog(); if (!err) { err = register_reboot_notifier(&nmi_reboot_notifier); if (err) { on_each_cpu(stop_nmi_watchdog, NULL, 1); atomic_set(&nmi_active, -1); } } return err; } static int __init setup_nmi_watchdog(char *str) { if (!strncmp(str, "panic", 5)) panic_on_timeout = 1; return 0; } __setup("nmi_watchdog=", setup_nmi_watchdog);
gpl-2.0
tjstyle/android_kernel_samsung_msm
arch/s390/kernel/suspend.c
4295
1950
/* * Suspend support specific for s390. * * Copyright IBM Corp. 2009 * * Author(s): Hans-Joachim Picht <hans@linux.vnet.ibm.com> */ #include <linux/pfn.h> #include <asm/system.h> /* * References to section boundaries */ extern const void __nosave_begin, __nosave_end; int pfn_is_nosave(unsigned long pfn) { unsigned long nosave_begin_pfn = PFN_DOWN(__pa(&__nosave_begin)); unsigned long nosave_end_pfn = PFN_DOWN(__pa(&__nosave_end)); /* Always save lowcore pages (LC protection might be enabled). */ if (pfn <= LC_PAGES) return 0; if (pfn >= nosave_begin_pfn && pfn < nosave_end_pfn) return 1; /* Skip memory holes and read-only pages (NSS, DCSS, ...). */ if (tprot(PFN_PHYS(pfn))) return 1; return 0; } void save_processor_state(void) { /* swsusp_arch_suspend() actually saves all cpu register contents. * Machine checks must be disabled since swsusp_arch_suspend() stores * register contents to their lowcore save areas. That's the same * place where register contents on machine checks would be saved. * To avoid register corruption disable machine checks. * We must also disable machine checks in the new psw mask for * program checks, since swsusp_arch_suspend() may generate program * checks. Disabling machine checks for all other new psw masks is * just paranoia. */ local_mcck_disable(); /* Disable lowcore protection */ __ctl_clear_bit(0,28); S390_lowcore.external_new_psw.mask &= ~PSW_MASK_MCHECK; S390_lowcore.svc_new_psw.mask &= ~PSW_MASK_MCHECK; S390_lowcore.io_new_psw.mask &= ~PSW_MASK_MCHECK; S390_lowcore.program_new_psw.mask &= ~PSW_MASK_MCHECK; } void restore_processor_state(void) { S390_lowcore.external_new_psw.mask |= PSW_MASK_MCHECK; S390_lowcore.svc_new_psw.mask |= PSW_MASK_MCHECK; S390_lowcore.io_new_psw.mask |= PSW_MASK_MCHECK; S390_lowcore.program_new_psw.mask |= PSW_MASK_MCHECK; /* Enable lowcore protection */ __ctl_set_bit(0,28); local_mcck_enable(); }
gpl-2.0
n3ocort3x/android_kernel_htc_m7
net/lapb/lapb_out.c
4807
5301
/* * LAPB release 002 * * This code REQUIRES 2.1.15 or higher/ NET3.038 * * This module: * This module 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. * * History * LAPB 001 Jonathan Naylor Started Coding * LAPB 002 Jonathan Naylor New timer architecture. */ #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/inet.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <net/lapb.h> /* * This procedure is passed a buffer descriptor for an iframe. It builds * the rest of the control part of the frame and then writes it out. */ static void lapb_send_iframe(struct lapb_cb *lapb, struct sk_buff *skb, int poll_bit) { unsigned char *frame; if (!skb) return; if (lapb->mode & LAPB_EXTENDED) { frame = skb_push(skb, 2); frame[0] = LAPB_I; frame[0] |= lapb->vs << 1; frame[1] = poll_bit ? LAPB_EPF : 0; frame[1] |= lapb->vr << 1; } else { frame = skb_push(skb, 1); *frame = LAPB_I; *frame |= poll_bit ? LAPB_SPF : 0; *frame |= lapb->vr << 5; *frame |= lapb->vs << 1; } #if LAPB_DEBUG > 1 printk(KERN_DEBUG "lapb: (%p) S%d TX I(%d) S%d R%d\n", lapb->dev, lapb->state, poll_bit, lapb->vs, lapb->vr); #endif lapb_transmit_buffer(lapb, skb, LAPB_COMMAND); } void lapb_kick(struct lapb_cb *lapb) { struct sk_buff *skb, *skbn; unsigned short modulus, start, end; modulus = (lapb->mode & LAPB_EXTENDED) ? LAPB_EMODULUS : LAPB_SMODULUS; start = !skb_peek(&lapb->ack_queue) ? lapb->va : lapb->vs; end = (lapb->va + lapb->window) % modulus; if (!(lapb->condition & LAPB_PEER_RX_BUSY_CONDITION) && start != end && skb_peek(&lapb->write_queue)) { lapb->vs = start; /* * Dequeue the frame and copy it. */ skb = skb_dequeue(&lapb->write_queue); do { if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL) { skb_queue_head(&lapb->write_queue, skb); break; } if (skb->sk) skb_set_owner_w(skbn, skb->sk); /* * Transmit the frame copy. */ lapb_send_iframe(lapb, skbn, LAPB_POLLOFF); lapb->vs = (lapb->vs + 1) % modulus; /* * Requeue the original data frame. */ skb_queue_tail(&lapb->ack_queue, skb); } while (lapb->vs != end && (skb = skb_dequeue(&lapb->write_queue)) != NULL); lapb->condition &= ~LAPB_ACK_PENDING_CONDITION; if (!lapb_t1timer_running(lapb)) lapb_start_t1timer(lapb); } } void lapb_transmit_buffer(struct lapb_cb *lapb, struct sk_buff *skb, int type) { unsigned char *ptr; ptr = skb_push(skb, 1); if (lapb->mode & LAPB_MLP) { if (lapb->mode & LAPB_DCE) { if (type == LAPB_COMMAND) *ptr = LAPB_ADDR_C; if (type == LAPB_RESPONSE) *ptr = LAPB_ADDR_D; } else { if (type == LAPB_COMMAND) *ptr = LAPB_ADDR_D; if (type == LAPB_RESPONSE) *ptr = LAPB_ADDR_C; } } else { if (lapb->mode & LAPB_DCE) { if (type == LAPB_COMMAND) *ptr = LAPB_ADDR_A; if (type == LAPB_RESPONSE) *ptr = LAPB_ADDR_B; } else { if (type == LAPB_COMMAND) *ptr = LAPB_ADDR_B; if (type == LAPB_RESPONSE) *ptr = LAPB_ADDR_A; } } #if LAPB_DEBUG > 2 printk(KERN_DEBUG "lapb: (%p) S%d TX %02X %02X %02X\n", lapb->dev, lapb->state, skb->data[0], skb->data[1], skb->data[2]); #endif if (!lapb_data_transmit(lapb, skb)) kfree_skb(skb); } void lapb_establish_data_link(struct lapb_cb *lapb) { lapb->condition = 0x00; lapb->n2count = 0; if (lapb->mode & LAPB_EXTENDED) { #if LAPB_DEBUG > 1 printk(KERN_DEBUG "lapb: (%p) S%d TX SABME(1)\n", lapb->dev, lapb->state); #endif lapb_send_control(lapb, LAPB_SABME, LAPB_POLLON, LAPB_COMMAND); } else { #if LAPB_DEBUG > 1 printk(KERN_DEBUG "lapb: (%p) S%d TX SABM(1)\n", lapb->dev, lapb->state); #endif lapb_send_control(lapb, LAPB_SABM, LAPB_POLLON, LAPB_COMMAND); } lapb_start_t1timer(lapb); lapb_stop_t2timer(lapb); } void lapb_enquiry_response(struct lapb_cb *lapb) { #if LAPB_DEBUG > 1 printk(KERN_DEBUG "lapb: (%p) S%d TX RR(1) R%d\n", lapb->dev, lapb->state, lapb->vr); #endif lapb_send_control(lapb, LAPB_RR, LAPB_POLLON, LAPB_RESPONSE); lapb->condition &= ~LAPB_ACK_PENDING_CONDITION; } void lapb_timeout_response(struct lapb_cb *lapb) { #if LAPB_DEBUG > 1 printk(KERN_DEBUG "lapb: (%p) S%d TX RR(0) R%d\n", lapb->dev, lapb->state, lapb->vr); #endif lapb_send_control(lapb, LAPB_RR, LAPB_POLLOFF, LAPB_RESPONSE); lapb->condition &= ~LAPB_ACK_PENDING_CONDITION; } void lapb_check_iframes_acked(struct lapb_cb *lapb, unsigned short nr) { if (lapb->vs == nr) { lapb_frames_acked(lapb, nr); lapb_stop_t1timer(lapb); lapb->n2count = 0; } else if (lapb->va != nr) { lapb_frames_acked(lapb, nr); lapb_start_t1timer(lapb); } } void lapb_check_need_response(struct lapb_cb *lapb, int type, int pf) { if (type == LAPB_COMMAND && pf) lapb_enquiry_response(lapb); }
gpl-2.0
Talustus/android_kernel_samsung_galaxys4
drivers/net/wireless/mwifiex/sta_rx.c
4807
6557
/* * Marvell Wireless LAN device driver: station RX data handling * * Copyright (C) 2011, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "11n_aggr.h" #include "11n_rxreorder.h" /* * This function processes the received packet and forwards it * to kernel/upper layer. * * This function parses through the received packet and determines * if it is a debug packet or normal packet. * * For non-debug packets, the function chops off unnecessary leading * header bytes, reconstructs the packet as an ethernet frame or * 802.2/llc/snap frame as required, and sends it to kernel/upper layer. * * The completion callback is called after processing in complete. */ int mwifiex_process_rx_packet(struct mwifiex_adapter *adapter, struct sk_buff *skb) { int ret; struct mwifiex_rxinfo *rx_info = MWIFIEX_SKB_RXCB(skb); struct mwifiex_private *priv = mwifiex_get_priv_by_id(adapter, rx_info->bss_num, rx_info->bss_type); struct rx_packet_hdr *rx_pkt_hdr; struct rxpd *local_rx_pd; int hdr_chop; struct ethhdr *eth_hdr; u8 rfc1042_eth_hdr[ETH_ALEN] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 }; local_rx_pd = (struct rxpd *) (skb->data); rx_pkt_hdr = (struct rx_packet_hdr *) ((u8 *) local_rx_pd + local_rx_pd->rx_pkt_offset); if (!memcmp(&rx_pkt_hdr->rfc1042_hdr, rfc1042_eth_hdr, sizeof(rfc1042_eth_hdr))) { /* * Replace the 803 header and rfc1042 header (llc/snap) with an * EthernetII header, keep the src/dst and snap_type * (ethertype). * The firmware only passes up SNAP frames converting * all RX Data from 802.11 to 802.2/LLC/SNAP frames. * To create the Ethernet II, just move the src, dst address * right before the snap_type. */ eth_hdr = (struct ethhdr *) ((u8 *) &rx_pkt_hdr->eth803_hdr + sizeof(rx_pkt_hdr->eth803_hdr) + sizeof(rx_pkt_hdr->rfc1042_hdr) - sizeof(rx_pkt_hdr->eth803_hdr.h_dest) - sizeof(rx_pkt_hdr->eth803_hdr.h_source) - sizeof(rx_pkt_hdr->rfc1042_hdr.snap_type)); memcpy(eth_hdr->h_source, rx_pkt_hdr->eth803_hdr.h_source, sizeof(eth_hdr->h_source)); memcpy(eth_hdr->h_dest, rx_pkt_hdr->eth803_hdr.h_dest, sizeof(eth_hdr->h_dest)); /* Chop off the rxpd + the excess memory from the 802.2/llc/snap header that was removed. */ hdr_chop = (u8 *) eth_hdr - (u8 *) local_rx_pd; } else { /* Chop off the rxpd */ hdr_chop = (u8 *) &rx_pkt_hdr->eth803_hdr - (u8 *) local_rx_pd; } /* Chop off the leading header bytes so the it points to the start of either the reconstructed EthII frame or the 802.2/llc/snap frame */ skb_pull(skb, hdr_chop); priv->rxpd_rate = local_rx_pd->rx_rate; priv->rxpd_htinfo = local_rx_pd->ht_info; ret = mwifiex_recv_packet(adapter, skb); if (ret == -1) dev_err(adapter->dev, "recv packet failed\n"); return ret; } /* * This function processes the received buffer. * * The function looks into the RxPD and performs sanity tests on the * received buffer to ensure its a valid packet, before processing it * further. If the packet is determined to be aggregated, it is * de-aggregated accordingly. Non-unicast packets are sent directly to * the kernel/upper layers. Unicast packets are handed over to the * Rx reordering routine if 11n is enabled. * * The completion callback is called after processing in complete. */ int mwifiex_process_sta_rx_packet(struct mwifiex_adapter *adapter, struct sk_buff *skb) { int ret = 0; struct rxpd *local_rx_pd; struct mwifiex_rxinfo *rx_info = MWIFIEX_SKB_RXCB(skb); struct rx_packet_hdr *rx_pkt_hdr; u8 ta[ETH_ALEN]; u16 rx_pkt_type; struct mwifiex_private *priv = mwifiex_get_priv_by_id(adapter, rx_info->bss_num, rx_info->bss_type); if (!priv) return -1; local_rx_pd = (struct rxpd *) (skb->data); rx_pkt_type = local_rx_pd->rx_pkt_type; rx_pkt_hdr = (struct rx_packet_hdr *) ((u8 *) local_rx_pd + local_rx_pd->rx_pkt_offset); if ((local_rx_pd->rx_pkt_offset + local_rx_pd->rx_pkt_length) > (u16) skb->len) { dev_err(adapter->dev, "wrong rx packet: len=%d," " rx_pkt_offset=%d, rx_pkt_length=%d\n", skb->len, local_rx_pd->rx_pkt_offset, local_rx_pd->rx_pkt_length); priv->stats.rx_dropped++; dev_kfree_skb_any(skb); return ret; } if (local_rx_pd->rx_pkt_type == PKT_TYPE_AMSDU) { struct sk_buff_head list; struct sk_buff *rx_skb; __skb_queue_head_init(&list); skb_pull(skb, local_rx_pd->rx_pkt_offset); skb_trim(skb, local_rx_pd->rx_pkt_length); ieee80211_amsdu_to_8023s(skb, &list, priv->curr_addr, priv->wdev->iftype, 0, false); while (!skb_queue_empty(&list)) { rx_skb = __skb_dequeue(&list); ret = mwifiex_recv_packet(adapter, rx_skb); if (ret == -1) dev_err(adapter->dev, "Rx of A-MSDU failed"); } return 0; } /* * If the packet is not an unicast packet then send the packet * directly to os. Don't pass thru rx reordering */ if (!IS_11N_ENABLED(priv) || memcmp(priv->curr_addr, rx_pkt_hdr->eth803_hdr.h_dest, ETH_ALEN)) { mwifiex_process_rx_packet(adapter, skb); return ret; } if (mwifiex_queuing_ra_based(priv)) { memcpy(ta, rx_pkt_hdr->eth803_hdr.h_source, ETH_ALEN); } else { if (rx_pkt_type != PKT_TYPE_BAR) priv->rx_seq[local_rx_pd->priority] = local_rx_pd->seq_num; memcpy(ta, priv->curr_bss_params.bss_descriptor.mac_address, ETH_ALEN); } /* Reorder and send to OS */ ret = mwifiex_11n_rx_reorder_pkt(priv, local_rx_pd->seq_num, local_rx_pd->priority, ta, (u8) local_rx_pd->rx_pkt_type, skb); if (ret || (rx_pkt_type == PKT_TYPE_BAR)) dev_kfree_skb_any(skb); if (ret) priv->stats.rx_dropped++; return ret; }
gpl-2.0
Blefish/android_kernel_qcom_msm7x30
drivers/isdn/hisax/avm_a1.c
4807
8281
/* $Id: avm_a1.c,v 2.15.2.4 2004/01/13 21:46:03 keil Exp $ * * low level stuff for AVM A1 (Fritz) isdn cards * * Author Karsten Keil * Copyright by Karsten Keil <keil@isdn4linux.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/init.h> #include "hisax.h" #include "isac.h" #include "hscx.h" #include "isdnl1.h" static const char *avm_revision = "$Revision: 2.15.2.4 $"; #define AVM_A1_STAT_ISAC 0x01 #define AVM_A1_STAT_HSCX 0x02 #define AVM_A1_STAT_TIMER 0x04 #define byteout(addr, val) outb(val, addr) #define bytein(addr) inb(addr) static inline u_char readreg(unsigned int adr, u_char off) { return (bytein(adr + off)); } static inline void writereg(unsigned int adr, u_char off, u_char data) { byteout(adr + off, data); } static inline void read_fifo(unsigned int adr, u_char *data, int size) { insb(adr, data, size); } static void write_fifo(unsigned int adr, u_char *data, int size) { outsb(adr, data, size); } /* Interface functions */ static u_char ReadISAC(struct IsdnCardState *cs, u_char offset) { return (readreg(cs->hw.avm.isac, offset)); } static void WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value) { writereg(cs->hw.avm.isac, offset, value); } static void ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size) { read_fifo(cs->hw.avm.isacfifo, data, size); } static void WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size) { write_fifo(cs->hw.avm.isacfifo, data, size); } static u_char ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset) { return (readreg(cs->hw.avm.hscx[hscx], offset)); } static void WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value) { writereg(cs->hw.avm.hscx[hscx], offset, value); } /* * fast interrupt HSCX stuff goes here */ #define READHSCX(cs, nr, reg) readreg(cs->hw.avm.hscx[nr], reg) #define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.avm.hscx[nr], reg, data) #define READHSCXFIFO(cs, nr, ptr, cnt) read_fifo(cs->hw.avm.hscxfifo[nr], ptr, cnt) #define WRITEHSCXFIFO(cs, nr, ptr, cnt) write_fifo(cs->hw.avm.hscxfifo[nr], ptr, cnt) #include "hscx_irq.c" static irqreturn_t avm_a1_interrupt(int intno, void *dev_id) { struct IsdnCardState *cs = dev_id; u_char val, sval; u_long flags; spin_lock_irqsave(&cs->lock, flags); while (((sval = bytein(cs->hw.avm.cfg_reg)) & 0xf) != 0x7) { if (!(sval & AVM_A1_STAT_TIMER)) { byteout(cs->hw.avm.cfg_reg, 0x1E); sval = bytein(cs->hw.avm.cfg_reg); } else if (cs->debug & L1_DEB_INTSTAT) debugl1(cs, "avm IntStatus %x", sval); if (!(sval & AVM_A1_STAT_HSCX)) { val = readreg(cs->hw.avm.hscx[1], HSCX_ISTA); if (val) hscx_int_main(cs, val); } if (!(sval & AVM_A1_STAT_ISAC)) { val = readreg(cs->hw.avm.isac, ISAC_ISTA); if (val) isac_interrupt(cs, val); } } writereg(cs->hw.avm.hscx[0], HSCX_MASK, 0xFF); writereg(cs->hw.avm.hscx[1], HSCX_MASK, 0xFF); writereg(cs->hw.avm.isac, ISAC_MASK, 0xFF); writereg(cs->hw.avm.isac, ISAC_MASK, 0x0); writereg(cs->hw.avm.hscx[0], HSCX_MASK, 0x0); writereg(cs->hw.avm.hscx[1], HSCX_MASK, 0x0); spin_unlock_irqrestore(&cs->lock, flags); return IRQ_HANDLED; } static inline void release_ioregs(struct IsdnCardState *cs, int mask) { release_region(cs->hw.avm.cfg_reg, 8); if (mask & 1) release_region(cs->hw.avm.isac + 32, 32); if (mask & 2) release_region(cs->hw.avm.isacfifo, 1); if (mask & 4) release_region(cs->hw.avm.hscx[0] + 32, 32); if (mask & 8) release_region(cs->hw.avm.hscxfifo[0], 1); if (mask & 0x10) release_region(cs->hw.avm.hscx[1] + 32, 32); if (mask & 0x20) release_region(cs->hw.avm.hscxfifo[1], 1); } static int AVM_card_msg(struct IsdnCardState *cs, int mt, void *arg) { u_long flags; switch (mt) { case CARD_RESET: return (0); case CARD_RELEASE: release_ioregs(cs, 0x3f); return (0); case CARD_INIT: spin_lock_irqsave(&cs->lock, flags); inithscxisac(cs, 1); byteout(cs->hw.avm.cfg_reg, 0x16); byteout(cs->hw.avm.cfg_reg, 0x1E); inithscxisac(cs, 2); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_TEST: return (0); } return (0); } int setup_avm_a1(struct IsdnCard *card) { u_char val; struct IsdnCardState *cs = card->cs; char tmp[64]; strcpy(tmp, avm_revision); printk(KERN_INFO "HiSax: AVM driver Rev. %s\n", HiSax_getrev(tmp)); if (cs->typ != ISDN_CTYPE_A1) return (0); cs->hw.avm.cfg_reg = card->para[1] + 0x1800; cs->hw.avm.isac = card->para[1] + 0x1400 - 0x20; cs->hw.avm.hscx[0] = card->para[1] + 0x400 - 0x20; cs->hw.avm.hscx[1] = card->para[1] + 0xc00 - 0x20; cs->hw.avm.isacfifo = card->para[1] + 0x1000; cs->hw.avm.hscxfifo[0] = card->para[1]; cs->hw.avm.hscxfifo[1] = card->para[1] + 0x800; cs->irq = card->para[0]; if (!request_region(cs->hw.avm.cfg_reg, 8, "avm cfg")) { printk(KERN_WARNING "HiSax: AVM A1 config port %x-%x already in use\n", cs->hw.avm.cfg_reg, cs->hw.avm.cfg_reg + 8); return (0); } if (!request_region(cs->hw.avm.isac + 32, 32, "HiSax isac")) { printk(KERN_WARNING "HiSax: AVM A1 isac ports %x-%x already in use\n", cs->hw.avm.isac + 32, cs->hw.avm.isac + 64); release_ioregs(cs, 0); return (0); } if (!request_region(cs->hw.avm.isacfifo, 1, "HiSax isac fifo")) { printk(KERN_WARNING "HiSax: AVM A1 isac fifo port %x already in use\n", cs->hw.avm.isacfifo); release_ioregs(cs, 1); return (0); } if (!request_region(cs->hw.avm.hscx[0] + 32, 32, "HiSax hscx A")) { printk(KERN_WARNING "HiSax: AVM A1 hscx A ports %x-%x already in use\n", cs->hw.avm.hscx[0] + 32, cs->hw.avm.hscx[0] + 64); release_ioregs(cs, 3); return (0); } if (!request_region(cs->hw.avm.hscxfifo[0], 1, "HiSax hscx A fifo")) { printk(KERN_WARNING "HiSax: AVM A1 hscx A fifo port %x already in use\n", cs->hw.avm.hscxfifo[0]); release_ioregs(cs, 7); return (0); } if (!request_region(cs->hw.avm.hscx[1] + 32, 32, "HiSax hscx B")) { printk(KERN_WARNING "HiSax: AVM A1 hscx B ports %x-%x already in use\n", cs->hw.avm.hscx[1] + 32, cs->hw.avm.hscx[1] + 64); release_ioregs(cs, 0xf); return (0); } if (!request_region(cs->hw.avm.hscxfifo[1], 1, "HiSax hscx B fifo")) { printk(KERN_WARNING "HiSax: AVM A1 hscx B fifo port %x already in use\n", cs->hw.avm.hscxfifo[1]); release_ioregs(cs, 0x1f); return (0); } byteout(cs->hw.avm.cfg_reg, 0x0); HZDELAY(HZ / 5 + 1); byteout(cs->hw.avm.cfg_reg, 0x1); HZDELAY(HZ / 5 + 1); byteout(cs->hw.avm.cfg_reg, 0x0); HZDELAY(HZ / 5 + 1); val = cs->irq; if (val == 9) val = 2; byteout(cs->hw.avm.cfg_reg + 1, val); HZDELAY(HZ / 5 + 1); byteout(cs->hw.avm.cfg_reg, 0x0); HZDELAY(HZ / 5 + 1); val = bytein(cs->hw.avm.cfg_reg); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg, val); val = bytein(cs->hw.avm.cfg_reg + 3); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg + 3, val); val = bytein(cs->hw.avm.cfg_reg + 2); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg + 2, val); val = bytein(cs->hw.avm.cfg_reg); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg, val); printk(KERN_INFO "HiSax: AVM A1 config irq:%d cfg:0x%X\n", cs->irq, cs->hw.avm.cfg_reg); printk(KERN_INFO "HiSax: isac:0x%X/0x%X\n", cs->hw.avm.isac + 32, cs->hw.avm.isacfifo); printk(KERN_INFO "HiSax: hscx A:0x%X/0x%X hscx B:0x%X/0x%X\n", cs->hw.avm.hscx[0] + 32, cs->hw.avm.hscxfifo[0], cs->hw.avm.hscx[1] + 32, cs->hw.avm.hscxfifo[1]); cs->readisac = &ReadISAC; cs->writeisac = &WriteISAC; cs->readisacfifo = &ReadISACfifo; cs->writeisacfifo = &WriteISACfifo; cs->BC_Read_Reg = &ReadHSCX; cs->BC_Write_Reg = &WriteHSCX; cs->BC_Send_Data = &hscx_fill_fifo; setup_isac(cs); cs->cardmsg = &AVM_card_msg; cs->irq_func = &avm_a1_interrupt; ISACVersion(cs, "AVM A1:"); if (HscxVersion(cs, "AVM A1:")) { printk(KERN_WARNING "AVM A1: wrong HSCX versions check IO address\n"); release_ioregs(cs, 0x3f); return (0); } return (1); }
gpl-2.0
CyanogenMod-E1/cafkernel
drivers/spi/spi-orion.c
4807
12841
/* * Marvell Orion SPI controller driver * * Author: Shadi Ammouri <shadi@marvell.com> * Copyright (C) 2007-2008 Marvell Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/err.h> #include <linux/io.h> #include <linux/spi/spi.h> #include <linux/spi/orion_spi.h> #include <linux/module.h> #include <asm/unaligned.h> #define DRIVER_NAME "orion_spi" #define ORION_NUM_CHIPSELECTS 1 /* only one slave is supported*/ #define ORION_SPI_WAIT_RDY_MAX_LOOP 2000 /* in usec */ #define ORION_SPI_IF_CTRL_REG 0x00 #define ORION_SPI_IF_CONFIG_REG 0x04 #define ORION_SPI_DATA_OUT_REG 0x08 #define ORION_SPI_DATA_IN_REG 0x0c #define ORION_SPI_INT_CAUSE_REG 0x10 #define ORION_SPI_IF_8_16_BIT_MODE (1 << 5) #define ORION_SPI_CLK_PRESCALE_MASK 0x1F struct orion_spi { struct work_struct work; /* Lock access to transfer list. */ spinlock_t lock; struct list_head msg_queue; struct spi_master *master; void __iomem *base; unsigned int max_speed; unsigned int min_speed; struct orion_spi_info *spi_info; }; static struct workqueue_struct *orion_spi_wq; static inline void __iomem *spi_reg(struct orion_spi *orion_spi, u32 reg) { return orion_spi->base + reg; } static inline void orion_spi_setbits(struct orion_spi *orion_spi, u32 reg, u32 mask) { void __iomem *reg_addr = spi_reg(orion_spi, reg); u32 val; val = readl(reg_addr); val |= mask; writel(val, reg_addr); } static inline void orion_spi_clrbits(struct orion_spi *orion_spi, u32 reg, u32 mask) { void __iomem *reg_addr = spi_reg(orion_spi, reg); u32 val; val = readl(reg_addr); val &= ~mask; writel(val, reg_addr); } static int orion_spi_set_transfer_size(struct orion_spi *orion_spi, int size) { if (size == 16) { orion_spi_setbits(orion_spi, ORION_SPI_IF_CONFIG_REG, ORION_SPI_IF_8_16_BIT_MODE); } else if (size == 8) { orion_spi_clrbits(orion_spi, ORION_SPI_IF_CONFIG_REG, ORION_SPI_IF_8_16_BIT_MODE); } else { pr_debug("Bad bits per word value %d (only 8 or 16 are " "allowed).\n", size); return -EINVAL; } return 0; } static int orion_spi_baudrate_set(struct spi_device *spi, unsigned int speed) { u32 tclk_hz; u32 rate; u32 prescale; u32 reg; struct orion_spi *orion_spi; orion_spi = spi_master_get_devdata(spi->master); tclk_hz = orion_spi->spi_info->tclk; /* * the supported rates are: 4,6,8...30 * round up as we look for equal or less speed */ rate = DIV_ROUND_UP(tclk_hz, speed); rate = roundup(rate, 2); /* check if requested speed is too small */ if (rate > 30) return -EINVAL; if (rate < 4) rate = 4; /* Convert the rate to SPI clock divisor value. */ prescale = 0x10 + rate/2; reg = readl(spi_reg(orion_spi, ORION_SPI_IF_CONFIG_REG)); reg = ((reg & ~ORION_SPI_CLK_PRESCALE_MASK) | prescale); writel(reg, spi_reg(orion_spi, ORION_SPI_IF_CONFIG_REG)); return 0; } /* * called only when no transfer is active on the bus */ static int orion_spi_setup_transfer(struct spi_device *spi, struct spi_transfer *t) { struct orion_spi *orion_spi; unsigned int speed = spi->max_speed_hz; unsigned int bits_per_word = spi->bits_per_word; int rc; orion_spi = spi_master_get_devdata(spi->master); if ((t != NULL) && t->speed_hz) speed = t->speed_hz; if ((t != NULL) && t->bits_per_word) bits_per_word = t->bits_per_word; rc = orion_spi_baudrate_set(spi, speed); if (rc) return rc; return orion_spi_set_transfer_size(orion_spi, bits_per_word); } static void orion_spi_set_cs(struct orion_spi *orion_spi, int enable) { if (enable) orion_spi_setbits(orion_spi, ORION_SPI_IF_CTRL_REG, 0x1); else orion_spi_clrbits(orion_spi, ORION_SPI_IF_CTRL_REG, 0x1); } static inline int orion_spi_wait_till_ready(struct orion_spi *orion_spi) { int i; for (i = 0; i < ORION_SPI_WAIT_RDY_MAX_LOOP; i++) { if (readl(spi_reg(orion_spi, ORION_SPI_INT_CAUSE_REG))) return 1; else udelay(1); } return -1; } static inline int orion_spi_write_read_8bit(struct spi_device *spi, const u8 **tx_buf, u8 **rx_buf) { void __iomem *tx_reg, *rx_reg, *int_reg; struct orion_spi *orion_spi; orion_spi = spi_master_get_devdata(spi->master); tx_reg = spi_reg(orion_spi, ORION_SPI_DATA_OUT_REG); rx_reg = spi_reg(orion_spi, ORION_SPI_DATA_IN_REG); int_reg = spi_reg(orion_spi, ORION_SPI_INT_CAUSE_REG); /* clear the interrupt cause register */ writel(0x0, int_reg); if (tx_buf && *tx_buf) writel(*(*tx_buf)++, tx_reg); else writel(0, tx_reg); if (orion_spi_wait_till_ready(orion_spi) < 0) { dev_err(&spi->dev, "TXS timed out\n"); return -1; } if (rx_buf && *rx_buf) *(*rx_buf)++ = readl(rx_reg); return 1; } static inline int orion_spi_write_read_16bit(struct spi_device *spi, const u16 **tx_buf, u16 **rx_buf) { void __iomem *tx_reg, *rx_reg, *int_reg; struct orion_spi *orion_spi; orion_spi = spi_master_get_devdata(spi->master); tx_reg = spi_reg(orion_spi, ORION_SPI_DATA_OUT_REG); rx_reg = spi_reg(orion_spi, ORION_SPI_DATA_IN_REG); int_reg = spi_reg(orion_spi, ORION_SPI_INT_CAUSE_REG); /* clear the interrupt cause register */ writel(0x0, int_reg); if (tx_buf && *tx_buf) writel(__cpu_to_le16(get_unaligned((*tx_buf)++)), tx_reg); else writel(0, tx_reg); if (orion_spi_wait_till_ready(orion_spi) < 0) { dev_err(&spi->dev, "TXS timed out\n"); return -1; } if (rx_buf && *rx_buf) put_unaligned(__le16_to_cpu(readl(rx_reg)), (*rx_buf)++); return 1; } static unsigned int orion_spi_write_read(struct spi_device *spi, struct spi_transfer *xfer) { struct orion_spi *orion_spi; unsigned int count; int word_len; orion_spi = spi_master_get_devdata(spi->master); word_len = spi->bits_per_word; count = xfer->len; if (word_len == 8) { const u8 *tx = xfer->tx_buf; u8 *rx = xfer->rx_buf; do { if (orion_spi_write_read_8bit(spi, &tx, &rx) < 0) goto out; count--; } while (count); } else if (word_len == 16) { const u16 *tx = xfer->tx_buf; u16 *rx = xfer->rx_buf; do { if (orion_spi_write_read_16bit(spi, &tx, &rx) < 0) goto out; count -= 2; } while (count); } out: return xfer->len - count; } static void orion_spi_work(struct work_struct *work) { struct orion_spi *orion_spi = container_of(work, struct orion_spi, work); spin_lock_irq(&orion_spi->lock); while (!list_empty(&orion_spi->msg_queue)) { struct spi_message *m; struct spi_device *spi; struct spi_transfer *t = NULL; int par_override = 0; int status = 0; int cs_active = 0; m = container_of(orion_spi->msg_queue.next, struct spi_message, queue); list_del_init(&m->queue); spin_unlock_irq(&orion_spi->lock); spi = m->spi; /* Load defaults */ status = orion_spi_setup_transfer(spi, NULL); if (status < 0) goto msg_done; list_for_each_entry(t, &m->transfers, transfer_list) { if (par_override || t->speed_hz || t->bits_per_word) { par_override = 1; status = orion_spi_setup_transfer(spi, t); if (status < 0) break; if (!t->speed_hz && !t->bits_per_word) par_override = 0; } if (!cs_active) { orion_spi_set_cs(orion_spi, 1); cs_active = 1; } if (t->len) m->actual_length += orion_spi_write_read(spi, t); if (t->delay_usecs) udelay(t->delay_usecs); if (t->cs_change) { orion_spi_set_cs(orion_spi, 0); cs_active = 0; } } msg_done: if (cs_active) orion_spi_set_cs(orion_spi, 0); m->status = status; m->complete(m->context); spin_lock_irq(&orion_spi->lock); } spin_unlock_irq(&orion_spi->lock); } static int __init orion_spi_reset(struct orion_spi *orion_spi) { /* Verify that the CS is deasserted */ orion_spi_set_cs(orion_spi, 0); return 0; } static int orion_spi_setup(struct spi_device *spi) { struct orion_spi *orion_spi; orion_spi = spi_master_get_devdata(spi->master); if ((spi->max_speed_hz == 0) || (spi->max_speed_hz > orion_spi->max_speed)) spi->max_speed_hz = orion_spi->max_speed; if (spi->max_speed_hz < orion_spi->min_speed) { dev_err(&spi->dev, "setup: requested speed too low %d Hz\n", spi->max_speed_hz); return -EINVAL; } /* * baudrate & width will be set orion_spi_setup_transfer */ return 0; } static int orion_spi_transfer(struct spi_device *spi, struct spi_message *m) { struct orion_spi *orion_spi; struct spi_transfer *t = NULL; unsigned long flags; m->actual_length = 0; m->status = 0; /* reject invalid messages and transfers */ if (list_empty(&m->transfers) || !m->complete) return -EINVAL; orion_spi = spi_master_get_devdata(spi->master); list_for_each_entry(t, &m->transfers, transfer_list) { unsigned int bits_per_word = spi->bits_per_word; if (t->tx_buf == NULL && t->rx_buf == NULL && t->len) { dev_err(&spi->dev, "message rejected : " "invalid transfer data buffers\n"); goto msg_rejected; } if (t->bits_per_word) bits_per_word = t->bits_per_word; if ((bits_per_word != 8) && (bits_per_word != 16)) { dev_err(&spi->dev, "message rejected : " "invalid transfer bits_per_word (%d bits)\n", bits_per_word); goto msg_rejected; } /*make sure buffer length is even when working in 16 bit mode*/ if ((t->bits_per_word == 16) && (t->len & 1)) { dev_err(&spi->dev, "message rejected : " "odd data length (%d) while in 16 bit mode\n", t->len); goto msg_rejected; } if (t->speed_hz && t->speed_hz < orion_spi->min_speed) { dev_err(&spi->dev, "message rejected : " "device min speed (%d Hz) exceeds " "required transfer speed (%d Hz)\n", orion_spi->min_speed, t->speed_hz); goto msg_rejected; } } spin_lock_irqsave(&orion_spi->lock, flags); list_add_tail(&m->queue, &orion_spi->msg_queue); queue_work(orion_spi_wq, &orion_spi->work); spin_unlock_irqrestore(&orion_spi->lock, flags); return 0; msg_rejected: /* Message rejected and not queued */ m->status = -EINVAL; if (m->complete) m->complete(m->context); return -EINVAL; } static int __init orion_spi_probe(struct platform_device *pdev) { struct spi_master *master; struct orion_spi *spi; struct resource *r; struct orion_spi_info *spi_info; int status = 0; spi_info = pdev->dev.platform_data; master = spi_alloc_master(&pdev->dev, sizeof *spi); if (master == NULL) { dev_dbg(&pdev->dev, "master allocation failed\n"); return -ENOMEM; } if (pdev->id != -1) master->bus_num = pdev->id; /* we support only mode 0, and no options */ master->mode_bits = 0; master->setup = orion_spi_setup; master->transfer = orion_spi_transfer; master->num_chipselect = ORION_NUM_CHIPSELECTS; dev_set_drvdata(&pdev->dev, master); spi = spi_master_get_devdata(master); spi->master = master; spi->spi_info = spi_info; spi->max_speed = DIV_ROUND_UP(spi_info->tclk, 4); spi->min_speed = DIV_ROUND_UP(spi_info->tclk, 30); r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (r == NULL) { status = -ENODEV; goto out; } if (!request_mem_region(r->start, resource_size(r), dev_name(&pdev->dev))) { status = -EBUSY; goto out; } spi->base = ioremap(r->start, SZ_1K); INIT_WORK(&spi->work, orion_spi_work); spin_lock_init(&spi->lock); INIT_LIST_HEAD(&spi->msg_queue); if (orion_spi_reset(spi) < 0) goto out_rel_mem; status = spi_register_master(master); if (status < 0) goto out_rel_mem; return status; out_rel_mem: release_mem_region(r->start, resource_size(r)); out: spi_master_put(master); return status; } static int __exit orion_spi_remove(struct platform_device *pdev) { struct spi_master *master; struct orion_spi *spi; struct resource *r; master = dev_get_drvdata(&pdev->dev); spi = spi_master_get_devdata(master); cancel_work_sync(&spi->work); r = platform_get_resource(pdev, IORESOURCE_MEM, 0); release_mem_region(r->start, resource_size(r)); spi_unregister_master(master); return 0; } MODULE_ALIAS("platform:" DRIVER_NAME); static struct platform_driver orion_spi_driver = { .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, }, .remove = __exit_p(orion_spi_remove), }; static int __init orion_spi_init(void) { orion_spi_wq = create_singlethread_workqueue( orion_spi_driver.driver.name); if (orion_spi_wq == NULL) return -ENOMEM; return platform_driver_probe(&orion_spi_driver, orion_spi_probe); } module_init(orion_spi_init); static void __exit orion_spi_exit(void) { flush_workqueue(orion_spi_wq); platform_driver_unregister(&orion_spi_driver); destroy_workqueue(orion_spi_wq); } module_exit(orion_spi_exit); MODULE_DESCRIPTION("Orion SPI driver"); MODULE_AUTHOR("Shadi Ammouri <shadi@marvell.com>"); MODULE_LICENSE("GPL");
gpl-2.0
spacecaker/android_kernel_acer_swing-CAF
drivers/net/wireless/wl12xx/ps.c
4807
7606
/* * This file is part of wl1271 * * Copyright (C) 2008-2009 Nokia Corporation * * Contact: Luciano Coelho <luciano.coelho@nokia.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 St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "reg.h" #include "ps.h" #include "io.h" #include "tx.h" #include "debug.h" #define WL1271_WAKEUP_TIMEOUT 500 void wl1271_elp_work(struct work_struct *work) { struct delayed_work *dwork; struct wl1271 *wl; struct wl12xx_vif *wlvif; dwork = container_of(work, struct delayed_work, work); wl = container_of(dwork, struct wl1271, elp_work); wl1271_debug(DEBUG_PSM, "elp work"); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; /* our work might have been already cancelled */ if (unlikely(!test_bit(WL1271_FLAG_ELP_REQUESTED, &wl->flags))) goto out; if (test_bit(WL1271_FLAG_IN_ELP, &wl->flags)) goto out; wl12xx_for_each_wlvif(wl, wlvif) { if (wlvif->bss_type == BSS_TYPE_AP_BSS) goto out; if (!test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags) && test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags)) goto out; } wl1271_debug(DEBUG_PSM, "chip to elp"); wl1271_raw_write32(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, ELPCTRL_SLEEP); set_bit(WL1271_FLAG_IN_ELP, &wl->flags); out: mutex_unlock(&wl->mutex); } /* Routines to toggle sleep mode while in ELP */ void wl1271_ps_elp_sleep(struct wl1271 *wl) { struct wl12xx_vif *wlvif; /* we shouldn't get consecutive sleep requests */ if (WARN_ON(test_and_set_bit(WL1271_FLAG_ELP_REQUESTED, &wl->flags))) return; wl12xx_for_each_wlvif(wl, wlvif) { if (wlvif->bss_type == BSS_TYPE_AP_BSS) return; if (!test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags) && test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags)) return; } ieee80211_queue_delayed_work(wl->hw, &wl->elp_work, msecs_to_jiffies(wl->conf.conn.dynamic_ps_timeout)); } int wl1271_ps_elp_wakeup(struct wl1271 *wl) { DECLARE_COMPLETION_ONSTACK(compl); unsigned long flags; int ret; u32 start_time = jiffies; bool pending = false; /* * we might try to wake up even if we didn't go to sleep * before (e.g. on boot) */ if (!test_and_clear_bit(WL1271_FLAG_ELP_REQUESTED, &wl->flags)) return 0; /* don't cancel_sync as it might contend for a mutex and deadlock */ cancel_delayed_work(&wl->elp_work); if (!test_bit(WL1271_FLAG_IN_ELP, &wl->flags)) return 0; wl1271_debug(DEBUG_PSM, "waking up chip from elp"); /* * The spinlock is required here to synchronize both the work and * the completion variable in one entity. */ spin_lock_irqsave(&wl->wl_lock, flags); if (test_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags)) pending = true; else wl->elp_compl = &compl; spin_unlock_irqrestore(&wl->wl_lock, flags); wl1271_raw_write32(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, ELPCTRL_WAKE_UP); if (!pending) { ret = wait_for_completion_timeout( &compl, msecs_to_jiffies(WL1271_WAKEUP_TIMEOUT)); if (ret == 0) { wl1271_error("ELP wakeup timeout!"); wl12xx_queue_recovery_work(wl); ret = -ETIMEDOUT; goto err; } else if (ret < 0) { wl1271_error("ELP wakeup completion error."); goto err; } } clear_bit(WL1271_FLAG_IN_ELP, &wl->flags); wl1271_debug(DEBUG_PSM, "wakeup time: %u ms", jiffies_to_msecs(jiffies - start_time)); goto out; err: spin_lock_irqsave(&wl->wl_lock, flags); wl->elp_compl = NULL; spin_unlock_irqrestore(&wl->wl_lock, flags); return ret; out: return 0; } int wl1271_ps_set_mode(struct wl1271 *wl, struct wl12xx_vif *wlvif, enum wl1271_cmd_ps_mode mode) { int ret; u16 timeout = wl->conf.conn.dynamic_ps_timeout; switch (mode) { case STATION_AUTO_PS_MODE: case STATION_POWER_SAVE_MODE: wl1271_debug(DEBUG_PSM, "entering psm (mode=%d,timeout=%u)", mode, timeout); ret = wl1271_acx_wake_up_conditions(wl, wlvif, wl->conf.conn.wake_up_event, wl->conf.conn.listen_interval); if (ret < 0) { wl1271_error("couldn't set wake up conditions"); return ret; } ret = wl1271_cmd_ps_mode(wl, wlvif, mode, timeout); if (ret < 0) return ret; set_bit(WLVIF_FLAG_IN_PS, &wlvif->flags); /* enable beacon early termination. Not relevant for 5GHz */ if (wlvif->band == IEEE80211_BAND_2GHZ) { ret = wl1271_acx_bet_enable(wl, wlvif, true); if (ret < 0) return ret; } break; case STATION_ACTIVE_MODE: wl1271_debug(DEBUG_PSM, "leaving psm"); /* disable beacon early termination */ if (wlvif->band == IEEE80211_BAND_2GHZ) { ret = wl1271_acx_bet_enable(wl, wlvif, false); if (ret < 0) return ret; } ret = wl1271_cmd_ps_mode(wl, wlvif, mode, 0); if (ret < 0) return ret; clear_bit(WLVIF_FLAG_IN_PS, &wlvif->flags); break; default: wl1271_warning("trying to set ps to unsupported mode %d", mode); ret = -EINVAL; } return ret; } static void wl1271_ps_filter_frames(struct wl1271 *wl, u8 hlid) { int i; struct sk_buff *skb; struct ieee80211_tx_info *info; unsigned long flags; int filtered[NUM_TX_QUEUES]; /* filter all frames currently in the low level queues for this hlid */ for (i = 0; i < NUM_TX_QUEUES; i++) { filtered[i] = 0; while ((skb = skb_dequeue(&wl->links[hlid].tx_queue[i]))) { filtered[i]++; if (WARN_ON(wl12xx_is_dummy_packet(wl, skb))) continue; info = IEEE80211_SKB_CB(skb); info->flags |= IEEE80211_TX_STAT_TX_FILTERED; info->status.rates[0].idx = -1; ieee80211_tx_status_ni(wl->hw, skb); } } spin_lock_irqsave(&wl->wl_lock, flags); for (i = 0; i < NUM_TX_QUEUES; i++) wl->tx_queue_count[i] -= filtered[i]; spin_unlock_irqrestore(&wl->wl_lock, flags); wl1271_handle_tx_low_watermark(wl); } void wl12xx_ps_link_start(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid, bool clean_queues) { struct ieee80211_sta *sta; struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif); if (test_bit(hlid, &wl->ap_ps_map)) return; wl1271_debug(DEBUG_PSM, "start mac80211 PSM on hlid %d pkts %d " "clean_queues %d", hlid, wl->links[hlid].allocated_pkts, clean_queues); rcu_read_lock(); sta = ieee80211_find_sta(vif, wl->links[hlid].addr); if (!sta) { wl1271_error("could not find sta %pM for starting ps", wl->links[hlid].addr); rcu_read_unlock(); return; } ieee80211_sta_ps_transition_ni(sta, true); rcu_read_unlock(); /* do we want to filter all frames from this link's queues? */ if (clean_queues) wl1271_ps_filter_frames(wl, hlid); __set_bit(hlid, &wl->ap_ps_map); } void wl12xx_ps_link_end(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid) { struct ieee80211_sta *sta; struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif); if (!test_bit(hlid, &wl->ap_ps_map)) return; wl1271_debug(DEBUG_PSM, "end mac80211 PSM on hlid %d", hlid); __clear_bit(hlid, &wl->ap_ps_map); rcu_read_lock(); sta = ieee80211_find_sta(vif, wl->links[hlid].addr); if (!sta) { wl1271_error("could not find sta %pM for ending ps", wl->links[hlid].addr); goto end; } ieee80211_sta_ps_transition_ni(sta, false); end: rcu_read_unlock(); }
gpl-2.0
JmzTaylor/android_kernel_htc_msm8960-1
tools/perf/util/ui/browsers/map.c
4807
3697
#include "../libslang.h" #include <elf.h> #include <newt.h> #include <inttypes.h> #include <sys/ttydefaults.h> #include <string.h> #include <linux/bitops.h> #include "../../util.h" #include "../../debug.h" #include "../../symbol.h" #include "../browser.h" #include "../helpline.h" #include "map.h" static int ui_entry__read(const char *title, char *bf, size_t size, int width) { struct newtExitStruct es; newtComponent form, entry; const char *result; int err = -1; newtCenteredWindow(width, 1, title); form = newtForm(NULL, NULL, 0); if (form == NULL) return -1; entry = newtEntry(0, 0, "0x", width, &result, NEWT_FLAG_SCROLL); if (entry == NULL) goto out_free_form; newtFormAddComponent(form, entry); newtFormAddHotKey(form, NEWT_KEY_ENTER); newtFormAddHotKey(form, NEWT_KEY_ESCAPE); newtFormAddHotKey(form, NEWT_KEY_LEFT); newtFormAddHotKey(form, CTRL('c')); newtFormRun(form, &es); if (result != NULL) { strncpy(bf, result, size); err = 0; } out_free_form: newtPopWindow(); newtFormDestroy(form); return err; } struct map_browser { struct ui_browser b; struct map *map; u8 addrlen; }; static void map_browser__write(struct ui_browser *self, void *nd, int row) { struct symbol *sym = rb_entry(nd, struct symbol, rb_node); struct map_browser *mb = container_of(self, struct map_browser, b); bool current_entry = ui_browser__is_current_entry(self, row); int width; ui_browser__set_percent_color(self, 0, current_entry); slsmg_printf("%*" PRIx64 " %*" PRIx64 " %c ", mb->addrlen, sym->start, mb->addrlen, sym->end, sym->binding == STB_GLOBAL ? 'g' : sym->binding == STB_LOCAL ? 'l' : 'w'); width = self->width - ((mb->addrlen * 2) + 4); if (width > 0) slsmg_write_nstring(sym->name, width); } /* FIXME uber-kludgy, see comment on cmd_report... */ static u32 *symbol__browser_index(struct symbol *self) { return ((void *)self) - sizeof(struct rb_node) - sizeof(u32); } static int map_browser__search(struct map_browser *self) { char target[512]; struct symbol *sym; int err = ui_entry__read("Search by name/addr", target, sizeof(target), 40); if (err) return err; if (target[0] == '0' && tolower(target[1]) == 'x') { u64 addr = strtoull(target, NULL, 16); sym = map__find_symbol(self->map, addr, NULL); } else sym = map__find_symbol_by_name(self->map, target, NULL); if (sym != NULL) { u32 *idx = symbol__browser_index(sym); self->b.top = &sym->rb_node; self->b.index = self->b.top_idx = *idx; } else ui_helpline__fpush("%s not found!", target); return 0; } static int map_browser__run(struct map_browser *self) { int key; if (ui_browser__show(&self->b, self->map->dso->long_name, "Press <- or ESC to exit, %s / to search", verbose ? "" : "restart with -v to use") < 0) return -1; while (1) { key = ui_browser__run(&self->b, 0); if (verbose && key == '/') map_browser__search(self); else break; } ui_browser__hide(&self->b); return key; } int map__browse(struct map *self) { struct map_browser mb = { .b = { .entries = &self->dso->symbols[self->type], .refresh = ui_browser__rb_tree_refresh, .seek = ui_browser__rb_tree_seek, .write = map_browser__write, }, .map = self, }; struct rb_node *nd; char tmp[BITS_PER_LONG / 4]; u64 maxaddr = 0; for (nd = rb_first(mb.b.entries); nd; nd = rb_next(nd)) { struct symbol *pos = rb_entry(nd, struct symbol, rb_node); if (maxaddr < pos->end) maxaddr = pos->end; if (verbose) { u32 *idx = symbol__browser_index(pos); *idx = mb.b.nr_entries; } ++mb.b.nr_entries; } mb.addrlen = snprintf(tmp, sizeof(tmp), "%" PRIx64, maxaddr); return map_browser__run(&mb); }
gpl-2.0
sub-b/android_kernel_samsung_matissewifi-old
drivers/i2c/busses/i2c-sh_mobile.c
5063
20493
/* * SuperH Mobile I2C Controller * * Copyright (C) 2008 Magnus Damm * * Portions of the code based on out-of-tree driver i2c-sh7343.c * Copyright (c) 2006 Carlos Munoz <carlos@kenati.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/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/err.h> #include <linux/pm_runtime.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/i2c/i2c-sh_mobile.h> /* Transmit operation: */ /* */ /* 0 byte transmit */ /* BUS: S A8 ACK P */ /* IRQ: DTE WAIT */ /* ICIC: */ /* ICCR: 0x94 0x90 */ /* ICDR: A8 */ /* */ /* 1 byte transmit */ /* BUS: S A8 ACK D8(1) ACK P */ /* IRQ: DTE WAIT WAIT */ /* ICIC: -DTE */ /* ICCR: 0x94 0x90 */ /* ICDR: A8 D8(1) */ /* */ /* 2 byte transmit */ /* BUS: S A8 ACK D8(1) ACK D8(2) ACK P */ /* IRQ: DTE WAIT WAIT WAIT */ /* ICIC: -DTE */ /* ICCR: 0x94 0x90 */ /* ICDR: A8 D8(1) D8(2) */ /* */ /* 3 bytes or more, +---------+ gets repeated */ /* */ /* */ /* Receive operation: */ /* */ /* 0 byte receive - not supported since slave may hold SDA low */ /* */ /* 1 byte receive [TX] | [RX] */ /* BUS: S A8 ACK | D8(1) ACK P */ /* IRQ: DTE WAIT | WAIT DTE */ /* ICIC: -DTE | +DTE */ /* ICCR: 0x94 0x81 | 0xc0 */ /* ICDR: A8 | D8(1) */ /* */ /* 2 byte receive [TX]| [RX] */ /* BUS: S A8 ACK | D8(1) ACK D8(2) ACK P */ /* IRQ: DTE WAIT | WAIT WAIT DTE */ /* ICIC: -DTE | +DTE */ /* ICCR: 0x94 0x81 | 0xc0 */ /* ICDR: A8 | D8(1) D8(2) */ /* */ /* 3 byte receive [TX] | [RX] */ /* BUS: S A8 ACK | D8(1) ACK D8(2) ACK D8(3) ACK P */ /* IRQ: DTE WAIT | WAIT WAIT WAIT DTE */ /* ICIC: -DTE | +DTE */ /* ICCR: 0x94 0x81 | 0xc0 */ /* ICDR: A8 | D8(1) D8(2) D8(3) */ /* */ /* 4 bytes or more, this part is repeated +---------+ */ /* */ /* */ /* Interrupt order and BUSY flag */ /* ___ _ */ /* SDA ___\___XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXAAAAAAAAA___/ */ /* SCL \_/1\_/2\_/3\_/4\_/5\_/6\_/7\_/8\___/9\_____/ */ /* */ /* S D7 D6 D5 D4 D3 D2 D1 D0 P */ /* ___ */ /* WAIT IRQ ________________________________/ \___________ */ /* TACK IRQ ____________________________________/ \_______ */ /* DTE IRQ __________________________________________/ \_ */ /* AL IRQ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ /* _______________________________________________ */ /* BUSY __/ \_ */ /* */ enum sh_mobile_i2c_op { OP_START = 0, OP_TX_FIRST, OP_TX, OP_TX_STOP, OP_TX_TO_RX, OP_RX, OP_RX_STOP, OP_RX_STOP_DATA, }; struct sh_mobile_i2c_data { struct device *dev; void __iomem *reg; struct i2c_adapter adap; unsigned long bus_speed; struct clk *clk; u_int8_t icic; u_int8_t iccl; u_int8_t icch; u_int8_t flags; spinlock_t lock; wait_queue_head_t wait; struct i2c_msg *msg; int pos; int sr; }; #define IIC_FLAG_HAS_ICIC67 (1 << 0) #define NORMAL_SPEED 100000 /* FAST_SPEED 400000 */ /* Register offsets */ #define ICDR 0x00 #define ICCR 0x04 #define ICSR 0x08 #define ICIC 0x0c #define ICCL 0x10 #define ICCH 0x14 /* Register bits */ #define ICCR_ICE 0x80 #define ICCR_RACK 0x40 #define ICCR_TRS 0x10 #define ICCR_BBSY 0x04 #define ICCR_SCP 0x01 #define ICSR_SCLM 0x80 #define ICSR_SDAM 0x40 #define SW_DONE 0x20 #define ICSR_BUSY 0x10 #define ICSR_AL 0x08 #define ICSR_TACK 0x04 #define ICSR_WAIT 0x02 #define ICSR_DTE 0x01 #define ICIC_ICCLB8 0x80 #define ICIC_ICCHB8 0x40 #define ICIC_ALE 0x08 #define ICIC_TACKE 0x04 #define ICIC_WAITE 0x02 #define ICIC_DTEE 0x01 static void iic_wr(struct sh_mobile_i2c_data *pd, int offs, unsigned char data) { if (offs == ICIC) data |= pd->icic; iowrite8(data, pd->reg + offs); } static unsigned char iic_rd(struct sh_mobile_i2c_data *pd, int offs) { return ioread8(pd->reg + offs); } static void iic_set_clr(struct sh_mobile_i2c_data *pd, int offs, unsigned char set, unsigned char clr) { iic_wr(pd, offs, (iic_rd(pd, offs) | set) & ~clr); } static void activate_ch(struct sh_mobile_i2c_data *pd) { unsigned long i2c_clk; u_int32_t num; u_int32_t denom; u_int32_t tmp; /* Wake up device and enable clock */ pm_runtime_get_sync(pd->dev); clk_enable(pd->clk); /* Get clock rate after clock is enabled */ i2c_clk = clk_get_rate(pd->clk); /* Calculate the value for iccl. From the data sheet: * iccl = (p clock / transfer rate) * (L / (L + H)) * where L and H are the SCL low/high ratio (5/4 in this case). * We also round off the result. */ num = i2c_clk * 5; denom = pd->bus_speed * 9; tmp = num * 10 / denom; if (tmp % 10 >= 5) pd->iccl = (u_int8_t)((num/denom) + 1); else pd->iccl = (u_int8_t)(num/denom); /* one more bit of ICCL in ICIC */ if (pd->flags & IIC_FLAG_HAS_ICIC67) { if ((num/denom) > 0xff) pd->icic |= ICIC_ICCLB8; else pd->icic &= ~ICIC_ICCLB8; } /* Calculate the value for icch. From the data sheet: icch = (p clock / transfer rate) * (H / (L + H)) */ num = i2c_clk * 4; tmp = num * 10 / denom; if (tmp % 10 >= 5) pd->icch = (u_int8_t)((num/denom) + 1); else pd->icch = (u_int8_t)(num/denom); /* one more bit of ICCH in ICIC */ if (pd->flags & IIC_FLAG_HAS_ICIC67) { if ((num/denom) > 0xff) pd->icic |= ICIC_ICCHB8; else pd->icic &= ~ICIC_ICCHB8; } /* Enable channel and configure rx ack */ iic_set_clr(pd, ICCR, ICCR_ICE, 0); /* Mask all interrupts */ iic_wr(pd, ICIC, 0); /* Set the clock */ iic_wr(pd, ICCL, pd->iccl); iic_wr(pd, ICCH, pd->icch); } static void deactivate_ch(struct sh_mobile_i2c_data *pd) { /* Clear/disable interrupts */ iic_wr(pd, ICSR, 0); iic_wr(pd, ICIC, 0); /* Disable channel */ iic_set_clr(pd, ICCR, 0, ICCR_ICE); /* Disable clock and mark device as idle */ clk_disable(pd->clk); pm_runtime_put_sync(pd->dev); } static unsigned char i2c_op(struct sh_mobile_i2c_data *pd, enum sh_mobile_i2c_op op, unsigned char data) { unsigned char ret = 0; unsigned long flags; dev_dbg(pd->dev, "op %d, data in 0x%02x\n", op, data); spin_lock_irqsave(&pd->lock, flags); switch (op) { case OP_START: /* issue start and trigger DTE interrupt */ iic_wr(pd, ICCR, 0x94); break; case OP_TX_FIRST: /* disable DTE interrupt and write data */ iic_wr(pd, ICIC, ICIC_WAITE | ICIC_ALE | ICIC_TACKE); iic_wr(pd, ICDR, data); break; case OP_TX: /* write data */ iic_wr(pd, ICDR, data); break; case OP_TX_STOP: /* write data and issue a stop afterwards */ iic_wr(pd, ICDR, data); iic_wr(pd, ICCR, 0x90); break; case OP_TX_TO_RX: /* select read mode */ iic_wr(pd, ICCR, 0x81); break; case OP_RX: /* just read data */ ret = iic_rd(pd, ICDR); break; case OP_RX_STOP: /* enable DTE interrupt, issue stop */ iic_wr(pd, ICIC, ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE); iic_wr(pd, ICCR, 0xc0); break; case OP_RX_STOP_DATA: /* enable DTE interrupt, read data, issue stop */ iic_wr(pd, ICIC, ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE); ret = iic_rd(pd, ICDR); iic_wr(pd, ICCR, 0xc0); break; } spin_unlock_irqrestore(&pd->lock, flags); dev_dbg(pd->dev, "op %d, data out 0x%02x\n", op, ret); return ret; } static int sh_mobile_i2c_is_first_byte(struct sh_mobile_i2c_data *pd) { if (pd->pos == -1) return 1; return 0; } static int sh_mobile_i2c_is_last_byte(struct sh_mobile_i2c_data *pd) { if (pd->pos == (pd->msg->len - 1)) return 1; return 0; } static void sh_mobile_i2c_get_data(struct sh_mobile_i2c_data *pd, unsigned char *buf) { switch (pd->pos) { case -1: *buf = (pd->msg->addr & 0x7f) << 1; *buf |= (pd->msg->flags & I2C_M_RD) ? 1 : 0; break; default: *buf = pd->msg->buf[pd->pos]; } } static int sh_mobile_i2c_isr_tx(struct sh_mobile_i2c_data *pd) { unsigned char data; if (pd->pos == pd->msg->len) return 1; sh_mobile_i2c_get_data(pd, &data); if (sh_mobile_i2c_is_last_byte(pd)) i2c_op(pd, OP_TX_STOP, data); else if (sh_mobile_i2c_is_first_byte(pd)) i2c_op(pd, OP_TX_FIRST, data); else i2c_op(pd, OP_TX, data); pd->pos++; return 0; } static int sh_mobile_i2c_isr_rx(struct sh_mobile_i2c_data *pd) { unsigned char data; int real_pos; do { if (pd->pos <= -1) { sh_mobile_i2c_get_data(pd, &data); if (sh_mobile_i2c_is_first_byte(pd)) i2c_op(pd, OP_TX_FIRST, data); else i2c_op(pd, OP_TX, data); break; } if (pd->pos == 0) { i2c_op(pd, OP_TX_TO_RX, 0); break; } real_pos = pd->pos - 2; if (pd->pos == pd->msg->len) { if (real_pos < 0) { i2c_op(pd, OP_RX_STOP, 0); break; } data = i2c_op(pd, OP_RX_STOP_DATA, 0); } else data = i2c_op(pd, OP_RX, 0); if (real_pos >= 0) pd->msg->buf[real_pos] = data; } while (0); pd->pos++; return pd->pos == (pd->msg->len + 2); } static irqreturn_t sh_mobile_i2c_isr(int irq, void *dev_id) { struct platform_device *dev = dev_id; struct sh_mobile_i2c_data *pd = platform_get_drvdata(dev); unsigned char sr; int wakeup; sr = iic_rd(pd, ICSR); pd->sr |= sr; /* remember state */ dev_dbg(pd->dev, "i2c_isr 0x%02x 0x%02x %s %d %d!\n", sr, pd->sr, (pd->msg->flags & I2C_M_RD) ? "read" : "write", pd->pos, pd->msg->len); if (sr & (ICSR_AL | ICSR_TACK)) { /* don't interrupt transaction - continue to issue stop */ iic_wr(pd, ICSR, sr & ~(ICSR_AL | ICSR_TACK)); wakeup = 0; } else if (pd->msg->flags & I2C_M_RD) wakeup = sh_mobile_i2c_isr_rx(pd); else wakeup = sh_mobile_i2c_isr_tx(pd); if (sr & ICSR_WAIT) /* TODO: add delay here to support slow acks */ iic_wr(pd, ICSR, sr & ~ICSR_WAIT); if (wakeup) { pd->sr |= SW_DONE; wake_up(&pd->wait); } return IRQ_HANDLED; } static int start_ch(struct sh_mobile_i2c_data *pd, struct i2c_msg *usr_msg) { if (usr_msg->len == 0 && (usr_msg->flags & I2C_M_RD)) { dev_err(pd->dev, "Unsupported zero length i2c read\n"); return -EIO; } /* Initialize channel registers */ iic_set_clr(pd, ICCR, 0, ICCR_ICE); /* Enable channel and configure rx ack */ iic_set_clr(pd, ICCR, ICCR_ICE, 0); /* Set the clock */ iic_wr(pd, ICCL, pd->iccl); iic_wr(pd, ICCH, pd->icch); pd->msg = usr_msg; pd->pos = -1; pd->sr = 0; /* Enable all interrupts to begin with */ iic_wr(pd, ICIC, ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE); return 0; } static int sh_mobile_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs, int num) { struct sh_mobile_i2c_data *pd = i2c_get_adapdata(adapter); struct i2c_msg *msg; int err = 0; u_int8_t val; int i, k, retry_count; activate_ch(pd); /* Process all messages */ for (i = 0; i < num; i++) { msg = &msgs[i]; err = start_ch(pd, msg); if (err) break; i2c_op(pd, OP_START, 0); /* The interrupt handler takes care of the rest... */ k = wait_event_timeout(pd->wait, pd->sr & (ICSR_TACK | SW_DONE), 5 * HZ); if (!k) dev_err(pd->dev, "Transfer request timed out\n"); retry_count = 1000; again: val = iic_rd(pd, ICSR); dev_dbg(pd->dev, "val 0x%02x pd->sr 0x%02x\n", val, pd->sr); /* the interrupt handler may wake us up before the * transfer is finished, so poll the hardware * until we're done. */ if (val & ICSR_BUSY) { udelay(10); if (retry_count--) goto again; err = -EIO; dev_err(pd->dev, "Polling timed out\n"); break; } /* handle missing acknowledge and arbitration lost */ if ((val | pd->sr) & (ICSR_TACK | ICSR_AL)) { err = -EIO; break; } } deactivate_ch(pd); if (!err) err = num; return err; } static u32 sh_mobile_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL; } static struct i2c_algorithm sh_mobile_i2c_algorithm = { .functionality = sh_mobile_i2c_func, .master_xfer = sh_mobile_i2c_xfer, }; static int sh_mobile_i2c_hook_irqs(struct platform_device *dev, int hook) { struct resource *res; int ret = -ENXIO; int n, k = 0; while ((res = platform_get_resource(dev, IORESOURCE_IRQ, k))) { for (n = res->start; hook && n <= res->end; n++) { if (request_irq(n, sh_mobile_i2c_isr, 0, dev_name(&dev->dev), dev)) { for (n--; n >= res->start; n--) free_irq(n, dev); goto rollback; } } k++; } if (hook) return k > 0 ? 0 : -ENOENT; ret = 0; rollback: k--; while (k >= 0) { res = platform_get_resource(dev, IORESOURCE_IRQ, k); for (n = res->start; n <= res->end; n++) free_irq(n, dev); k--; } return ret; } static int sh_mobile_i2c_probe(struct platform_device *dev) { struct i2c_sh_mobile_platform_data *pdata = dev->dev.platform_data; struct sh_mobile_i2c_data *pd; struct i2c_adapter *adap; struct resource *res; int size; int ret; pd = kzalloc(sizeof(struct sh_mobile_i2c_data), GFP_KERNEL); if (pd == NULL) { dev_err(&dev->dev, "cannot allocate private data\n"); return -ENOMEM; } pd->clk = clk_get(&dev->dev, NULL); if (IS_ERR(pd->clk)) { dev_err(&dev->dev, "cannot get clock\n"); ret = PTR_ERR(pd->clk); goto err; } ret = sh_mobile_i2c_hook_irqs(dev, 1); if (ret) { dev_err(&dev->dev, "cannot request IRQ\n"); goto err_clk; } pd->dev = &dev->dev; platform_set_drvdata(dev, pd); res = platform_get_resource(dev, IORESOURCE_MEM, 0); if (res == NULL) { dev_err(&dev->dev, "cannot find IO resource\n"); ret = -ENOENT; goto err_irq; } size = resource_size(res); pd->reg = ioremap(res->start, size); if (pd->reg == NULL) { dev_err(&dev->dev, "cannot map IO\n"); ret = -ENXIO; goto err_irq; } /* Use platformd data bus speed or NORMAL_SPEED */ pd->bus_speed = NORMAL_SPEED; if (pdata && pdata->bus_speed) pd->bus_speed = pdata->bus_speed; /* The IIC blocks on SH-Mobile ARM processors * come with two new bits in ICIC. */ if (size > 0x17) pd->flags |= IIC_FLAG_HAS_ICIC67; /* Enable Runtime PM for this device. * * Also tell the Runtime PM core to ignore children * for this device since it is valid for us to suspend * this I2C master driver even though the slave devices * on the I2C bus may not be suspended. * * The state of the I2C hardware bus is unaffected by * the Runtime PM state. */ pm_suspend_ignore_children(&dev->dev, true); pm_runtime_enable(&dev->dev); /* setup the private data */ adap = &pd->adap; i2c_set_adapdata(adap, pd); adap->owner = THIS_MODULE; adap->algo = &sh_mobile_i2c_algorithm; adap->dev.parent = &dev->dev; adap->retries = 5; adap->nr = dev->id; strlcpy(adap->name, dev->name, sizeof(adap->name)); spin_lock_init(&pd->lock); init_waitqueue_head(&pd->wait); ret = i2c_add_numbered_adapter(adap); if (ret < 0) { dev_err(&dev->dev, "cannot add numbered adapter\n"); goto err_all; } dev_info(&dev->dev, "I2C adapter %d with bus speed %lu Hz\n", adap->nr, pd->bus_speed); return 0; err_all: iounmap(pd->reg); err_irq: sh_mobile_i2c_hook_irqs(dev, 0); err_clk: clk_put(pd->clk); err: kfree(pd); return ret; } static int sh_mobile_i2c_remove(struct platform_device *dev) { struct sh_mobile_i2c_data *pd = platform_get_drvdata(dev); i2c_del_adapter(&pd->adap); iounmap(pd->reg); sh_mobile_i2c_hook_irqs(dev, 0); clk_put(pd->clk); pm_runtime_disable(&dev->dev); kfree(pd); return 0; } static int sh_mobile_i2c_runtime_nop(struct device *dev) { /* Runtime PM callback shared between ->runtime_suspend() * and ->runtime_resume(). Simply returns success. * * This driver re-initializes all registers after * pm_runtime_get_sync() anyway so there is no need * to save and restore registers here. */ return 0; } static const struct dev_pm_ops sh_mobile_i2c_dev_pm_ops = { .runtime_suspend = sh_mobile_i2c_runtime_nop, .runtime_resume = sh_mobile_i2c_runtime_nop, }; static struct platform_driver sh_mobile_i2c_driver = { .driver = { .name = "i2c-sh_mobile", .owner = THIS_MODULE, .pm = &sh_mobile_i2c_dev_pm_ops, }, .probe = sh_mobile_i2c_probe, .remove = sh_mobile_i2c_remove, }; static int __init sh_mobile_i2c_adap_init(void) { return platform_driver_register(&sh_mobile_i2c_driver); } static void __exit sh_mobile_i2c_adap_exit(void) { platform_driver_unregister(&sh_mobile_i2c_driver); } subsys_initcall(sh_mobile_i2c_adap_init); module_exit(sh_mobile_i2c_adap_exit); MODULE_DESCRIPTION("SuperH Mobile I2C Bus Controller driver"); MODULE_AUTHOR("Magnus Damm"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:i2c-sh_mobile");
gpl-2.0
yank555-lu/N3-AOSP-KK
drivers/mfd/pcf50633-adc.c
5063
6062
/* NXP PCF50633 ADC Driver * * (C) 2006-2008 by Openmoko, Inc. * Author: Balaji Rao <balajirrao@openmoko.org> * All rights reserved. * * Broken down from monstrous PCF50633 driver mainly by * Harald Welte, Andy Green and Werner Almesberger * * 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. * * NOTE: This driver does not yet support subtractive ADC mode, which means * you can do only one measurement per read request. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/completion.h> #include <linux/mfd/pcf50633/core.h> #include <linux/mfd/pcf50633/adc.h> struct pcf50633_adc_request { int mux; int avg; void (*callback)(struct pcf50633 *, void *, int); void *callback_param; }; struct pcf50633_adc_sync_request { int result; struct completion completion; }; #define PCF50633_MAX_ADC_FIFO_DEPTH 8 struct pcf50633_adc { struct pcf50633 *pcf; /* Private stuff */ struct pcf50633_adc_request *queue[PCF50633_MAX_ADC_FIFO_DEPTH]; int queue_head; int queue_tail; struct mutex queue_mutex; }; static inline struct pcf50633_adc *__to_adc(struct pcf50633 *pcf) { return platform_get_drvdata(pcf->adc_pdev); } static void adc_setup(struct pcf50633 *pcf, int channel, int avg) { channel &= PCF50633_ADCC1_ADCMUX_MASK; /* kill ratiometric, but enable ACCSW biasing */ pcf50633_reg_write(pcf, PCF50633_REG_ADCC2, 0x00); pcf50633_reg_write(pcf, PCF50633_REG_ADCC3, 0x01); /* start ADC conversion on selected channel */ pcf50633_reg_write(pcf, PCF50633_REG_ADCC1, channel | avg | PCF50633_ADCC1_ADCSTART | PCF50633_ADCC1_RES_10BIT); } static void trigger_next_adc_job_if_any(struct pcf50633 *pcf) { struct pcf50633_adc *adc = __to_adc(pcf); int head; head = adc->queue_head; if (!adc->queue[head]) return; adc_setup(pcf, adc->queue[head]->mux, adc->queue[head]->avg); } static int adc_enqueue_request(struct pcf50633 *pcf, struct pcf50633_adc_request *req) { struct pcf50633_adc *adc = __to_adc(pcf); int head, tail; mutex_lock(&adc->queue_mutex); head = adc->queue_head; tail = adc->queue_tail; if (adc->queue[tail]) { mutex_unlock(&adc->queue_mutex); dev_err(pcf->dev, "ADC queue is full, dropping request\n"); return -EBUSY; } adc->queue[tail] = req; if (head == tail) trigger_next_adc_job_if_any(pcf); adc->queue_tail = (tail + 1) & (PCF50633_MAX_ADC_FIFO_DEPTH - 1); mutex_unlock(&adc->queue_mutex); return 0; } static void pcf50633_adc_sync_read_callback(struct pcf50633 *pcf, void *param, int result) { struct pcf50633_adc_sync_request *req = param; req->result = result; complete(&req->completion); } int pcf50633_adc_sync_read(struct pcf50633 *pcf, int mux, int avg) { struct pcf50633_adc_sync_request req; int ret; init_completion(&req.completion); ret = pcf50633_adc_async_read(pcf, mux, avg, pcf50633_adc_sync_read_callback, &req); if (ret) return ret; wait_for_completion(&req.completion); return req.result; } EXPORT_SYMBOL_GPL(pcf50633_adc_sync_read); int pcf50633_adc_async_read(struct pcf50633 *pcf, int mux, int avg, void (*callback)(struct pcf50633 *, void *, int), void *callback_param) { struct pcf50633_adc_request *req; /* req is freed when the result is ready, in interrupt handler */ req = kmalloc(sizeof(*req), GFP_KERNEL); if (!req) return -ENOMEM; req->mux = mux; req->avg = avg; req->callback = callback; req->callback_param = callback_param; return adc_enqueue_request(pcf, req); } EXPORT_SYMBOL_GPL(pcf50633_adc_async_read); static int adc_result(struct pcf50633 *pcf) { u8 adcs1, adcs3; u16 result; adcs1 = pcf50633_reg_read(pcf, PCF50633_REG_ADCS1); adcs3 = pcf50633_reg_read(pcf, PCF50633_REG_ADCS3); result = (adcs1 << 2) | (adcs3 & PCF50633_ADCS3_ADCDAT1L_MASK); dev_dbg(pcf->dev, "adc result = %d\n", result); return result; } static void pcf50633_adc_irq(int irq, void *data) { struct pcf50633_adc *adc = data; struct pcf50633 *pcf = adc->pcf; struct pcf50633_adc_request *req; int head, res; mutex_lock(&adc->queue_mutex); head = adc->queue_head; req = adc->queue[head]; if (WARN_ON(!req)) { dev_err(pcf->dev, "pcf50633-adc irq: ADC queue empty!\n"); mutex_unlock(&adc->queue_mutex); return; } adc->queue[head] = NULL; adc->queue_head = (head + 1) & (PCF50633_MAX_ADC_FIFO_DEPTH - 1); res = adc_result(pcf); trigger_next_adc_job_if_any(pcf); mutex_unlock(&adc->queue_mutex); req->callback(pcf, req->callback_param, res); kfree(req); } static int __devinit pcf50633_adc_probe(struct platform_device *pdev) { struct pcf50633_adc *adc; adc = kzalloc(sizeof(*adc), GFP_KERNEL); if (!adc) return -ENOMEM; adc->pcf = dev_to_pcf50633(pdev->dev.parent); platform_set_drvdata(pdev, adc); pcf50633_register_irq(adc->pcf, PCF50633_IRQ_ADCRDY, pcf50633_adc_irq, adc); mutex_init(&adc->queue_mutex); return 0; } static int __devexit pcf50633_adc_remove(struct platform_device *pdev) { struct pcf50633_adc *adc = platform_get_drvdata(pdev); int i, head; pcf50633_free_irq(adc->pcf, PCF50633_IRQ_ADCRDY); mutex_lock(&adc->queue_mutex); head = adc->queue_head; if (WARN_ON(adc->queue[head])) dev_err(adc->pcf->dev, "adc driver removed with request pending\n"); for (i = 0; i < PCF50633_MAX_ADC_FIFO_DEPTH; i++) kfree(adc->queue[i]); mutex_unlock(&adc->queue_mutex); kfree(adc); return 0; } static struct platform_driver pcf50633_adc_driver = { .driver = { .name = "pcf50633-adc", }, .probe = pcf50633_adc_probe, .remove = __devexit_p(pcf50633_adc_remove), }; module_platform_driver(pcf50633_adc_driver); MODULE_AUTHOR("Balaji Rao <balajirrao@openmoko.org>"); MODULE_DESCRIPTION("PCF50633 adc driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:pcf50633-adc");
gpl-2.0
kozmikkick/tripndroid-endeavoru-3.5.7
arch/arm/mach-omap2/clock_common_data.c
7879
1378
/* * linux/arch/arm/mach-omap2/clock_common_data.c * * Copyright (C) 2005-2009 Texas Instruments, Inc. * Copyright (C) 2004-2009 Nokia Corporation * * Contacts: * Richard Woodruff <r-woodruff2@ti.com> * Paul Walmsley * * 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 file contains clock data that is common to both the OMAP2xxx and * OMAP3xxx clock definition files. */ #include "clock.h" /* clksel_rate data common to 24xx/343x */ const struct clksel_rate gpt_32k_rates[] = { { .div = 1, .val = 0, .flags = RATE_IN_24XX | RATE_IN_3XXX }, { .div = 0 } }; const struct clksel_rate gpt_sys_rates[] = { { .div = 1, .val = 1, .flags = RATE_IN_24XX | RATE_IN_3XXX }, { .div = 0 } }; const struct clksel_rate gfx_l3_rates[] = { { .div = 1, .val = 1, .flags = RATE_IN_24XX | RATE_IN_3XXX }, { .div = 2, .val = 2, .flags = RATE_IN_24XX | RATE_IN_3XXX }, { .div = 3, .val = 3, .flags = RATE_IN_243X | RATE_IN_3XXX }, { .div = 4, .val = 4, .flags = RATE_IN_243X | RATE_IN_3XXX }, { .div = 0 } }; const struct clksel_rate dsp_ick_rates[] = { { .div = 1, .val = 1, .flags = RATE_IN_24XX }, { .div = 2, .val = 2, .flags = RATE_IN_24XX }, { .div = 3, .val = 3, .flags = RATE_IN_243X }, { .div = 0 }, };
gpl-2.0
mightysween/vs980-kernel
arch/avr32/boards/atngw100/mrmt.c
9671
10132
/* * Board-specific setup code for Remote Media Terminal 1 (RMT1) * add-on board for the ATNGW100 Network Gateway * * Copyright (C) 2008 Mediama Technologies * Based on ATNGW100 Network Gateway (Copyright (C) Atmel) * * 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/gpio.h> #include <linux/init.h> #include <linux/irq.h> #include <linux/linkage.h> #include <linux/platform_device.h> #include <linux/types.h> #include <linux/fb.h> #include <linux/leds.h> #include <linux/input.h> #include <linux/gpio_keys.h> #include <linux/atmel_serial.h> #include <linux/spi/spi.h> #include <linux/spi/ads7846.h> #include <video/atmel_lcdc.h> #include <sound/atmel-ac97c.h> #include <asm/delay.h> #include <asm/io.h> #include <asm/setup.h> #include <mach/at32ap700x.h> #include <mach/board.h> #include <mach/init.h> #include <mach/portmux.h> /* Define board-specifoic GPIO assignments */ #define PIN_LCD_BL GPIO_PIN_PA(28) #define PWM_CH_BL 0 /* Must match with GPIO pin definition */ #define PIN_LCD_DISP GPIO_PIN_PA(31) #define PIN_AC97_RST_N GPIO_PIN_PA(30) #define PB_EXTINT_BASE 25 #define TS_IRQ 0 #define PIN_TS_EXTINT GPIO_PIN_PB(PB_EXTINT_BASE+TS_IRQ) #define PIN_PB_LEFT GPIO_PIN_PB(11) #define PIN_PB_RIGHT GPIO_PIN_PB(12) #define PIN_PWR_SW_N GPIO_PIN_PB(14) #define PIN_PWR_ON GPIO_PIN_PB(13) #define PIN_ZB_RST_N GPIO_PIN_PA(21) #define PIN_BT_RST GPIO_PIN_PA(22) #define PIN_LED_SYS GPIO_PIN_PA(16) #define PIN_LED_A GPIO_PIN_PA(19) #define PIN_LED_B GPIO_PIN_PE(19) #ifdef CONFIG_BOARD_MRMT_LCD_LQ043T3DX0X /* Sharp LQ043T3DX0x (or compatible) panel */ static struct fb_videomode __initdata lcd_fb_modes[] = { { .name = "480x272 @ 59.94Hz", .refresh = 59.94, .xres = 480, .yres = 272, .pixclock = KHZ2PICOS(9000), .left_margin = 2, .right_margin = 2, .upper_margin = 3, .lower_margin = 9, .hsync_len = 41, .vsync_len = 1, .sync = 0, .vmode = FB_VMODE_NONINTERLACED, }, }; static struct fb_monspecs __initdata lcd_fb_default_monspecs = { .manufacturer = "SHA", .monitor = "LQ043T3DX02", .modedb = lcd_fb_modes, .modedb_len = ARRAY_SIZE(lcd_fb_modes), .hfmin = 14915, .hfmax = 17638, .vfmin = 53, .vfmax = 61, .dclkmax = 9260000, }; static struct atmel_lcdfb_info __initdata rmt_lcdc_data = { .default_bpp = 24, .default_dmacon = ATMEL_LCDC_DMAEN | ATMEL_LCDC_DMA2DEN, .default_lcdcon2 = (ATMEL_LCDC_DISTYPE_TFT | ATMEL_LCDC_CLKMOD_ALWAYSACTIVE | ATMEL_LCDC_INVCLK_NORMAL | ATMEL_LCDC_MEMOR_BIG), .lcd_wiring_mode = ATMEL_LCDC_WIRING_RGB, .default_monspecs = &lcd_fb_default_monspecs, .guard_time = 2, }; #endif #ifdef CONFIG_BOARD_MRMT_LCD_KWH043GM08 /* Sharp KWH043GM08-Fxx (or compatible) panel */ static struct fb_videomode __initdata lcd_fb_modes[] = { { .name = "480x272 @ 59.94Hz", .refresh = 59.94, .xres = 480, .yres = 272, .pixclock = KHZ2PICOS(9000), .left_margin = 2, .right_margin = 2, .upper_margin = 3, .lower_margin = 9, .hsync_len = 41, .vsync_len = 1, .sync = 0, .vmode = FB_VMODE_NONINTERLACED, }, }; static struct fb_monspecs __initdata lcd_fb_default_monspecs = { .manufacturer = "FOR", .monitor = "KWH043GM08", .modedb = lcd_fb_modes, .modedb_len = ARRAY_SIZE(lcd_fb_modes), .hfmin = 14915, .hfmax = 17638, .vfmin = 53, .vfmax = 61, .dclkmax = 9260000, }; static struct atmel_lcdfb_info __initdata rmt_lcdc_data = { .default_bpp = 24, .default_dmacon = ATMEL_LCDC_DMAEN | ATMEL_LCDC_DMA2DEN, .default_lcdcon2 = (ATMEL_LCDC_DISTYPE_TFT | ATMEL_LCDC_CLKMOD_ALWAYSACTIVE | ATMEL_LCDC_INVCLK_INVERTED | ATMEL_LCDC_MEMOR_BIG), .lcd_wiring_mode = ATMEL_LCDC_WIRING_RGB, .default_monspecs = &lcd_fb_default_monspecs, .guard_time = 2, }; #endif #ifdef CONFIG_BOARD_MRMT_AC97 static struct ac97c_platform_data __initdata ac97c0_data = { .reset_pin = PIN_AC97_RST_N, }; #endif #ifdef CONFIG_BOARD_MRMT_UCB1400_TS /* NOTE: IRQ assignment relies on kernel module parameter */ static struct platform_device rmt_ts_device = { .name = "ucb1400_ts", .id = -1, } }; #endif #ifdef CONFIG_BOARD_MRMT_BL_PWM /* PWM LEDs: LCD Backlight, etc */ static struct gpio_led rmt_pwm_led[] = { /* here the "gpio" is actually a PWM channel */ { .name = "backlight", .gpio = PWM_CH_BL, }, }; static struct gpio_led_platform_data rmt_pwm_led_data = { .num_leds = ARRAY_SIZE(rmt_pwm_led), .leds = rmt_pwm_led, }; static struct platform_device rmt_pwm_led_dev = { .name = "leds-atmel-pwm", .id = -1, .dev = { .platform_data = &rmt_pwm_led_data, }, }; #endif #ifdef CONFIG_BOARD_MRMT_ADS7846_TS static int ads7846_pendown_state(void) { return !gpio_get_value( PIN_TS_EXTINT ); /* PENIRQ.*/ } static struct ads7846_platform_data ads_info = { .model = 7846, .keep_vref_on = 0, /* Use external VREF pin */ .vref_delay_usecs = 0, .vref_mv = 3300, /* VREF = 3.3V */ .settle_delay_usecs = 800, .penirq_recheck_delay_usecs = 800, .x_plate_ohms = 750, .y_plate_ohms = 300, .pressure_max = 4096, .debounce_max = 1, .debounce_rep = 0, .debounce_tol = (~0), .get_pendown_state = ads7846_pendown_state, .filter = NULL, .filter_init = NULL, }; static struct spi_board_info spi01_board_info[] __initdata = { { .modalias = "ads7846", .max_speed_hz = 31250*26, .bus_num = 0, .chip_select = 1, .platform_data = &ads_info, .irq = AT32_EXTINT(TS_IRQ), }, }; #endif /* GPIO Keys: left, right, power, etc */ static const struct gpio_keys_button rmt_gpio_keys_buttons[] = { [0] = { .type = EV_KEY, .code = KEY_POWER, .gpio = PIN_PWR_SW_N, .active_low = 1, .desc = "power button", }, [1] = { .type = EV_KEY, .code = KEY_LEFT, .gpio = PIN_PB_LEFT, .active_low = 1, .desc = "left button", }, [2] = { .type = EV_KEY, .code = KEY_RIGHT, .gpio = PIN_PB_RIGHT, .active_low = 1, .desc = "right button", }, }; static const struct gpio_keys_platform_data rmt_gpio_keys_data = { .nbuttons = ARRAY_SIZE(rmt_gpio_keys_buttons), .buttons = (void *) rmt_gpio_keys_buttons, }; static struct platform_device rmt_gpio_keys = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = (void *) &rmt_gpio_keys_data, } }; #ifdef CONFIG_BOARD_MRMT_RTC_I2C static struct i2c_board_info __initdata mrmt1_i2c_rtc = { I2C_BOARD_INFO("s35390a", 0x30), .irq = 0, }; #endif static void mrmt_power_off(void) { /* PWR_ON=0 will force power off */ gpio_set_value( PIN_PWR_ON, 0 ); } static int __init mrmt1_init(void) { gpio_set_value( PIN_PWR_ON, 1 ); /* Ensure PWR_ON is enabled */ pm_power_off = mrmt_power_off; /* Setup USARTS (other than console) */ at32_map_usart(2, 1, 0); /* USART 2: /dev/ttyS1, RMT1:DB9M */ at32_map_usart(3, 2, ATMEL_USART_RTS | ATMEL_USART_CTS); /* USART 3: /dev/ttyS2, RMT1:Wireless, w/ RTS/CTS */ at32_add_device_usart(1); at32_add_device_usart(2); /* Select GPIO Key pins */ at32_select_gpio( PIN_PWR_SW_N, AT32_GPIOF_DEGLITCH); at32_select_gpio( PIN_PB_LEFT, AT32_GPIOF_DEGLITCH); at32_select_gpio( PIN_PB_RIGHT, AT32_GPIOF_DEGLITCH); platform_device_register(&rmt_gpio_keys); #ifdef CONFIG_BOARD_MRMT_RTC_I2C i2c_register_board_info(0, &mrmt1_i2c_rtc, 1); #endif #ifndef CONFIG_BOARD_MRMT_LCD_DISABLE /* User "alternate" LCDC inferface on Port E & D */ /* NB: exclude LCDC_CC pin, as NGW100 reserves it for other use */ at32_add_device_lcdc(0, &rmt_lcdc_data, fbmem_start, fbmem_size, (ATMEL_LCDC_ALT_24BIT | ATMEL_LCDC_PE_DVAL ) ); #endif #ifdef CONFIG_BOARD_MRMT_AC97 at32_add_device_ac97c(0, &ac97c0_data, AC97C_BOTH); #endif #ifdef CONFIG_BOARD_MRMT_ADS7846_TS /* Select the Touchscreen interrupt pin mode */ at32_select_periph( GPIO_PIOB_BASE, 1 << (PB_EXTINT_BASE+TS_IRQ), GPIO_PERIPH_A, AT32_GPIOF_DEGLITCH); irq_set_irq_type(AT32_EXTINT(TS_IRQ), IRQ_TYPE_EDGE_FALLING); at32_spi_setup_slaves(0,spi01_board_info,ARRAY_SIZE(spi01_board_info)); spi_register_board_info(spi01_board_info,ARRAY_SIZE(spi01_board_info)); #endif #ifdef CONFIG_BOARD_MRMT_UCB1400_TS /* Select the Touchscreen interrupt pin mode */ at32_select_periph( GPIO_PIOB_BASE, 1 << (PB_EXTINT_BASE+TS_IRQ), GPIO_PERIPH_A, AT32_GPIOF_DEGLITCH); platform_device_register(&rmt_ts_device); #endif at32_select_gpio( PIN_LCD_DISP, AT32_GPIOF_OUTPUT ); gpio_request( PIN_LCD_DISP, "LCD_DISP" ); gpio_direction_output( PIN_LCD_DISP, 0 ); /* LCD DISP */ #ifdef CONFIG_BOARD_MRMT_LCD_DISABLE /* Keep Backlight and DISP off */ at32_select_gpio( PIN_LCD_BL, AT32_GPIOF_OUTPUT ); gpio_request( PIN_LCD_BL, "LCD_BL" ); gpio_direction_output( PIN_LCD_BL, 0 ); /* Backlight */ #else gpio_set_value( PIN_LCD_DISP, 1 ); /* DISP asserted first */ #ifdef CONFIG_BOARD_MRMT_BL_PWM /* Use PWM for Backlight controls */ at32_add_device_pwm(1 << PWM_CH_BL); platform_device_register(&rmt_pwm_led_dev); #else /* Backlight always on */ udelay( 1 ); at32_select_gpio( PIN_LCD_BL, AT32_GPIOF_OUTPUT ); gpio_request( PIN_LCD_BL, "LCD_BL" ); gpio_direction_output( PIN_LCD_BL, 1 ); #endif #endif /* Make sure BT and Zigbee modules in reset */ at32_select_gpio( PIN_BT_RST, AT32_GPIOF_OUTPUT ); gpio_request( PIN_BT_RST, "BT_RST" ); gpio_direction_output( PIN_BT_RST, 1 ); /* BT Module in Reset */ at32_select_gpio( PIN_ZB_RST_N, AT32_GPIOF_OUTPUT ); gpio_request( PIN_ZB_RST_N, "ZB_RST_N" ); gpio_direction_output( PIN_ZB_RST_N, 0 ); /* XBee Module in Reset */ #ifdef CONFIG_BOARD_MRMT_WIRELESS_ZB udelay( 1000 ); /* Unreset the XBee Module */ gpio_set_value( PIN_ZB_RST_N, 1 ); #endif #ifdef CONFIG_BOARD_MRMT_WIRELESS_BT udelay( 1000 ); /* Unreset the BT Module */ gpio_set_value( PIN_BT_RST, 0 ); #endif return 0; } arch_initcall(mrmt1_init); static int __init mrmt1_early_init(void) { /* To maintain power-on signal in case boot loader did not already */ at32_select_gpio( PIN_PWR_ON, AT32_GPIOF_OUTPUT ); gpio_request( PIN_PWR_ON, "PIN_PWR_ON" ); gpio_direction_output( PIN_PWR_ON, 1 ); return 0; } core_initcall(mrmt1_early_init);
gpl-2.0
adwaitnd/Kronux
drivers/video/fbdev/nvidia/nv_accel.c
14535
12525
/***************************************************************************\ |* *| |* Copyright 1993-2003 NVIDIA, Corporation. All rights reserved. *| |* *| |* NOTICE TO USER: The source code is copyrighted under U.S. and *| |* international laws. Users and possessors of this source code are *| |* hereby granted a nonexclusive, royalty-free copyright license to *| |* use this code in individual and commercial software. *| |* *| |* Any use of this source code must include, in the user documenta- *| |* tion and internal comments to the code, notices to the end user *| |* as follows: *| |* *| |* Copyright 1993-2003 NVIDIA, Corporation. All rights reserved. *| |* *| |* NVIDIA, CORPORATION MAKES NO REPRESENTATION ABOUT THE SUITABILITY *| |* OF THIS SOURCE CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" *| |* WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. NVIDIA, CORPOR- *| |* ATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOURCE CODE, *| |* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGE- *| |* MENT, AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL *| |* NVIDIA, CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT, INCI- *| |* DENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RE- *| |* SULTING 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 SOURCE CODE. *| |* *| |* U.S. Government End Users. This source code is a "commercial *| |* item," as that term is defined at 48 C.F.R. 2.101 (OCT 1995), *| |* consisting of "commercial computer software" and "commercial *| |* computer software documentation," as such terms are used in *| |* 48 C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Govern- *| |* ment only as a commercial end item. Consistent with 48 C.F.R. *| |* 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), *| |* all U.S. Government End Users acquire the source code with only *| |* those rights set forth herein. *| |* *| \***************************************************************************/ /* * GPL Licensing Note - According to Mark Vojkovich, author of the Xorg/ * XFree86 'nv' driver, this source code is provided under MIT-style licensing * where the source code is provided "as is" without warranty of any kind. * The only usage restriction is for the copyright notices to be retained * whenever code is used. * * Antonino Daplas <adaplas@pol.net> 2005-03-11 */ #include <linux/fb.h> #include "nv_type.h" #include "nv_proto.h" #include "nv_dma.h" #include "nv_local.h" /* There is a HW race condition with videoram command buffers. You can't jump to the location of your put offset. We write put at the jump offset + SKIPS dwords with noop padding in between to solve this problem */ #define SKIPS 8 static const int NVCopyROP[16] = { 0xCC, /* copy */ 0x55 /* invert */ }; static const int NVCopyROP_PM[16] = { 0xCA, /* copy */ 0x5A, /* invert */ }; static inline void nvidiafb_safe_mode(struct fb_info *info) { struct nvidia_par *par = info->par; touch_softlockup_watchdog(); info->pixmap.scan_align = 1; par->lockup = 1; } static inline void NVFlush(struct fb_info *info) { struct nvidia_par *par = info->par; int count = 1000000000; while (--count && READ_GET(par) != par->dmaPut) ; if (!count) { printk("nvidiafb: DMA Flush lockup\n"); nvidiafb_safe_mode(info); } } static inline void NVSync(struct fb_info *info) { struct nvidia_par *par = info->par; int count = 1000000000; while (--count && NV_RD32(par->PGRAPH, 0x0700)) ; if (!count) { printk("nvidiafb: DMA Sync lockup\n"); nvidiafb_safe_mode(info); } } static void NVDmaKickoff(struct nvidia_par *par) { if (par->dmaCurrent != par->dmaPut) { par->dmaPut = par->dmaCurrent; WRITE_PUT(par, par->dmaPut); } } static void NVDmaWait(struct fb_info *info, int size) { struct nvidia_par *par = info->par; int dmaGet; int count = 1000000000, cnt; size++; while (par->dmaFree < size && --count && !par->lockup) { dmaGet = READ_GET(par); if (par->dmaPut >= dmaGet) { par->dmaFree = par->dmaMax - par->dmaCurrent; if (par->dmaFree < size) { NVDmaNext(par, 0x20000000); if (dmaGet <= SKIPS) { if (par->dmaPut <= SKIPS) WRITE_PUT(par, SKIPS + 1); cnt = 1000000000; do { dmaGet = READ_GET(par); } while (--cnt && dmaGet <= SKIPS); if (!cnt) { printk("DMA Get lockup\n"); par->lockup = 1; } } WRITE_PUT(par, SKIPS); par->dmaCurrent = par->dmaPut = SKIPS; par->dmaFree = dmaGet - (SKIPS + 1); } } else par->dmaFree = dmaGet - par->dmaCurrent - 1; } if (!count) { printk("nvidiafb: DMA Wait Lockup\n"); nvidiafb_safe_mode(info); } } static void NVSetPattern(struct fb_info *info, u32 clr0, u32 clr1, u32 pat0, u32 pat1) { struct nvidia_par *par = info->par; NVDmaStart(info, par, PATTERN_COLOR_0, 4); NVDmaNext(par, clr0); NVDmaNext(par, clr1); NVDmaNext(par, pat0); NVDmaNext(par, pat1); } static void NVSetRopSolid(struct fb_info *info, u32 rop, u32 planemask) { struct nvidia_par *par = info->par; if (planemask != ~0) { NVSetPattern(info, 0, planemask, ~0, ~0); if (par->currentRop != (rop + 32)) { NVDmaStart(info, par, ROP_SET, 1); NVDmaNext(par, NVCopyROP_PM[rop]); par->currentRop = rop + 32; } } else if (par->currentRop != rop) { if (par->currentRop >= 16) NVSetPattern(info, ~0, ~0, ~0, ~0); NVDmaStart(info, par, ROP_SET, 1); NVDmaNext(par, NVCopyROP[rop]); par->currentRop = rop; } } static void NVSetClippingRectangle(struct fb_info *info, int x1, int y1, int x2, int y2) { struct nvidia_par *par = info->par; int h = y2 - y1 + 1; int w = x2 - x1 + 1; NVDmaStart(info, par, CLIP_POINT, 2); NVDmaNext(par, (y1 << 16) | x1); NVDmaNext(par, (h << 16) | w); } void NVResetGraphics(struct fb_info *info) { struct nvidia_par *par = info->par; u32 surfaceFormat, patternFormat, rectFormat, lineFormat; int pitch, i; pitch = info->fix.line_length; par->dmaBase = (u32 __iomem *) (&par->FbStart[par->FbUsableSize]); for (i = 0; i < SKIPS; i++) NV_WR32(&par->dmaBase[i], 0, 0x00000000); NV_WR32(&par->dmaBase[0x0 + SKIPS], 0, 0x00040000); NV_WR32(&par->dmaBase[0x1 + SKIPS], 0, 0x80000010); NV_WR32(&par->dmaBase[0x2 + SKIPS], 0, 0x00042000); NV_WR32(&par->dmaBase[0x3 + SKIPS], 0, 0x80000011); NV_WR32(&par->dmaBase[0x4 + SKIPS], 0, 0x00044000); NV_WR32(&par->dmaBase[0x5 + SKIPS], 0, 0x80000012); NV_WR32(&par->dmaBase[0x6 + SKIPS], 0, 0x00046000); NV_WR32(&par->dmaBase[0x7 + SKIPS], 0, 0x80000013); NV_WR32(&par->dmaBase[0x8 + SKIPS], 0, 0x00048000); NV_WR32(&par->dmaBase[0x9 + SKIPS], 0, 0x80000014); NV_WR32(&par->dmaBase[0xA + SKIPS], 0, 0x0004A000); NV_WR32(&par->dmaBase[0xB + SKIPS], 0, 0x80000015); NV_WR32(&par->dmaBase[0xC + SKIPS], 0, 0x0004C000); NV_WR32(&par->dmaBase[0xD + SKIPS], 0, 0x80000016); NV_WR32(&par->dmaBase[0xE + SKIPS], 0, 0x0004E000); NV_WR32(&par->dmaBase[0xF + SKIPS], 0, 0x80000017); par->dmaPut = 0; par->dmaCurrent = 16 + SKIPS; par->dmaMax = 8191; par->dmaFree = par->dmaMax - par->dmaCurrent; switch (info->var.bits_per_pixel) { case 32: case 24: surfaceFormat = SURFACE_FORMAT_DEPTH24; patternFormat = PATTERN_FORMAT_DEPTH24; rectFormat = RECT_FORMAT_DEPTH24; lineFormat = LINE_FORMAT_DEPTH24; break; case 16: surfaceFormat = SURFACE_FORMAT_DEPTH16; patternFormat = PATTERN_FORMAT_DEPTH16; rectFormat = RECT_FORMAT_DEPTH16; lineFormat = LINE_FORMAT_DEPTH16; break; default: surfaceFormat = SURFACE_FORMAT_DEPTH8; patternFormat = PATTERN_FORMAT_DEPTH8; rectFormat = RECT_FORMAT_DEPTH8; lineFormat = LINE_FORMAT_DEPTH8; break; } NVDmaStart(info, par, SURFACE_FORMAT, 4); NVDmaNext(par, surfaceFormat); NVDmaNext(par, pitch | (pitch << 16)); NVDmaNext(par, 0); NVDmaNext(par, 0); NVDmaStart(info, par, PATTERN_FORMAT, 1); NVDmaNext(par, patternFormat); NVDmaStart(info, par, RECT_FORMAT, 1); NVDmaNext(par, rectFormat); NVDmaStart(info, par, LINE_FORMAT, 1); NVDmaNext(par, lineFormat); par->currentRop = ~0; /* set to something invalid */ NVSetRopSolid(info, ROP_COPY, ~0); NVSetClippingRectangle(info, 0, 0, info->var.xres_virtual, info->var.yres_virtual); NVDmaKickoff(par); } int nvidiafb_sync(struct fb_info *info) { struct nvidia_par *par = info->par; if (info->state != FBINFO_STATE_RUNNING) return 0; if (!par->lockup) NVFlush(info); if (!par->lockup) NVSync(info); return 0; } void nvidiafb_copyarea(struct fb_info *info, const struct fb_copyarea *region) { struct nvidia_par *par = info->par; if (info->state != FBINFO_STATE_RUNNING) return; if (par->lockup) { cfb_copyarea(info, region); return; } NVDmaStart(info, par, BLIT_POINT_SRC, 3); NVDmaNext(par, (region->sy << 16) | region->sx); NVDmaNext(par, (region->dy << 16) | region->dx); NVDmaNext(par, (region->height << 16) | region->width); NVDmaKickoff(par); } void nvidiafb_fillrect(struct fb_info *info, const struct fb_fillrect *rect) { struct nvidia_par *par = info->par; u32 color; if (info->state != FBINFO_STATE_RUNNING) return; if (par->lockup) { cfb_fillrect(info, rect); return; } if (info->var.bits_per_pixel == 8) color = rect->color; else color = ((u32 *) info->pseudo_palette)[rect->color]; if (rect->rop != ROP_COPY) NVSetRopSolid(info, rect->rop, ~0); NVDmaStart(info, par, RECT_SOLID_COLOR, 1); NVDmaNext(par, color); NVDmaStart(info, par, RECT_SOLID_RECTS(0), 2); NVDmaNext(par, (rect->dx << 16) | rect->dy); NVDmaNext(par, (rect->width << 16) | rect->height); NVDmaKickoff(par); if (rect->rop != ROP_COPY) NVSetRopSolid(info, ROP_COPY, ~0); } static void nvidiafb_mono_color_expand(struct fb_info *info, const struct fb_image *image) { struct nvidia_par *par = info->par; u32 fg, bg, mask = ~(~0 >> (32 - info->var.bits_per_pixel)); u32 dsize, width, *data = (u32 *) image->data, tmp; int j, k = 0; width = (image->width + 31) & ~31; dsize = (width * image->height) >> 5; if (info->var.bits_per_pixel == 8) { fg = image->fg_color | mask; bg = image->bg_color | mask; } else { fg = ((u32 *) info->pseudo_palette)[image->fg_color] | mask; bg = ((u32 *) info->pseudo_palette)[image->bg_color] | mask; } NVDmaStart(info, par, RECT_EXPAND_TWO_COLOR_CLIP, 7); NVDmaNext(par, (image->dy << 16) | (image->dx & 0xffff)); NVDmaNext(par, ((image->dy + image->height) << 16) | ((image->dx + image->width) & 0xffff)); NVDmaNext(par, bg); NVDmaNext(par, fg); NVDmaNext(par, (image->height << 16) | width); NVDmaNext(par, (image->height << 16) | width); NVDmaNext(par, (image->dy << 16) | (image->dx & 0xffff)); while (dsize >= RECT_EXPAND_TWO_COLOR_DATA_MAX_DWORDS) { NVDmaStart(info, par, RECT_EXPAND_TWO_COLOR_DATA(0), RECT_EXPAND_TWO_COLOR_DATA_MAX_DWORDS); for (j = RECT_EXPAND_TWO_COLOR_DATA_MAX_DWORDS; j--;) { tmp = data[k++]; reverse_order(&tmp); NVDmaNext(par, tmp); } dsize -= RECT_EXPAND_TWO_COLOR_DATA_MAX_DWORDS; } if (dsize) { NVDmaStart(info, par, RECT_EXPAND_TWO_COLOR_DATA(0), dsize); for (j = dsize; j--;) { tmp = data[k++]; reverse_order(&tmp); NVDmaNext(par, tmp); } } NVDmaKickoff(par); } void nvidiafb_imageblit(struct fb_info *info, const struct fb_image *image) { struct nvidia_par *par = info->par; if (info->state != FBINFO_STATE_RUNNING) return; if (image->depth == 1 && !par->lockup) nvidiafb_mono_color_expand(info, image); else cfb_imageblit(info, image); }
gpl-2.0
kozmikkick/nvidia3.9
drivers/hid/hid-picolcd_core.c
200
19318
/*************************************************************************** * Copyright (C) 2010-2012 by Bruno Prémont <bonbons@linux-vserver.org> * * * * Based on Logitech G13 driver (v0.4) * * Copyright (C) 2009 by Rick L. Vinyard, Jr. <rvinyard@cs.nmsu.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, version 2 of the License. * * * * This driver 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 software. If not see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include <linux/hid.h> #include <linux/hid-debug.h> #include <linux/input.h> #include "hid-ids.h" #include <linux/fb.h> #include <linux/vmalloc.h> #include <linux/completion.h> #include <linux/uaccess.h> #include <linux/module.h> #include "hid-picolcd.h" /* Input device * * The PicoLCD has an IR receiver header, a built-in keypad with 5 keys * and header for 4x4 key matrix. The built-in keys are part of the matrix. */ static const unsigned short def_keymap[PICOLCD_KEYS] = { KEY_RESERVED, /* none */ KEY_BACK, /* col 4 + row 1 */ KEY_HOMEPAGE, /* col 3 + row 1 */ KEY_RESERVED, /* col 2 + row 1 */ KEY_RESERVED, /* col 1 + row 1 */ KEY_SCROLLUP, /* col 4 + row 2 */ KEY_OK, /* col 3 + row 2 */ KEY_SCROLLDOWN, /* col 2 + row 2 */ KEY_RESERVED, /* col 1 + row 2 */ KEY_RESERVED, /* col 4 + row 3 */ KEY_RESERVED, /* col 3 + row 3 */ KEY_RESERVED, /* col 2 + row 3 */ KEY_RESERVED, /* col 1 + row 3 */ KEY_RESERVED, /* col 4 + row 4 */ KEY_RESERVED, /* col 3 + row 4 */ KEY_RESERVED, /* col 2 + row 4 */ KEY_RESERVED, /* col 1 + row 4 */ }; /* Find a given report */ struct hid_report *picolcd_report(int id, struct hid_device *hdev, int dir) { struct list_head *feature_report_list = &hdev->report_enum[dir].report_list; struct hid_report *report = NULL; list_for_each_entry(report, feature_report_list, list) { if (report->id == id) return report; } hid_warn(hdev, "No report with id 0x%x found\n", id); return NULL; } /* Submit a report and wait for a reply from device - if device fades away * or does not respond in time, return NULL */ struct picolcd_pending *picolcd_send_and_wait(struct hid_device *hdev, int report_id, const u8 *raw_data, int size) { struct picolcd_data *data = hid_get_drvdata(hdev); struct picolcd_pending *work; struct hid_report *report = picolcd_out_report(report_id, hdev); unsigned long flags; int i, j, k; if (!report || !data) return NULL; if (data->status & PICOLCD_FAILED) return NULL; work = kzalloc(sizeof(*work), GFP_KERNEL); if (!work) return NULL; init_completion(&work->ready); work->out_report = report; work->in_report = NULL; work->raw_size = 0; mutex_lock(&data->mutex); spin_lock_irqsave(&data->lock, flags); for (i = k = 0; i < report->maxfield; i++) for (j = 0; j < report->field[i]->report_count; j++) { hid_set_field(report->field[i], j, k < size ? raw_data[k] : 0); k++; } if (data->status & PICOLCD_FAILED) { kfree(work); work = NULL; } else { data->pending = work; hid_hw_request(data->hdev, report, HID_REQ_SET_REPORT); spin_unlock_irqrestore(&data->lock, flags); wait_for_completion_interruptible_timeout(&work->ready, HZ*2); spin_lock_irqsave(&data->lock, flags); data->pending = NULL; } spin_unlock_irqrestore(&data->lock, flags); mutex_unlock(&data->mutex); return work; } /* * input class device */ static int picolcd_raw_keypad(struct picolcd_data *data, struct hid_report *report, u8 *raw_data, int size) { /* * Keypad event * First and second data bytes list currently pressed keys, * 0x00 means no key and at most 2 keys may be pressed at same time */ int i, j; /* determine newly pressed keys */ for (i = 0; i < size; i++) { unsigned int key_code; if (raw_data[i] == 0) continue; for (j = 0; j < sizeof(data->pressed_keys); j++) if (data->pressed_keys[j] == raw_data[i]) goto key_already_down; for (j = 0; j < sizeof(data->pressed_keys); j++) if (data->pressed_keys[j] == 0) { data->pressed_keys[j] = raw_data[i]; break; } input_event(data->input_keys, EV_MSC, MSC_SCAN, raw_data[i]); if (raw_data[i] < PICOLCD_KEYS) key_code = data->keycode[raw_data[i]]; else key_code = KEY_UNKNOWN; if (key_code != KEY_UNKNOWN) { dbg_hid(PICOLCD_NAME " got key press for %u:%d", raw_data[i], key_code); input_report_key(data->input_keys, key_code, 1); } input_sync(data->input_keys); key_already_down: continue; } /* determine newly released keys */ for (j = 0; j < sizeof(data->pressed_keys); j++) { unsigned int key_code; if (data->pressed_keys[j] == 0) continue; for (i = 0; i < size; i++) if (data->pressed_keys[j] == raw_data[i]) goto key_still_down; input_event(data->input_keys, EV_MSC, MSC_SCAN, data->pressed_keys[j]); if (data->pressed_keys[j] < PICOLCD_KEYS) key_code = data->keycode[data->pressed_keys[j]]; else key_code = KEY_UNKNOWN; if (key_code != KEY_UNKNOWN) { dbg_hid(PICOLCD_NAME " got key release for %u:%d", data->pressed_keys[j], key_code); input_report_key(data->input_keys, key_code, 0); } input_sync(data->input_keys); data->pressed_keys[j] = 0; key_still_down: continue; } return 1; } static int picolcd_check_version(struct hid_device *hdev) { struct picolcd_data *data = hid_get_drvdata(hdev); struct picolcd_pending *verinfo; int ret = 0; if (!data) return -ENODEV; verinfo = picolcd_send_and_wait(hdev, REPORT_VERSION, NULL, 0); if (!verinfo) { hid_err(hdev, "no version response from PicoLCD\n"); return -ENODEV; } if (verinfo->raw_size == 2) { data->version[0] = verinfo->raw_data[1]; data->version[1] = verinfo->raw_data[0]; if (data->status & PICOLCD_BOOTLOADER) { hid_info(hdev, "PicoLCD, bootloader version %d.%d\n", verinfo->raw_data[1], verinfo->raw_data[0]); } else { hid_info(hdev, "PicoLCD, firmware version %d.%d\n", verinfo->raw_data[1], verinfo->raw_data[0]); } } else { hid_err(hdev, "confused, got unexpected version response from PicoLCD\n"); ret = -EINVAL; } kfree(verinfo); return ret; } /* * Reset our device and wait for answer to VERSION request */ int picolcd_reset(struct hid_device *hdev) { struct picolcd_data *data = hid_get_drvdata(hdev); struct hid_report *report = picolcd_out_report(REPORT_RESET, hdev); unsigned long flags; int error; if (!data || !report || report->maxfield != 1) return -ENODEV; spin_lock_irqsave(&data->lock, flags); if (hdev->product == USB_DEVICE_ID_PICOLCD_BOOTLOADER) data->status |= PICOLCD_BOOTLOADER; /* perform the reset */ hid_set_field(report->field[0], 0, 1); if (data->status & PICOLCD_FAILED) { spin_unlock_irqrestore(&data->lock, flags); return -ENODEV; } hid_hw_request(hdev, report, HID_REQ_SET_REPORT); spin_unlock_irqrestore(&data->lock, flags); error = picolcd_check_version(hdev); if (error) return error; picolcd_resume_lcd(data); picolcd_resume_backlight(data); picolcd_fb_refresh(data); picolcd_leds_set(data); return 0; } /* * The "operation_mode" sysfs attribute */ static ssize_t picolcd_operation_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct picolcd_data *data = dev_get_drvdata(dev); if (data->status & PICOLCD_BOOTLOADER) return snprintf(buf, PAGE_SIZE, "[bootloader] lcd\n"); else return snprintf(buf, PAGE_SIZE, "bootloader [lcd]\n"); } static ssize_t picolcd_operation_mode_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct picolcd_data *data = dev_get_drvdata(dev); struct hid_report *report = NULL; size_t cnt = count; int timeout = data->opmode_delay; unsigned long flags; if (cnt >= 3 && strncmp("lcd", buf, 3) == 0) { if (data->status & PICOLCD_BOOTLOADER) report = picolcd_out_report(REPORT_EXIT_FLASHER, data->hdev); buf += 3; cnt -= 3; } else if (cnt >= 10 && strncmp("bootloader", buf, 10) == 0) { if (!(data->status & PICOLCD_BOOTLOADER)) report = picolcd_out_report(REPORT_EXIT_KEYBOARD, data->hdev); buf += 10; cnt -= 10; } if (!report) return -EINVAL; while (cnt > 0 && (buf[cnt-1] == '\n' || buf[cnt-1] == '\r')) cnt--; if (cnt != 0) return -EINVAL; spin_lock_irqsave(&data->lock, flags); hid_set_field(report->field[0], 0, timeout & 0xff); hid_set_field(report->field[0], 1, (timeout >> 8) & 0xff); hid_hw_request(data->hdev, report, HID_REQ_SET_REPORT); spin_unlock_irqrestore(&data->lock, flags); return count; } static DEVICE_ATTR(operation_mode, 0644, picolcd_operation_mode_show, picolcd_operation_mode_store); /* * The "operation_mode_delay" sysfs attribute */ static ssize_t picolcd_operation_mode_delay_show(struct device *dev, struct device_attribute *attr, char *buf) { struct picolcd_data *data = dev_get_drvdata(dev); return snprintf(buf, PAGE_SIZE, "%hu\n", data->opmode_delay); } static ssize_t picolcd_operation_mode_delay_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct picolcd_data *data = dev_get_drvdata(dev); unsigned u; if (sscanf(buf, "%u", &u) != 1) return -EINVAL; if (u > 30000) return -EINVAL; else data->opmode_delay = u; return count; } static DEVICE_ATTR(operation_mode_delay, 0644, picolcd_operation_mode_delay_show, picolcd_operation_mode_delay_store); /* * Handle raw report as sent by device */ static int picolcd_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *raw_data, int size) { struct picolcd_data *data = hid_get_drvdata(hdev); unsigned long flags; int ret = 0; if (!data) return 1; if (report->id == REPORT_KEY_STATE) { if (data->input_keys) ret = picolcd_raw_keypad(data, report, raw_data+1, size-1); } else if (report->id == REPORT_IR_DATA) { ret = picolcd_raw_cir(data, report, raw_data+1, size-1); } else { spin_lock_irqsave(&data->lock, flags); /* * We let the caller of picolcd_send_and_wait() check if the * report we got is one of the expected ones or not. */ if (data->pending) { memcpy(data->pending->raw_data, raw_data+1, size-1); data->pending->raw_size = size-1; data->pending->in_report = report; complete(&data->pending->ready); } spin_unlock_irqrestore(&data->lock, flags); } picolcd_debug_raw_event(data, hdev, report, raw_data, size); return 1; } #ifdef CONFIG_PM static int picolcd_suspend(struct hid_device *hdev, pm_message_t message) { if (PMSG_IS_AUTO(message)) return 0; picolcd_suspend_backlight(hid_get_drvdata(hdev)); dbg_hid(PICOLCD_NAME " device ready for suspend\n"); return 0; } static int picolcd_resume(struct hid_device *hdev) { int ret; ret = picolcd_resume_backlight(hid_get_drvdata(hdev)); if (ret) dbg_hid(PICOLCD_NAME " restoring backlight failed: %d\n", ret); return 0; } static int picolcd_reset_resume(struct hid_device *hdev) { int ret; ret = picolcd_reset(hdev); if (ret) dbg_hid(PICOLCD_NAME " resetting our device failed: %d\n", ret); ret = picolcd_fb_reset(hid_get_drvdata(hdev), 0); if (ret) dbg_hid(PICOLCD_NAME " restoring framebuffer content failed: %d\n", ret); ret = picolcd_resume_lcd(hid_get_drvdata(hdev)); if (ret) dbg_hid(PICOLCD_NAME " restoring lcd failed: %d\n", ret); ret = picolcd_resume_backlight(hid_get_drvdata(hdev)); if (ret) dbg_hid(PICOLCD_NAME " restoring backlight failed: %d\n", ret); picolcd_leds_set(hid_get_drvdata(hdev)); return 0; } #endif /* initialize keypad input device */ static int picolcd_init_keys(struct picolcd_data *data, struct hid_report *report) { struct hid_device *hdev = data->hdev; struct input_dev *idev; int error, i; if (!report) return -ENODEV; if (report->maxfield != 1 || report->field[0]->report_count != 2 || report->field[0]->report_size != 8) { hid_err(hdev, "unsupported KEY_STATE report\n"); return -EINVAL; } idev = input_allocate_device(); if (idev == NULL) { hid_err(hdev, "failed to allocate input device\n"); return -ENOMEM; } input_set_drvdata(idev, hdev); memcpy(data->keycode, def_keymap, sizeof(def_keymap)); idev->name = hdev->name; idev->phys = hdev->phys; idev->uniq = hdev->uniq; idev->id.bustype = hdev->bus; idev->id.vendor = hdev->vendor; idev->id.product = hdev->product; idev->id.version = hdev->version; idev->dev.parent = &hdev->dev; idev->keycode = &data->keycode; idev->keycodemax = PICOLCD_KEYS; idev->keycodesize = sizeof(data->keycode[0]); input_set_capability(idev, EV_MSC, MSC_SCAN); set_bit(EV_REP, idev->evbit); for (i = 0; i < PICOLCD_KEYS; i++) input_set_capability(idev, EV_KEY, data->keycode[i]); error = input_register_device(idev); if (error) { hid_err(hdev, "error registering the input device\n"); input_free_device(idev); return error; } data->input_keys = idev; return 0; } static void picolcd_exit_keys(struct picolcd_data *data) { struct input_dev *idev = data->input_keys; data->input_keys = NULL; if (idev) input_unregister_device(idev); } static int picolcd_probe_lcd(struct hid_device *hdev, struct picolcd_data *data) { int error; /* Setup keypad input device */ error = picolcd_init_keys(data, picolcd_in_report(REPORT_KEY_STATE, hdev)); if (error) goto err; /* Setup CIR input device */ error = picolcd_init_cir(data, picolcd_in_report(REPORT_IR_DATA, hdev)); if (error) goto err; /* Set up the framebuffer device */ error = picolcd_init_framebuffer(data); if (error) goto err; /* Setup lcd class device */ error = picolcd_init_lcd(data, picolcd_out_report(REPORT_CONTRAST, hdev)); if (error) goto err; /* Setup backlight class device */ error = picolcd_init_backlight(data, picolcd_out_report(REPORT_BRIGHTNESS, hdev)); if (error) goto err; /* Setup the LED class devices */ error = picolcd_init_leds(data, picolcd_out_report(REPORT_LED_STATE, hdev)); if (error) goto err; picolcd_init_devfs(data, picolcd_out_report(REPORT_EE_READ, hdev), picolcd_out_report(REPORT_EE_WRITE, hdev), picolcd_out_report(REPORT_READ_MEMORY, hdev), picolcd_out_report(REPORT_WRITE_MEMORY, hdev), picolcd_out_report(REPORT_RESET, hdev)); return 0; err: picolcd_exit_leds(data); picolcd_exit_backlight(data); picolcd_exit_lcd(data); picolcd_exit_framebuffer(data); picolcd_exit_cir(data); picolcd_exit_keys(data); return error; } static int picolcd_probe_bootloader(struct hid_device *hdev, struct picolcd_data *data) { picolcd_init_devfs(data, NULL, NULL, picolcd_out_report(REPORT_BL_READ_MEMORY, hdev), picolcd_out_report(REPORT_BL_WRITE_MEMORY, hdev), NULL); return 0; } static int picolcd_probe(struct hid_device *hdev, const struct hid_device_id *id) { struct picolcd_data *data; int error = -ENOMEM; dbg_hid(PICOLCD_NAME " hardware probe...\n"); /* * Let's allocate the picolcd data structure, set some reasonable * defaults, and associate it with the device */ data = kzalloc(sizeof(struct picolcd_data), GFP_KERNEL); if (data == NULL) { hid_err(hdev, "can't allocate space for Minibox PicoLCD device data\n"); error = -ENOMEM; goto err_no_cleanup; } spin_lock_init(&data->lock); mutex_init(&data->mutex); data->hdev = hdev; data->opmode_delay = 5000; if (hdev->product == USB_DEVICE_ID_PICOLCD_BOOTLOADER) data->status |= PICOLCD_BOOTLOADER; hid_set_drvdata(hdev, data); /* Parse the device reports and start it up */ error = hid_parse(hdev); if (error) { hid_err(hdev, "device report parse failed\n"); goto err_cleanup_data; } error = hid_hw_start(hdev, 0); if (error) { hid_err(hdev, "hardware start failed\n"); goto err_cleanup_data; } error = hid_hw_open(hdev); if (error) { hid_err(hdev, "failed to open input interrupt pipe for key and IR events\n"); goto err_cleanup_hid_hw; } error = device_create_file(&hdev->dev, &dev_attr_operation_mode_delay); if (error) { hid_err(hdev, "failed to create sysfs attributes\n"); goto err_cleanup_hid_ll; } error = device_create_file(&hdev->dev, &dev_attr_operation_mode); if (error) { hid_err(hdev, "failed to create sysfs attributes\n"); goto err_cleanup_sysfs1; } if (data->status & PICOLCD_BOOTLOADER) error = picolcd_probe_bootloader(hdev, data); else error = picolcd_probe_lcd(hdev, data); if (error) goto err_cleanup_sysfs2; dbg_hid(PICOLCD_NAME " activated and initialized\n"); return 0; err_cleanup_sysfs2: device_remove_file(&hdev->dev, &dev_attr_operation_mode); err_cleanup_sysfs1: device_remove_file(&hdev->dev, &dev_attr_operation_mode_delay); err_cleanup_hid_ll: hid_hw_close(hdev); err_cleanup_hid_hw: hid_hw_stop(hdev); err_cleanup_data: kfree(data); err_no_cleanup: hid_set_drvdata(hdev, NULL); return error; } static void picolcd_remove(struct hid_device *hdev) { struct picolcd_data *data = hid_get_drvdata(hdev); unsigned long flags; dbg_hid(PICOLCD_NAME " hardware remove...\n"); spin_lock_irqsave(&data->lock, flags); data->status |= PICOLCD_FAILED; spin_unlock_irqrestore(&data->lock, flags); picolcd_exit_devfs(data); device_remove_file(&hdev->dev, &dev_attr_operation_mode); device_remove_file(&hdev->dev, &dev_attr_operation_mode_delay); hid_hw_close(hdev); hid_hw_stop(hdev); /* Shortcut potential pending reply that will never arrive */ spin_lock_irqsave(&data->lock, flags); if (data->pending) complete(&data->pending->ready); spin_unlock_irqrestore(&data->lock, flags); /* Cleanup LED */ picolcd_exit_leds(data); /* Clean up the framebuffer */ picolcd_exit_backlight(data); picolcd_exit_lcd(data); picolcd_exit_framebuffer(data); /* Cleanup input */ picolcd_exit_cir(data); picolcd_exit_keys(data); hid_set_drvdata(hdev, NULL); mutex_destroy(&data->mutex); /* Finally, clean up the picolcd data itself */ kfree(data); } static const struct hid_device_id picolcd_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD_BOOTLOADER) }, { } }; MODULE_DEVICE_TABLE(hid, picolcd_devices); static struct hid_driver picolcd_driver = { .name = "hid-picolcd", .id_table = picolcd_devices, .probe = picolcd_probe, .remove = picolcd_remove, .raw_event = picolcd_raw_event, #ifdef CONFIG_PM .suspend = picolcd_suspend, .resume = picolcd_resume, .reset_resume = picolcd_reset_resume, #endif }; module_hid_driver(picolcd_driver); MODULE_DESCRIPTION("Minibox graphics PicoLCD Driver"); MODULE_LICENSE("GPL v2");
gpl-2.0
mingit/mstcp_v0.89.4
drivers/net/wireless/iwlwifi/dvm/mac80211.c
200
43159
/****************************************************************************** * * Copyright(c) 2003 - 2014 Intel Corporation. All rights reserved. * * Portions of this file are derived from the ipw3945 project, as well * as portions of the ieee80211 subsystem header files. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * Intel Linux Wireless <ilw@linux.intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * *****************************************************************************/ #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/dma-mapping.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/if_arp.h> #include <net/ieee80211_radiotap.h> #include <net/mac80211.h> #include <asm/div64.h> #include "iwl-io.h" #include "iwl-trans.h" #include "iwl-op-mode.h" #include "iwl-modparams.h" #include "dev.h" #include "calib.h" #include "agn.h" /***************************************************************************** * * mac80211 entry point functions * *****************************************************************************/ static const struct ieee80211_iface_limit iwlagn_sta_ap_limits[] = { { .max = 1, .types = BIT(NL80211_IFTYPE_STATION), }, { .max = 1, .types = BIT(NL80211_IFTYPE_AP), }, }; static const struct ieee80211_iface_limit iwlagn_2sta_limits[] = { { .max = 2, .types = BIT(NL80211_IFTYPE_STATION), }, }; static const struct ieee80211_iface_combination iwlagn_iface_combinations_dualmode[] = { { .num_different_channels = 1, .max_interfaces = 2, .beacon_int_infra_match = true, .limits = iwlagn_sta_ap_limits, .n_limits = ARRAY_SIZE(iwlagn_sta_ap_limits), }, { .num_different_channels = 1, .max_interfaces = 2, .limits = iwlagn_2sta_limits, .n_limits = ARRAY_SIZE(iwlagn_2sta_limits), }, }; /* * Not a mac80211 entry point function, but it fits in with all the * other mac80211 functions grouped here. */ int iwlagn_mac_setup_register(struct iwl_priv *priv, const struct iwl_ucode_capabilities *capa) { int ret; struct ieee80211_hw *hw = priv->hw; struct iwl_rxon_context *ctx; hw->rate_control_algorithm = "iwl-agn-rs"; /* Tell mac80211 our characteristics */ hw->flags = IEEE80211_HW_SIGNAL_DBM | IEEE80211_HW_AMPDU_AGGREGATION | IEEE80211_HW_NEED_DTIM_BEFORE_ASSOC | IEEE80211_HW_SPECTRUM_MGMT | IEEE80211_HW_REPORTS_TX_ACK_STATUS | IEEE80211_HW_QUEUE_CONTROL | IEEE80211_HW_SUPPORTS_PS | IEEE80211_HW_SUPPORTS_DYNAMIC_PS | IEEE80211_HW_WANT_MONITOR_VIF; hw->offchannel_tx_hw_queue = IWL_AUX_QUEUE; hw->radiotap_mcs_details |= IEEE80211_RADIOTAP_MCS_HAVE_FMT; /* * Including the following line will crash some AP's. This * workaround removes the stimulus which causes the crash until * the AP software can be fixed. hw->max_tx_aggregation_subframes = LINK_QUAL_AGG_FRAME_LIMIT_DEF; */ if (priv->nvm_data->sku_cap_11n_enable) hw->flags |= IEEE80211_HW_SUPPORTS_DYNAMIC_SMPS | IEEE80211_HW_SUPPORTS_STATIC_SMPS; /* * Enable 11w if advertised by firmware and software crypto * is not enabled (as the firmware will interpret some mgmt * packets, so enabling it with software crypto isn't safe) */ if (priv->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_MFP && !iwlwifi_mod_params.sw_crypto) hw->flags |= IEEE80211_HW_MFP_CAPABLE; hw->sta_data_size = sizeof(struct iwl_station_priv); hw->vif_data_size = sizeof(struct iwl_vif_priv); for_each_context(priv, ctx) { hw->wiphy->interface_modes |= ctx->interface_modes; hw->wiphy->interface_modes |= ctx->exclusive_interface_modes; } BUILD_BUG_ON(NUM_IWL_RXON_CTX != 2); if (hw->wiphy->interface_modes & BIT(NL80211_IFTYPE_AP)) { hw->wiphy->iface_combinations = iwlagn_iface_combinations_dualmode; hw->wiphy->n_iface_combinations = ARRAY_SIZE(iwlagn_iface_combinations_dualmode); } hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN; hw->wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG | REGULATORY_DISABLE_BEACON_HINTS; #ifdef CONFIG_PM_SLEEP if (priv->fw->img[IWL_UCODE_WOWLAN].sec[0].len && priv->trans->ops->d3_suspend && priv->trans->ops->d3_resume && device_can_wakeup(priv->trans->dev)) { priv->wowlan_support.flags = WIPHY_WOWLAN_MAGIC_PKT | WIPHY_WOWLAN_DISCONNECT | WIPHY_WOWLAN_EAP_IDENTITY_REQ | WIPHY_WOWLAN_RFKILL_RELEASE; if (!iwlwifi_mod_params.sw_crypto) priv->wowlan_support.flags |= WIPHY_WOWLAN_SUPPORTS_GTK_REKEY | WIPHY_WOWLAN_GTK_REKEY_FAILURE; priv->wowlan_support.n_patterns = IWLAGN_WOWLAN_MAX_PATTERNS; priv->wowlan_support.pattern_min_len = IWLAGN_WOWLAN_MIN_PATTERN_LEN; priv->wowlan_support.pattern_max_len = IWLAGN_WOWLAN_MAX_PATTERN_LEN; hw->wiphy->wowlan = &priv->wowlan_support; } #endif if (iwlwifi_mod_params.power_save) hw->wiphy->flags |= WIPHY_FLAG_PS_ON_BY_DEFAULT; else hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT; hw->wiphy->max_scan_ssids = PROBE_OPTION_MAX; /* we create the 802.11 header and a max-length SSID element */ hw->wiphy->max_scan_ie_len = capa->max_probe_length - 24 - 34; /* * We don't use all queues: 4 and 9 are unused and any * aggregation queue gets mapped down to the AC queue. */ hw->queues = IWLAGN_FIRST_AMPDU_QUEUE; hw->max_listen_interval = IWL_CONN_MAX_LISTEN_INTERVAL; if (priv->nvm_data->bands[IEEE80211_BAND_2GHZ].n_channels) priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &priv->nvm_data->bands[IEEE80211_BAND_2GHZ]; if (priv->nvm_data->bands[IEEE80211_BAND_5GHZ].n_channels) priv->hw->wiphy->bands[IEEE80211_BAND_5GHZ] = &priv->nvm_data->bands[IEEE80211_BAND_5GHZ]; hw->wiphy->hw_version = priv->trans->hw_id; iwl_leds_init(priv); ret = ieee80211_register_hw(priv->hw); if (ret) { IWL_ERR(priv, "Failed to register hw (error %d)\n", ret); iwl_leds_exit(priv); return ret; } priv->mac80211_registered = 1; return 0; } void iwlagn_mac_unregister(struct iwl_priv *priv) { if (!priv->mac80211_registered) return; iwl_leds_exit(priv); ieee80211_unregister_hw(priv->hw); priv->mac80211_registered = 0; } static int __iwl_up(struct iwl_priv *priv) { struct iwl_rxon_context *ctx; int ret; lockdep_assert_held(&priv->mutex); if (test_bit(STATUS_EXIT_PENDING, &priv->status)) { IWL_WARN(priv, "Exit pending; will not bring the NIC up\n"); return -EIO; } for_each_context(priv, ctx) { ret = iwlagn_alloc_bcast_station(priv, ctx); if (ret) { iwl_dealloc_bcast_stations(priv); return ret; } } ret = iwl_run_init_ucode(priv); if (ret) { IWL_ERR(priv, "Failed to run INIT ucode: %d\n", ret); goto error; } ret = iwl_load_ucode_wait_alive(priv, IWL_UCODE_REGULAR); if (ret) { IWL_ERR(priv, "Failed to start RT ucode: %d\n", ret); goto error; } ret = iwl_alive_start(priv); if (ret) goto error; return 0; error: set_bit(STATUS_EXIT_PENDING, &priv->status); iwl_down(priv); clear_bit(STATUS_EXIT_PENDING, &priv->status); IWL_ERR(priv, "Unable to initialize device.\n"); return ret; } static int iwlagn_mac_start(struct ieee80211_hw *hw) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); int ret; IWL_DEBUG_MAC80211(priv, "enter\n"); /* we should be verifying the device is ready to be opened */ mutex_lock(&priv->mutex); ret = __iwl_up(priv); mutex_unlock(&priv->mutex); if (ret) return ret; IWL_DEBUG_INFO(priv, "Start UP work done.\n"); /* Now we should be done, and the READY bit should be set. */ if (WARN_ON(!test_bit(STATUS_READY, &priv->status))) ret = -EIO; iwlagn_led_enable(priv); priv->is_open = 1; IWL_DEBUG_MAC80211(priv, "leave\n"); return 0; } static void iwlagn_mac_stop(struct ieee80211_hw *hw) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); IWL_DEBUG_MAC80211(priv, "enter\n"); if (!priv->is_open) return; priv->is_open = 0; mutex_lock(&priv->mutex); iwl_down(priv); mutex_unlock(&priv->mutex); iwl_cancel_deferred_work(priv); flush_workqueue(priv->workqueue); IWL_DEBUG_MAC80211(priv, "leave\n"); } static void iwlagn_mac_set_rekey_data(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_gtk_rekey_data *data) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); if (iwlwifi_mod_params.sw_crypto) return; IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); if (priv->contexts[IWL_RXON_CTX_BSS].vif != vif) goto out; memcpy(priv->kek, data->kek, NL80211_KEK_LEN); memcpy(priv->kck, data->kck, NL80211_KCK_LEN); priv->replay_ctr = cpu_to_le64(be64_to_cpup((__be64 *)&data->replay_ctr)); priv->have_rekey_data = true; out: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); } #ifdef CONFIG_PM_SLEEP static int iwlagn_mac_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS]; int ret; if (WARN_ON(!wowlan)) return -EINVAL; IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); /* Don't attempt WoWLAN when not associated, tear down instead. */ if (!ctx->vif || ctx->vif->type != NL80211_IFTYPE_STATION || !iwl_is_associated_ctx(ctx)) { ret = 1; goto out; } ret = iwlagn_suspend(priv, wowlan); if (ret) goto error; /* let the ucode operate on its own */ iwl_write32(priv->trans, CSR_UCODE_DRV_GP1_SET, CSR_UCODE_DRV_GP1_BIT_D3_CFG_COMPLETE); iwl_trans_d3_suspend(priv->trans, false); goto out; error: priv->wowlan = false; iwlagn_prepare_restart(priv); ieee80211_restart_hw(priv->hw); out: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return ret; } struct iwl_resume_data { struct iwl_priv *priv; struct iwlagn_wowlan_status *cmd; bool valid; }; static bool iwl_resume_status_fn(struct iwl_notif_wait_data *notif_wait, struct iwl_rx_packet *pkt, void *data) { struct iwl_resume_data *resume_data = data; struct iwl_priv *priv = resume_data->priv; if (iwl_rx_packet_payload_len(pkt) != sizeof(*resume_data->cmd)) { IWL_ERR(priv, "rx wrong size data\n"); return true; } memcpy(resume_data->cmd, pkt->data, sizeof(*resume_data->cmd)); resume_data->valid = true; return true; } static int iwlagn_mac_resume(struct ieee80211_hw *hw) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS]; struct ieee80211_vif *vif; u32 base; int ret; enum iwl_d3_status d3_status; struct error_table_start { /* cf. struct iwl_error_event_table */ u32 valid; u32 error_id; } err_info; struct iwl_notification_wait status_wait; static const u8 status_cmd[] = { REPLY_WOWLAN_GET_STATUS, }; struct iwlagn_wowlan_status status_data = {}; struct iwl_resume_data resume_data = { .priv = priv, .cmd = &status_data, .valid = false, }; struct cfg80211_wowlan_wakeup wakeup = { .pattern_idx = -1, }; #ifdef CONFIG_IWLWIFI_DEBUGFS const struct fw_img *img; #endif IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); /* we'll clear ctx->vif during iwlagn_prepare_restart() */ vif = ctx->vif; ret = iwl_trans_d3_resume(priv->trans, &d3_status, false); if (ret) goto out_unlock; if (d3_status != IWL_D3_STATUS_ALIVE) { IWL_INFO(priv, "Device was reset during suspend\n"); goto out_unlock; } /* uCode is no longer operating by itself */ iwl_write32(priv->trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_DRV_GP1_BIT_D3_CFG_COMPLETE); base = priv->device_pointers.error_event_table; if (!iwlagn_hw_valid_rtc_data_addr(base)) { IWL_WARN(priv, "Invalid error table during resume!\n"); goto out_unlock; } iwl_trans_read_mem_bytes(priv->trans, base, &err_info, sizeof(err_info)); if (err_info.valid) { IWL_INFO(priv, "error table is valid (%d, 0x%x)\n", err_info.valid, err_info.error_id); if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) { wakeup.rfkill_release = true; ieee80211_report_wowlan_wakeup(vif, &wakeup, GFP_KERNEL); } goto out_unlock; } #ifdef CONFIG_IWLWIFI_DEBUGFS img = &priv->fw->img[IWL_UCODE_WOWLAN]; if (!priv->wowlan_sram) priv->wowlan_sram = kzalloc(img->sec[IWL_UCODE_SECTION_DATA].len, GFP_KERNEL); if (priv->wowlan_sram) iwl_trans_read_mem(priv->trans, 0x800000, priv->wowlan_sram, img->sec[IWL_UCODE_SECTION_DATA].len / 4); #endif /* * This is very strange. The GET_STATUS command is sent but the device * doesn't reply properly, it seems it doesn't close the RBD so one is * always left open ... As a result, we need to send another command * and have to reset the driver afterwards. As we need to switch to * runtime firmware again that'll happen. */ iwl_init_notification_wait(&priv->notif_wait, &status_wait, status_cmd, ARRAY_SIZE(status_cmd), iwl_resume_status_fn, &resume_data); iwl_dvm_send_cmd_pdu(priv, REPLY_WOWLAN_GET_STATUS, CMD_ASYNC, 0, NULL); iwl_dvm_send_cmd_pdu(priv, REPLY_ECHO, CMD_ASYNC, 0, NULL); /* an RBD is left open in the firmware now! */ ret = iwl_wait_notification(&priv->notif_wait, &status_wait, HZ/5); if (ret) goto out_unlock; if (resume_data.valid && priv->contexts[IWL_RXON_CTX_BSS].vif) { u32 reasons = le32_to_cpu(status_data.wakeup_reason); struct cfg80211_wowlan_wakeup *wakeup_report; IWL_INFO(priv, "WoWLAN wakeup reason(s): 0x%.8x\n", reasons); if (reasons) { if (reasons & IWLAGN_WOWLAN_WAKEUP_MAGIC_PACKET) wakeup.magic_pkt = true; if (reasons & IWLAGN_WOWLAN_WAKEUP_PATTERN_MATCH) wakeup.pattern_idx = status_data.pattern_number; if (reasons & (IWLAGN_WOWLAN_WAKEUP_BEACON_MISS | IWLAGN_WOWLAN_WAKEUP_LINK_CHANGE)) wakeup.disconnect = true; if (reasons & IWLAGN_WOWLAN_WAKEUP_GTK_REKEY_FAIL) wakeup.gtk_rekey_failure = true; if (reasons & IWLAGN_WOWLAN_WAKEUP_EAP_IDENT_REQ) wakeup.eap_identity_req = true; if (reasons & IWLAGN_WOWLAN_WAKEUP_4WAY_HANDSHAKE) wakeup.four_way_handshake = true; wakeup_report = &wakeup; } else { wakeup_report = NULL; } ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL); } priv->wowlan = false; iwlagn_prepare_restart(priv); memset((void *)&ctx->active, 0, sizeof(ctx->active)); iwl_connection_init_rx_config(priv, ctx); iwlagn_set_rxon_chain(priv, ctx); out_unlock: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); ieee80211_resume_disconnect(vif); return 1; } static void iwlagn_mac_set_wakeup(struct ieee80211_hw *hw, bool enabled) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); device_set_wakeup_enable(priv->trans->dev, enabled); } #endif static void iwlagn_mac_tx(struct ieee80211_hw *hw, struct ieee80211_tx_control *control, struct sk_buff *skb) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); if (iwlagn_tx_skb(priv, control->sta, skb)) ieee80211_free_txskb(hw, skb); } static void iwlagn_mac_update_tkip_key(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_key_conf *keyconf, struct ieee80211_sta *sta, u32 iv32, u16 *phase1key) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); iwl_update_tkip_key(priv, vif, keyconf, sta, iv32, phase1key); } static int iwlagn_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv; struct iwl_rxon_context *ctx = vif_priv->ctx; int ret; bool is_default_wep_key = false; IWL_DEBUG_MAC80211(priv, "enter\n"); if (iwlwifi_mod_params.sw_crypto) { IWL_DEBUG_MAC80211(priv, "leave - hwcrypto disabled\n"); return -EOPNOTSUPP; } switch (key->cipher) { case WLAN_CIPHER_SUITE_TKIP: key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC; /* fall through */ case WLAN_CIPHER_SUITE_CCMP: key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV; break; default: break; } /* * We could program these keys into the hardware as well, but we * don't expect much multicast traffic in IBSS and having keys * for more stations is probably more useful. * * Mark key TX-only and return 0. */ if (vif->type == NL80211_IFTYPE_ADHOC && !(key->flags & IEEE80211_KEY_FLAG_PAIRWISE)) { key->hw_key_idx = WEP_INVALID_OFFSET; return 0; } /* If they key was TX-only, accept deletion */ if (cmd == DISABLE_KEY && key->hw_key_idx == WEP_INVALID_OFFSET) return 0; mutex_lock(&priv->mutex); iwl_scan_cancel_timeout(priv, 100); BUILD_BUG_ON(WEP_INVALID_OFFSET == IWLAGN_HW_KEY_DEFAULT); /* * If we are getting WEP group key and we didn't receive any key mapping * so far, we are in legacy wep mode (group key only), otherwise we are * in 1X mode. * In legacy wep mode, we use another host command to the uCode. */ if ((key->cipher == WLAN_CIPHER_SUITE_WEP40 || key->cipher == WLAN_CIPHER_SUITE_WEP104) && !sta) { if (cmd == SET_KEY) is_default_wep_key = !ctx->key_mapping_keys; else is_default_wep_key = key->hw_key_idx == IWLAGN_HW_KEY_DEFAULT; } switch (cmd) { case SET_KEY: if (is_default_wep_key) { ret = iwl_set_default_wep_key(priv, vif_priv->ctx, key); break; } ret = iwl_set_dynamic_key(priv, vif_priv->ctx, key, sta); if (ret) { /* * can't add key for RX, but we don't need it * in the device for TX so still return 0 */ ret = 0; key->hw_key_idx = WEP_INVALID_OFFSET; } IWL_DEBUG_MAC80211(priv, "enable hwcrypto key\n"); break; case DISABLE_KEY: if (is_default_wep_key) ret = iwl_remove_default_wep_key(priv, ctx, key); else ret = iwl_remove_dynamic_key(priv, ctx, key, sta); IWL_DEBUG_MAC80211(priv, "disable hwcrypto key\n"); break; default: ret = -EINVAL; } mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return ret; } static inline bool iwl_enable_rx_ampdu(const struct iwl_cfg *cfg) { if (iwlwifi_mod_params.disable_11n & IWL_DISABLE_HT_RXAGG) return false; return true; } static inline bool iwl_enable_tx_ampdu(const struct iwl_cfg *cfg) { if (iwlwifi_mod_params.disable_11n & IWL_DISABLE_HT_TXAGG) return false; if (iwlwifi_mod_params.disable_11n & IWL_ENABLE_HT_TXAGG) return true; /* disabled by default */ return false; } static int iwlagn_mac_ampdu_action(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum ieee80211_ampdu_mlme_action action, struct ieee80211_sta *sta, u16 tid, u16 *ssn, u8 buf_size) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); int ret = -EINVAL; struct iwl_station_priv *sta_priv = (void *) sta->drv_priv; IWL_DEBUG_HT(priv, "A-MPDU action on addr %pM tid %d\n", sta->addr, tid); if (!(priv->nvm_data->sku_cap_11n_enable)) return -EACCES; IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); switch (action) { case IEEE80211_AMPDU_RX_START: if (!iwl_enable_rx_ampdu(priv->cfg)) break; IWL_DEBUG_HT(priv, "start Rx\n"); ret = iwl_sta_rx_agg_start(priv, sta, tid, *ssn); break; case IEEE80211_AMPDU_RX_STOP: IWL_DEBUG_HT(priv, "stop Rx\n"); ret = iwl_sta_rx_agg_stop(priv, sta, tid); break; case IEEE80211_AMPDU_TX_START: if (!priv->trans->ops->txq_enable) break; if (!iwl_enable_tx_ampdu(priv->cfg)) break; IWL_DEBUG_HT(priv, "start Tx\n"); ret = iwlagn_tx_agg_start(priv, vif, sta, tid, ssn); break; case IEEE80211_AMPDU_TX_STOP_FLUSH: case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT: IWL_DEBUG_HT(priv, "Flush Tx\n"); ret = iwlagn_tx_agg_flush(priv, vif, sta, tid); break; case IEEE80211_AMPDU_TX_STOP_CONT: IWL_DEBUG_HT(priv, "stop Tx\n"); ret = iwlagn_tx_agg_stop(priv, vif, sta, tid); if ((ret == 0) && (priv->agg_tids_count > 0)) { priv->agg_tids_count--; IWL_DEBUG_HT(priv, "priv->agg_tids_count = %u\n", priv->agg_tids_count); } if (!priv->agg_tids_count && priv->hw_params.use_rts_for_aggregation) { /* * switch off RTS/CTS if it was previously enabled */ sta_priv->lq_sta.lq.general_params.flags &= ~LINK_QUAL_FLAGS_SET_STA_TLC_RTS_MSK; iwl_send_lq_cmd(priv, iwl_rxon_ctx_from_vif(vif), &sta_priv->lq_sta.lq, CMD_ASYNC, false); } break; case IEEE80211_AMPDU_TX_OPERATIONAL: ret = iwlagn_tx_agg_oper(priv, vif, sta, tid, buf_size); break; } mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return ret; } static int iwlagn_mac_sta_add(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_station_priv *sta_priv = (void *)sta->drv_priv; struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv; bool is_ap = vif->type == NL80211_IFTYPE_STATION; int ret; u8 sta_id; IWL_DEBUG_INFO(priv, "proceeding to add station %pM\n", sta->addr); sta_priv->sta_id = IWL_INVALID_STATION; atomic_set(&sta_priv->pending_frames, 0); if (vif->type == NL80211_IFTYPE_AP) sta_priv->client = true; ret = iwl_add_station_common(priv, vif_priv->ctx, sta->addr, is_ap, sta, &sta_id); if (ret) { IWL_ERR(priv, "Unable to add station %pM (%d)\n", sta->addr, ret); /* Should we return success if return code is EEXIST ? */ return ret; } sta_priv->sta_id = sta_id; return 0; } static int iwlagn_mac_sta_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_station_priv *sta_priv = (void *)sta->drv_priv; int ret; IWL_DEBUG_INFO(priv, "proceeding to remove station %pM\n", sta->addr); if (vif->type == NL80211_IFTYPE_STATION) { /* * Station will be removed from device when the RXON * is set to unassociated -- just deactivate it here * to avoid re-programming it. */ ret = 0; iwl_deactivate_station(priv, sta_priv->sta_id, sta->addr); } else { ret = iwl_remove_station(priv, sta_priv->sta_id, sta->addr); if (ret) IWL_DEBUG_QUIET_RFKILL(priv, "Error removing station %pM\n", sta->addr); } return ret; } static int iwlagn_mac_sta_state(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv; enum { NONE, ADD, REMOVE, HT_RATE_INIT, ADD_RATE_INIT, } op = NONE; int ret; IWL_DEBUG_MAC80211(priv, "station %pM state change %d->%d\n", sta->addr, old_state, new_state); mutex_lock(&priv->mutex); if (vif->type == NL80211_IFTYPE_STATION) { if (old_state == IEEE80211_STA_NOTEXIST && new_state == IEEE80211_STA_NONE) op = ADD; else if (old_state == IEEE80211_STA_NONE && new_state == IEEE80211_STA_NOTEXIST) op = REMOVE; else if (old_state == IEEE80211_STA_AUTH && new_state == IEEE80211_STA_ASSOC) op = HT_RATE_INIT; } else { if (old_state == IEEE80211_STA_AUTH && new_state == IEEE80211_STA_ASSOC) op = ADD_RATE_INIT; else if (old_state == IEEE80211_STA_ASSOC && new_state == IEEE80211_STA_AUTH) op = REMOVE; } switch (op) { case ADD: ret = iwlagn_mac_sta_add(hw, vif, sta); if (ret) break; /* * Clear the in-progress flag, the AP station entry was added * but we'll initialize LQ only when we've associated (which * would also clear the in-progress flag). This is necessary * in case we never initialize LQ because association fails. */ spin_lock_bh(&priv->sta_lock); priv->stations[iwl_sta_id(sta)].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_bh(&priv->sta_lock); break; case REMOVE: ret = iwlagn_mac_sta_remove(hw, vif, sta); break; case ADD_RATE_INIT: ret = iwlagn_mac_sta_add(hw, vif, sta); if (ret) break; /* Initialize rate scaling */ IWL_DEBUG_INFO(priv, "Initializing rate scaling for station %pM\n", sta->addr); iwl_rs_rate_init(priv, sta, iwl_sta_id(sta)); ret = 0; break; case HT_RATE_INIT: /* Initialize rate scaling */ ret = iwl_sta_update_ht(priv, vif_priv->ctx, sta); if (ret) break; IWL_DEBUG_INFO(priv, "Initializing rate scaling for station %pM\n", sta->addr); iwl_rs_rate_init(priv, sta, iwl_sta_id(sta)); ret = 0; break; default: ret = 0; break; } /* * mac80211 might WARN if we fail, but due the way we * (badly) handle hard rfkill, we might fail here */ if (iwl_is_rfkill(priv)) ret = 0; mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return ret; } static void iwlagn_mac_channel_switch(struct ieee80211_hw *hw, struct ieee80211_channel_switch *ch_switch) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct ieee80211_conf *conf = &hw->conf; struct ieee80211_channel *channel = ch_switch->chandef.chan; struct iwl_ht_config *ht_conf = &priv->current_ht_config; /* * MULTI-FIXME * When we add support for multiple interfaces, we need to * revisit this. The channel switch command in the device * only affects the BSS context, but what does that really * mean? And what if we get a CSA on the second interface? * This needs a lot of work. */ struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS]; u16 ch; IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); if (iwl_is_rfkill(priv)) goto out; if (test_bit(STATUS_EXIT_PENDING, &priv->status) || test_bit(STATUS_SCANNING, &priv->status) || test_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status)) goto out; if (!iwl_is_associated_ctx(ctx)) goto out; if (!priv->lib->set_channel_switch) goto out; ch = channel->hw_value; if (le16_to_cpu(ctx->active.channel) == ch) goto out; priv->current_ht_config.smps = conf->smps_mode; /* Configure HT40 channels */ switch (cfg80211_get_chandef_type(&ch_switch->chandef)) { case NL80211_CHAN_NO_HT: case NL80211_CHAN_HT20: ctx->ht.is_40mhz = false; ctx->ht.extension_chan_offset = IEEE80211_HT_PARAM_CHA_SEC_NONE; break; case NL80211_CHAN_HT40MINUS: ctx->ht.extension_chan_offset = IEEE80211_HT_PARAM_CHA_SEC_BELOW; ctx->ht.is_40mhz = true; break; case NL80211_CHAN_HT40PLUS: ctx->ht.extension_chan_offset = IEEE80211_HT_PARAM_CHA_SEC_ABOVE; ctx->ht.is_40mhz = true; break; } if ((le16_to_cpu(ctx->staging.channel) != ch)) ctx->staging.flags = 0; iwl_set_rxon_channel(priv, channel, ctx); iwl_set_rxon_ht(priv, ht_conf); iwl_set_flags_for_band(priv, ctx, channel->band, ctx->vif); /* * at this point, staging_rxon has the * configuration for channel switch */ set_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status); priv->switch_channel = cpu_to_le16(ch); if (priv->lib->set_channel_switch(priv, ch_switch)) { clear_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status); priv->switch_channel = 0; ieee80211_chswitch_done(ctx->vif, false); } out: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); } void iwl_chswitch_done(struct iwl_priv *priv, bool is_success) { /* * MULTI-FIXME * See iwlagn_mac_channel_switch. */ struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS]; if (test_bit(STATUS_EXIT_PENDING, &priv->status)) return; if (!test_and_clear_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status)) return; if (ctx->vif) ieee80211_chswitch_done(ctx->vif, is_success); } static void iwlagn_configure_filter(struct ieee80211_hw *hw, unsigned int changed_flags, unsigned int *total_flags, u64 multicast) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); __le32 filter_or = 0, filter_nand = 0; struct iwl_rxon_context *ctx; #define CHK(test, flag) do { \ if (*total_flags & (test)) \ filter_or |= (flag); \ else \ filter_nand |= (flag); \ } while (0) IWL_DEBUG_MAC80211(priv, "Enter: changed: 0x%x, total: 0x%x\n", changed_flags, *total_flags); CHK(FIF_OTHER_BSS | FIF_PROMISC_IN_BSS, RXON_FILTER_PROMISC_MSK); /* Setting _just_ RXON_FILTER_CTL2HOST_MSK causes FH errors */ CHK(FIF_CONTROL, RXON_FILTER_CTL2HOST_MSK | RXON_FILTER_PROMISC_MSK); CHK(FIF_BCN_PRBRESP_PROMISC, RXON_FILTER_BCON_AWARE_MSK); #undef CHK mutex_lock(&priv->mutex); for_each_context(priv, ctx) { ctx->staging.filter_flags &= ~filter_nand; ctx->staging.filter_flags |= filter_or; /* * Not committing directly because hardware can perform a scan, * but we'll eventually commit the filter flags change anyway. */ } mutex_unlock(&priv->mutex); /* * Receiving all multicast frames is always enabled by the * default flags setup in iwl_connection_init_rx_config() * since we currently do not support programming multicast * filters into the device. */ *total_flags &= FIF_OTHER_BSS | FIF_ALLMULTI | FIF_PROMISC_IN_BSS | FIF_BCN_PRBRESP_PROMISC | FIF_CONTROL; } static void iwlagn_mac_flush(struct ieee80211_hw *hw, u32 queues, bool drop) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); mutex_lock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "enter\n"); if (test_bit(STATUS_EXIT_PENDING, &priv->status)) { IWL_DEBUG_TX(priv, "Aborting flush due to device shutdown\n"); goto done; } if (iwl_is_rfkill(priv)) { IWL_DEBUG_TX(priv, "Aborting flush due to RF Kill\n"); goto done; } /* * mac80211 will not push any more frames for transmit * until the flush is completed */ if (drop) { IWL_DEBUG_MAC80211(priv, "send flush command\n"); if (iwlagn_txfifo_flush(priv, 0)) { IWL_ERR(priv, "flush request fail\n"); goto done; } } IWL_DEBUG_MAC80211(priv, "wait transmit/flush all frames\n"); iwl_trans_wait_tx_queue_empty(priv->trans); done: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); } static void iwlagn_mac_rssi_callback(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum ieee80211_rssi_event rssi_event) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); if (priv->lib->bt_params && priv->lib->bt_params->advanced_bt_coexist) { if (rssi_event == RSSI_EVENT_LOW) priv->bt_enable_pspoll = true; else if (rssi_event == RSSI_EVENT_HIGH) priv->bt_enable_pspoll = false; iwlagn_send_advance_bt_config(priv); } else { IWL_DEBUG_MAC80211(priv, "Advanced BT coex disabled," "ignoring RSSI callback\n"); } mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); } static int iwlagn_mac_set_tim(struct ieee80211_hw *hw, struct ieee80211_sta *sta, bool set) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); queue_work(priv->workqueue, &priv->beacon_update); return 0; } static int iwlagn_mac_conf_tx(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 queue, const struct ieee80211_tx_queue_params *params) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv; struct iwl_rxon_context *ctx = vif_priv->ctx; int q; if (WARN_ON(!ctx)) return -EINVAL; IWL_DEBUG_MAC80211(priv, "enter\n"); if (!iwl_is_ready_rf(priv)) { IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n"); return -EIO; } if (queue >= AC_NUM) { IWL_DEBUG_MAC80211(priv, "leave - queue >= AC_NUM %d\n", queue); return 0; } q = AC_NUM - 1 - queue; mutex_lock(&priv->mutex); ctx->qos_data.def_qos_parm.ac[q].cw_min = cpu_to_le16(params->cw_min); ctx->qos_data.def_qos_parm.ac[q].cw_max = cpu_to_le16(params->cw_max); ctx->qos_data.def_qos_parm.ac[q].aifsn = params->aifs; ctx->qos_data.def_qos_parm.ac[q].edca_txop = cpu_to_le16((params->txop * 32)); ctx->qos_data.def_qos_parm.ac[q].reserved1 = 0; mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return 0; } static int iwlagn_mac_tx_last_beacon(struct ieee80211_hw *hw) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); return priv->ibss_manager == IWL_IBSS_MANAGER; } static int iwl_set_mode(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { iwl_connection_init_rx_config(priv, ctx); iwlagn_set_rxon_chain(priv, ctx); return iwlagn_commit_rxon(priv, ctx); } static int iwl_setup_interface(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { struct ieee80211_vif *vif = ctx->vif; int err, ac; lockdep_assert_held(&priv->mutex); /* * This variable will be correct only when there's just * a single context, but all code using it is for hardware * that supports only one context. */ priv->iw_mode = vif->type; ctx->is_active = true; err = iwl_set_mode(priv, ctx); if (err) { if (!ctx->always_active) ctx->is_active = false; return err; } if (priv->lib->bt_params && priv->lib->bt_params->advanced_bt_coexist && vif->type == NL80211_IFTYPE_ADHOC) { /* * pretend to have high BT traffic as long as we * are operating in IBSS mode, as this will cause * the rate scaling etc. to behave as intended. */ priv->bt_traffic_load = IWL_BT_COEX_TRAFFIC_LOAD_HIGH; } /* set up queue mappings */ for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) vif->hw_queue[ac] = ctx->ac_to_queue[ac]; if (vif->type == NL80211_IFTYPE_AP) vif->cab_queue = ctx->mcast_queue; else vif->cab_queue = IEEE80211_INVAL_HW_QUEUE; return 0; } static int iwlagn_mac_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv; struct iwl_rxon_context *tmp, *ctx = NULL; int err; enum nl80211_iftype viftype = ieee80211_vif_type_p2p(vif); bool reset = false; IWL_DEBUG_MAC80211(priv, "enter: type %d, addr %pM\n", viftype, vif->addr); mutex_lock(&priv->mutex); if (!iwl_is_ready_rf(priv)) { IWL_WARN(priv, "Try to add interface when device not ready\n"); err = -EINVAL; goto out; } for_each_context(priv, tmp) { u32 possible_modes = tmp->interface_modes | tmp->exclusive_interface_modes; if (tmp->vif) { /* On reset we need to add the same interface again */ if (tmp->vif == vif) { reset = true; ctx = tmp; break; } /* check if this busy context is exclusive */ if (tmp->exclusive_interface_modes & BIT(tmp->vif->type)) { err = -EINVAL; goto out; } continue; } if (!(possible_modes & BIT(viftype))) continue; /* have maybe usable context w/o interface */ ctx = tmp; break; } if (!ctx) { err = -EOPNOTSUPP; goto out; } vif_priv->ctx = ctx; ctx->vif = vif; /* * In SNIFFER device type, the firmware reports the FCS to * the host, rather than snipping it off. Unfortunately, * mac80211 doesn't (yet) provide a per-packet flag for * this, so that we have to set the hardware flag based * on the interfaces added. As the monitor interface can * only be present by itself, and will be removed before * other interfaces are added, this is safe. */ if (vif->type == NL80211_IFTYPE_MONITOR) priv->hw->flags |= IEEE80211_HW_RX_INCLUDES_FCS; else priv->hw->flags &= ~IEEE80211_HW_RX_INCLUDES_FCS; err = iwl_setup_interface(priv, ctx); if (!err || reset) goto out; ctx->vif = NULL; priv->iw_mode = NL80211_IFTYPE_STATION; out: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return err; } static void iwl_teardown_interface(struct iwl_priv *priv, struct ieee80211_vif *vif, bool mode_change) { struct iwl_rxon_context *ctx = iwl_rxon_ctx_from_vif(vif); lockdep_assert_held(&priv->mutex); if (priv->scan_vif == vif) { iwl_scan_cancel_timeout(priv, 200); iwl_force_scan_end(priv); } if (!mode_change) { iwl_set_mode(priv, ctx); if (!ctx->always_active) ctx->is_active = false; } /* * When removing the IBSS interface, overwrite the * BT traffic load with the stored one from the last * notification, if any. If this is a device that * doesn't implement this, this has no effect since * both values are the same and zero. */ if (vif->type == NL80211_IFTYPE_ADHOC) priv->bt_traffic_load = priv->last_bt_traffic_load; } static void iwlagn_mac_remove_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_rxon_context *ctx = iwl_rxon_ctx_from_vif(vif); IWL_DEBUG_MAC80211(priv, "enter\n"); mutex_lock(&priv->mutex); if (WARN_ON(ctx->vif != vif)) { struct iwl_rxon_context *tmp; IWL_ERR(priv, "ctx->vif = %p, vif = %p\n", ctx->vif, vif); for_each_context(priv, tmp) IWL_ERR(priv, "\tID = %d:\tctx = %p\tctx->vif = %p\n", tmp->ctxid, tmp, tmp->vif); } ctx->vif = NULL; iwl_teardown_interface(priv, vif, false); mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); } static int iwlagn_mac_change_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_iftype newtype, bool newp2p) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_rxon_context *ctx, *tmp; enum nl80211_iftype newviftype = newtype; u32 interface_modes; int err; IWL_DEBUG_MAC80211(priv, "enter\n"); newtype = ieee80211_iftype_p2p(newtype, newp2p); mutex_lock(&priv->mutex); ctx = iwl_rxon_ctx_from_vif(vif); /* * To simplify this code, only support changes on the * BSS context. The PAN context is usually reassigned * by creating/removing P2P interfaces anyway. */ if (ctx->ctxid != IWL_RXON_CTX_BSS) { err = -EBUSY; goto out; } if (!ctx->vif || !iwl_is_ready_rf(priv)) { /* * Huh? But wait ... this can maybe happen when * we're in the middle of a firmware restart! */ err = -EBUSY; goto out; } /* Check if the switch is supported in the same context */ interface_modes = ctx->interface_modes | ctx->exclusive_interface_modes; if (!(interface_modes & BIT(newtype))) { err = -EBUSY; goto out; } if (ctx->exclusive_interface_modes & BIT(newtype)) { for_each_context(priv, tmp) { if (ctx == tmp) continue; if (!tmp->is_active) continue; /* * The current mode switch would be exclusive, but * another context is active ... refuse the switch. */ err = -EBUSY; goto out; } } /* success */ iwl_teardown_interface(priv, vif, true); vif->type = newviftype; vif->p2p = newp2p; err = iwl_setup_interface(priv, ctx); WARN_ON(err); /* * We've switched internally, but submitting to the * device may have failed for some reason. Mask this * error, because otherwise mac80211 will not switch * (and set the interface type back) and we'll be * out of sync with it. */ err = 0; out: mutex_unlock(&priv->mutex); IWL_DEBUG_MAC80211(priv, "leave\n"); return err; } static int iwlagn_mac_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_scan_request *req) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); int ret; IWL_DEBUG_MAC80211(priv, "enter\n"); if (req->n_channels == 0) return -EINVAL; mutex_lock(&priv->mutex); /* * If an internal scan is in progress, just set * up the scan_request as per above. */ if (priv->scan_type != IWL_SCAN_NORMAL) { IWL_DEBUG_SCAN(priv, "SCAN request during internal scan - defer\n"); priv->scan_request = req; priv->scan_vif = vif; ret = 0; } else { priv->scan_request = req; priv->scan_vif = vif; /* * mac80211 will only ask for one band at a time * so using channels[0] here is ok */ ret = iwl_scan_initiate(priv, vif, IWL_SCAN_NORMAL, req->channels[0]->band); if (ret) { priv->scan_request = NULL; priv->scan_vif = NULL; } } IWL_DEBUG_MAC80211(priv, "leave\n"); mutex_unlock(&priv->mutex); return ret; } static void iwl_sta_modify_ps_wake(struct iwl_priv *priv, int sta_id) { struct iwl_addsta_cmd cmd = { .mode = STA_CONTROL_MODIFY_MSK, .station_flags_msk = STA_FLG_PWR_SAVE_MSK, .sta.sta_id = sta_id, }; iwl_send_add_sta(priv, &cmd, CMD_ASYNC); } static void iwlagn_mac_sta_notify(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum sta_notify_cmd cmd, struct ieee80211_sta *sta) { struct iwl_priv *priv = IWL_MAC80211_GET_DVM(hw); struct iwl_station_priv *sta_priv = (void *)sta->drv_priv; int sta_id; IWL_DEBUG_MAC80211(priv, "enter\n"); switch (cmd) { case STA_NOTIFY_SLEEP: WARN_ON(!sta_priv->client); sta_priv->asleep = true; if (atomic_read(&sta_priv->pending_frames) > 0) ieee80211_sta_block_awake(hw, sta, true); break; case STA_NOTIFY_AWAKE: WARN_ON(!sta_priv->client); if (!sta_priv->asleep) break; sta_priv->asleep = false; sta_id = iwl_sta_id(sta); if (sta_id != IWL_INVALID_STATION) iwl_sta_modify_ps_wake(priv, sta_id); break; default: break; } IWL_DEBUG_MAC80211(priv, "leave\n"); } struct ieee80211_ops iwlagn_hw_ops = { .tx = iwlagn_mac_tx, .start = iwlagn_mac_start, .stop = iwlagn_mac_stop, #ifdef CONFIG_PM_SLEEP .suspend = iwlagn_mac_suspend, .resume = iwlagn_mac_resume, .set_wakeup = iwlagn_mac_set_wakeup, #endif .add_interface = iwlagn_mac_add_interface, .remove_interface = iwlagn_mac_remove_interface, .change_interface = iwlagn_mac_change_interface, .config = iwlagn_mac_config, .configure_filter = iwlagn_configure_filter, .set_key = iwlagn_mac_set_key, .update_tkip_key = iwlagn_mac_update_tkip_key, .set_rekey_data = iwlagn_mac_set_rekey_data, .conf_tx = iwlagn_mac_conf_tx, .bss_info_changed = iwlagn_bss_info_changed, .ampdu_action = iwlagn_mac_ampdu_action, .hw_scan = iwlagn_mac_hw_scan, .sta_notify = iwlagn_mac_sta_notify, .sta_state = iwlagn_mac_sta_state, .channel_switch = iwlagn_mac_channel_switch, .flush = iwlagn_mac_flush, .tx_last_beacon = iwlagn_mac_tx_last_beacon, .rssi_callback = iwlagn_mac_rssi_callback, .set_tim = iwlagn_mac_set_tim, }; /* This function both allocates and initializes hw and priv. */ struct ieee80211_hw *iwl_alloc_all(void) { struct iwl_priv *priv; struct iwl_op_mode *op_mode; /* mac80211 allocates memory for this device instance, including * space for this driver's private structure */ struct ieee80211_hw *hw; hw = ieee80211_alloc_hw(sizeof(struct iwl_priv) + sizeof(struct iwl_op_mode), &iwlagn_hw_ops); if (!hw) goto out; op_mode = hw->priv; priv = IWL_OP_MODE_GET_DVM(op_mode); priv->hw = hw; out: return hw; }
gpl-2.0
skywalker01/Samsung-Galaxy-S-Plus
drivers/scsi/libsas/sas_scsi_host.c
200
29557
/* * Serial Attached SCSI (SAS) class SCSI Host glue. * * Copyright (C) 2005 Adaptec, Inc. All rights reserved. * Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com> * * This file is licensed under GPLv2. * * 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/kthread.h> #include <linux/firmware.h> #include <linux/ctype.h> #include "sas_internal.h" #include <scsi/scsi_host.h> #include <scsi/scsi_device.h> #include <scsi/scsi_tcq.h> #include <scsi/scsi.h> #include <scsi/scsi_eh.h> #include <scsi/scsi_transport.h> #include <scsi/scsi_transport_sas.h> #include <scsi/sas_ata.h> #include "../scsi_sas_internal.h" #include "../scsi_transport_api.h" #include "../scsi_priv.h" #include <linux/err.h> #include <linux/blkdev.h> #include <linux/freezer.h> #include <linux/gfp.h> #include <linux/scatterlist.h> #include <linux/libata.h> /* ---------- SCSI Host glue ---------- */ static void sas_scsi_task_done(struct sas_task *task) { struct task_status_struct *ts = &task->task_status; struct scsi_cmnd *sc = task->uldd_task; int hs = 0, stat = 0; if (unlikely(task->task_state_flags & SAS_TASK_STATE_ABORTED)) { /* Aborted tasks will be completed by the error handler */ SAS_DPRINTK("task done but aborted\n"); return; } if (unlikely(!sc)) { SAS_DPRINTK("task_done called with non existing SCSI cmnd!\n"); list_del_init(&task->list); sas_free_task(task); return; } if (ts->resp == SAS_TASK_UNDELIVERED) { /* transport error */ hs = DID_NO_CONNECT; } else { /* ts->resp == SAS_TASK_COMPLETE */ /* task delivered, what happened afterwards? */ switch (ts->stat) { case SAS_DEV_NO_RESPONSE: case SAS_INTERRUPTED: case SAS_PHY_DOWN: case SAS_NAK_R_ERR: case SAS_OPEN_TO: hs = DID_NO_CONNECT; break; case SAS_DATA_UNDERRUN: scsi_set_resid(sc, ts->residual); if (scsi_bufflen(sc) - scsi_get_resid(sc) < sc->underflow) hs = DID_ERROR; break; case SAS_DATA_OVERRUN: hs = DID_ERROR; break; case SAS_QUEUE_FULL: hs = DID_SOFT_ERROR; /* retry */ break; case SAS_DEVICE_UNKNOWN: hs = DID_BAD_TARGET; break; case SAS_SG_ERR: hs = DID_PARITY; break; case SAS_OPEN_REJECT: if (ts->open_rej_reason == SAS_OREJ_RSVD_RETRY) hs = DID_SOFT_ERROR; /* retry */ else hs = DID_ERROR; break; case SAS_PROTO_RESPONSE: SAS_DPRINTK("LLDD:%s sent SAS_PROTO_RESP for an SSP " "task; please report this\n", task->dev->port->ha->sas_ha_name); break; case SAS_ABORTED_TASK: hs = DID_ABORT; break; case SAM_CHECK_COND: memcpy(sc->sense_buffer, ts->buf, min(SCSI_SENSE_BUFFERSIZE, ts->buf_valid_size)); stat = SAM_CHECK_COND; break; default: stat = ts->stat; break; } } ASSIGN_SAS_TASK(sc, NULL); sc->result = (hs << 16) | stat; list_del_init(&task->list); sas_free_task(task); sc->scsi_done(sc); } static enum task_attribute sas_scsi_get_task_attr(struct scsi_cmnd *cmd) { enum task_attribute ta = TASK_ATTR_SIMPLE; if (cmd->request && blk_rq_tagged(cmd->request)) { if (cmd->device->ordered_tags && (cmd->request->cmd_flags & REQ_HARDBARRIER)) ta = TASK_ATTR_ORDERED; } return ta; } static struct sas_task *sas_create_task(struct scsi_cmnd *cmd, struct domain_device *dev, gfp_t gfp_flags) { struct sas_task *task = sas_alloc_task(gfp_flags); struct scsi_lun lun; if (!task) return NULL; task->uldd_task = cmd; ASSIGN_SAS_TASK(cmd, task); task->dev = dev; task->task_proto = task->dev->tproto; /* BUG_ON(!SSP) */ task->ssp_task.retry_count = 1; int_to_scsilun(cmd->device->lun, &lun); memcpy(task->ssp_task.LUN, &lun.scsi_lun, 8); task->ssp_task.task_attr = sas_scsi_get_task_attr(cmd); memcpy(task->ssp_task.cdb, cmd->cmnd, 16); task->scatter = scsi_sglist(cmd); task->num_scatter = scsi_sg_count(cmd); task->total_xfer_len = scsi_bufflen(cmd); task->data_dir = cmd->sc_data_direction; task->task_done = sas_scsi_task_done; return task; } int sas_queue_up(struct sas_task *task) { struct sas_ha_struct *sas_ha = task->dev->port->ha; struct scsi_core *core = &sas_ha->core; unsigned long flags; LIST_HEAD(list); spin_lock_irqsave(&core->task_queue_lock, flags); if (sas_ha->lldd_queue_size < core->task_queue_size + 1) { spin_unlock_irqrestore(&core->task_queue_lock, flags); return -SAS_QUEUE_FULL; } list_add_tail(&task->list, &core->task_queue); core->task_queue_size += 1; spin_unlock_irqrestore(&core->task_queue_lock, flags); wake_up_process(core->queue_thread); return 0; } /** * sas_queuecommand -- Enqueue a command for processing * @parameters: See SCSI Core documentation * * Note: XXX: Remove the host unlock/lock pair when SCSI Core can * call us without holding an IRQ spinlock... */ int sas_queuecommand(struct scsi_cmnd *cmd, void (*scsi_done)(struct scsi_cmnd *)) __releases(host->host_lock) __acquires(dev->sata_dev.ap->lock) __releases(dev->sata_dev.ap->lock) __acquires(host->host_lock) { int res = 0; struct domain_device *dev = cmd_to_domain_dev(cmd); struct Scsi_Host *host = cmd->device->host; struct sas_internal *i = to_sas_internal(host->transportt); spin_unlock_irq(host->host_lock); { struct sas_ha_struct *sas_ha = dev->port->ha; struct sas_task *task; if (dev_is_sata(dev)) { unsigned long flags; spin_lock_irqsave(dev->sata_dev.ap->lock, flags); res = ata_sas_queuecmd(cmd, scsi_done, dev->sata_dev.ap); spin_unlock_irqrestore(dev->sata_dev.ap->lock, flags); goto out; } res = -ENOMEM; task = sas_create_task(cmd, dev, GFP_ATOMIC); if (!task) goto out; cmd->scsi_done = scsi_done; /* Queue up, Direct Mode or Task Collector Mode. */ if (sas_ha->lldd_max_execute_num < 2) res = i->dft->lldd_execute_task(task, 1, GFP_ATOMIC); else res = sas_queue_up(task); /* Examine */ if (res) { SAS_DPRINTK("lldd_execute_task returned: %d\n", res); ASSIGN_SAS_TASK(cmd, NULL); sas_free_task(task); if (res == -SAS_QUEUE_FULL) { cmd->result = DID_SOFT_ERROR << 16; /* retry */ res = 0; scsi_done(cmd); } goto out; } } out: spin_lock_irq(host->host_lock); return res; } static void sas_eh_finish_cmd(struct scsi_cmnd *cmd) { struct sas_task *task = TO_SAS_TASK(cmd); struct sas_ha_struct *sas_ha = SHOST_TO_SAS_HA(cmd->device->host); /* remove the aborted task flag to allow the task to be * completed now. At this point, we only get called following * an actual abort of the task, so we should be guaranteed not * to be racing with any completions from the LLD (hence we * don't need the task state lock to clear the flag) */ task->task_state_flags &= ~SAS_TASK_STATE_ABORTED; /* Now call task_done. However, task will be free'd after * this */ task->task_done(task); /* now finish the command and move it on to the error * handler done list, this also takes it off the * error handler pending list */ scsi_eh_finish_cmd(cmd, &sas_ha->eh_done_q); } static void sas_scsi_clear_queue_lu(struct list_head *error_q, struct scsi_cmnd *my_cmd) { struct scsi_cmnd *cmd, *n; list_for_each_entry_safe(cmd, n, error_q, eh_entry) { if (cmd->device->sdev_target == my_cmd->device->sdev_target && cmd->device->lun == my_cmd->device->lun) sas_eh_finish_cmd(cmd); } } static void sas_scsi_clear_queue_I_T(struct list_head *error_q, struct domain_device *dev) { struct scsi_cmnd *cmd, *n; list_for_each_entry_safe(cmd, n, error_q, eh_entry) { struct domain_device *x = cmd_to_domain_dev(cmd); if (x == dev) sas_eh_finish_cmd(cmd); } } static void sas_scsi_clear_queue_port(struct list_head *error_q, struct asd_sas_port *port) { struct scsi_cmnd *cmd, *n; list_for_each_entry_safe(cmd, n, error_q, eh_entry) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct asd_sas_port *x = dev->port; if (x == port) sas_eh_finish_cmd(cmd); } } enum task_disposition { TASK_IS_DONE, TASK_IS_ABORTED, TASK_IS_AT_LU, TASK_IS_NOT_AT_LU, TASK_ABORT_FAILED, }; static enum task_disposition sas_scsi_find_task(struct sas_task *task) { struct sas_ha_struct *ha = task->dev->port->ha; unsigned long flags; int i, res; struct sas_internal *si = to_sas_internal(task->dev->port->ha->core.shost->transportt); if (ha->lldd_max_execute_num > 1) { struct scsi_core *core = &ha->core; struct sas_task *t, *n; spin_lock_irqsave(&core->task_queue_lock, flags); list_for_each_entry_safe(t, n, &core->task_queue, list) { if (task == t) { list_del_init(&t->list); spin_unlock_irqrestore(&core->task_queue_lock, flags); SAS_DPRINTK("%s: task 0x%p aborted from " "task_queue\n", __func__, task); return TASK_IS_ABORTED; } } spin_unlock_irqrestore(&core->task_queue_lock, flags); } for (i = 0; i < 5; i++) { SAS_DPRINTK("%s: aborting task 0x%p\n", __func__, task); res = si->dft->lldd_abort_task(task); spin_lock_irqsave(&task->task_state_lock, flags); if (task->task_state_flags & SAS_TASK_STATE_DONE) { spin_unlock_irqrestore(&task->task_state_lock, flags); SAS_DPRINTK("%s: task 0x%p is done\n", __func__, task); return TASK_IS_DONE; } spin_unlock_irqrestore(&task->task_state_lock, flags); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("%s: task 0x%p is aborted\n", __func__, task); return TASK_IS_ABORTED; } else if (si->dft->lldd_query_task) { SAS_DPRINTK("%s: querying task 0x%p\n", __func__, task); res = si->dft->lldd_query_task(task); switch (res) { case TMF_RESP_FUNC_SUCC: SAS_DPRINTK("%s: task 0x%p at LU\n", __func__, task); return TASK_IS_AT_LU; case TMF_RESP_FUNC_COMPLETE: SAS_DPRINTK("%s: task 0x%p not at LU\n", __func__, task); return TASK_IS_NOT_AT_LU; case TMF_RESP_FUNC_FAILED: SAS_DPRINTK("%s: task 0x%p failed to abort\n", __func__, task); return TASK_ABORT_FAILED; } } } return res; } static int sas_recover_lu(struct domain_device *dev, struct scsi_cmnd *cmd) { int res = TMF_RESP_FUNC_FAILED; struct scsi_lun lun; struct sas_internal *i = to_sas_internal(dev->port->ha->core.shost->transportt); int_to_scsilun(cmd->device->lun, &lun); SAS_DPRINTK("eh: device %llx LUN %x has the task\n", SAS_ADDR(dev->sas_addr), cmd->device->lun); if (i->dft->lldd_abort_task_set) res = i->dft->lldd_abort_task_set(dev, lun.scsi_lun); if (res == TMF_RESP_FUNC_FAILED) { if (i->dft->lldd_clear_task_set) res = i->dft->lldd_clear_task_set(dev, lun.scsi_lun); } if (res == TMF_RESP_FUNC_FAILED) { if (i->dft->lldd_lu_reset) res = i->dft->lldd_lu_reset(dev, lun.scsi_lun); } return res; } static int sas_recover_I_T(struct domain_device *dev) { int res = TMF_RESP_FUNC_FAILED; struct sas_internal *i = to_sas_internal(dev->port->ha->core.shost->transportt); SAS_DPRINTK("I_T nexus reset for dev %016llx\n", SAS_ADDR(dev->sas_addr)); if (i->dft->lldd_I_T_nexus_reset) res = i->dft->lldd_I_T_nexus_reset(dev); return res; } /* Find the sas_phy that's attached to this device */ struct sas_phy *sas_find_local_phy(struct domain_device *dev) { struct domain_device *pdev = dev->parent; struct ex_phy *exphy = NULL; int i; /* Directly attached device */ if (!pdev) return dev->port->phy; /* Otherwise look in the expander */ for (i = 0; i < pdev->ex_dev.num_phys; i++) if (!memcmp(dev->sas_addr, pdev->ex_dev.ex_phy[i].attached_sas_addr, SAS_ADDR_SIZE)) { exphy = &pdev->ex_dev.ex_phy[i]; break; } BUG_ON(!exphy); return exphy->phy; } EXPORT_SYMBOL_GPL(sas_find_local_phy); /* Attempt to send a LUN reset message to a device */ int sas_eh_device_reset_handler(struct scsi_cmnd *cmd) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_internal *i = to_sas_internal(dev->port->ha->core.shost->transportt); struct scsi_lun lun; int res; int_to_scsilun(cmd->device->lun, &lun); if (!i->dft->lldd_lu_reset) return FAILED; res = i->dft->lldd_lu_reset(dev, lun.scsi_lun); if (res == TMF_RESP_FUNC_SUCC || res == TMF_RESP_FUNC_COMPLETE) return SUCCESS; return FAILED; } /* Attempt to send a phy (bus) reset */ int sas_eh_bus_reset_handler(struct scsi_cmnd *cmd) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_phy *phy = sas_find_local_phy(dev); int res; res = sas_phy_reset(phy, 1); if (res) SAS_DPRINTK("Bus reset of %s failed 0x%x\n", kobject_name(&phy->dev.kobj), res); if (res == TMF_RESP_FUNC_SUCC || res == TMF_RESP_FUNC_COMPLETE) return SUCCESS; return FAILED; } /* Try to reset a device */ static int try_to_reset_cmd_device(struct scsi_cmnd *cmd) { int res; struct Scsi_Host *shost = cmd->device->host; if (!shost->hostt->eh_device_reset_handler) goto try_bus_reset; res = shost->hostt->eh_device_reset_handler(cmd); if (res == SUCCESS) return res; try_bus_reset: if (shost->hostt->eh_bus_reset_handler) return shost->hostt->eh_bus_reset_handler(cmd); return FAILED; } static int sas_eh_handle_sas_errors(struct Scsi_Host *shost, struct list_head *work_q, struct list_head *done_q) { struct scsi_cmnd *cmd, *n; enum task_disposition res = TASK_IS_DONE; int tmf_resp, need_reset; struct sas_internal *i = to_sas_internal(shost->transportt); unsigned long flags; struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); Again: list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct sas_task *task = TO_SAS_TASK(cmd); if (!task) continue; list_del_init(&cmd->eh_entry); spin_lock_irqsave(&task->task_state_lock, flags); need_reset = task->task_state_flags & SAS_TASK_NEED_DEV_RESET; spin_unlock_irqrestore(&task->task_state_lock, flags); if (need_reset) { SAS_DPRINTK("%s: task 0x%p requests reset\n", __func__, task); goto reset; } SAS_DPRINTK("trying to find task 0x%p\n", task); res = sas_scsi_find_task(task); cmd->eh_eflags = 0; switch (res) { case TASK_IS_DONE: SAS_DPRINTK("%s: task 0x%p is done\n", __func__, task); sas_eh_finish_cmd(cmd); continue; case TASK_IS_ABORTED: SAS_DPRINTK("%s: task 0x%p is aborted\n", __func__, task); sas_eh_finish_cmd(cmd); continue; case TASK_IS_AT_LU: SAS_DPRINTK("task 0x%p is at LU: lu recover\n", task); reset: tmf_resp = sas_recover_lu(task->dev, cmd); if (tmf_resp == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("dev %016llx LU %x is " "recovered\n", SAS_ADDR(task->dev), cmd->device->lun); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_lu(work_q, cmd); goto Again; } /* fallthrough */ case TASK_IS_NOT_AT_LU: case TASK_ABORT_FAILED: SAS_DPRINTK("task 0x%p is not at LU: I_T recover\n", task); tmf_resp = sas_recover_I_T(task->dev); if (tmf_resp == TMF_RESP_FUNC_COMPLETE) { struct domain_device *dev = task->dev; SAS_DPRINTK("I_T %016llx recovered\n", SAS_ADDR(task->dev->sas_addr)); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_I_T(work_q, dev); goto Again; } /* Hammer time :-) */ try_to_reset_cmd_device(cmd); if (i->dft->lldd_clear_nexus_port) { struct asd_sas_port *port = task->dev->port; SAS_DPRINTK("clearing nexus for port:%d\n", port->id); res = i->dft->lldd_clear_nexus_port(port); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus port:%d " "succeeded\n", port->id); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_port(work_q, port); goto Again; } } if (i->dft->lldd_clear_nexus_ha) { SAS_DPRINTK("clear nexus ha\n"); res = i->dft->lldd_clear_nexus_ha(ha); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus ha " "succeeded\n"); sas_eh_finish_cmd(cmd); goto clear_q; } } /* If we are here -- this means that no amount * of effort could recover from errors. Quite * possibly the HA just disappeared. */ SAS_DPRINTK("error from device %llx, LUN %x " "couldn't be recovered in any way\n", SAS_ADDR(task->dev->sas_addr), cmd->device->lun); sas_eh_finish_cmd(cmd); goto clear_q; } } return list_empty(work_q); clear_q: SAS_DPRINTK("--- Exit %s -- clear_q\n", __func__); list_for_each_entry_safe(cmd, n, work_q, eh_entry) sas_eh_finish_cmd(cmd); return list_empty(work_q); } void sas_scsi_recover_host(struct Scsi_Host *shost) { struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); unsigned long flags; LIST_HEAD(eh_work_q); spin_lock_irqsave(shost->host_lock, flags); list_splice_init(&shost->eh_cmd_q, &eh_work_q); shost->host_eh_scheduled = 0; spin_unlock_irqrestore(shost->host_lock, flags); SAS_DPRINTK("Enter %s\n", __func__); /* * Deal with commands that still have SAS tasks (i.e. they didn't * complete via the normal sas_task completion mechanism) */ if (sas_eh_handle_sas_errors(shost, &eh_work_q, &ha->eh_done_q)) goto out; /* * Now deal with SCSI commands that completed ok but have a an error * code (and hopefully sense data) attached. This is roughly what * scsi_unjam_host does, but we skip scsi_eh_abort_cmds because any * command we see here has no sas_task and is thus unknown to the HA. */ if (!scsi_eh_get_sense(&eh_work_q, &ha->eh_done_q)) scsi_eh_ready_devs(shost, &eh_work_q, &ha->eh_done_q); out: scsi_eh_flush_done_q(&ha->eh_done_q); SAS_DPRINTK("--- Exit %s\n", __func__); return; } enum blk_eh_timer_return sas_scsi_timed_out(struct scsi_cmnd *cmd) { struct sas_task *task = TO_SAS_TASK(cmd); unsigned long flags; if (!task) { cmd->request->timeout /= 2; SAS_DPRINTK("command 0x%p, task 0x%p, gone: %s\n", cmd, task, (cmd->request->timeout ? "BLK_EH_RESET_TIMER" : "BLK_EH_NOT_HANDLED")); if (!cmd->request->timeout) return BLK_EH_NOT_HANDLED; return BLK_EH_RESET_TIMER; } spin_lock_irqsave(&task->task_state_lock, flags); BUG_ON(task->task_state_flags & SAS_TASK_STATE_ABORTED); if (task->task_state_flags & SAS_TASK_STATE_DONE) { spin_unlock_irqrestore(&task->task_state_lock, flags); SAS_DPRINTK("command 0x%p, task 0x%p, timed out: " "BLK_EH_HANDLED\n", cmd, task); return BLK_EH_HANDLED; } if (!(task->task_state_flags & SAS_TASK_AT_INITIATOR)) { spin_unlock_irqrestore(&task->task_state_lock, flags); SAS_DPRINTK("command 0x%p, task 0x%p, not at initiator: " "BLK_EH_RESET_TIMER\n", cmd, task); return BLK_EH_RESET_TIMER; } task->task_state_flags |= SAS_TASK_STATE_ABORTED; spin_unlock_irqrestore(&task->task_state_lock, flags); SAS_DPRINTK("command 0x%p, task 0x%p, timed out: BLK_EH_NOT_HANDLED\n", cmd, task); return BLK_EH_NOT_HANDLED; } int sas_ioctl(struct scsi_device *sdev, int cmd, void __user *arg) { struct domain_device *dev = sdev_to_domain_dev(sdev); if (dev_is_sata(dev)) return ata_sas_scsi_ioctl(dev->sata_dev.ap, sdev, cmd, arg); return -EINVAL; } struct domain_device *sas_find_dev_by_rphy(struct sas_rphy *rphy) { struct Scsi_Host *shost = dev_to_shost(rphy->dev.parent); struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); struct domain_device *found_dev = NULL; int i; unsigned long flags; spin_lock_irqsave(&ha->phy_port_lock, flags); for (i = 0; i < ha->num_phys; i++) { struct asd_sas_port *port = ha->sas_port[i]; struct domain_device *dev; spin_lock(&port->dev_list_lock); list_for_each_entry(dev, &port->dev_list, dev_list_node) { if (rphy == dev->rphy) { found_dev = dev; spin_unlock(&port->dev_list_lock); goto found; } } spin_unlock(&port->dev_list_lock); } found: spin_unlock_irqrestore(&ha->phy_port_lock, flags); return found_dev; } static inline struct domain_device *sas_find_target(struct scsi_target *starget) { struct sas_rphy *rphy = dev_to_rphy(starget->dev.parent); return sas_find_dev_by_rphy(rphy); } int sas_target_alloc(struct scsi_target *starget) { struct domain_device *found_dev = sas_find_target(starget); int res; if (!found_dev) return -ENODEV; if (dev_is_sata(found_dev)) { res = sas_ata_init_host_and_port(found_dev, starget); if (res) return res; } starget->hostdata = found_dev; return 0; } #define SAS_DEF_QD 32 #define SAS_MAX_QD 64 int sas_slave_configure(struct scsi_device *scsi_dev) { struct domain_device *dev = sdev_to_domain_dev(scsi_dev); struct sas_ha_struct *sas_ha; BUG_ON(dev->rphy->identify.device_type != SAS_END_DEVICE); if (dev_is_sata(dev)) { ata_sas_slave_configure(scsi_dev, dev->sata_dev.ap); return 0; } sas_ha = dev->port->ha; sas_read_port_mode_page(scsi_dev); if (scsi_dev->tagged_supported) { scsi_set_tag_type(scsi_dev, MSG_SIMPLE_TAG); scsi_activate_tcq(scsi_dev, SAS_DEF_QD); } else { SAS_DPRINTK("device %llx, LUN %x doesn't support " "TCQ\n", SAS_ADDR(dev->sas_addr), scsi_dev->lun); scsi_dev->tagged_supported = 0; scsi_set_tag_type(scsi_dev, 0); scsi_deactivate_tcq(scsi_dev, 1); } scsi_dev->allow_restart = 1; return 0; } void sas_slave_destroy(struct scsi_device *scsi_dev) { struct domain_device *dev = sdev_to_domain_dev(scsi_dev); if (dev_is_sata(dev)) dev->sata_dev.ap->link.device[0].class = ATA_DEV_NONE; } int sas_change_queue_depth(struct scsi_device *scsi_dev, int new_depth, int reason) { int res = min(new_depth, SAS_MAX_QD); if (reason != SCSI_QDEPTH_DEFAULT) return -EOPNOTSUPP; if (scsi_dev->tagged_supported) scsi_adjust_queue_depth(scsi_dev, scsi_get_tag_type(scsi_dev), res); else { struct domain_device *dev = sdev_to_domain_dev(scsi_dev); sas_printk("device %llx LUN %x queue depth changed to 1\n", SAS_ADDR(dev->sas_addr), scsi_dev->lun); scsi_adjust_queue_depth(scsi_dev, 0, 1); res = 1; } return res; } int sas_change_queue_type(struct scsi_device *scsi_dev, int qt) { if (!scsi_dev->tagged_supported) return 0; scsi_deactivate_tcq(scsi_dev, 1); scsi_set_tag_type(scsi_dev, qt); scsi_activate_tcq(scsi_dev, scsi_dev->queue_depth); return qt; } int sas_bios_param(struct scsi_device *scsi_dev, struct block_device *bdev, sector_t capacity, int *hsc) { hsc[0] = 255; hsc[1] = 63; sector_div(capacity, 255*63); hsc[2] = capacity; return 0; } /* ---------- Task Collector Thread implementation ---------- */ static void sas_queue(struct sas_ha_struct *sas_ha) { struct scsi_core *core = &sas_ha->core; unsigned long flags; LIST_HEAD(q); int can_queue; int res; struct sas_internal *i = to_sas_internal(core->shost->transportt); spin_lock_irqsave(&core->task_queue_lock, flags); while (!kthread_should_stop() && !list_empty(&core->task_queue)) { can_queue = sas_ha->lldd_queue_size - core->task_queue_size; if (can_queue >= 0) { can_queue = core->task_queue_size; list_splice_init(&core->task_queue, &q); } else { struct list_head *a, *n; can_queue = sas_ha->lldd_queue_size; list_for_each_safe(a, n, &core->task_queue) { list_move_tail(a, &q); if (--can_queue == 0) break; } can_queue = sas_ha->lldd_queue_size; } core->task_queue_size -= can_queue; spin_unlock_irqrestore(&core->task_queue_lock, flags); { struct sas_task *task = list_entry(q.next, struct sas_task, list); list_del_init(&q); res = i->dft->lldd_execute_task(task, can_queue, GFP_KERNEL); if (unlikely(res)) __list_add(&q, task->list.prev, &task->list); } spin_lock_irqsave(&core->task_queue_lock, flags); if (res) { list_splice_init(&q, &core->task_queue); /*at head*/ core->task_queue_size += can_queue; } } spin_unlock_irqrestore(&core->task_queue_lock, flags); } /** * sas_queue_thread -- The Task Collector thread * @_sas_ha: pointer to struct sas_ha */ static int sas_queue_thread(void *_sas_ha) { struct sas_ha_struct *sas_ha = _sas_ha; while (1) { set_current_state(TASK_INTERRUPTIBLE); schedule(); sas_queue(sas_ha); if (kthread_should_stop()) break; } return 0; } int sas_init_queue(struct sas_ha_struct *sas_ha) { struct scsi_core *core = &sas_ha->core; spin_lock_init(&core->task_queue_lock); core->task_queue_size = 0; INIT_LIST_HEAD(&core->task_queue); core->queue_thread = kthread_run(sas_queue_thread, sas_ha, "sas_queue_%d", core->shost->host_no); if (IS_ERR(core->queue_thread)) return PTR_ERR(core->queue_thread); return 0; } void sas_shutdown_queue(struct sas_ha_struct *sas_ha) { unsigned long flags; struct scsi_core *core = &sas_ha->core; struct sas_task *task, *n; kthread_stop(core->queue_thread); if (!list_empty(&core->task_queue)) SAS_DPRINTK("HA: %llx: scsi core task queue is NOT empty!?\n", SAS_ADDR(sas_ha->sas_addr)); spin_lock_irqsave(&core->task_queue_lock, flags); list_for_each_entry_safe(task, n, &core->task_queue, list) { struct scsi_cmnd *cmd = task->uldd_task; list_del_init(&task->list); ASSIGN_SAS_TASK(cmd, NULL); sas_free_task(task); cmd->result = DID_ABORT << 16; cmd->scsi_done(cmd); } spin_unlock_irqrestore(&core->task_queue_lock, flags); } /* * Call the LLDD task abort routine directly. This function is intended for * use by upper layers that need to tell the LLDD to abort a task. */ int __sas_task_abort(struct sas_task *task) { struct sas_internal *si = to_sas_internal(task->dev->port->ha->core.shost->transportt); unsigned long flags; int res; spin_lock_irqsave(&task->task_state_lock, flags); if (task->task_state_flags & SAS_TASK_STATE_ABORTED || task->task_state_flags & SAS_TASK_STATE_DONE) { spin_unlock_irqrestore(&task->task_state_lock, flags); SAS_DPRINTK("%s: Task %p already finished.\n", __func__, task); return 0; } task->task_state_flags |= SAS_TASK_STATE_ABORTED; spin_unlock_irqrestore(&task->task_state_lock, flags); if (!si->dft->lldd_abort_task) return -ENODEV; res = si->dft->lldd_abort_task(task); spin_lock_irqsave(&task->task_state_lock, flags); if ((task->task_state_flags & SAS_TASK_STATE_DONE) || (res == TMF_RESP_FUNC_COMPLETE)) { spin_unlock_irqrestore(&task->task_state_lock, flags); task->task_done(task); return 0; } if (!(task->task_state_flags & SAS_TASK_STATE_DONE)) task->task_state_flags &= ~SAS_TASK_STATE_ABORTED; spin_unlock_irqrestore(&task->task_state_lock, flags); return -EAGAIN; } /* * Tell an upper layer that it needs to initiate an abort for a given task. * This should only ever be called by an LLDD. */ void sas_task_abort(struct sas_task *task) { struct scsi_cmnd *sc = task->uldd_task; /* Escape for libsas internal commands */ if (!sc) { if (!del_timer(&task->timer)) return; task->timer.function(task->timer.data); return; } if (dev_is_sata(task->dev)) { sas_ata_task_abort(task); } else { struct request_queue *q = sc->device->request_queue; unsigned long flags; spin_lock_irqsave(q->queue_lock, flags); blk_abort_request(sc->request); spin_unlock_irqrestore(q->queue_lock, flags); scsi_schedule_eh(sc->device->host); } } int sas_slave_alloc(struct scsi_device *scsi_dev) { struct domain_device *dev = sdev_to_domain_dev(scsi_dev); if (dev_is_sata(dev)) return ata_sas_port_init(dev->sata_dev.ap); return 0; } void sas_target_destroy(struct scsi_target *starget) { struct domain_device *found_dev = sas_find_target(starget); if (!found_dev) return; if (dev_is_sata(found_dev)) ata_sas_port_destroy(found_dev->sata_dev.ap); return; } static void sas_parse_addr(u8 *sas_addr, const char *p) { int i; for (i = 0; i < SAS_ADDR_SIZE; i++) { u8 h, l; if (!*p) break; h = isdigit(*p) ? *p-'0' : toupper(*p)-'A'+10; p++; l = isdigit(*p) ? *p-'0' : toupper(*p)-'A'+10; p++; sas_addr[i] = (h<<4) | l; } } #define SAS_STRING_ADDR_SIZE 16 int sas_request_addr(struct Scsi_Host *shost, u8 *addr) { int res; const struct firmware *fw; res = request_firmware(&fw, "sas_addr", &shost->shost_gendev); if (res) return res; if (fw->size < SAS_STRING_ADDR_SIZE) { res = -ENODEV; goto out; } sas_parse_addr(addr, fw->data); out: release_firmware(fw); return res; } EXPORT_SYMBOL_GPL(sas_request_addr); EXPORT_SYMBOL_GPL(sas_queuecommand); EXPORT_SYMBOL_GPL(sas_target_alloc); EXPORT_SYMBOL_GPL(sas_slave_configure); EXPORT_SYMBOL_GPL(sas_slave_destroy); EXPORT_SYMBOL_GPL(sas_change_queue_depth); EXPORT_SYMBOL_GPL(sas_change_queue_type); EXPORT_SYMBOL_GPL(sas_bios_param); EXPORT_SYMBOL_GPL(__sas_task_abort); EXPORT_SYMBOL_GPL(sas_task_abort); EXPORT_SYMBOL_GPL(sas_phy_reset); EXPORT_SYMBOL_GPL(sas_phy_enable); EXPORT_SYMBOL_GPL(sas_eh_device_reset_handler); EXPORT_SYMBOL_GPL(sas_eh_bus_reset_handler); EXPORT_SYMBOL_GPL(sas_slave_alloc); EXPORT_SYMBOL_GPL(sas_target_destroy); EXPORT_SYMBOL_GPL(sas_ioctl);
gpl-2.0
sencis/kernel_huawei_u8500
arch/arm/plat-omap/clock.c
456
10731
/* * linux/arch/arm/plat-omap/clock.c * * Copyright (C) 2004 - 2008 Nokia corporation * Written by Tuukka Tikkanen <tuukka.tikkanen@elektrobit.com> * * Modified for omap shared clock framework by Tony Lindgren <tony@atomide.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/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/err.h> #include <linux/string.h> #include <linux/clk.h> #include <linux/mutex.h> #include <linux/platform_device.h> #include <linux/cpufreq.h> #include <linux/debugfs.h> #include <linux/io.h> #include <mach/clock.h> static LIST_HEAD(clocks); static DEFINE_MUTEX(clocks_mutex); static DEFINE_SPINLOCK(clockfw_lock); static struct clk_functions *arch_clock; /*------------------------------------------------------------------------- * Standard clock functions defined in include/linux/clk.h *-------------------------------------------------------------------------*/ /* This functions is moved to arch/arm/common/clkdev.c. For OMAP4 since * clock framework is not up , it is defined here to avoid rework in * every driver. Also dummy prcm reset function is added */ /* Dummy hooks only for OMAP4.For rest OMAPs, common clkdev is used */ #if defined(CONFIG_ARCH_OMAP4) struct clk *clk_get(struct device *dev, const char *id) { return NULL; } EXPORT_SYMBOL(clk_get); void clk_put(struct clk *clk) { } EXPORT_SYMBOL(clk_put); void omap2_clk_prepare_for_reboot(void) { } EXPORT_SYMBOL(omap2_clk_prepare_for_reboot); void omap_prcm_arch_reset(char mode) { } EXPORT_SYMBOL(omap_prcm_arch_reset); #endif int clk_enable(struct clk *clk) { unsigned long flags; int ret = 0; if (cpu_is_omap44xx()) /* OMAP4 clk framework not supported yet */ return 0; if (clk == NULL || IS_ERR(clk)) return -EINVAL; spin_lock_irqsave(&clockfw_lock, flags); if (arch_clock->clk_enable) ret = arch_clock->clk_enable(clk); spin_unlock_irqrestore(&clockfw_lock, flags); return ret; } EXPORT_SYMBOL(clk_enable); void clk_disable(struct clk *clk) { unsigned long flags; if (clk == NULL || IS_ERR(clk)) return; spin_lock_irqsave(&clockfw_lock, flags); if (clk->usecount == 0) { printk(KERN_ERR "Trying disable clock %s with 0 usecount\n", clk->name); WARN_ON(1); goto out; } if (arch_clock->clk_disable) arch_clock->clk_disable(clk); out: spin_unlock_irqrestore(&clockfw_lock, flags); } EXPORT_SYMBOL(clk_disable); unsigned long clk_get_rate(struct clk *clk) { unsigned long flags; unsigned long ret = 0; if (clk == NULL || IS_ERR(clk)) return 0; spin_lock_irqsave(&clockfw_lock, flags); ret = clk->rate; spin_unlock_irqrestore(&clockfw_lock, flags); return ret; } EXPORT_SYMBOL(clk_get_rate); /*------------------------------------------------------------------------- * Optional clock functions defined in include/linux/clk.h *-------------------------------------------------------------------------*/ long clk_round_rate(struct clk *clk, unsigned long rate) { unsigned long flags; long ret = 0; if (clk == NULL || IS_ERR(clk)) return ret; spin_lock_irqsave(&clockfw_lock, flags); if (arch_clock->clk_round_rate) ret = arch_clock->clk_round_rate(clk, rate); spin_unlock_irqrestore(&clockfw_lock, flags); return ret; } EXPORT_SYMBOL(clk_round_rate); int clk_set_rate(struct clk *clk, unsigned long rate) { unsigned long flags; int ret = -EINVAL; if (clk == NULL || IS_ERR(clk)) return ret; spin_lock_irqsave(&clockfw_lock, flags); if (arch_clock->clk_set_rate) ret = arch_clock->clk_set_rate(clk, rate); if (ret == 0) { if (clk->recalc) clk->rate = clk->recalc(clk); propagate_rate(clk); } spin_unlock_irqrestore(&clockfw_lock, flags); return ret; } EXPORT_SYMBOL(clk_set_rate); int clk_set_parent(struct clk *clk, struct clk *parent) { unsigned long flags; int ret = -EINVAL; if (cpu_is_omap44xx()) /* OMAP4 clk framework not supported yet */ return 0; if (clk == NULL || IS_ERR(clk) || parent == NULL || IS_ERR(parent)) return ret; spin_lock_irqsave(&clockfw_lock, flags); if (clk->usecount == 0) { if (arch_clock->clk_set_parent) ret = arch_clock->clk_set_parent(clk, parent); if (ret == 0) { if (clk->recalc) clk->rate = clk->recalc(clk); propagate_rate(clk); } } else ret = -EBUSY; spin_unlock_irqrestore(&clockfw_lock, flags); return ret; } EXPORT_SYMBOL(clk_set_parent); struct clk *clk_get_parent(struct clk *clk) { return clk->parent; } EXPORT_SYMBOL(clk_get_parent); /*------------------------------------------------------------------------- * OMAP specific clock functions shared between omap1 and omap2 *-------------------------------------------------------------------------*/ unsigned int __initdata mpurate; /* * By default we use the rate set by the bootloader. * You can override this with mpurate= cmdline option. */ static int __init omap_clk_setup(char *str) { get_option(&str, &mpurate); if (!mpurate) return 1; if (mpurate < 1000) mpurate *= 1000000; return 1; } __setup("mpurate=", omap_clk_setup); /* Used for clocks that always have same value as the parent clock */ unsigned long followparent_recalc(struct clk *clk) { return clk->parent->rate; } void clk_reparent(struct clk *child, struct clk *parent) { list_del_init(&child->sibling); if (parent) list_add(&child->sibling, &parent->children); child->parent = parent; /* now do the debugfs renaming to reattach the child to the proper parent */ } /* Propagate rate to children */ void propagate_rate(struct clk * tclk) { struct clk *clkp; list_for_each_entry(clkp, &tclk->children, sibling) { if (clkp->recalc) clkp->rate = clkp->recalc(clkp); propagate_rate(clkp); } } static LIST_HEAD(root_clks); /** * recalculate_root_clocks - recalculate and propagate all root clocks * * Recalculates all root clocks (clocks with no parent), which if the * clock's .recalc is set correctly, should also propagate their rates. * Called at init. */ void recalculate_root_clocks(void) { struct clk *clkp; list_for_each_entry(clkp, &root_clks, sibling) { if (clkp->recalc) clkp->rate = clkp->recalc(clkp); propagate_rate(clkp); } } /** * clk_preinit - initialize any fields in the struct clk before clk init * @clk: struct clk * to initialize * * Initialize any struct clk fields needed before normal clk initialization * can run. No return value. */ void clk_preinit(struct clk *clk) { INIT_LIST_HEAD(&clk->children); } int clk_register(struct clk *clk) { if (clk == NULL || IS_ERR(clk)) return -EINVAL; /* * trap out already registered clocks */ if (clk->node.next || clk->node.prev) return 0; mutex_lock(&clocks_mutex); if (clk->parent) list_add(&clk->sibling, &clk->parent->children); else list_add(&clk->sibling, &root_clks); list_add(&clk->node, &clocks); if (clk->init) clk->init(clk); mutex_unlock(&clocks_mutex); return 0; } EXPORT_SYMBOL(clk_register); void clk_unregister(struct clk *clk) { if (clk == NULL || IS_ERR(clk)) return; mutex_lock(&clocks_mutex); list_del(&clk->sibling); list_del(&clk->node); mutex_unlock(&clocks_mutex); } EXPORT_SYMBOL(clk_unregister); void clk_enable_init_clocks(void) { struct clk *clkp; list_for_each_entry(clkp, &clocks, node) { if (clkp->flags & ENABLE_ON_INIT) clk_enable(clkp); } } EXPORT_SYMBOL(clk_enable_init_clocks); /* * Low level helpers */ static int clkll_enable_null(struct clk *clk) { return 0; } static void clkll_disable_null(struct clk *clk) { } const struct clkops clkops_null = { .enable = clkll_enable_null, .disable = clkll_disable_null, }; #ifdef CONFIG_CPU_FREQ void clk_init_cpufreq_table(struct cpufreq_frequency_table **table) { unsigned long flags; spin_lock_irqsave(&clockfw_lock, flags); if (arch_clock->clk_init_cpufreq_table) arch_clock->clk_init_cpufreq_table(table); spin_unlock_irqrestore(&clockfw_lock, flags); } EXPORT_SYMBOL(clk_init_cpufreq_table); #endif /*-------------------------------------------------------------------------*/ #ifdef CONFIG_OMAP_RESET_CLOCKS /* * Disable any unused clocks left on by the bootloader */ static int __init clk_disable_unused(void) { struct clk *ck; unsigned long flags; list_for_each_entry(ck, &clocks, node) { if (ck->ops == &clkops_null) continue; if (ck->usecount > 0 || ck->enable_reg == 0) continue; spin_lock_irqsave(&clockfw_lock, flags); if (arch_clock->clk_disable_unused) arch_clock->clk_disable_unused(ck); spin_unlock_irqrestore(&clockfw_lock, flags); } return 0; } late_initcall(clk_disable_unused); #endif int __init clk_init(struct clk_functions * custom_clocks) { if (!custom_clocks) { printk(KERN_ERR "No custom clock functions registered\n"); BUG(); } arch_clock = custom_clocks; return 0; } #if defined(CONFIG_PM_DEBUG) && defined(CONFIG_DEBUG_FS) /* * debugfs support to trace clock tree hierarchy and attributes */ static struct dentry *clk_debugfs_root; static int clk_debugfs_register_one(struct clk *c) { int err; struct dentry *d, *child; struct clk *pa = c->parent; char s[255]; char *p = s; p += sprintf(p, "%s", c->name); if (c->id != 0) sprintf(p, ":%d", c->id); d = debugfs_create_dir(s, pa ? pa->dent : clk_debugfs_root); if (!d) return -ENOMEM; c->dent = d; d = debugfs_create_u8("usecount", S_IRUGO, c->dent, (u8 *)&c->usecount); if (!d) { err = -ENOMEM; goto err_out; } d = debugfs_create_u32("rate", S_IRUGO, c->dent, (u32 *)&c->rate); if (!d) { err = -ENOMEM; goto err_out; } d = debugfs_create_x32("flags", S_IRUGO, c->dent, (u32 *)&c->flags); if (!d) { err = -ENOMEM; goto err_out; } return 0; err_out: d = c->dent; list_for_each_entry(child, &d->d_subdirs, d_u.d_child) debugfs_remove(child); debugfs_remove(c->dent); return err; } static int clk_debugfs_register(struct clk *c) { int err; struct clk *pa = c->parent; if (pa && !pa->dent) { err = clk_debugfs_register(pa); if (err) return err; } if (!c->dent) { err = clk_debugfs_register_one(c); if (err) return err; } return 0; } static int __init clk_debugfs_init(void) { struct clk *c; struct dentry *d; int err; d = debugfs_create_dir("clock", NULL); if (!d) return -ENOMEM; clk_debugfs_root = d; list_for_each_entry(c, &clocks, node) { err = clk_debugfs_register(c); if (err) goto err_out; } return 0; err_out: debugfs_remove_recursive(clk_debugfs_root); return err; } late_initcall(clk_debugfs_init); #endif /* defined(CONFIG_PM_DEBUG) && defined(CONFIG_DEBUG_FS) */
gpl-2.0
blade-af3/android_kernel_zte_P731A20
sound/soc/blackfin/bf5xx-tdm-pcm.c
2248
9178
/* * File: sound/soc/blackfin/bf5xx-tdm-pcm.c * Author: Barry Song <Barry.Song@analog.com> * * Created: Tue June 06 2009 * Description: DMA driver for tdm codec * * Modified: * Copyright 2009 Analog Devices Inc. * * Bugs: Enter bugs at http://blackfin.uclinux.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 the file COPYING, or write * to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/gfp.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <asm/dma.h> #include "bf5xx-tdm-pcm.h" #include "bf5xx-tdm.h" #include "bf5xx-sport.h" #define PCM_BUFFER_MAX 0x8000 #define FRAGMENT_SIZE_MIN (4*1024) #define FRAGMENTS_MIN 2 #define FRAGMENTS_MAX 32 static void bf5xx_dma_irq(void *data) { struct snd_pcm_substream *pcm = data; snd_pcm_period_elapsed(pcm); } static const struct snd_pcm_hardware bf5xx_pcm_hardware = { .info = (SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_RESUME), .formats = SNDRV_PCM_FMTBIT_S32_LE, .rates = SNDRV_PCM_RATE_48000, .channels_min = 2, .channels_max = 8, .buffer_bytes_max = PCM_BUFFER_MAX, .period_bytes_min = FRAGMENT_SIZE_MIN, .period_bytes_max = PCM_BUFFER_MAX/2, .periods_min = FRAGMENTS_MIN, .periods_max = FRAGMENTS_MAX, }; static int bf5xx_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { size_t size = bf5xx_pcm_hardware.buffer_bytes_max; snd_pcm_lib_malloc_pages(substream, size * 4); return 0; } static int bf5xx_pcm_hw_free(struct snd_pcm_substream *substream) { snd_pcm_lib_free_pages(substream); return 0; } static int bf5xx_pcm_prepare(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct sport_device *sport = runtime->private_data; int fragsize_bytes = frames_to_bytes(runtime, runtime->period_size); fragsize_bytes /= runtime->channels; /* inflate the fragsize to match the dma width of SPORT */ fragsize_bytes *= 8; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { sport_set_tx_callback(sport, bf5xx_dma_irq, substream); sport_config_tx_dma(sport, runtime->dma_area, runtime->periods, fragsize_bytes); } else { sport_set_rx_callback(sport, bf5xx_dma_irq, substream); sport_config_rx_dma(sport, runtime->dma_area, runtime->periods, fragsize_bytes); } return 0; } static int bf5xx_pcm_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_pcm_runtime *runtime = substream->runtime; struct sport_device *sport = runtime->private_data; int ret = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_START: if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) sport_tx_start(sport); else sport_rx_start(sport); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) sport_tx_stop(sport); else sport_rx_stop(sport); break; default: ret = -EINVAL; } return ret; } static snd_pcm_uframes_t bf5xx_pcm_pointer(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct sport_device *sport = runtime->private_data; unsigned int diff; snd_pcm_uframes_t frames; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { diff = sport_curr_offset_tx(sport); frames = diff / (8*4); /* 32 bytes per frame */ } else { diff = sport_curr_offset_rx(sport); frames = diff / (8*4); } return frames; } static int bf5xx_pcm_open(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct sport_device *sport_handle = snd_soc_dai_get_drvdata(cpu_dai); struct snd_pcm_runtime *runtime = substream->runtime; struct snd_dma_buffer *buf = &substream->dma_buffer; int ret = 0; snd_soc_set_runtime_hwparams(substream, &bf5xx_pcm_hardware); ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); if (ret < 0) goto out; if (sport_handle != NULL) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) sport_handle->tx_buf = buf->area; else sport_handle->rx_buf = buf->area; runtime->private_data = sport_handle; } else { pr_err("sport_handle is NULL\n"); ret = -ENODEV; } out: return ret; } static int bf5xx_pcm_copy(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void *buf, snd_pcm_uframes_t count) { struct snd_pcm_runtime *runtime = substream->runtime; struct sport_device *sport = runtime->private_data; struct bf5xx_tdm_port *tdm_port = sport->private_data; unsigned int *src; unsigned int *dst; int i; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { src = buf; dst = (unsigned int *)substream->runtime->dma_area; dst += pos * 8; while (count--) { for (i = 0; i < substream->runtime->channels; i++) *(dst + tdm_port->tx_map[i]) = *src++; dst += 8; } } else { src = (unsigned int *)substream->runtime->dma_area; dst = buf; src += pos * 8; while (count--) { for (i = 0; i < substream->runtime->channels; i++) *dst++ = *(src + tdm_port->rx_map[i]); src += 8; } } return 0; } static int bf5xx_pcm_silence(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, snd_pcm_uframes_t count) { unsigned char *buf = substream->runtime->dma_area; buf += pos * 8 * 4; memset(buf, '\0', count * 8 * 4); return 0; } struct snd_pcm_ops bf5xx_pcm_tdm_ops = { .open = bf5xx_pcm_open, .ioctl = snd_pcm_lib_ioctl, .hw_params = bf5xx_pcm_hw_params, .hw_free = bf5xx_pcm_hw_free, .prepare = bf5xx_pcm_prepare, .trigger = bf5xx_pcm_trigger, .pointer = bf5xx_pcm_pointer, .copy = bf5xx_pcm_copy, .silence = bf5xx_pcm_silence, }; static int bf5xx_pcm_preallocate_dma_buffer(struct snd_pcm *pcm, int stream) { struct snd_pcm_substream *substream = pcm->streams[stream].substream; struct snd_dma_buffer *buf = &substream->dma_buffer; size_t size = bf5xx_pcm_hardware.buffer_bytes_max; buf->dev.type = SNDRV_DMA_TYPE_DEV; buf->dev.dev = pcm->card->dev; buf->private_data = NULL; buf->area = dma_alloc_coherent(pcm->card->dev, size * 4, &buf->addr, GFP_KERNEL); if (!buf->area) { pr_err("Failed to allocate dma memory - Please increase uncached DMA memory region\n"); return -ENOMEM; } buf->bytes = size; return 0; } static void bf5xx_pcm_free_dma_buffers(struct snd_pcm *pcm) { struct snd_pcm_substream *substream; struct snd_dma_buffer *buf; int stream; for (stream = 0; stream < 2; stream++) { substream = pcm->streams[stream].substream; if (!substream) continue; buf = &substream->dma_buffer; if (!buf->area) continue; dma_free_coherent(NULL, buf->bytes, buf->area, 0); buf->area = NULL; } } static u64 bf5xx_pcm_dmamask = DMA_BIT_MASK(32); static int bf5xx_pcm_tdm_new(struct snd_soc_pcm_runtime *rtd) { struct snd_card *card = rtd->card->snd_card; struct snd_pcm *pcm = rtd->pcm; int ret = 0; if (!card->dev->dma_mask) card->dev->dma_mask = &bf5xx_pcm_dmamask; if (!card->dev->coherent_dma_mask) card->dev->coherent_dma_mask = DMA_BIT_MASK(32); if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream) { ret = bf5xx_pcm_preallocate_dma_buffer(pcm, SNDRV_PCM_STREAM_PLAYBACK); if (ret) goto out; } if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream) { ret = bf5xx_pcm_preallocate_dma_buffer(pcm, SNDRV_PCM_STREAM_CAPTURE); if (ret) goto out; } out: return ret; } static struct snd_soc_platform_driver bf5xx_tdm_soc_platform = { .ops = &bf5xx_pcm_tdm_ops, .pcm_new = bf5xx_pcm_tdm_new, .pcm_free = bf5xx_pcm_free_dma_buffers, }; static int bf5xx_soc_platform_probe(struct platform_device *pdev) { return snd_soc_register_platform(&pdev->dev, &bf5xx_tdm_soc_platform); } static int bf5xx_soc_platform_remove(struct platform_device *pdev) { snd_soc_unregister_platform(&pdev->dev); return 0; } static struct platform_driver bfin_tdm_driver = { .driver = { .name = "bfin-tdm-pcm-audio", .owner = THIS_MODULE, }, .probe = bf5xx_soc_platform_probe, .remove = bf5xx_soc_platform_remove, }; module_platform_driver(bfin_tdm_driver); MODULE_AUTHOR("Barry Song"); MODULE_DESCRIPTION("ADI Blackfin TDM PCM DMA module"); MODULE_LICENSE("GPL");
gpl-2.0
Emotroid-Team/emotion_kernel_tw_edge
drivers/staging/gdm72xx/gdm_wimax.c
2248
22701
/* * Copyright (c) 2012 GCT Semiconductor, Inc. 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/etherdevice.h> #include <asm/byteorder.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/udp.h> #include <linux/in.h> #include "gdm_wimax.h" #include "hci.h" #include "wm_ioctl.h" #include "netlink_k.h" #define gdm_wimax_send(n, d, l) \ (n->phy_dev->send_func)(n->phy_dev->priv_dev, d, l, NULL, NULL) #define gdm_wimax_send_with_cb(n, d, l, c, b) \ (n->phy_dev->send_func)(n->phy_dev->priv_dev, d, l, c, b) #define gdm_wimax_rcv_with_cb(n, c, b) \ (n->phy_dev->rcv_func)(n->phy_dev->priv_dev, c, b) #define EVT_MAX_SIZE 2048 struct evt_entry { struct list_head list; struct net_device *dev; char evt_data[EVT_MAX_SIZE]; int size; }; static void __gdm_wimax_event_send(struct work_struct *work); static inline struct evt_entry *alloc_event_entry(void); static inline void free_event_entry(struct evt_entry *e); static struct evt_entry *get_event_entry(void); static void put_event_entry(struct evt_entry *e); static struct { int ref_cnt; struct sock *sock; struct list_head evtq; spinlock_t evt_lock; struct list_head freeq; struct work_struct ws; } wm_event; static u8 gdm_wimax_macaddr[6] = {0x00, 0x0a, 0x3b, 0xf0, 0x01, 0x30}; static void gdm_wimax_ind_fsm_update(struct net_device *dev, struct fsm_s *fsm); static void gdm_wimax_ind_if_updown(struct net_device *dev, int if_up); #if defined(DEBUG_SDU) static void printk_hex(u8 *buf, u32 size) { int i; for (i = 0; i < size; i++) { if (i && i % 16 == 0) printk(KERN_DEBUG "\n%02x ", *buf++); else printk(KERN_DEBUG "%02x ", *buf++); } printk(KERN_DEBUG "\n"); } static const char *get_protocol_name(u16 protocol) { static char buf[32]; const char *name = "-"; switch (protocol) { case ETH_P_ARP: name = "ARP"; break; case ETH_P_IP: name = "IP"; break; case ETH_P_IPV6: name = "IPv6"; break; } sprintf(buf, "0x%04x(%s)", protocol, name); return buf; } static const char *get_ip_protocol_name(u8 ip_protocol) { static char buf[32]; const char *name = "-"; switch (ip_protocol) { case IPPROTO_TCP: name = "TCP"; break; case IPPROTO_UDP: name = "UDP"; break; case IPPROTO_ICMP: name = "ICMP"; break; } sprintf(buf, "%u(%s)", ip_protocol, name); return buf; } static const char *get_port_name(u16 port) { static char buf[32]; const char *name = "-"; switch (port) { case 67: name = "DHCP-Server"; break; case 68: name = "DHCP-Client"; break; case 69: name = "TFTP"; break; } sprintf(buf, "%u(%s)", port, name); return buf; } static void dump_eth_packet(const char *title, u8 *data, int len) { struct iphdr *ih = NULL; struct udphdr *uh = NULL; u16 protocol = 0; u8 ip_protocol = 0; u16 port = 0; protocol = (data[12]<<8) | data[13]; ih = (struct iphdr *) (data+ETH_HLEN); if (protocol == ETH_P_IP) { uh = (struct udphdr *) ((char *)ih + sizeof(struct iphdr)); ip_protocol = ih->protocol; port = ntohs(uh->dest); } else if (protocol == ETH_P_IPV6) { struct ipv6hdr *i6h = (struct ipv6hdr *) data; uh = (struct udphdr *) ((char *)i6h + sizeof(struct ipv6hdr)); ip_protocol = i6h->nexthdr; port = ntohs(uh->dest); } printk(KERN_DEBUG "[%s] len=%d, %s, %s, %s\n", title, len, get_protocol_name(protocol), get_ip_protocol_name(ip_protocol), get_port_name(port)); if (!(data[0] == 0xff && data[1] == 0xff)) { if (protocol == ETH_P_IP) { printk(KERN_DEBUG " src=%pI4\n", &ih->saddr); } else if (protocol == ETH_P_IPV6) { printk(KERN_DEBUG " src=%pI6\n", &ih->saddr); } } #if (DUMP_PACKET & DUMP_SDU_ALL) printk_hex(data, len); #else #if (DUMP_PACKET & DUMP_SDU_ARP) if (protocol == ETH_P_ARP) printk_hex(data, len); #endif #if (DUMP_PACKET & DUMP_SDU_IP) if (protocol == ETH_P_IP || protocol == ETH_P_IPV6) printk_hex(data, len); #else #if (DUMP_PACKET & DUMP_SDU_IP_TCP) if (ip_protocol == IPPROTO_TCP) printk_hex(data, len); #endif #if (DUMP_PACKET & DUMP_SDU_IP_UDP) if (ip_protocol == IPPROTO_UDP) printk_hex(data, len); #endif #if (DUMP_PACKET & DUMP_SDU_IP_ICMP) if (ip_protocol == IPPROTO_ICMP) printk_hex(data, len); #endif #endif #endif } #endif static inline int gdm_wimax_header(struct sk_buff **pskb) { u16 buf[HCI_HEADER_SIZE / sizeof(u16)]; struct sk_buff *skb = *pskb; int ret = 0; if (unlikely(skb_headroom(skb) < HCI_HEADER_SIZE)) { struct sk_buff *skb2; skb2 = skb_realloc_headroom(skb, HCI_HEADER_SIZE); if (skb2 == NULL) return -ENOMEM; if (skb->sk) skb_set_owner_w(skb2, skb->sk); kfree_skb(skb); skb = skb2; } skb_push(skb, HCI_HEADER_SIZE); buf[0] = H2B(WIMAX_TX_SDU); buf[1] = H2B(skb->len - HCI_HEADER_SIZE); memcpy(skb->data, buf, HCI_HEADER_SIZE); *pskb = skb; return ret; } static void gdm_wimax_event_rcv(struct net_device *dev, u16 type, void *msg, int len) { struct nic *nic = netdev_priv(dev); #if defined(DEBUG_HCI) u8 *buf = (u8 *) msg; u16 hci_cmd = (buf[0]<<8) | buf[1]; u16 hci_len = (buf[2]<<8) | buf[3]; printk(KERN_DEBUG "H=>D: 0x%04x(%d)\n", hci_cmd, hci_len); #endif gdm_wimax_send(nic, msg, len); } static int gdm_wimax_event_init(void) { if (!wm_event.ref_cnt) { wm_event.sock = netlink_init(NETLINK_WIMAX, gdm_wimax_event_rcv); if (wm_event.sock) { INIT_LIST_HEAD(&wm_event.evtq); INIT_LIST_HEAD(&wm_event.freeq); INIT_WORK(&wm_event.ws, __gdm_wimax_event_send); spin_lock_init(&wm_event.evt_lock); } } if (wm_event.sock) { wm_event.ref_cnt++; return 0; } pr_err("Creating WiMax Event netlink is failed\n"); return -1; } static void gdm_wimax_event_exit(void) { if (wm_event.sock && --wm_event.ref_cnt == 0) { struct evt_entry *e, *temp; unsigned long flags; spin_lock_irqsave(&wm_event.evt_lock, flags); list_for_each_entry_safe(e, temp, &wm_event.evtq, list) { list_del(&e->list); free_event_entry(e); } list_for_each_entry_safe(e, temp, &wm_event.freeq, list) { list_del(&e->list); free_event_entry(e); } spin_unlock_irqrestore(&wm_event.evt_lock, flags); netlink_exit(wm_event.sock); wm_event.sock = NULL; } } static inline struct evt_entry *alloc_event_entry(void) { return kmalloc(sizeof(struct evt_entry), GFP_ATOMIC); } static inline void free_event_entry(struct evt_entry *e) { kfree(e); } static struct evt_entry *get_event_entry(void) { struct evt_entry *e; if (list_empty(&wm_event.freeq)) e = alloc_event_entry(); else { e = list_entry(wm_event.freeq.next, struct evt_entry, list); list_del(&e->list); } return e; } static void put_event_entry(struct evt_entry *e) { BUG_ON(!e); list_add_tail(&e->list, &wm_event.freeq); } static void __gdm_wimax_event_send(struct work_struct *work) { int idx; unsigned long flags; struct evt_entry *e; spin_lock_irqsave(&wm_event.evt_lock, flags); while (!list_empty(&wm_event.evtq)) { e = list_entry(wm_event.evtq.next, struct evt_entry, list); spin_unlock_irqrestore(&wm_event.evt_lock, flags); sscanf(e->dev->name, "wm%d", &idx); netlink_send(wm_event.sock, idx, 0, e->evt_data, e->size); spin_lock_irqsave(&wm_event.evt_lock, flags); list_del(&e->list); put_event_entry(e); } spin_unlock_irqrestore(&wm_event.evt_lock, flags); } static int gdm_wimax_event_send(struct net_device *dev, char *buf, int size) { struct evt_entry *e; unsigned long flags; #if defined(DEBUG_HCI) u16 hci_cmd = ((u8)buf[0]<<8) | (u8)buf[1]; u16 hci_len = ((u8)buf[2]<<8) | (u8)buf[3]; printk(KERN_DEBUG "D=>H: 0x%04x(%d)\n", hci_cmd, hci_len); #endif spin_lock_irqsave(&wm_event.evt_lock, flags); e = get_event_entry(); if (!e) { netdev_err(dev, "%s: No memory for event\n", __func__); spin_unlock_irqrestore(&wm_event.evt_lock, flags); return -ENOMEM; } e->dev = dev; e->size = size; memcpy(e->evt_data, buf, size); list_add_tail(&e->list, &wm_event.evtq); spin_unlock_irqrestore(&wm_event.evt_lock, flags); schedule_work(&wm_event.ws); return 0; } static void tx_complete(void *arg) { struct nic *nic = arg; if (netif_queue_stopped(nic->netdev)) netif_wake_queue(nic->netdev); } int gdm_wimax_send_tx(struct sk_buff *skb, struct net_device *dev) { int ret = 0; struct nic *nic = netdev_priv(dev); ret = gdm_wimax_send_with_cb(nic, skb->data, skb->len, tx_complete, nic); if (ret == -ENOSPC) { netif_stop_queue(dev); ret = 0; } if (ret) { skb_pull(skb, HCI_HEADER_SIZE); return ret; } nic->stats.tx_packets++; nic->stats.tx_bytes += skb->len - HCI_HEADER_SIZE; kfree_skb(skb); return ret; } static int gdm_wimax_tx(struct sk_buff *skb, struct net_device *dev) { int ret = 0; struct nic *nic = netdev_priv(dev); struct fsm_s *fsm = (struct fsm_s *) nic->sdk_data[SIOC_DATA_FSM].buf; #if defined(DEBUG_SDU) dump_eth_packet("TX", skb->data, skb->len); #endif ret = gdm_wimax_header(&skb); if (ret < 0) { skb_pull(skb, HCI_HEADER_SIZE); return ret; } #if !defined(LOOPBACK_TEST) if (!fsm) netdev_err(dev, "ASSERTION ERROR: fsm is NULL!!\n"); else if (fsm->m_status != M_CONNECTED) { netdev_emerg(dev, "ASSERTION ERROR: Device is NOT ready. status=%d\n", fsm->m_status); kfree_skb(skb); return 0; } #endif #if defined(CONFIG_WIMAX_GDM72XX_QOS) ret = gdm_qos_send_hci_pkt(skb, dev); #else ret = gdm_wimax_send_tx(skb, dev); #endif return ret; } static int gdm_wimax_set_config(struct net_device *dev, struct ifmap *map) { if (dev->flags & IFF_UP) return -EBUSY; return 0; } static void __gdm_wimax_set_mac_addr(struct net_device *dev, char *mac_addr) { u16 hci_pkt_buf[32 / sizeof(u16)]; u8 *pkt = (u8 *) &hci_pkt_buf[0]; struct nic *nic = netdev_priv(dev); /* Since dev is registered as a ethernet device, * ether_setup has made dev->addr_len to be ETH_ALEN */ memcpy(dev->dev_addr, mac_addr, dev->addr_len); /* Let lower layer know of this change by sending * SetInformation(MAC Address) */ hci_pkt_buf[0] = H2B(WIMAX_SET_INFO); /* cmd_evt */ hci_pkt_buf[1] = H2B(8); /* size */ pkt[4] = 0; /* T */ pkt[5] = 6; /* L */ memcpy(pkt + 6, mac_addr, dev->addr_len); /* V */ gdm_wimax_send(nic, pkt, HCI_HEADER_SIZE + 8); } /* A driver function */ static int gdm_wimax_set_mac_addr(struct net_device *dev, void *p) { struct sockaddr *addr = p; if (netif_running(dev)) return -EBUSY; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; __gdm_wimax_set_mac_addr(dev, addr->sa_data); return 0; } static struct net_device_stats *gdm_wimax_stats(struct net_device *dev) { struct nic *nic = netdev_priv(dev); return &nic->stats; } static int gdm_wimax_open(struct net_device *dev) { struct nic *nic = netdev_priv(dev); struct fsm_s *fsm = (struct fsm_s *) nic->sdk_data[SIOC_DATA_FSM].buf; netif_start_queue(dev); if (fsm && fsm->m_status != M_INIT) gdm_wimax_ind_if_updown(dev, 1); return 0; } static int gdm_wimax_close(struct net_device *dev) { struct nic *nic = netdev_priv(dev); struct fsm_s *fsm = (struct fsm_s *) nic->sdk_data[SIOC_DATA_FSM].buf; netif_stop_queue(dev); if (fsm && fsm->m_status != M_INIT) gdm_wimax_ind_if_updown(dev, 0); return 0; } static void kdelete(void **buf) { if (buf && *buf) { kfree(*buf); *buf = NULL; } } static int gdm_wimax_ioctl_get_data(struct data_s *dst, struct data_s *src) { int size; size = dst->size < src->size ? dst->size : src->size; dst->size = size; if (src->size) { if (!dst->buf) return -EINVAL; if (copy_to_user(dst->buf, src->buf, size)) return -EFAULT; } return 0; } static int gdm_wimax_ioctl_set_data(struct data_s *dst, struct data_s *src) { if (!src->size) { dst->size = 0; return 0; } if (!src->buf) return -EINVAL; if (!(dst->buf && dst->size == src->size)) { kdelete(&dst->buf); dst->buf = kmalloc(src->size, GFP_KERNEL); if (dst->buf == NULL) return -ENOMEM; } if (copy_from_user(dst->buf, src->buf, src->size)) { kdelete(&dst->buf); return -EFAULT; } dst->size = src->size; return 0; } static void gdm_wimax_cleanup_ioctl(struct net_device *dev) { struct nic *nic = netdev_priv(dev); int i; for (i = 0; i < SIOC_DATA_MAX; i++) kdelete(&nic->sdk_data[i].buf); } static void gdm_update_fsm(struct net_device *dev, struct fsm_s *new_fsm) { struct nic *nic = netdev_priv(dev); struct fsm_s *cur_fsm = (struct fsm_s *) nic->sdk_data[SIOC_DATA_FSM].buf; if (!cur_fsm) return; if (cur_fsm->m_status != new_fsm->m_status || cur_fsm->c_status != new_fsm->c_status) { if (new_fsm->m_status == M_CONNECTED) netif_carrier_on(dev); else if (cur_fsm->m_status == M_CONNECTED) { netif_carrier_off(dev); #if defined(CONFIG_WIMAX_GDM72XX_QOS) gdm_qos_release_list(nic); #endif } gdm_wimax_ind_fsm_update(dev, new_fsm); } } static int gdm_wimax_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct wm_req_s *req = (struct wm_req_s *) ifr; struct nic *nic = netdev_priv(dev); int ret; if (cmd != SIOCWMIOCTL) return -EOPNOTSUPP; switch (req->cmd) { case SIOCG_DATA: case SIOCS_DATA: if (req->data_id >= SIOC_DATA_MAX) { netdev_err(dev, "%s error: data-index(%d) is invalid!!\n", __func__, req->data_id); return -EOPNOTSUPP; } if (req->cmd == SIOCG_DATA) { ret = gdm_wimax_ioctl_get_data(&req->data, &nic->sdk_data[req->data_id]); if (ret < 0) return ret; } else if (req->cmd == SIOCS_DATA) { if (req->data_id == SIOC_DATA_FSM) { /*NOTE: gdm_update_fsm should be called before gdm_wimax_ioctl_set_data is called*/ gdm_update_fsm(dev, (struct fsm_s *) req->data.buf); } ret = gdm_wimax_ioctl_set_data( &nic->sdk_data[req->data_id], &req->data); if (ret < 0) return ret; } break; default: netdev_err(dev, "%s: %x unknown ioctl\n", __func__, cmd); return -EOPNOTSUPP; } return 0; } static void gdm_wimax_prepare_device(struct net_device *dev) { struct nic *nic = netdev_priv(dev); u16 buf[32 / sizeof(u16)]; struct hci_s *hci = (struct hci_s *) buf; u16 len = 0; u32 val = 0; #define BIT_MULTI_CS 0 #define BIT_WIMAX 1 #define BIT_QOS 2 #define BIT_AGGREGATION 3 /* GetInformation mac address */ len = 0; hci->cmd_evt = H2B(WIMAX_GET_INFO); hci->data[len++] = TLV_T(T_MAC_ADDRESS); hci->length = H2B(len); gdm_wimax_send(nic, hci, HCI_HEADER_SIZE+len); val = (1<<BIT_WIMAX) | (1<<BIT_MULTI_CS); #if defined(CONFIG_WIMAX_GDM72XX_QOS) val |= (1<<BIT_QOS); #endif #if defined(CONFIG_WIMAX_GDM72XX_WIMAX2) val |= (1<<BIT_AGGREGATION); #endif /* Set capability */ len = 0; hci->cmd_evt = H2B(WIMAX_SET_INFO); hci->data[len++] = TLV_T(T_CAPABILITY); hci->data[len++] = TLV_L(T_CAPABILITY); val = DH2B(val); memcpy(&hci->data[len], &val, TLV_L(T_CAPABILITY)); len += TLV_L(T_CAPABILITY); hci->length = H2B(len); gdm_wimax_send(nic, hci, HCI_HEADER_SIZE+len); netdev_info(dev, "GDM WiMax Set CAPABILITY: 0x%08X\n", DB2H(val)); } static int gdm_wimax_hci_get_tlv(u8 *buf, u8 *T, u16 *L, u8 **V) { #define __U82U16(b) ((u16)((u8 *)(b))[0] | ((u16)((u8 *)(b))[1] << 8)) int next_pos; *T = buf[0]; if (buf[1] == 0x82) { *L = B2H(__U82U16(&buf[2])); next_pos = 1/*type*/+3/*len*/; } else { *L = buf[1]; next_pos = 1/*type*/+1/*len*/; } *V = &buf[next_pos]; next_pos += *L/*length of val*/; return next_pos; } static int gdm_wimax_get_prepared_info(struct net_device *dev, char *buf, int len) { u8 T, *V; u16 L; u16 cmd_evt, cmd_len; int pos = HCI_HEADER_SIZE; cmd_evt = B2H(*(u16 *)&buf[0]); cmd_len = B2H(*(u16 *)&buf[2]); if (len < cmd_len + HCI_HEADER_SIZE) { netdev_err(dev, "%s: invalid length [%d/%d]\n", __func__, cmd_len + HCI_HEADER_SIZE, len); return -1; } if (cmd_evt == WIMAX_GET_INFO_RESULT) { if (cmd_len < 2) { netdev_err(dev, "%s: len is too short [%x/%d]\n", __func__, cmd_evt, len); return -1; } pos += gdm_wimax_hci_get_tlv(&buf[pos], &T, &L, &V); if (T == TLV_T(T_MAC_ADDRESS)) { if (L != dev->addr_len) { netdev_err(dev, "%s Invalid inofrmation result T/L [%x/%d]\n", __func__, T, L); return -1; } netdev_info(dev, "MAC change [%pM]->[%pM]\n", dev->dev_addr, V); memcpy(dev->dev_addr, V, dev->addr_len); return 1; } } gdm_wimax_event_send(dev, buf, len); return 0; } static void gdm_wimax_netif_rx(struct net_device *dev, char *buf, int len) { struct nic *nic = netdev_priv(dev); struct sk_buff *skb; int ret; #if defined(DEBUG_SDU) dump_eth_packet("RX", buf, len); #endif skb = dev_alloc_skb(len + 2); if (!skb) { netdev_err(dev, "%s: dev_alloc_skb failed!\n", __func__); return; } skb_reserve(skb, 2); nic->stats.rx_packets++; nic->stats.rx_bytes += len; memcpy(skb_put(skb, len), buf, len); skb->dev = dev; skb->protocol = eth_type_trans(skb, dev); /* what will happen? */ ret = in_interrupt() ? netif_rx(skb) : netif_rx_ni(skb); if (ret == NET_RX_DROP) netdev_err(dev, "%s skb dropped\n", __func__); } static void gdm_wimax_transmit_aggr_pkt(struct net_device *dev, char *buf, int len) { #define HCI_PADDING_BYTE 4 #define HCI_RESERVED_BYTE 4 struct hci_s *hci; int length; while (len > 0) { hci = (struct hci_s *) buf; if (B2H(hci->cmd_evt) != WIMAX_RX_SDU) { netdev_err(dev, "Wrong cmd_evt(0x%04X)\n", B2H(hci->cmd_evt)); break; } length = B2H(hci->length); gdm_wimax_netif_rx(dev, hci->data, length); if (length & 0x3) { /* Add padding size */ length += HCI_PADDING_BYTE - (length & 0x3); } length += HCI_HEADER_SIZE + HCI_RESERVED_BYTE; len -= length; buf += length; } } static void gdm_wimax_transmit_pkt(struct net_device *dev, char *buf, int len) { #if defined(CONFIG_WIMAX_GDM72XX_QOS) struct nic *nic = netdev_priv(dev); #endif u16 cmd_evt, cmd_len; /* This code is added for certain rx packet to be ignored. */ if (len == 0) return; cmd_evt = B2H(*(u16 *)&buf[0]); cmd_len = B2H(*(u16 *)&buf[2]); if (len < cmd_len + HCI_HEADER_SIZE) { if (len) netdev_err(dev, "%s: invalid length [%d/%d]\n", __func__, cmd_len + HCI_HEADER_SIZE, len); return; } switch (cmd_evt) { case WIMAX_RX_SDU_AGGR: gdm_wimax_transmit_aggr_pkt(dev, &buf[HCI_HEADER_SIZE], cmd_len); break; case WIMAX_RX_SDU: gdm_wimax_netif_rx(dev, &buf[HCI_HEADER_SIZE], cmd_len); break; #if defined(CONFIG_WIMAX_GDM72XX_QOS) case WIMAX_EVT_MODEM_REPORT: gdm_recv_qos_hci_packet(nic, buf, len); break; #endif case WIMAX_SDU_TX_FLOW: if (buf[4] == 0) { if (!netif_queue_stopped(dev)) netif_stop_queue(dev); } else if (buf[4] == 1) { if (netif_queue_stopped(dev)) netif_wake_queue(dev); } break; default: gdm_wimax_event_send(dev, buf, len); break; } } static void gdm_wimax_ind_fsm_update(struct net_device *dev, struct fsm_s *fsm) { u16 buf[32 / sizeof(u16)]; u8 *hci_pkt_buf = (u8 *)&buf[0]; /* Indicate updating fsm */ buf[0] = H2B(WIMAX_FSM_UPDATE); buf[1] = H2B(sizeof(struct fsm_s)); memcpy(&hci_pkt_buf[HCI_HEADER_SIZE], fsm, sizeof(struct fsm_s)); gdm_wimax_event_send(dev, hci_pkt_buf, HCI_HEADER_SIZE + sizeof(struct fsm_s)); } static void gdm_wimax_ind_if_updown(struct net_device *dev, int if_up) { u16 buf[32 / sizeof(u16)]; struct hci_s *hci = (struct hci_s *) buf; unsigned char up_down; up_down = if_up ? WIMAX_IF_UP : WIMAX_IF_DOWN; /* Indicate updating fsm */ hci->cmd_evt = H2B(WIMAX_IF_UPDOWN); hci->length = H2B(sizeof(up_down)); hci->data[0] = up_down; gdm_wimax_event_send(dev, (char *)hci, HCI_HEADER_SIZE+sizeof(up_down)); } static void rx_complete(void *arg, void *data, int len) { struct nic *nic = arg; gdm_wimax_transmit_pkt(nic->netdev, data, len); gdm_wimax_rcv_with_cb(nic, rx_complete, nic); } static void prepare_rx_complete(void *arg, void *data, int len) { struct nic *nic = arg; int ret; ret = gdm_wimax_get_prepared_info(nic->netdev, data, len); if (ret == 1) gdm_wimax_rcv_with_cb(nic, rx_complete, nic); else { if (ret < 0) netdev_err(nic->netdev, "get_prepared_info failed(%d)\n", ret); gdm_wimax_rcv_with_cb(nic, prepare_rx_complete, nic); #if 0 /* Re-prepare WiMax device */ gdm_wimax_prepare_device(nic->netdev); #endif } } static void start_rx_proc(struct nic *nic) { gdm_wimax_rcv_with_cb(nic, prepare_rx_complete, nic); } static struct net_device_ops gdm_netdev_ops = { .ndo_open = gdm_wimax_open, .ndo_stop = gdm_wimax_close, .ndo_set_config = gdm_wimax_set_config, .ndo_start_xmit = gdm_wimax_tx, .ndo_get_stats = gdm_wimax_stats, .ndo_set_mac_address = gdm_wimax_set_mac_addr, .ndo_do_ioctl = gdm_wimax_ioctl, }; int register_wimax_device(struct phy_dev *phy_dev, struct device *pdev) { struct nic *nic = NULL; struct net_device *dev; int ret; dev = (struct net_device *)alloc_netdev(sizeof(*nic), "wm%d", ether_setup); if (dev == NULL) { pr_err("alloc_etherdev failed\n"); return -ENOMEM; } SET_NETDEV_DEV(dev, pdev); dev->mtu = 1400; dev->netdev_ops = &gdm_netdev_ops; dev->flags &= ~IFF_MULTICAST; memcpy(dev->dev_addr, gdm_wimax_macaddr, sizeof(gdm_wimax_macaddr)); nic = netdev_priv(dev); memset(nic, 0, sizeof(*nic)); nic->netdev = dev; nic->phy_dev = phy_dev; phy_dev->netdev = dev; /* event socket init */ ret = gdm_wimax_event_init(); if (ret < 0) { pr_err("Cannot create event.\n"); goto cleanup; } ret = register_netdev(dev); if (ret) goto cleanup; #if defined(LOOPBACK_TEST) netif_start_queue(dev); netif_carrier_on(dev); #else netif_carrier_off(dev); #endif #ifdef CONFIG_WIMAX_GDM72XX_QOS gdm_qos_init(nic); #endif start_rx_proc(nic); /* Prepare WiMax device */ gdm_wimax_prepare_device(dev); return 0; cleanup: pr_err("register_netdev failed\n"); free_netdev(dev); return ret; } void unregister_wimax_device(struct phy_dev *phy_dev) { struct nic *nic = netdev_priv(phy_dev->netdev); struct fsm_s *fsm = (struct fsm_s *) nic->sdk_data[SIOC_DATA_FSM].buf; if (fsm) fsm->m_status = M_INIT; unregister_netdev(nic->netdev); gdm_wimax_event_exit(); #if defined(CONFIG_WIMAX_GDM72XX_QOS) gdm_qos_release_list(nic); #endif gdm_wimax_cleanup_ioctl(phy_dev->netdev); free_netdev(nic->netdev); }
gpl-2.0
halaszk/Perseus-halaszk-universal5433
sound/isa/cs423x/cs4231.c
2248
5932
/* * Generic driver for CS4231 chips * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * Originally the CS4232/CS4232A driver, modified for use on CS4231 by * Tugrul Galatali <galatalt@stuy.edu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/init.h> #include <linux/err.h> #include <linux/isa.h> #include <linux/time.h> #include <linux/wait.h> #include <linux/module.h> #include <sound/core.h> #include <sound/wss.h> #include <sound/mpu401.h> #include <sound/initval.h> #define CRD_NAME "Generic CS4231" #define DEV_NAME "cs4231" MODULE_DESCRIPTION(CRD_NAME); MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Crystal Semiconductors,CS4231}}"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */ static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,11,12,15 */ static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 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 */ module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for " CRD_NAME " soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for " CRD_NAME " soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable " CRD_NAME " soundcard."); module_param_array(port, long, NULL, 0444); MODULE_PARM_DESC(port, "Port # for " CRD_NAME " driver."); module_param_array(mpu_port, long, NULL, 0444); MODULE_PARM_DESC(mpu_port, "MPU-401 port # for " CRD_NAME " driver."); module_param_array(irq, int, NULL, 0444); MODULE_PARM_DESC(irq, "IRQ # for " CRD_NAME " driver."); module_param_array(mpu_irq, int, NULL, 0444); MODULE_PARM_DESC(mpu_irq, "MPU-401 IRQ # for " CRD_NAME " driver."); module_param_array(dma1, int, NULL, 0444); MODULE_PARM_DESC(dma1, "DMA1 # for " CRD_NAME " driver."); module_param_array(dma2, int, NULL, 0444); MODULE_PARM_DESC(dma2, "DMA2 # for " CRD_NAME " driver."); static int snd_cs4231_match(struct device *dev, unsigned int n) { if (!enable[n]) return 0; if (port[n] == SNDRV_AUTO_PORT) { dev_err(dev, "please specify port\n"); return 0; } if (irq[n] == SNDRV_AUTO_IRQ) { dev_err(dev, "please specify irq\n"); return 0; } if (dma1[n] == SNDRV_AUTO_DMA) { dev_err(dev, "please specify dma1\n"); return 0; } return 1; } static int snd_cs4231_probe(struct device *dev, unsigned int n) { struct snd_card *card; struct snd_wss *chip; struct snd_pcm *pcm; int error; error = snd_card_create(index[n], id[n], THIS_MODULE, 0, &card); if (error < 0) return error; error = snd_wss_create(card, port[n], -1, irq[n], dma1[n], dma2[n], WSS_HW_DETECT, 0, &chip); if (error < 0) goto out; card->private_data = chip; error = snd_wss_pcm(chip, 0, &pcm); if (error < 0) goto out; strcpy(card->driver, "CS4231"); strcpy(card->shortname, pcm->name); sprintf(card->longname, "%s at 0x%lx, irq %d, dma %d", pcm->name, chip->port, irq[n], dma1[n]); if (dma2[n] >= 0) sprintf(card->longname + strlen(card->longname), "&%d", dma2[n]); error = snd_wss_mixer(chip); if (error < 0) goto out; error = snd_wss_timer(chip, 0, NULL); if (error < 0) goto out; if (mpu_port[n] > 0 && mpu_port[n] != SNDRV_AUTO_PORT) { if (mpu_irq[n] == SNDRV_AUTO_IRQ) mpu_irq[n] = -1; if (snd_mpu401_uart_new(card, 0, MPU401_HW_CS4232, mpu_port[n], 0, mpu_irq[n], NULL) < 0) dev_warn(dev, "MPU401 not detected\n"); } snd_card_set_dev(card, dev); error = snd_card_register(card); if (error < 0) goto out; dev_set_drvdata(dev, card); return 0; out: snd_card_free(card); return error; } static int snd_cs4231_remove(struct device *dev, unsigned int n) { snd_card_free(dev_get_drvdata(dev)); dev_set_drvdata(dev, NULL); return 0; } #ifdef CONFIG_PM static int snd_cs4231_suspend(struct device *dev, unsigned int n, pm_message_t state) { struct snd_card *card = dev_get_drvdata(dev); struct snd_wss *chip = card->private_data; snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); chip->suspend(chip); return 0; } static int snd_cs4231_resume(struct device *dev, unsigned int n) { struct snd_card *card = dev_get_drvdata(dev); struct snd_wss *chip = card->private_data; chip->resume(chip); snd_power_change_state(card, SNDRV_CTL_POWER_D0); return 0; } #endif static struct isa_driver snd_cs4231_driver = { .match = snd_cs4231_match, .probe = snd_cs4231_probe, .remove = snd_cs4231_remove, #ifdef CONFIG_PM .suspend = snd_cs4231_suspend, .resume = snd_cs4231_resume, #endif .driver = { .name = DEV_NAME } }; static int __init alsa_card_cs4231_init(void) { return isa_register_driver(&snd_cs4231_driver, SNDRV_CARDS); } static void __exit alsa_card_cs4231_exit(void) { isa_unregister_driver(&snd_cs4231_driver); } module_init(alsa_card_cs4231_init); module_exit(alsa_card_cs4231_exit);
gpl-2.0
chenxiaolong/Note4Kernel
sound/soc/codecs/wm9712.c
2248
24272
/* * wm9712.c -- ALSA Soc WM9712 codec support * * Copyright 2006-12 Wolfson Microelectronics PLC. * Author: Liam Girdwood <lrg@slimlogic.co.uk> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/ac97_codec.h> #include <sound/initval.h> #include <sound/soc.h> #include <sound/tlv.h> #include "wm9712.h" static unsigned int ac97_read(struct snd_soc_codec *codec, unsigned int reg); static int ac97_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int val); /* * WM9712 register cache */ static const u16 wm9712_reg[] = { 0x6174, 0x8000, 0x8000, 0x8000, /* 6 */ 0x0f0f, 0xaaa0, 0xc008, 0x6808, /* e */ 0xe808, 0xaaa0, 0xad00, 0x8000, /* 16 */ 0xe808, 0x3000, 0x8000, 0x0000, /* 1e */ 0x0000, 0x0000, 0x0000, 0x000f, /* 26 */ 0x0405, 0x0410, 0xbb80, 0xbb80, /* 2e */ 0x0000, 0xbb80, 0x0000, 0x0000, /* 36 */ 0x0000, 0x2000, 0x0000, 0x0000, /* 3e */ 0x0000, 0x0000, 0x0000, 0x0000, /* 46 */ 0x0000, 0x0000, 0xf83e, 0xffff, /* 4e */ 0x0000, 0x0000, 0x0000, 0xf83e, /* 56 */ 0x0008, 0x0000, 0x0000, 0x0000, /* 5e */ 0xb032, 0x3e00, 0x0000, 0x0000, /* 66 */ 0x0000, 0x0000, 0x0000, 0x0000, /* 6e */ 0x0000, 0x0000, 0x0000, 0x0006, /* 76 */ 0x0001, 0x0000, 0x574d, 0x4c12, /* 7e */ 0x0000, 0x0000 /* virtual hp mixers */ }; /* virtual HP mixers regs */ #define HPL_MIXER 0x80 #define HPR_MIXER 0x82 static const char *wm9712_alc_select[] = {"None", "Left", "Right", "Stereo"}; static const char *wm9712_alc_mux[] = {"Stereo", "Left", "Right", "None"}; static const char *wm9712_out3_src[] = {"Left", "VREF", "Left + Right", "Mono"}; static const char *wm9712_spk_src[] = {"Speaker Mix", "Headphone Mix"}; static const char *wm9712_rec_adc[] = {"Stereo", "Left", "Right", "Mute"}; static const char *wm9712_base[] = {"Linear Control", "Adaptive Boost"}; static const char *wm9712_rec_gain[] = {"+1.5dB Steps", "+0.75dB Steps"}; static const char *wm9712_mic[] = {"Mic 1", "Differential", "Mic 2", "Stereo"}; static const char *wm9712_rec_sel[] = {"Mic", "NC", "NC", "Speaker Mixer", "Line", "Headphone Mixer", "Phone Mixer", "Phone"}; static const char *wm9712_ng_type[] = {"Constant Gain", "Mute"}; static const char *wm9712_diff_sel[] = {"Mic", "Line"}; static const DECLARE_TLV_DB_SCALE(main_tlv, -3450, 150, 0); static const DECLARE_TLV_DB_SCALE(boost_tlv, 0, 2000, 0); static const struct soc_enum wm9712_enum[] = { SOC_ENUM_SINGLE(AC97_PCI_SVID, 14, 4, wm9712_alc_select), SOC_ENUM_SINGLE(AC97_VIDEO, 12, 4, wm9712_alc_mux), SOC_ENUM_SINGLE(AC97_AUX, 9, 4, wm9712_out3_src), SOC_ENUM_SINGLE(AC97_AUX, 8, 2, wm9712_spk_src), SOC_ENUM_SINGLE(AC97_REC_SEL, 12, 4, wm9712_rec_adc), SOC_ENUM_SINGLE(AC97_MASTER_TONE, 15, 2, wm9712_base), SOC_ENUM_DOUBLE(AC97_REC_GAIN, 14, 6, 2, wm9712_rec_gain), SOC_ENUM_SINGLE(AC97_MIC, 5, 4, wm9712_mic), SOC_ENUM_SINGLE(AC97_REC_SEL, 8, 8, wm9712_rec_sel), SOC_ENUM_SINGLE(AC97_REC_SEL, 0, 8, wm9712_rec_sel), SOC_ENUM_SINGLE(AC97_PCI_SVID, 5, 2, wm9712_ng_type), SOC_ENUM_SINGLE(0x5c, 8, 2, wm9712_diff_sel), }; static const struct snd_kcontrol_new wm9712_snd_ac97_controls[] = { SOC_DOUBLE("Speaker Playback Volume", AC97_MASTER, 8, 0, 31, 1), SOC_SINGLE("Speaker Playback Switch", AC97_MASTER, 15, 1, 1), SOC_DOUBLE("Headphone Playback Volume", AC97_HEADPHONE, 8, 0, 31, 1), SOC_SINGLE("Headphone Playback Switch", AC97_HEADPHONE, 15, 1, 1), SOC_DOUBLE("PCM Playback Volume", AC97_PCM, 8, 0, 31, 1), SOC_SINGLE("Speaker Playback ZC Switch", AC97_MASTER, 7, 1, 0), SOC_SINGLE("Speaker Playback Invert Switch", AC97_MASTER, 6, 1, 0), SOC_SINGLE("Headphone Playback ZC Switch", AC97_HEADPHONE, 7, 1, 0), SOC_SINGLE("Mono Playback ZC Switch", AC97_MASTER_MONO, 7, 1, 0), SOC_SINGLE("Mono Playback Volume", AC97_MASTER_MONO, 0, 31, 1), SOC_SINGLE("Mono Playback Switch", AC97_MASTER_MONO, 15, 1, 1), SOC_SINGLE("ALC Target Volume", AC97_CODEC_CLASS_REV, 12, 15, 0), SOC_SINGLE("ALC Hold Time", AC97_CODEC_CLASS_REV, 8, 15, 0), SOC_SINGLE("ALC Decay Time", AC97_CODEC_CLASS_REV, 4, 15, 0), SOC_SINGLE("ALC Attack Time", AC97_CODEC_CLASS_REV, 0, 15, 0), SOC_ENUM("ALC Function", wm9712_enum[0]), SOC_SINGLE("ALC Max Volume", AC97_PCI_SVID, 11, 7, 0), SOC_SINGLE("ALC ZC Timeout", AC97_PCI_SVID, 9, 3, 1), SOC_SINGLE("ALC ZC Switch", AC97_PCI_SVID, 8, 1, 0), SOC_SINGLE("ALC NG Switch", AC97_PCI_SVID, 7, 1, 0), SOC_ENUM("ALC NG Type", wm9712_enum[10]), SOC_SINGLE("ALC NG Threshold", AC97_PCI_SVID, 0, 31, 1), SOC_SINGLE("Mic Headphone Volume", AC97_VIDEO, 12, 7, 1), SOC_SINGLE("ALC Headphone Volume", AC97_VIDEO, 7, 7, 1), SOC_SINGLE("Out3 Switch", AC97_AUX, 15, 1, 1), SOC_SINGLE("Out3 ZC Switch", AC97_AUX, 7, 1, 1), SOC_SINGLE("Out3 Volume", AC97_AUX, 0, 31, 1), SOC_SINGLE("PCBeep Bypass Headphone Volume", AC97_PC_BEEP, 12, 7, 1), SOC_SINGLE("PCBeep Bypass Speaker Volume", AC97_PC_BEEP, 8, 7, 1), SOC_SINGLE("PCBeep Bypass Phone Volume", AC97_PC_BEEP, 4, 7, 1), SOC_SINGLE("Aux Playback Headphone Volume", AC97_CD, 12, 7, 1), SOC_SINGLE("Aux Playback Speaker Volume", AC97_CD, 8, 7, 1), SOC_SINGLE("Aux Playback Phone Volume", AC97_CD, 4, 7, 1), SOC_SINGLE("Phone Volume", AC97_PHONE, 0, 15, 1), SOC_DOUBLE("Line Capture Volume", AC97_LINE, 8, 0, 31, 1), SOC_SINGLE_TLV("Capture Boost Switch", AC97_REC_SEL, 14, 1, 0, boost_tlv), SOC_SINGLE_TLV("Capture to Phone Boost Switch", AC97_REC_SEL, 11, 1, 1, boost_tlv), SOC_SINGLE("3D Upper Cut-off Switch", AC97_3D_CONTROL, 5, 1, 1), SOC_SINGLE("3D Lower Cut-off Switch", AC97_3D_CONTROL, 4, 1, 1), SOC_SINGLE("3D Playback Volume", AC97_3D_CONTROL, 0, 15, 0), SOC_ENUM("Bass Control", wm9712_enum[5]), SOC_SINGLE("Bass Cut-off Switch", AC97_MASTER_TONE, 12, 1, 1), SOC_SINGLE("Tone Cut-off Switch", AC97_MASTER_TONE, 4, 1, 1), SOC_SINGLE("Playback Attenuate (-6dB) Switch", AC97_MASTER_TONE, 6, 1, 0), SOC_SINGLE("Bass Volume", AC97_MASTER_TONE, 8, 15, 1), SOC_SINGLE("Treble Volume", AC97_MASTER_TONE, 0, 15, 1), SOC_SINGLE("Capture Switch", AC97_REC_GAIN, 15, 1, 1), SOC_ENUM("Capture Volume Steps", wm9712_enum[6]), SOC_DOUBLE("Capture Volume", AC97_REC_GAIN, 8, 0, 63, 0), SOC_SINGLE("Capture ZC Switch", AC97_REC_GAIN, 7, 1, 0), SOC_SINGLE_TLV("Mic 1 Volume", AC97_MIC, 8, 31, 1, main_tlv), SOC_SINGLE_TLV("Mic 2 Volume", AC97_MIC, 0, 31, 1, main_tlv), SOC_SINGLE_TLV("Mic Boost Volume", AC97_MIC, 7, 1, 0, boost_tlv), }; /* We have to create a fake left and right HP mixers because * the codec only has a single control that is shared by both channels. * This makes it impossible to determine the audio path. */ static int mixer_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { u16 l, r, beep, line, phone, mic, pcm, aux; l = ac97_read(w->codec, HPL_MIXER); r = ac97_read(w->codec, HPR_MIXER); beep = ac97_read(w->codec, AC97_PC_BEEP); mic = ac97_read(w->codec, AC97_VIDEO); phone = ac97_read(w->codec, AC97_PHONE); line = ac97_read(w->codec, AC97_LINE); pcm = ac97_read(w->codec, AC97_PCM); aux = ac97_read(w->codec, AC97_CD); if (l & 0x1 || r & 0x1) ac97_write(w->codec, AC97_VIDEO, mic & 0x7fff); else ac97_write(w->codec, AC97_VIDEO, mic | 0x8000); if (l & 0x2 || r & 0x2) ac97_write(w->codec, AC97_PCM, pcm & 0x7fff); else ac97_write(w->codec, AC97_PCM, pcm | 0x8000); if (l & 0x4 || r & 0x4) ac97_write(w->codec, AC97_LINE, line & 0x7fff); else ac97_write(w->codec, AC97_LINE, line | 0x8000); if (l & 0x8 || r & 0x8) ac97_write(w->codec, AC97_PHONE, phone & 0x7fff); else ac97_write(w->codec, AC97_PHONE, phone | 0x8000); if (l & 0x10 || r & 0x10) ac97_write(w->codec, AC97_CD, aux & 0x7fff); else ac97_write(w->codec, AC97_CD, aux | 0x8000); if (l & 0x20 || r & 0x20) ac97_write(w->codec, AC97_PC_BEEP, beep & 0x7fff); else ac97_write(w->codec, AC97_PC_BEEP, beep | 0x8000); return 0; } /* Left Headphone Mixers */ static const struct snd_kcontrol_new wm9712_hpl_mixer_controls[] = { SOC_DAPM_SINGLE("PCBeep Bypass Switch", HPL_MIXER, 5, 1, 0), SOC_DAPM_SINGLE("Aux Playback Switch", HPL_MIXER, 4, 1, 0), SOC_DAPM_SINGLE("Phone Bypass Switch", HPL_MIXER, 3, 1, 0), SOC_DAPM_SINGLE("Line Bypass Switch", HPL_MIXER, 2, 1, 0), SOC_DAPM_SINGLE("PCM Playback Switch", HPL_MIXER, 1, 1, 0), SOC_DAPM_SINGLE("Mic Sidetone Switch", HPL_MIXER, 0, 1, 0), }; /* Right Headphone Mixers */ static const struct snd_kcontrol_new wm9712_hpr_mixer_controls[] = { SOC_DAPM_SINGLE("PCBeep Bypass Switch", HPR_MIXER, 5, 1, 0), SOC_DAPM_SINGLE("Aux Playback Switch", HPR_MIXER, 4, 1, 0), SOC_DAPM_SINGLE("Phone Bypass Switch", HPR_MIXER, 3, 1, 0), SOC_DAPM_SINGLE("Line Bypass Switch", HPR_MIXER, 2, 1, 0), SOC_DAPM_SINGLE("PCM Playback Switch", HPR_MIXER, 1, 1, 0), SOC_DAPM_SINGLE("Mic Sidetone Switch", HPR_MIXER, 0, 1, 0), }; /* Speaker Mixer */ static const struct snd_kcontrol_new wm9712_speaker_mixer_controls[] = { SOC_DAPM_SINGLE("PCBeep Bypass Switch", AC97_PC_BEEP, 11, 1, 1), SOC_DAPM_SINGLE("Aux Playback Switch", AC97_CD, 11, 1, 1), SOC_DAPM_SINGLE("Phone Bypass Switch", AC97_PHONE, 14, 1, 1), SOC_DAPM_SINGLE("Line Bypass Switch", AC97_LINE, 14, 1, 1), SOC_DAPM_SINGLE("PCM Playback Switch", AC97_PCM, 14, 1, 1), }; /* Phone Mixer */ static const struct snd_kcontrol_new wm9712_phone_mixer_controls[] = { SOC_DAPM_SINGLE("PCBeep Bypass Switch", AC97_PC_BEEP, 7, 1, 1), SOC_DAPM_SINGLE("Aux Playback Switch", AC97_CD, 7, 1, 1), SOC_DAPM_SINGLE("Line Bypass Switch", AC97_LINE, 13, 1, 1), SOC_DAPM_SINGLE("PCM Playback Switch", AC97_PCM, 13, 1, 1), SOC_DAPM_SINGLE("Mic 1 Sidetone Switch", AC97_MIC, 14, 1, 1), SOC_DAPM_SINGLE("Mic 2 Sidetone Switch", AC97_MIC, 13, 1, 1), }; /* ALC headphone mux */ static const struct snd_kcontrol_new wm9712_alc_mux_controls = SOC_DAPM_ENUM("Route", wm9712_enum[1]); /* out 3 mux */ static const struct snd_kcontrol_new wm9712_out3_mux_controls = SOC_DAPM_ENUM("Route", wm9712_enum[2]); /* spk mux */ static const struct snd_kcontrol_new wm9712_spk_mux_controls = SOC_DAPM_ENUM("Route", wm9712_enum[3]); /* Capture to Phone mux */ static const struct snd_kcontrol_new wm9712_capture_phone_mux_controls = SOC_DAPM_ENUM("Route", wm9712_enum[4]); /* Capture left select */ static const struct snd_kcontrol_new wm9712_capture_selectl_controls = SOC_DAPM_ENUM("Route", wm9712_enum[8]); /* Capture right select */ static const struct snd_kcontrol_new wm9712_capture_selectr_controls = SOC_DAPM_ENUM("Route", wm9712_enum[9]); /* Mic select */ static const struct snd_kcontrol_new wm9712_mic_src_controls = SOC_DAPM_ENUM("Mic Source Select", wm9712_enum[7]); /* diff select */ static const struct snd_kcontrol_new wm9712_diff_sel_controls = SOC_DAPM_ENUM("Route", wm9712_enum[11]); static const struct snd_soc_dapm_widget wm9712_dapm_widgets[] = { SND_SOC_DAPM_MUX("ALC Sidetone Mux", SND_SOC_NOPM, 0, 0, &wm9712_alc_mux_controls), SND_SOC_DAPM_MUX("Out3 Mux", SND_SOC_NOPM, 0, 0, &wm9712_out3_mux_controls), SND_SOC_DAPM_MUX("Speaker Mux", SND_SOC_NOPM, 0, 0, &wm9712_spk_mux_controls), SND_SOC_DAPM_MUX("Capture Phone Mux", SND_SOC_NOPM, 0, 0, &wm9712_capture_phone_mux_controls), SND_SOC_DAPM_MUX("Left Capture Select", SND_SOC_NOPM, 0, 0, &wm9712_capture_selectl_controls), SND_SOC_DAPM_MUX("Right Capture Select", SND_SOC_NOPM, 0, 0, &wm9712_capture_selectr_controls), SND_SOC_DAPM_MUX("Left Mic Select Source", SND_SOC_NOPM, 0, 0, &wm9712_mic_src_controls), SND_SOC_DAPM_MUX("Right Mic Select Source", SND_SOC_NOPM, 0, 0, &wm9712_mic_src_controls), SND_SOC_DAPM_MUX("Differential Source", SND_SOC_NOPM, 0, 0, &wm9712_diff_sel_controls), SND_SOC_DAPM_MIXER("AC97 Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER_E("Left HP Mixer", AC97_INT_PAGING, 9, 1, &wm9712_hpl_mixer_controls[0], ARRAY_SIZE(wm9712_hpl_mixer_controls), mixer_event, SND_SOC_DAPM_POST_REG), SND_SOC_DAPM_MIXER_E("Right HP Mixer", AC97_INT_PAGING, 8, 1, &wm9712_hpr_mixer_controls[0], ARRAY_SIZE(wm9712_hpr_mixer_controls), mixer_event, SND_SOC_DAPM_POST_REG), SND_SOC_DAPM_MIXER("Phone Mixer", AC97_INT_PAGING, 6, 1, &wm9712_phone_mixer_controls[0], ARRAY_SIZE(wm9712_phone_mixer_controls)), SND_SOC_DAPM_MIXER("Speaker Mixer", AC97_INT_PAGING, 7, 1, &wm9712_speaker_mixer_controls[0], ARRAY_SIZE(wm9712_speaker_mixer_controls)), SND_SOC_DAPM_MIXER("Mono Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_DAC("Left DAC", "Left HiFi Playback", AC97_INT_PAGING, 14, 1), SND_SOC_DAPM_DAC("Right DAC", "Right HiFi Playback", AC97_INT_PAGING, 13, 1), SND_SOC_DAPM_DAC("Aux DAC", "Aux Playback", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_ADC("Left ADC", "Left HiFi Capture", AC97_INT_PAGING, 12, 1), SND_SOC_DAPM_ADC("Right ADC", "Right HiFi Capture", AC97_INT_PAGING, 11, 1), SND_SOC_DAPM_PGA("Headphone PGA", AC97_INT_PAGING, 4, 1, NULL, 0), SND_SOC_DAPM_PGA("Speaker PGA", AC97_INT_PAGING, 3, 1, NULL, 0), SND_SOC_DAPM_PGA("Out 3 PGA", AC97_INT_PAGING, 5, 1, NULL, 0), SND_SOC_DAPM_PGA("Line PGA", AC97_INT_PAGING, 2, 1, NULL, 0), SND_SOC_DAPM_PGA("Phone PGA", AC97_INT_PAGING, 1, 1, NULL, 0), SND_SOC_DAPM_PGA("Mic PGA", AC97_INT_PAGING, 0, 1, NULL, 0), SND_SOC_DAPM_PGA("Differential Mic", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MICBIAS("Mic Bias", AC97_INT_PAGING, 10, 1), SND_SOC_DAPM_OUTPUT("MONOOUT"), SND_SOC_DAPM_OUTPUT("HPOUTL"), SND_SOC_DAPM_OUTPUT("HPOUTR"), SND_SOC_DAPM_OUTPUT("LOUT2"), SND_SOC_DAPM_OUTPUT("ROUT2"), SND_SOC_DAPM_OUTPUT("OUT3"), SND_SOC_DAPM_INPUT("LINEINL"), SND_SOC_DAPM_INPUT("LINEINR"), SND_SOC_DAPM_INPUT("PHONE"), SND_SOC_DAPM_INPUT("PCBEEP"), SND_SOC_DAPM_INPUT("MIC1"), SND_SOC_DAPM_INPUT("MIC2"), }; static const struct snd_soc_dapm_route wm9712_audio_map[] = { /* virtual mixer - mixes left & right channels for spk and mono */ {"AC97 Mixer", NULL, "Left DAC"}, {"AC97 Mixer", NULL, "Right DAC"}, /* Left HP mixer */ {"Left HP Mixer", "PCBeep Bypass Switch", "PCBEEP"}, {"Left HP Mixer", "Aux Playback Switch", "Aux DAC"}, {"Left HP Mixer", "Phone Bypass Switch", "Phone PGA"}, {"Left HP Mixer", "Line Bypass Switch", "Line PGA"}, {"Left HP Mixer", "PCM Playback Switch", "Left DAC"}, {"Left HP Mixer", "Mic Sidetone Switch", "Mic PGA"}, {"Left HP Mixer", NULL, "ALC Sidetone Mux"}, /* Right HP mixer */ {"Right HP Mixer", "PCBeep Bypass Switch", "PCBEEP"}, {"Right HP Mixer", "Aux Playback Switch", "Aux DAC"}, {"Right HP Mixer", "Phone Bypass Switch", "Phone PGA"}, {"Right HP Mixer", "Line Bypass Switch", "Line PGA"}, {"Right HP Mixer", "PCM Playback Switch", "Right DAC"}, {"Right HP Mixer", "Mic Sidetone Switch", "Mic PGA"}, {"Right HP Mixer", NULL, "ALC Sidetone Mux"}, /* speaker mixer */ {"Speaker Mixer", "PCBeep Bypass Switch", "PCBEEP"}, {"Speaker Mixer", "Line Bypass Switch", "Line PGA"}, {"Speaker Mixer", "PCM Playback Switch", "AC97 Mixer"}, {"Speaker Mixer", "Phone Bypass Switch", "Phone PGA"}, {"Speaker Mixer", "Aux Playback Switch", "Aux DAC"}, /* Phone mixer */ {"Phone Mixer", "PCBeep Bypass Switch", "PCBEEP"}, {"Phone Mixer", "Line Bypass Switch", "Line PGA"}, {"Phone Mixer", "Aux Playback Switch", "Aux DAC"}, {"Phone Mixer", "PCM Playback Switch", "AC97 Mixer"}, {"Phone Mixer", "Mic 1 Sidetone Switch", "Mic PGA"}, {"Phone Mixer", "Mic 2 Sidetone Switch", "Mic PGA"}, /* inputs */ {"Line PGA", NULL, "LINEINL"}, {"Line PGA", NULL, "LINEINR"}, {"Phone PGA", NULL, "PHONE"}, {"Mic PGA", NULL, "MIC1"}, {"Mic PGA", NULL, "MIC2"}, /* microphones */ {"Differential Mic", NULL, "MIC1"}, {"Differential Mic", NULL, "MIC2"}, {"Left Mic Select Source", "Mic 1", "MIC1"}, {"Left Mic Select Source", "Mic 2", "MIC2"}, {"Left Mic Select Source", "Stereo", "MIC1"}, {"Left Mic Select Source", "Differential", "Differential Mic"}, {"Right Mic Select Source", "Mic 1", "MIC1"}, {"Right Mic Select Source", "Mic 2", "MIC2"}, {"Right Mic Select Source", "Stereo", "MIC2"}, {"Right Mic Select Source", "Differential", "Differential Mic"}, /* left capture selector */ {"Left Capture Select", "Mic", "MIC1"}, {"Left Capture Select", "Speaker Mixer", "Speaker Mixer"}, {"Left Capture Select", "Line", "LINEINL"}, {"Left Capture Select", "Headphone Mixer", "Left HP Mixer"}, {"Left Capture Select", "Phone Mixer", "Phone Mixer"}, {"Left Capture Select", "Phone", "PHONE"}, /* right capture selector */ {"Right Capture Select", "Mic", "MIC2"}, {"Right Capture Select", "Speaker Mixer", "Speaker Mixer"}, {"Right Capture Select", "Line", "LINEINR"}, {"Right Capture Select", "Headphone Mixer", "Right HP Mixer"}, {"Right Capture Select", "Phone Mixer", "Phone Mixer"}, {"Right Capture Select", "Phone", "PHONE"}, /* ALC Sidetone */ {"ALC Sidetone Mux", "Stereo", "Left Capture Select"}, {"ALC Sidetone Mux", "Stereo", "Right Capture Select"}, {"ALC Sidetone Mux", "Left", "Left Capture Select"}, {"ALC Sidetone Mux", "Right", "Right Capture Select"}, /* ADC's */ {"Left ADC", NULL, "Left Capture Select"}, {"Right ADC", NULL, "Right Capture Select"}, /* outputs */ {"MONOOUT", NULL, "Phone Mixer"}, {"HPOUTL", NULL, "Headphone PGA"}, {"Headphone PGA", NULL, "Left HP Mixer"}, {"HPOUTR", NULL, "Headphone PGA"}, {"Headphone PGA", NULL, "Right HP Mixer"}, /* mono mixer */ {"Mono Mixer", NULL, "Left HP Mixer"}, {"Mono Mixer", NULL, "Right HP Mixer"}, /* Out3 Mux */ {"Out3 Mux", "Left", "Left HP Mixer"}, {"Out3 Mux", "Mono", "Phone Mixer"}, {"Out3 Mux", "Left + Right", "Mono Mixer"}, {"Out 3 PGA", NULL, "Out3 Mux"}, {"OUT3", NULL, "Out 3 PGA"}, /* speaker Mux */ {"Speaker Mux", "Speaker Mix", "Speaker Mixer"}, {"Speaker Mux", "Headphone Mix", "Mono Mixer"}, {"Speaker PGA", NULL, "Speaker Mux"}, {"LOUT2", NULL, "Speaker PGA"}, {"ROUT2", NULL, "Speaker PGA"}, }; static unsigned int ac97_read(struct snd_soc_codec *codec, unsigned int reg) { u16 *cache = codec->reg_cache; if (reg == AC97_RESET || reg == AC97_GPIO_STATUS || reg == AC97_VENDOR_ID1 || reg == AC97_VENDOR_ID2 || reg == AC97_REC_GAIN) return soc_ac97_ops.read(codec->ac97, reg); else { reg = reg >> 1; if (reg >= (ARRAY_SIZE(wm9712_reg))) return -EIO; return cache[reg]; } } static int ac97_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int val) { u16 *cache = codec->reg_cache; if (reg < 0x7c) soc_ac97_ops.write(codec->ac97, reg, val); reg = reg >> 1; if (reg < (ARRAY_SIZE(wm9712_reg))) cache[reg] = val; return 0; } static int ac97_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; int reg; u16 vra; struct snd_pcm_runtime *runtime = substream->runtime; vra = ac97_read(codec, AC97_EXTENDED_STATUS); ac97_write(codec, AC97_EXTENDED_STATUS, vra | 0x1); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) reg = AC97_PCM_FRONT_DAC_RATE; else reg = AC97_PCM_LR_ADC_RATE; return ac97_write(codec, reg, runtime->rate); } static int ac97_aux_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; u16 vra, xsle; struct snd_pcm_runtime *runtime = substream->runtime; vra = ac97_read(codec, AC97_EXTENDED_STATUS); ac97_write(codec, AC97_EXTENDED_STATUS, vra | 0x1); xsle = ac97_read(codec, AC97_PCI_SID); ac97_write(codec, AC97_PCI_SID, xsle | 0x8000); if (substream->stream != SNDRV_PCM_STREAM_PLAYBACK) return -ENODEV; return ac97_write(codec, AC97_PCM_SURR_DAC_RATE, runtime->rate); } #define WM9712_AC97_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\ SNDRV_PCM_RATE_22050 | SNDRV_PCM_RATE_44100 |\ SNDRV_PCM_RATE_48000) static const struct snd_soc_dai_ops wm9712_dai_ops_hifi = { .prepare = ac97_prepare, }; static const struct snd_soc_dai_ops wm9712_dai_ops_aux = { .prepare = ac97_aux_prepare, }; static struct snd_soc_dai_driver wm9712_dai[] = { { .name = "wm9712-hifi", .ac97_control = 1, .playback = { .stream_name = "HiFi Playback", .channels_min = 1, .channels_max = 2, .rates = WM9712_AC97_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .capture = { .stream_name = "HiFi Capture", .channels_min = 1, .channels_max = 2, .rates = WM9712_AC97_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .ops = &wm9712_dai_ops_hifi, }, { .name = "wm9712-aux", .playback = { .stream_name = "Aux Playback", .channels_min = 1, .channels_max = 1, .rates = WM9712_AC97_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .ops = &wm9712_dai_ops_aux, } }; static int wm9712_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { switch (level) { case SND_SOC_BIAS_ON: case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: ac97_write(codec, AC97_POWERDOWN, 0x0000); break; case SND_SOC_BIAS_OFF: /* disable everything including AC link */ ac97_write(codec, AC97_EXTENDED_MSTATUS, 0xffff); ac97_write(codec, AC97_POWERDOWN, 0xffff); break; } codec->dapm.bias_level = level; return 0; } static int wm9712_reset(struct snd_soc_codec *codec, int try_warm) { if (try_warm && soc_ac97_ops.warm_reset) { soc_ac97_ops.warm_reset(codec->ac97); if (ac97_read(codec, 0) == wm9712_reg[0]) return 1; } soc_ac97_ops.reset(codec->ac97); if (soc_ac97_ops.warm_reset) soc_ac97_ops.warm_reset(codec->ac97); if (ac97_read(codec, 0) != wm9712_reg[0]) goto err; return 0; err: printk(KERN_ERR "WM9712 AC97 reset failed\n"); return -EIO; } static int wm9712_soc_suspend(struct snd_soc_codec *codec) { wm9712_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int wm9712_soc_resume(struct snd_soc_codec *codec) { int i, ret; u16 *cache = codec->reg_cache; ret = wm9712_reset(codec, 1); if (ret < 0) { printk(KERN_ERR "could not reset AC97 codec\n"); return ret; } wm9712_set_bias_level(codec, SND_SOC_BIAS_STANDBY); if (ret == 0) { /* Sync reg_cache with the hardware after cold reset */ for (i = 2; i < ARRAY_SIZE(wm9712_reg) << 1; i += 2) { if (i == AC97_INT_PAGING || i == AC97_POWERDOWN || (i > 0x58 && i != 0x5c)) continue; soc_ac97_ops.write(codec->ac97, i, cache[i>>1]); } } return ret; } static int wm9712_soc_probe(struct snd_soc_codec *codec) { int ret = 0; ret = snd_soc_new_ac97_codec(codec, &soc_ac97_ops, 0); if (ret < 0) { printk(KERN_ERR "wm9712: failed to register AC97 codec\n"); return ret; } ret = wm9712_reset(codec, 0); if (ret < 0) { printk(KERN_ERR "Failed to reset WM9712: AC97 link error\n"); goto reset_err; } /* set alc mux to none */ ac97_write(codec, AC97_VIDEO, ac97_read(codec, AC97_VIDEO) | 0x3000); wm9712_set_bias_level(codec, SND_SOC_BIAS_STANDBY); snd_soc_add_codec_controls(codec, wm9712_snd_ac97_controls, ARRAY_SIZE(wm9712_snd_ac97_controls)); return 0; reset_err: snd_soc_free_ac97_codec(codec); return ret; } static int wm9712_soc_remove(struct snd_soc_codec *codec) { snd_soc_free_ac97_codec(codec); return 0; } static struct snd_soc_codec_driver soc_codec_dev_wm9712 = { .probe = wm9712_soc_probe, .remove = wm9712_soc_remove, .suspend = wm9712_soc_suspend, .resume = wm9712_soc_resume, .read = ac97_read, .write = ac97_write, .set_bias_level = wm9712_set_bias_level, .reg_cache_size = ARRAY_SIZE(wm9712_reg), .reg_word_size = sizeof(u16), .reg_cache_step = 2, .reg_cache_default = wm9712_reg, .dapm_widgets = wm9712_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(wm9712_dapm_widgets), .dapm_routes = wm9712_audio_map, .num_dapm_routes = ARRAY_SIZE(wm9712_audio_map), }; static int wm9712_probe(struct platform_device *pdev) { return snd_soc_register_codec(&pdev->dev, &soc_codec_dev_wm9712, wm9712_dai, ARRAY_SIZE(wm9712_dai)); } static int wm9712_remove(struct platform_device *pdev) { snd_soc_unregister_codec(&pdev->dev); return 0; } static struct platform_driver wm9712_codec_driver = { .driver = { .name = "wm9712-codec", .owner = THIS_MODULE, }, .probe = wm9712_probe, .remove = wm9712_remove, }; module_platform_driver(wm9712_codec_driver); MODULE_DESCRIPTION("ASoC WM9711/WM9712 driver"); MODULE_AUTHOR("Liam Girdwood"); MODULE_LICENSE("GPL");
gpl-2.0
Alberto96/android_kernel_samsung_tassve
arch/mips/alchemy/devboards/db1x00/platform.c
3784
4109
/* * DBAu1xxx board platform device registration * * Copyright (C) 2009 Manuel Lauss * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <linux/init.h> #include <linux/platform_device.h> #include <asm/mach-au1x00/au1xxx.h> #include <asm/mach-db1x00/bcsr.h> #include "../platform.h" /* DB1xxx PCMCIA interrupt sources: * CD0/1 GPIO0/3 * STSCHG0/1 GPIO1/4 * CARD0/1 GPIO2/5 * Db1550: 0/1, 21/22, 3/5 */ #define DB1XXX_HAS_PCMCIA #define F_SWAPPED (bcsr_read(BCSR_STATUS) & BCSR_STATUS_DB1000_SWAPBOOT) #if defined(CONFIG_MIPS_DB1000) #define DB1XXX_PCMCIA_CD0 AU1000_GPIO0_INT #define DB1XXX_PCMCIA_STSCHG0 AU1000_GPIO1_INT #define DB1XXX_PCMCIA_CARD0 AU1000_GPIO2_INT #define DB1XXX_PCMCIA_CD1 AU1000_GPIO3_INT #define DB1XXX_PCMCIA_STSCHG1 AU1000_GPIO4_INT #define DB1XXX_PCMCIA_CARD1 AU1000_GPIO5_INT #define BOARD_FLASH_SIZE 0x02000000 /* 32MB */ #define BOARD_FLASH_WIDTH 4 /* 32-bits */ #elif defined(CONFIG_MIPS_DB1100) #define DB1XXX_PCMCIA_CD0 AU1100_GPIO0_INT #define DB1XXX_PCMCIA_STSCHG0 AU1100_GPIO1_INT #define DB1XXX_PCMCIA_CARD0 AU1100_GPIO2_INT #define DB1XXX_PCMCIA_CD1 AU1100_GPIO3_INT #define DB1XXX_PCMCIA_STSCHG1 AU1100_GPIO4_INT #define DB1XXX_PCMCIA_CARD1 AU1100_GPIO5_INT #define BOARD_FLASH_SIZE 0x02000000 /* 32MB */ #define BOARD_FLASH_WIDTH 4 /* 32-bits */ #elif defined(CONFIG_MIPS_DB1500) #define DB1XXX_PCMCIA_CD0 AU1500_GPIO0_INT #define DB1XXX_PCMCIA_STSCHG0 AU1500_GPIO1_INT #define DB1XXX_PCMCIA_CARD0 AU1500_GPIO2_INT #define DB1XXX_PCMCIA_CD1 AU1500_GPIO3_INT #define DB1XXX_PCMCIA_STSCHG1 AU1500_GPIO4_INT #define DB1XXX_PCMCIA_CARD1 AU1500_GPIO5_INT #define BOARD_FLASH_SIZE 0x02000000 /* 32MB */ #define BOARD_FLASH_WIDTH 4 /* 32-bits */ #elif defined(CONFIG_MIPS_DB1550) #define DB1XXX_PCMCIA_CD0 AU1550_GPIO0_INT #define DB1XXX_PCMCIA_STSCHG0 AU1550_GPIO21_INT #define DB1XXX_PCMCIA_CARD0 AU1550_GPIO3_INT #define DB1XXX_PCMCIA_CD1 AU1550_GPIO1_INT #define DB1XXX_PCMCIA_STSCHG1 AU1550_GPIO22_INT #define DB1XXX_PCMCIA_CARD1 AU1550_GPIO5_INT #define BOARD_FLASH_SIZE 0x08000000 /* 128MB */ #define BOARD_FLASH_WIDTH 4 /* 32-bits */ #else /* other board: no PCMCIA */ #undef DB1XXX_HAS_PCMCIA #undef F_SWAPPED #define F_SWAPPED 0 #if defined(CONFIG_MIPS_BOSPORUS) #define BOARD_FLASH_SIZE 0x01000000 /* 16MB */ #define BOARD_FLASH_WIDTH 2 /* 16-bits */ #elif defined(CONFIG_MIPS_MIRAGE) #define BOARD_FLASH_SIZE 0x04000000 /* 64MB */ #define BOARD_FLASH_WIDTH 4 /* 32-bits */ #endif #endif static int __init db1xxx_dev_init(void) { #ifdef DB1XXX_HAS_PCMCIA db1x_register_pcmcia_socket(PCMCIA_ATTR_PHYS_ADDR, PCMCIA_ATTR_PHYS_ADDR + 0x000400000 - 1, PCMCIA_MEM_PHYS_ADDR, PCMCIA_MEM_PHYS_ADDR + 0x000400000 - 1, PCMCIA_IO_PHYS_ADDR, PCMCIA_IO_PHYS_ADDR + 0x000010000 - 1, DB1XXX_PCMCIA_CARD0, DB1XXX_PCMCIA_CD0, /*DB1XXX_PCMCIA_STSCHG0*/0, 0, 0); db1x_register_pcmcia_socket(PCMCIA_ATTR_PHYS_ADDR + 0x004000000, PCMCIA_ATTR_PHYS_ADDR + 0x004400000 - 1, PCMCIA_MEM_PHYS_ADDR + 0x004000000, PCMCIA_MEM_PHYS_ADDR + 0x004400000 - 1, PCMCIA_IO_PHYS_ADDR + 0x004000000, PCMCIA_IO_PHYS_ADDR + 0x004010000 - 1, DB1XXX_PCMCIA_CARD1, DB1XXX_PCMCIA_CD1, /*DB1XXX_PCMCIA_STSCHG1*/0, 0, 1); #endif db1x_register_norflash(BOARD_FLASH_SIZE, BOARD_FLASH_WIDTH, F_SWAPPED); return 0; } device_initcall(db1xxx_dev_init);
gpl-2.0
emceethemouth/kernel_msm
arch/mips/bcm63xx/cpu.c
4552
6546
/* * 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) 2008 Maxime Bizon <mbizon@freebox.fr> * Copyright (C) 2009 Florian Fainelli <florian@openwrt.org> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/cpu.h> #include <asm/cpu.h> #include <asm/cpu-info.h> #include <asm/mipsregs.h> #include <bcm63xx_cpu.h> #include <bcm63xx_regs.h> #include <bcm63xx_io.h> #include <bcm63xx_irq.h> const unsigned long *bcm63xx_regs_base; EXPORT_SYMBOL(bcm63xx_regs_base); const int *bcm63xx_irqs; EXPORT_SYMBOL(bcm63xx_irqs); static u16 bcm63xx_cpu_id; static u16 bcm63xx_cpu_rev; static unsigned int bcm63xx_cpu_freq; static unsigned int bcm63xx_memory_size; static const unsigned long bcm6338_regs_base[] = { __GEN_CPU_REGS_TABLE(6338) }; static const int bcm6338_irqs[] = { __GEN_CPU_IRQ_TABLE(6338) }; static const unsigned long bcm6345_regs_base[] = { __GEN_CPU_REGS_TABLE(6345) }; static const int bcm6345_irqs[] = { __GEN_CPU_IRQ_TABLE(6345) }; static const unsigned long bcm6348_regs_base[] = { __GEN_CPU_REGS_TABLE(6348) }; static const int bcm6348_irqs[] = { __GEN_CPU_IRQ_TABLE(6348) }; static const unsigned long bcm6358_regs_base[] = { __GEN_CPU_REGS_TABLE(6358) }; static const int bcm6358_irqs[] = { __GEN_CPU_IRQ_TABLE(6358) }; static const unsigned long bcm6368_regs_base[] = { __GEN_CPU_REGS_TABLE(6368) }; static const int bcm6368_irqs[] = { __GEN_CPU_IRQ_TABLE(6368) }; u16 __bcm63xx_get_cpu_id(void) { return bcm63xx_cpu_id; } EXPORT_SYMBOL(__bcm63xx_get_cpu_id); u16 bcm63xx_get_cpu_rev(void) { return bcm63xx_cpu_rev; } EXPORT_SYMBOL(bcm63xx_get_cpu_rev); unsigned int bcm63xx_get_cpu_freq(void) { return bcm63xx_cpu_freq; } unsigned int bcm63xx_get_memory_size(void) { return bcm63xx_memory_size; } static unsigned int detect_cpu_clock(void) { switch (bcm63xx_get_cpu_id()) { case BCM6338_CPU_ID: /* BCM6338 has a fixed 240 Mhz frequency */ return 240000000; case BCM6345_CPU_ID: /* BCM6345 has a fixed 140Mhz frequency */ return 140000000; case BCM6348_CPU_ID: { unsigned int tmp, n1, n2, m1; /* 16MHz * (N1 + 1) * (N2 + 2) / (M1_CPU + 1) */ tmp = bcm_perf_readl(PERF_MIPSPLLCTL_REG); n1 = (tmp & MIPSPLLCTL_N1_MASK) >> MIPSPLLCTL_N1_SHIFT; n2 = (tmp & MIPSPLLCTL_N2_MASK) >> MIPSPLLCTL_N2_SHIFT; m1 = (tmp & MIPSPLLCTL_M1CPU_MASK) >> MIPSPLLCTL_M1CPU_SHIFT; n1 += 1; n2 += 2; m1 += 1; return (16 * 1000000 * n1 * n2) / m1; } case BCM6358_CPU_ID: { unsigned int tmp, n1, n2, m1; /* 16MHz * N1 * N2 / M1_CPU */ tmp = bcm_ddr_readl(DDR_DMIPSPLLCFG_REG); n1 = (tmp & DMIPSPLLCFG_N1_MASK) >> DMIPSPLLCFG_N1_SHIFT; n2 = (tmp & DMIPSPLLCFG_N2_MASK) >> DMIPSPLLCFG_N2_SHIFT; m1 = (tmp & DMIPSPLLCFG_M1_MASK) >> DMIPSPLLCFG_M1_SHIFT; return (16 * 1000000 * n1 * n2) / m1; } case BCM6368_CPU_ID: { unsigned int tmp, p1, p2, ndiv, m1; /* (64MHz / P1) * P2 * NDIV / M1_CPU */ tmp = bcm_ddr_readl(DDR_DMIPSPLLCFG_6368_REG); p1 = (tmp & DMIPSPLLCFG_6368_P1_MASK) >> DMIPSPLLCFG_6368_P1_SHIFT; p2 = (tmp & DMIPSPLLCFG_6368_P2_MASK) >> DMIPSPLLCFG_6368_P2_SHIFT; ndiv = (tmp & DMIPSPLLCFG_6368_NDIV_MASK) >> DMIPSPLLCFG_6368_NDIV_SHIFT; tmp = bcm_ddr_readl(DDR_DMIPSPLLDIV_6368_REG); m1 = (tmp & DMIPSPLLDIV_6368_MDIV_MASK) >> DMIPSPLLDIV_6368_MDIV_SHIFT; return (((64 * 1000000) / p1) * p2 * ndiv) / m1; } default: BUG(); } } /* * attempt to detect the amount of memory installed */ static unsigned int detect_memory_size(void) { unsigned int cols = 0, rows = 0, is_32bits = 0, banks = 0; u32 val; if (BCMCPU_IS_6345()) { val = bcm_sdram_readl(SDRAM_MBASE_REG); return (val * 8 * 1024 * 1024); } if (BCMCPU_IS_6338() || BCMCPU_IS_6348()) { val = bcm_sdram_readl(SDRAM_CFG_REG); rows = (val & SDRAM_CFG_ROW_MASK) >> SDRAM_CFG_ROW_SHIFT; cols = (val & SDRAM_CFG_COL_MASK) >> SDRAM_CFG_COL_SHIFT; is_32bits = (val & SDRAM_CFG_32B_MASK) ? 1 : 0; banks = (val & SDRAM_CFG_BANK_MASK) ? 2 : 1; } if (BCMCPU_IS_6358() || BCMCPU_IS_6368()) { val = bcm_memc_readl(MEMC_CFG_REG); rows = (val & MEMC_CFG_ROW_MASK) >> MEMC_CFG_ROW_SHIFT; cols = (val & MEMC_CFG_COL_MASK) >> MEMC_CFG_COL_SHIFT; is_32bits = (val & MEMC_CFG_32B_MASK) ? 0 : 1; banks = 2; } /* 0 => 11 address bits ... 2 => 13 address bits */ rows += 11; /* 0 => 8 address bits ... 2 => 10 address bits */ cols += 8; return 1 << (cols + rows + (is_32bits + 1) + banks); } void __init bcm63xx_cpu_init(void) { unsigned int tmp, expected_cpu_id; struct cpuinfo_mips *c = &current_cpu_data; unsigned int cpu = smp_processor_id(); /* soc registers location depends on cpu type */ expected_cpu_id = 0; switch (c->cputype) { case CPU_BMIPS3300: if ((read_c0_prid() & 0xff00) == PRID_IMP_BMIPS3300_ALT) { expected_cpu_id = BCM6348_CPU_ID; bcm63xx_regs_base = bcm6348_regs_base; bcm63xx_irqs = bcm6348_irqs; } else { __cpu_name[cpu] = "Broadcom BCM6338"; expected_cpu_id = BCM6338_CPU_ID; bcm63xx_regs_base = bcm6338_regs_base; bcm63xx_irqs = bcm6338_irqs; } break; case CPU_BMIPS32: expected_cpu_id = BCM6345_CPU_ID; bcm63xx_regs_base = bcm6345_regs_base; bcm63xx_irqs = bcm6345_irqs; break; case CPU_BMIPS4350: switch (read_c0_prid() & 0xf0) { case 0x10: expected_cpu_id = BCM6358_CPU_ID; bcm63xx_regs_base = bcm6358_regs_base; bcm63xx_irqs = bcm6358_irqs; break; case 0x30: expected_cpu_id = BCM6368_CPU_ID; bcm63xx_regs_base = bcm6368_regs_base; bcm63xx_irqs = bcm6368_irqs; break; } break; } /* * really early to panic, but delaying panic would not help since we * will never get any working console */ if (!expected_cpu_id) panic("unsupported Broadcom CPU"); /* * bcm63xx_regs_base is set, we can access soc registers */ /* double check CPU type */ tmp = bcm_perf_readl(PERF_REV_REG); bcm63xx_cpu_id = (tmp & REV_CHIPID_MASK) >> REV_CHIPID_SHIFT; bcm63xx_cpu_rev = (tmp & REV_REVID_MASK) >> REV_REVID_SHIFT; if (bcm63xx_cpu_id != expected_cpu_id) panic("bcm63xx CPU id mismatch"); bcm63xx_cpu_freq = detect_cpu_clock(); bcm63xx_memory_size = detect_memory_size(); printk(KERN_INFO "Detected Broadcom 0x%04x CPU revision %02x\n", bcm63xx_cpu_id, bcm63xx_cpu_rev); printk(KERN_INFO "CPU frequency is %u MHz\n", bcm63xx_cpu_freq / 1000000); printk(KERN_INFO "%uMB of RAM installed\n", bcm63xx_memory_size >> 20); }
gpl-2.0
major91/Zeta-Chromium-N5
net/batman-adv/originator.c
4808
16881
/* * Copyright (C) 2009-2012 B.A.T.M.A.N. contributors: * * Marek Lindner, Simon Wunderlich * * 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-1301, USA * */ #include "main.h" #include "originator.h" #include "hash.h" #include "translation-table.h" #include "routing.h" #include "gateway_client.h" #include "hard-interface.h" #include "unicast.h" #include "soft-interface.h" static void purge_orig(struct work_struct *work); static void start_purge_timer(struct bat_priv *bat_priv) { INIT_DELAYED_WORK(&bat_priv->orig_work, purge_orig); queue_delayed_work(bat_event_workqueue, &bat_priv->orig_work, 1 * HZ); } /* returns 1 if they are the same originator */ static int compare_orig(const struct hlist_node *node, const void *data2) { const void *data1 = container_of(node, struct orig_node, hash_entry); return (memcmp(data1, data2, ETH_ALEN) == 0 ? 1 : 0); } int originator_init(struct bat_priv *bat_priv) { if (bat_priv->orig_hash) return 1; bat_priv->orig_hash = hash_new(1024); if (!bat_priv->orig_hash) goto err; start_purge_timer(bat_priv); return 1; err: return 0; } void neigh_node_free_ref(struct neigh_node *neigh_node) { if (atomic_dec_and_test(&neigh_node->refcount)) kfree_rcu(neigh_node, rcu); } /* increases the refcounter of a found router */ struct neigh_node *orig_node_get_router(struct orig_node *orig_node) { struct neigh_node *router; rcu_read_lock(); router = rcu_dereference(orig_node->router); if (router && !atomic_inc_not_zero(&router->refcount)) router = NULL; rcu_read_unlock(); return router; } struct neigh_node *create_neighbor(struct orig_node *orig_node, struct orig_node *orig_neigh_node, const uint8_t *neigh, struct hard_iface *if_incoming) { struct bat_priv *bat_priv = netdev_priv(if_incoming->soft_iface); struct neigh_node *neigh_node; bat_dbg(DBG_BATMAN, bat_priv, "Creating new last-hop neighbor of originator\n"); neigh_node = kzalloc(sizeof(*neigh_node), GFP_ATOMIC); if (!neigh_node) return NULL; INIT_HLIST_NODE(&neigh_node->list); INIT_LIST_HEAD(&neigh_node->bonding_list); spin_lock_init(&neigh_node->tq_lock); memcpy(neigh_node->addr, neigh, ETH_ALEN); neigh_node->orig_node = orig_neigh_node; neigh_node->if_incoming = if_incoming; /* extra reference for return */ atomic_set(&neigh_node->refcount, 2); spin_lock_bh(&orig_node->neigh_list_lock); hlist_add_head_rcu(&neigh_node->list, &orig_node->neigh_list); spin_unlock_bh(&orig_node->neigh_list_lock); return neigh_node; } static void orig_node_free_rcu(struct rcu_head *rcu) { struct hlist_node *node, *node_tmp; struct neigh_node *neigh_node, *tmp_neigh_node; struct orig_node *orig_node; orig_node = container_of(rcu, struct orig_node, rcu); spin_lock_bh(&orig_node->neigh_list_lock); /* for all bonding members ... */ list_for_each_entry_safe(neigh_node, tmp_neigh_node, &orig_node->bond_list, bonding_list) { list_del_rcu(&neigh_node->bonding_list); neigh_node_free_ref(neigh_node); } /* for all neighbors towards this originator ... */ hlist_for_each_entry_safe(neigh_node, node, node_tmp, &orig_node->neigh_list, list) { hlist_del_rcu(&neigh_node->list); neigh_node_free_ref(neigh_node); } spin_unlock_bh(&orig_node->neigh_list_lock); frag_list_free(&orig_node->frag_list); tt_global_del_orig(orig_node->bat_priv, orig_node, "originator timed out"); kfree(orig_node->tt_buff); kfree(orig_node->bcast_own); kfree(orig_node->bcast_own_sum); kfree(orig_node); } void orig_node_free_ref(struct orig_node *orig_node) { if (atomic_dec_and_test(&orig_node->refcount)) call_rcu(&orig_node->rcu, orig_node_free_rcu); } void originator_free(struct bat_priv *bat_priv) { struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node, *node_tmp; struct hlist_head *head; spinlock_t *list_lock; /* spinlock to protect write access */ struct orig_node *orig_node; uint32_t i; if (!hash) return; cancel_delayed_work_sync(&bat_priv->orig_work); bat_priv->orig_hash = NULL; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; list_lock = &hash->list_locks[i]; spin_lock_bh(list_lock); hlist_for_each_entry_safe(orig_node, node, node_tmp, head, hash_entry) { hlist_del_rcu(node); orig_node_free_ref(orig_node); } spin_unlock_bh(list_lock); } hash_destroy(hash); } /* this function finds or creates an originator entry for the given * address if it does not exits */ struct orig_node *get_orig_node(struct bat_priv *bat_priv, const uint8_t *addr) { struct orig_node *orig_node; int size; int hash_added; orig_node = orig_hash_find(bat_priv, addr); if (orig_node) return orig_node; bat_dbg(DBG_BATMAN, bat_priv, "Creating new originator: %pM\n", addr); orig_node = kzalloc(sizeof(*orig_node), GFP_ATOMIC); if (!orig_node) return NULL; INIT_HLIST_HEAD(&orig_node->neigh_list); INIT_LIST_HEAD(&orig_node->bond_list); spin_lock_init(&orig_node->ogm_cnt_lock); spin_lock_init(&orig_node->bcast_seqno_lock); spin_lock_init(&orig_node->neigh_list_lock); spin_lock_init(&orig_node->tt_buff_lock); /* extra reference for return */ atomic_set(&orig_node->refcount, 2); orig_node->tt_initialised = false; orig_node->tt_poss_change = false; orig_node->bat_priv = bat_priv; memcpy(orig_node->orig, addr, ETH_ALEN); orig_node->router = NULL; orig_node->tt_crc = 0; atomic_set(&orig_node->last_ttvn, 0); orig_node->tt_buff = NULL; orig_node->tt_buff_len = 0; atomic_set(&orig_node->tt_size, 0); orig_node->bcast_seqno_reset = jiffies - 1 - msecs_to_jiffies(RESET_PROTECTION_MS); orig_node->batman_seqno_reset = jiffies - 1 - msecs_to_jiffies(RESET_PROTECTION_MS); atomic_set(&orig_node->bond_candidates, 0); size = bat_priv->num_ifaces * sizeof(unsigned long) * NUM_WORDS; orig_node->bcast_own = kzalloc(size, GFP_ATOMIC); if (!orig_node->bcast_own) goto free_orig_node; size = bat_priv->num_ifaces * sizeof(uint8_t); orig_node->bcast_own_sum = kzalloc(size, GFP_ATOMIC); INIT_LIST_HEAD(&orig_node->frag_list); orig_node->last_frag_packet = 0; if (!orig_node->bcast_own_sum) goto free_bcast_own; hash_added = hash_add(bat_priv->orig_hash, compare_orig, choose_orig, orig_node, &orig_node->hash_entry); if (hash_added != 0) goto free_bcast_own_sum; return orig_node; free_bcast_own_sum: kfree(orig_node->bcast_own_sum); free_bcast_own: kfree(orig_node->bcast_own); free_orig_node: kfree(orig_node); return NULL; } static bool purge_orig_neighbors(struct bat_priv *bat_priv, struct orig_node *orig_node, struct neigh_node **best_neigh_node) { struct hlist_node *node, *node_tmp; struct neigh_node *neigh_node; bool neigh_purged = false; *best_neigh_node = NULL; spin_lock_bh(&orig_node->neigh_list_lock); /* for all neighbors towards this originator ... */ hlist_for_each_entry_safe(neigh_node, node, node_tmp, &orig_node->neigh_list, list) { if ((has_timed_out(neigh_node->last_valid, PURGE_TIMEOUT)) || (neigh_node->if_incoming->if_status == IF_INACTIVE) || (neigh_node->if_incoming->if_status == IF_NOT_IN_USE) || (neigh_node->if_incoming->if_status == IF_TO_BE_REMOVED)) { if ((neigh_node->if_incoming->if_status == IF_INACTIVE) || (neigh_node->if_incoming->if_status == IF_NOT_IN_USE) || (neigh_node->if_incoming->if_status == IF_TO_BE_REMOVED)) bat_dbg(DBG_BATMAN, bat_priv, "neighbor purge: originator %pM, neighbor: %pM, iface: %s\n", orig_node->orig, neigh_node->addr, neigh_node->if_incoming->net_dev->name); else bat_dbg(DBG_BATMAN, bat_priv, "neighbor timeout: originator %pM, neighbor: %pM, last_valid: %lu\n", orig_node->orig, neigh_node->addr, (neigh_node->last_valid / HZ)); neigh_purged = true; hlist_del_rcu(&neigh_node->list); bonding_candidate_del(orig_node, neigh_node); neigh_node_free_ref(neigh_node); } else { if ((!*best_neigh_node) || (neigh_node->tq_avg > (*best_neigh_node)->tq_avg)) *best_neigh_node = neigh_node; } } spin_unlock_bh(&orig_node->neigh_list_lock); return neigh_purged; } static bool purge_orig_node(struct bat_priv *bat_priv, struct orig_node *orig_node) { struct neigh_node *best_neigh_node; if (has_timed_out(orig_node->last_valid, 2 * PURGE_TIMEOUT)) { bat_dbg(DBG_BATMAN, bat_priv, "Originator timeout: originator %pM, last_valid %lu\n", orig_node->orig, (orig_node->last_valid / HZ)); return true; } else { if (purge_orig_neighbors(bat_priv, orig_node, &best_neigh_node)) update_route(bat_priv, orig_node, best_neigh_node); } return false; } static void _purge_orig(struct bat_priv *bat_priv) { struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node, *node_tmp; struct hlist_head *head; spinlock_t *list_lock; /* spinlock to protect write access */ struct orig_node *orig_node; uint32_t i; if (!hash) return; /* for all origins... */ for (i = 0; i < hash->size; i++) { head = &hash->table[i]; list_lock = &hash->list_locks[i]; spin_lock_bh(list_lock); hlist_for_each_entry_safe(orig_node, node, node_tmp, head, hash_entry) { if (purge_orig_node(bat_priv, orig_node)) { if (orig_node->gw_flags) gw_node_delete(bat_priv, orig_node); hlist_del_rcu(node); orig_node_free_ref(orig_node); continue; } if (has_timed_out(orig_node->last_frag_packet, FRAG_TIMEOUT)) frag_list_free(&orig_node->frag_list); } spin_unlock_bh(list_lock); } gw_node_purge(bat_priv); gw_election(bat_priv); softif_neigh_purge(bat_priv); } static void purge_orig(struct work_struct *work) { struct delayed_work *delayed_work = container_of(work, struct delayed_work, work); struct bat_priv *bat_priv = container_of(delayed_work, struct bat_priv, orig_work); _purge_orig(bat_priv); start_purge_timer(bat_priv); } void purge_orig_ref(struct bat_priv *bat_priv) { _purge_orig(bat_priv); } int orig_seq_print_text(struct seq_file *seq, void *offset) { struct net_device *net_dev = (struct net_device *)seq->private; struct bat_priv *bat_priv = netdev_priv(net_dev); struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node, *node_tmp; struct hlist_head *head; struct hard_iface *primary_if; struct orig_node *orig_node; struct neigh_node *neigh_node, *neigh_node_tmp; int batman_count = 0; int last_seen_secs; int last_seen_msecs; uint32_t i; int ret = 0; primary_if = primary_if_get_selected(bat_priv); if (!primary_if) { ret = seq_printf(seq, "BATMAN mesh %s disabled - please specify interfaces to enable it\n", net_dev->name); goto out; } if (primary_if->if_status != IF_ACTIVE) { ret = seq_printf(seq, "BATMAN mesh %s disabled - primary interface not active\n", net_dev->name); goto out; } seq_printf(seq, "[B.A.T.M.A.N. adv %s, MainIF/MAC: %s/%pM (%s)]\n", SOURCE_VERSION, primary_if->net_dev->name, primary_if->net_dev->dev_addr, net_dev->name); seq_printf(seq, " %-15s %s (%s/%i) %17s [%10s]: %20s ...\n", "Originator", "last-seen", "#", TQ_MAX_VALUE, "Nexthop", "outgoingIF", "Potential nexthops"); for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { neigh_node = orig_node_get_router(orig_node); if (!neigh_node) continue; if (neigh_node->tq_avg == 0) goto next; last_seen_secs = jiffies_to_msecs(jiffies - orig_node->last_valid) / 1000; last_seen_msecs = jiffies_to_msecs(jiffies - orig_node->last_valid) % 1000; seq_printf(seq, "%pM %4i.%03is (%3i) %pM [%10s]:", orig_node->orig, last_seen_secs, last_seen_msecs, neigh_node->tq_avg, neigh_node->addr, neigh_node->if_incoming->net_dev->name); hlist_for_each_entry_rcu(neigh_node_tmp, node_tmp, &orig_node->neigh_list, list) { seq_printf(seq, " %pM (%3i)", neigh_node_tmp->addr, neigh_node_tmp->tq_avg); } seq_printf(seq, "\n"); batman_count++; next: neigh_node_free_ref(neigh_node); } rcu_read_unlock(); } if (batman_count == 0) seq_printf(seq, "No batman nodes in range ...\n"); out: if (primary_if) hardif_free_ref(primary_if); return ret; } static int orig_node_add_if(struct orig_node *orig_node, int max_if_num) { void *data_ptr; data_ptr = kmalloc(max_if_num * sizeof(unsigned long) * NUM_WORDS, GFP_ATOMIC); if (!data_ptr) return -1; memcpy(data_ptr, orig_node->bcast_own, (max_if_num - 1) * sizeof(unsigned long) * NUM_WORDS); kfree(orig_node->bcast_own); orig_node->bcast_own = data_ptr; data_ptr = kmalloc(max_if_num * sizeof(uint8_t), GFP_ATOMIC); if (!data_ptr) return -1; memcpy(data_ptr, orig_node->bcast_own_sum, (max_if_num - 1) * sizeof(uint8_t)); kfree(orig_node->bcast_own_sum); orig_node->bcast_own_sum = data_ptr; return 0; } int orig_hash_add_if(struct hard_iface *hard_iface, int max_if_num) { struct bat_priv *bat_priv = netdev_priv(hard_iface->soft_iface); struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; uint32_t i; int ret; /* resize all orig nodes because orig_node->bcast_own(_sum) depend on * if_num */ for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { spin_lock_bh(&orig_node->ogm_cnt_lock); ret = orig_node_add_if(orig_node, max_if_num); spin_unlock_bh(&orig_node->ogm_cnt_lock); if (ret == -1) goto err; } rcu_read_unlock(); } return 0; err: rcu_read_unlock(); return -ENOMEM; } static int orig_node_del_if(struct orig_node *orig_node, int max_if_num, int del_if_num) { void *data_ptr = NULL; int chunk_size; /* last interface was removed */ if (max_if_num == 0) goto free_bcast_own; chunk_size = sizeof(unsigned long) * NUM_WORDS; data_ptr = kmalloc(max_if_num * chunk_size, GFP_ATOMIC); if (!data_ptr) return -1; /* copy first part */ memcpy(data_ptr, orig_node->bcast_own, del_if_num * chunk_size); /* copy second part */ memcpy((char *)data_ptr + del_if_num * chunk_size, orig_node->bcast_own + ((del_if_num + 1) * chunk_size), (max_if_num - del_if_num) * chunk_size); free_bcast_own: kfree(orig_node->bcast_own); orig_node->bcast_own = data_ptr; if (max_if_num == 0) goto free_own_sum; data_ptr = kmalloc(max_if_num * sizeof(uint8_t), GFP_ATOMIC); if (!data_ptr) return -1; memcpy(data_ptr, orig_node->bcast_own_sum, del_if_num * sizeof(uint8_t)); memcpy((char *)data_ptr + del_if_num * sizeof(uint8_t), orig_node->bcast_own_sum + ((del_if_num + 1) * sizeof(uint8_t)), (max_if_num - del_if_num) * sizeof(uint8_t)); free_own_sum: kfree(orig_node->bcast_own_sum); orig_node->bcast_own_sum = data_ptr; return 0; } int orig_hash_del_if(struct hard_iface *hard_iface, int max_if_num) { struct bat_priv *bat_priv = netdev_priv(hard_iface->soft_iface); struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node; struct hlist_head *head; struct hard_iface *hard_iface_tmp; struct orig_node *orig_node; uint32_t i; int ret; /* resize all orig nodes because orig_node->bcast_own(_sum) depend on * if_num */ for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { spin_lock_bh(&orig_node->ogm_cnt_lock); ret = orig_node_del_if(orig_node, max_if_num, hard_iface->if_num); spin_unlock_bh(&orig_node->ogm_cnt_lock); if (ret == -1) goto err; } rcu_read_unlock(); } /* renumber remaining batman interfaces _inside_ of orig_hash_lock */ rcu_read_lock(); list_for_each_entry_rcu(hard_iface_tmp, &hardif_list, list) { if (hard_iface_tmp->if_status == IF_NOT_IN_USE) continue; if (hard_iface == hard_iface_tmp) continue; if (hard_iface->soft_iface != hard_iface_tmp->soft_iface) continue; if (hard_iface_tmp->if_num > hard_iface->if_num) hard_iface_tmp->if_num--; } rcu_read_unlock(); hard_iface->if_num = -1; return 0; err: rcu_read_unlock(); return -ENOMEM; }
gpl-2.0
silence-star/z5_kernel
drivers/s390/cio/ccwgroup.c
4808
16238
/* * bus driver for ccwgroup * * Copyright IBM Corp. 2002, 2009 * * Author(s): Arnd Bergmann (arndb@de.ibm.com) * Cornelia Huck (cornelia.huck@de.ibm.com) */ #include <linux/module.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/device.h> #include <linux/init.h> #include <linux/ctype.h> #include <linux/dcache.h> #include <asm/ccwdev.h> #include <asm/ccwgroup.h> #define CCW_BUS_ID_SIZE 20 /* In Linux 2.4, we had a channel device layer called "chandev" * that did all sorts of obscure stuff for networking devices. * This is another driver that serves as a replacement for just * one of its functions, namely the translation of single subchannels * to devices that use multiple subchannels. */ /* a device matches a driver if all its slave devices match the same * entry of the driver */ static int ccwgroup_bus_match(struct device *dev, struct device_driver * drv) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(drv); if (gdev->creator_id == gdrv->driver_id) return 1; return 0; } static struct bus_type ccwgroup_bus_type; static void __ccwgroup_remove_symlinks(struct ccwgroup_device *gdev) { int i; char str[8]; for (i = 0; i < gdev->count; i++) { sprintf(str, "cdev%d", i); sysfs_remove_link(&gdev->dev.kobj, str); sysfs_remove_link(&gdev->cdev[i]->dev.kobj, "group_device"); } } /* * Remove references from ccw devices to ccw group device and from * ccw group device to ccw devices. */ static void __ccwgroup_remove_cdev_refs(struct ccwgroup_device *gdev) { struct ccw_device *cdev; int i; for (i = 0; i < gdev->count; i++) { cdev = gdev->cdev[i]; if (!cdev) continue; spin_lock_irq(cdev->ccwlock); dev_set_drvdata(&cdev->dev, NULL); spin_unlock_irq(cdev->ccwlock); gdev->cdev[i] = NULL; put_device(&cdev->dev); } } static int ccwgroup_set_online(struct ccwgroup_device *gdev) { struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver); int ret = 0; if (atomic_cmpxchg(&gdev->onoff, 0, 1) != 0) return -EAGAIN; if (gdev->state == CCWGROUP_ONLINE) goto out; if (gdrv->set_online) ret = gdrv->set_online(gdev); if (ret) goto out; gdev->state = CCWGROUP_ONLINE; out: atomic_set(&gdev->onoff, 0); return ret; } static int ccwgroup_set_offline(struct ccwgroup_device *gdev) { struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver); int ret = 0; if (atomic_cmpxchg(&gdev->onoff, 0, 1) != 0) return -EAGAIN; if (gdev->state == CCWGROUP_OFFLINE) goto out; if (gdrv->set_offline) ret = gdrv->set_offline(gdev); if (ret) goto out; gdev->state = CCWGROUP_OFFLINE; out: atomic_set(&gdev->onoff, 0); return ret; } static ssize_t ccwgroup_online_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver); unsigned long value; int ret; if (!dev->driver) return -EINVAL; if (!try_module_get(gdrv->driver.owner)) return -EINVAL; ret = strict_strtoul(buf, 0, &value); if (ret) goto out; if (value == 1) ret = ccwgroup_set_online(gdev); else if (value == 0) ret = ccwgroup_set_offline(gdev); else ret = -EINVAL; out: module_put(gdrv->driver.owner); return (ret == 0) ? count : ret; } static ssize_t ccwgroup_online_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); int online; online = (gdev->state == CCWGROUP_ONLINE) ? 1 : 0; return scnprintf(buf, PAGE_SIZE, "%d\n", online); } /* * Provide an 'ungroup' attribute so the user can remove group devices no * longer needed or accidentially created. Saves memory :) */ static void ccwgroup_ungroup_callback(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); mutex_lock(&gdev->reg_mutex); if (device_is_registered(&gdev->dev)) { __ccwgroup_remove_symlinks(gdev); device_unregister(dev); __ccwgroup_remove_cdev_refs(gdev); } mutex_unlock(&gdev->reg_mutex); } static ssize_t ccwgroup_ungroup_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); int rc; /* Prevent concurrent online/offline processing and ungrouping. */ if (atomic_cmpxchg(&gdev->onoff, 0, 1) != 0) return -EAGAIN; if (gdev->state != CCWGROUP_OFFLINE) { rc = -EINVAL; goto out; } /* Note that we cannot unregister the device from one of its * attribute methods, so we have to use this roundabout approach. */ rc = device_schedule_callback(dev, ccwgroup_ungroup_callback); out: if (rc) { if (rc != -EAGAIN) /* Release onoff "lock" when ungrouping failed. */ atomic_set(&gdev->onoff, 0); return rc; } return count; } static DEVICE_ATTR(ungroup, 0200, NULL, ccwgroup_ungroup_store); static DEVICE_ATTR(online, 0644, ccwgroup_online_show, ccwgroup_online_store); static struct attribute *ccwgroup_attrs[] = { &dev_attr_online.attr, &dev_attr_ungroup.attr, NULL, }; static struct attribute_group ccwgroup_attr_group = { .attrs = ccwgroup_attrs, }; static const struct attribute_group *ccwgroup_attr_groups[] = { &ccwgroup_attr_group, NULL, }; static void ccwgroup_release(struct device *dev) { kfree(to_ccwgroupdev(dev)); } static int __ccwgroup_create_symlinks(struct ccwgroup_device *gdev) { char str[8]; int i, rc; for (i = 0; i < gdev->count; i++) { rc = sysfs_create_link(&gdev->cdev[i]->dev.kobj, &gdev->dev.kobj, "group_device"); if (rc) { for (--i; i >= 0; i--) sysfs_remove_link(&gdev->cdev[i]->dev.kobj, "group_device"); return rc; } } for (i = 0; i < gdev->count; i++) { sprintf(str, "cdev%d", i); rc = sysfs_create_link(&gdev->dev.kobj, &gdev->cdev[i]->dev.kobj, str); if (rc) { for (--i; i >= 0; i--) { sprintf(str, "cdev%d", i); sysfs_remove_link(&gdev->dev.kobj, str); } for (i = 0; i < gdev->count; i++) sysfs_remove_link(&gdev->cdev[i]->dev.kobj, "group_device"); return rc; } } return 0; } static int __get_next_bus_id(const char **buf, char *bus_id) { int rc, len; char *start, *end; start = (char *)*buf; end = strchr(start, ','); if (!end) { /* Last entry. Strip trailing newline, if applicable. */ end = strchr(start, '\n'); if (end) *end = '\0'; len = strlen(start) + 1; } else { len = end - start + 1; end++; } if (len < CCW_BUS_ID_SIZE) { strlcpy(bus_id, start, len); rc = 0; } else rc = -EINVAL; *buf = end; return rc; } static int __is_valid_bus_id(char bus_id[CCW_BUS_ID_SIZE]) { int cssid, ssid, devno; /* Must be of form %x.%x.%04x */ if (sscanf(bus_id, "%x.%1x.%04x", &cssid, &ssid, &devno) != 3) return 0; return 1; } /** * ccwgroup_create_from_string() - create and register a ccw group device * @root: parent device for the new device * @creator_id: identifier of creating driver * @cdrv: ccw driver of slave devices * @num_devices: number of slave devices * @buf: buffer containing comma separated bus ids of slave devices * * Create and register a new ccw group device as a child of @root. Slave * devices are obtained from the list of bus ids given in @buf and must all * belong to @cdrv. * Returns: * %0 on success and an error code on failure. * Context: * non-atomic */ int ccwgroup_create_from_string(struct device *root, unsigned int creator_id, struct ccw_driver *cdrv, int num_devices, const char *buf) { struct ccwgroup_device *gdev; int rc, i; char tmp_bus_id[CCW_BUS_ID_SIZE]; const char *curr_buf; gdev = kzalloc(sizeof(*gdev) + num_devices * sizeof(gdev->cdev[0]), GFP_KERNEL); if (!gdev) return -ENOMEM; atomic_set(&gdev->onoff, 0); mutex_init(&gdev->reg_mutex); mutex_lock(&gdev->reg_mutex); gdev->creator_id = creator_id; gdev->count = num_devices; gdev->dev.bus = &ccwgroup_bus_type; gdev->dev.parent = root; gdev->dev.release = ccwgroup_release; device_initialize(&gdev->dev); curr_buf = buf; for (i = 0; i < num_devices && curr_buf; i++) { rc = __get_next_bus_id(&curr_buf, tmp_bus_id); if (rc != 0) goto error; if (!__is_valid_bus_id(tmp_bus_id)) { rc = -EINVAL; goto error; } gdev->cdev[i] = get_ccwdev_by_busid(cdrv, tmp_bus_id); /* * All devices have to be of the same type in * order to be grouped. */ if (!gdev->cdev[i] || gdev->cdev[i]->id.driver_info != gdev->cdev[0]->id.driver_info) { rc = -EINVAL; goto error; } /* Don't allow a device to belong to more than one group. */ spin_lock_irq(gdev->cdev[i]->ccwlock); if (dev_get_drvdata(&gdev->cdev[i]->dev)) { spin_unlock_irq(gdev->cdev[i]->ccwlock); rc = -EINVAL; goto error; } dev_set_drvdata(&gdev->cdev[i]->dev, gdev); spin_unlock_irq(gdev->cdev[i]->ccwlock); } /* Check for sufficient number of bus ids. */ if (i < num_devices && !curr_buf) { rc = -EINVAL; goto error; } /* Check for trailing stuff. */ if (i == num_devices && strlen(curr_buf) > 0) { rc = -EINVAL; goto error; } dev_set_name(&gdev->dev, "%s", dev_name(&gdev->cdev[0]->dev)); gdev->dev.groups = ccwgroup_attr_groups; rc = device_add(&gdev->dev); if (rc) goto error; rc = __ccwgroup_create_symlinks(gdev); if (rc) { device_del(&gdev->dev); goto error; } mutex_unlock(&gdev->reg_mutex); return 0; error: for (i = 0; i < num_devices; i++) if (gdev->cdev[i]) { spin_lock_irq(gdev->cdev[i]->ccwlock); if (dev_get_drvdata(&gdev->cdev[i]->dev) == gdev) dev_set_drvdata(&gdev->cdev[i]->dev, NULL); spin_unlock_irq(gdev->cdev[i]->ccwlock); put_device(&gdev->cdev[i]->dev); gdev->cdev[i] = NULL; } mutex_unlock(&gdev->reg_mutex); put_device(&gdev->dev); return rc; } EXPORT_SYMBOL(ccwgroup_create_from_string); static int ccwgroup_notifier(struct notifier_block *nb, unsigned long action, void *data) { struct device *dev = data; if (action == BUS_NOTIFY_UNBIND_DRIVER) device_schedule_callback(dev, ccwgroup_ungroup_callback); return NOTIFY_OK; } static struct notifier_block ccwgroup_nb = { .notifier_call = ccwgroup_notifier }; static int __init init_ccwgroup(void) { int ret; ret = bus_register(&ccwgroup_bus_type); if (ret) return ret; ret = bus_register_notifier(&ccwgroup_bus_type, &ccwgroup_nb); if (ret) bus_unregister(&ccwgroup_bus_type); return ret; } static void __exit cleanup_ccwgroup(void) { bus_unregister_notifier(&ccwgroup_bus_type, &ccwgroup_nb); bus_unregister(&ccwgroup_bus_type); } module_init(init_ccwgroup); module_exit(cleanup_ccwgroup); /************************** driver stuff ******************************/ static int ccwgroup_probe(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver); return gdrv->probe ? gdrv->probe(gdev) : -ENODEV; } static int ccwgroup_remove(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver); if (!dev->driver) return 0; if (gdrv->remove) gdrv->remove(gdev); return 0; } static void ccwgroup_shutdown(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver); if (!dev->driver) return; if (gdrv->shutdown) gdrv->shutdown(gdev); } static int ccwgroup_pm_prepare(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver); /* Fail while device is being set online/offline. */ if (atomic_read(&gdev->onoff)) return -EAGAIN; if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE) return 0; return gdrv->prepare ? gdrv->prepare(gdev) : 0; } static void ccwgroup_pm_complete(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver); if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE) return; if (gdrv->complete) gdrv->complete(gdev); } static int ccwgroup_pm_freeze(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver); if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE) return 0; return gdrv->freeze ? gdrv->freeze(gdev) : 0; } static int ccwgroup_pm_thaw(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver); if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE) return 0; return gdrv->thaw ? gdrv->thaw(gdev) : 0; } static int ccwgroup_pm_restore(struct device *dev) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver); if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE) return 0; return gdrv->restore ? gdrv->restore(gdev) : 0; } static const struct dev_pm_ops ccwgroup_pm_ops = { .prepare = ccwgroup_pm_prepare, .complete = ccwgroup_pm_complete, .freeze = ccwgroup_pm_freeze, .thaw = ccwgroup_pm_thaw, .restore = ccwgroup_pm_restore, }; static struct bus_type ccwgroup_bus_type = { .name = "ccwgroup", .match = ccwgroup_bus_match, .probe = ccwgroup_probe, .remove = ccwgroup_remove, .shutdown = ccwgroup_shutdown, .pm = &ccwgroup_pm_ops, }; /** * ccwgroup_driver_register() - register a ccw group driver * @cdriver: driver to be registered * * This function is mainly a wrapper around driver_register(). */ int ccwgroup_driver_register(struct ccwgroup_driver *cdriver) { /* register our new driver with the core */ cdriver->driver.bus = &ccwgroup_bus_type; return driver_register(&cdriver->driver); } EXPORT_SYMBOL(ccwgroup_driver_register); static int __ccwgroup_match_all(struct device *dev, void *data) { return 1; } /** * ccwgroup_driver_unregister() - deregister a ccw group driver * @cdriver: driver to be deregistered * * This function is mainly a wrapper around driver_unregister(). */ void ccwgroup_driver_unregister(struct ccwgroup_driver *cdriver) { struct device *dev; /* We don't want ccwgroup devices to live longer than their driver. */ while ((dev = driver_find_device(&cdriver->driver, NULL, NULL, __ccwgroup_match_all))) { struct ccwgroup_device *gdev = to_ccwgroupdev(dev); mutex_lock(&gdev->reg_mutex); __ccwgroup_remove_symlinks(gdev); device_unregister(dev); __ccwgroup_remove_cdev_refs(gdev); mutex_unlock(&gdev->reg_mutex); put_device(dev); } driver_unregister(&cdriver->driver); } EXPORT_SYMBOL(ccwgroup_driver_unregister); /** * ccwgroup_probe_ccwdev() - probe function for slave devices * @cdev: ccw device to be probed * * This is a dummy probe function for ccw devices that are slave devices in * a ccw group device. * Returns: * always %0 */ int ccwgroup_probe_ccwdev(struct ccw_device *cdev) { return 0; } EXPORT_SYMBOL(ccwgroup_probe_ccwdev); /** * ccwgroup_remove_ccwdev() - remove function for slave devices * @cdev: ccw device to be removed * * This is a remove function for ccw devices that are slave devices in a ccw * group device. It sets the ccw device offline and also deregisters the * embedding ccw group device. */ void ccwgroup_remove_ccwdev(struct ccw_device *cdev) { struct ccwgroup_device *gdev; /* Ignore offlining errors, device is gone anyway. */ ccw_device_set_offline(cdev); /* If one of its devices is gone, the whole group is done for. */ spin_lock_irq(cdev->ccwlock); gdev = dev_get_drvdata(&cdev->dev); if (!gdev) { spin_unlock_irq(cdev->ccwlock); return; } /* Get ccwgroup device reference for local processing. */ get_device(&gdev->dev); spin_unlock_irq(cdev->ccwlock); /* Unregister group device. */ mutex_lock(&gdev->reg_mutex); if (device_is_registered(&gdev->dev)) { __ccwgroup_remove_symlinks(gdev); device_unregister(&gdev->dev); __ccwgroup_remove_cdev_refs(gdev); } mutex_unlock(&gdev->reg_mutex); /* Release ccwgroup device reference for local processing. */ put_device(&gdev->dev); } EXPORT_SYMBOL(ccwgroup_remove_ccwdev); MODULE_LICENSE("GPL");
gpl-2.0
dennes544/aosp_kernel_lge_hammerhead_dennes544
fs/xfs/xfs_bmap.c
4808
181964
/* * Copyright (c) 2000-2006 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * 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. 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_types.h" #include "xfs_bit.h" #include "xfs_log.h" #include "xfs_inum.h" #include "xfs_trans.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_dir2.h" #include "xfs_da_btree.h" #include "xfs_bmap_btree.h" #include "xfs_alloc_btree.h" #include "xfs_ialloc_btree.h" #include "xfs_dinode.h" #include "xfs_inode.h" #include "xfs_btree.h" #include "xfs_mount.h" #include "xfs_itable.h" #include "xfs_inode_item.h" #include "xfs_extfree_item.h" #include "xfs_alloc.h" #include "xfs_bmap.h" #include "xfs_rtalloc.h" #include "xfs_error.h" #include "xfs_attr_leaf.h" #include "xfs_rw.h" #include "xfs_quota.h" #include "xfs_trans_space.h" #include "xfs_buf_item.h" #include "xfs_filestream.h" #include "xfs_vnodeops.h" #include "xfs_trace.h" kmem_zone_t *xfs_bmap_free_item_zone; /* * Prototypes for internal bmap routines. */ #ifdef DEBUG STATIC void xfs_bmap_check_leaf_extents( struct xfs_btree_cur *cur, struct xfs_inode *ip, int whichfork); #else #define xfs_bmap_check_leaf_extents(cur, ip, whichfork) do { } while (0) #endif /* * Called from xfs_bmap_add_attrfork to handle extents format files. */ STATIC int /* error */ xfs_bmap_add_attrfork_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated */ xfs_bmap_free_t *flist, /* blocks to free at commit */ int *flags); /* inode logging flags */ /* * Called from xfs_bmap_add_attrfork to handle local format files. */ STATIC int /* error */ xfs_bmap_add_attrfork_local( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated */ xfs_bmap_free_t *flist, /* blocks to free at commit */ int *flags); /* inode logging flags */ /* * xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file. * It figures out where to ask the underlying allocator to put the new extent. */ STATIC int /* error */ xfs_bmap_alloc( xfs_bmalloca_t *ap); /* bmap alloc argument struct */ /* * Transform a btree format file with only one leaf node, where the * extents list will fit in the inode, into an extents format file. * Since the file extents are already in-core, all we have to do is * give up the space for the btree root and pitch the leaf block. */ STATIC int /* error */ xfs_bmap_btree_to_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_btree_cur_t *cur, /* btree cursor */ int *logflagsp, /* inode logging flags */ int whichfork); /* data or attr fork */ /* * Remove the entry "free" from the free item list. Prev points to the * previous entry, unless "free" is the head of the list. */ STATIC void xfs_bmap_del_free( xfs_bmap_free_t *flist, /* free item list header */ xfs_bmap_free_item_t *prev, /* previous item on list, if any */ xfs_bmap_free_item_t *free); /* list item to be freed */ /* * Convert an extents-format file into a btree-format file. * The new file will have a root block (in the inode) and a single child block. */ STATIC int /* error */ xfs_bmap_extents_to_btree( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first-block-allocated */ xfs_bmap_free_t *flist, /* blocks freed in xaction */ xfs_btree_cur_t **curp, /* cursor returned to caller */ int wasdel, /* converting a delayed alloc */ int *logflagsp, /* inode logging flags */ int whichfork); /* data or attr fork */ /* * Convert a local file to an extents file. * This code is sort of bogus, since the file data needs to get * logged so it won't be lost. The bmap-level manipulations are ok, though. */ STATIC int /* error */ xfs_bmap_local_to_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated in xaction */ xfs_extlen_t total, /* total blocks needed by transaction */ int *logflagsp, /* inode logging flags */ int whichfork); /* data or attr fork */ /* * Search the extents list for the inode, for the extent containing bno. * If bno lies in a hole, point to the next entry. If bno lies past eof, * *eofp will be set, and *prevp will contain the last entry (null if none). * Else, *lastxp will be set to the index of the found * entry; *gotp will contain the entry. */ STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */ xfs_bmap_search_extents( xfs_inode_t *ip, /* incore inode pointer */ xfs_fileoff_t bno, /* block number searched for */ int whichfork, /* data or attr fork */ int *eofp, /* out: end of file found */ xfs_extnum_t *lastxp, /* out: last extent index */ xfs_bmbt_irec_t *gotp, /* out: extent entry found */ xfs_bmbt_irec_t *prevp); /* out: previous extent entry found */ /* * Compute the worst-case number of indirect blocks that will be used * for ip's delayed extent of length "len". */ STATIC xfs_filblks_t xfs_bmap_worst_indlen( xfs_inode_t *ip, /* incore inode pointer */ xfs_filblks_t len); /* delayed extent length */ #ifdef DEBUG /* * Perform various validation checks on the values being returned * from xfs_bmapi(). */ STATIC void xfs_bmap_validate_ret( xfs_fileoff_t bno, xfs_filblks_t len, int flags, xfs_bmbt_irec_t *mval, int nmap, int ret_nmap); #else #define xfs_bmap_validate_ret(bno,len,flags,mval,onmap,nmap) #endif /* DEBUG */ STATIC int xfs_bmap_count_tree( xfs_mount_t *mp, xfs_trans_t *tp, xfs_ifork_t *ifp, xfs_fsblock_t blockno, int levelin, int *count); STATIC void xfs_bmap_count_leaves( xfs_ifork_t *ifp, xfs_extnum_t idx, int numrecs, int *count); STATIC void xfs_bmap_disk_count_leaves( struct xfs_mount *mp, struct xfs_btree_block *block, int numrecs, int *count); /* * Bmap internal routines. */ STATIC int /* error */ xfs_bmbt_lookup_eq( struct xfs_btree_cur *cur, xfs_fileoff_t off, xfs_fsblock_t bno, xfs_filblks_t len, int *stat) /* success/failure */ { cur->bc_rec.b.br_startoff = off; cur->bc_rec.b.br_startblock = bno; cur->bc_rec.b.br_blockcount = len; return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat); } STATIC int /* error */ xfs_bmbt_lookup_ge( struct xfs_btree_cur *cur, xfs_fileoff_t off, xfs_fsblock_t bno, xfs_filblks_t len, int *stat) /* success/failure */ { cur->bc_rec.b.br_startoff = off; cur->bc_rec.b.br_startblock = bno; cur->bc_rec.b.br_blockcount = len; return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat); } /* * Check if the inode needs to be converted to btree format. */ static inline bool xfs_bmap_needs_btree(struct xfs_inode *ip, int whichfork) { return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS && XFS_IFORK_NEXTENTS(ip, whichfork) > XFS_IFORK_MAXEXT(ip, whichfork); } /* * Check if the inode should be converted to extent format. */ static inline bool xfs_bmap_wants_extents(struct xfs_inode *ip, int whichfork) { return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE && XFS_IFORK_NEXTENTS(ip, whichfork) <= XFS_IFORK_MAXEXT(ip, whichfork); } /* * Update the record referred to by cur to the value given * by [off, bno, len, state]. * This either works (return 0) or gets an EFSCORRUPTED error. */ STATIC int xfs_bmbt_update( struct xfs_btree_cur *cur, xfs_fileoff_t off, xfs_fsblock_t bno, xfs_filblks_t len, xfs_exntst_t state) { union xfs_btree_rec rec; xfs_bmbt_disk_set_allf(&rec.bmbt, off, bno, len, state); return xfs_btree_update(cur, &rec); } /* * Called from xfs_bmap_add_attrfork to handle btree format files. */ STATIC int /* error */ xfs_bmap_add_attrfork_btree( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated */ xfs_bmap_free_t *flist, /* blocks to free at commit */ int *flags) /* inode logging flags */ { xfs_btree_cur_t *cur; /* btree cursor */ int error; /* error return value */ xfs_mount_t *mp; /* file system mount struct */ int stat; /* newroot status */ mp = ip->i_mount; if (ip->i_df.if_broot_bytes <= XFS_IFORK_DSIZE(ip)) *flags |= XFS_ILOG_DBROOT; else { cur = xfs_bmbt_init_cursor(mp, tp, ip, XFS_DATA_FORK); cur->bc_private.b.flist = flist; cur->bc_private.b.firstblock = *firstblock; if ((error = xfs_bmbt_lookup_ge(cur, 0, 0, 0, &stat))) goto error0; /* must be at least one entry */ XFS_WANT_CORRUPTED_GOTO(stat == 1, error0); if ((error = xfs_btree_new_iroot(cur, flags, &stat))) goto error0; if (stat == 0) { xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR); return XFS_ERROR(ENOSPC); } *firstblock = cur->bc_private.b.firstblock; cur->bc_private.b.allocated = 0; xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR); } return 0; error0: xfs_btree_del_cursor(cur, XFS_BTREE_ERROR); return error; } /* * Called from xfs_bmap_add_attrfork to handle extents format files. */ STATIC int /* error */ xfs_bmap_add_attrfork_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated */ xfs_bmap_free_t *flist, /* blocks to free at commit */ int *flags) /* inode logging flags */ { xfs_btree_cur_t *cur; /* bmap btree cursor */ int error; /* error return value */ if (ip->i_d.di_nextents * sizeof(xfs_bmbt_rec_t) <= XFS_IFORK_DSIZE(ip)) return 0; cur = NULL; error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist, &cur, 0, flags, XFS_DATA_FORK); if (cur) { cur->bc_private.b.allocated = 0; xfs_btree_del_cursor(cur, error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR); } return error; } /* * Called from xfs_bmap_add_attrfork to handle local format files. */ STATIC int /* error */ xfs_bmap_add_attrfork_local( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated */ xfs_bmap_free_t *flist, /* blocks to free at commit */ int *flags) /* inode logging flags */ { xfs_da_args_t dargs; /* args for dir/attr code */ int error; /* error return value */ xfs_mount_t *mp; /* mount structure pointer */ if (ip->i_df.if_bytes <= XFS_IFORK_DSIZE(ip)) return 0; if (S_ISDIR(ip->i_d.di_mode)) { mp = ip->i_mount; memset(&dargs, 0, sizeof(dargs)); dargs.dp = ip; dargs.firstblock = firstblock; dargs.flist = flist; dargs.total = mp->m_dirblkfsbs; dargs.whichfork = XFS_DATA_FORK; dargs.trans = tp; error = xfs_dir2_sf_to_block(&dargs); } else error = xfs_bmap_local_to_extents(tp, ip, firstblock, 1, flags, XFS_DATA_FORK); return error; } /* * Convert a delayed allocation to a real allocation. */ STATIC int /* error */ xfs_bmap_add_extent_delay_real( struct xfs_bmalloca *bma) { struct xfs_bmbt_irec *new = &bma->got; int diff; /* temp value */ xfs_bmbt_rec_host_t *ep; /* extent entry for idx */ int error; /* error return value */ int i; /* temp state */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_fileoff_t new_endoff; /* end offset of new entry */ xfs_bmbt_irec_t r[3]; /* neighbor extent entries */ /* left is 0, right is 1, prev is 2 */ int rval=0; /* return value (logging flags) */ int state = 0;/* state bits, accessed thru macros */ xfs_filblks_t da_new; /* new count del alloc blocks used */ xfs_filblks_t da_old; /* old count del alloc blocks used */ xfs_filblks_t temp=0; /* value for da_new calculations */ xfs_filblks_t temp2=0;/* value for da_new calculations */ int tmp_rval; /* partial logging flags */ ifp = XFS_IFORK_PTR(bma->ip, XFS_DATA_FORK); ASSERT(bma->idx >= 0); ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec)); ASSERT(!isnullstartblock(new->br_startblock)); ASSERT(!bma->cur || (bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL)); XFS_STATS_INC(xs_add_exlist); #define LEFT r[0] #define RIGHT r[1] #define PREV r[2] /* * Set up a bunch of variables to make the tests simpler. */ ep = xfs_iext_get_ext(ifp, bma->idx); xfs_bmbt_get_all(ep, &PREV); new_endoff = new->br_startoff + new->br_blockcount; ASSERT(PREV.br_startoff <= new->br_startoff); ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff); da_old = startblockval(PREV.br_startblock); da_new = 0; /* * Set flags determining what part of the previous delayed allocation * extent is being replaced by a real allocation. */ if (PREV.br_startoff == new->br_startoff) state |= BMAP_LEFT_FILLING; if (PREV.br_startoff + PREV.br_blockcount == new_endoff) state |= BMAP_RIGHT_FILLING; /* * Check and set flags if this segment has a left neighbor. * Don't set contiguous if the combined extent would be too large. */ if (bma->idx > 0) { state |= BMAP_LEFT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &LEFT); if (isnullstartblock(LEFT.br_startblock)) state |= BMAP_LEFT_DELAY; } if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) && LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff && LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock && LEFT.br_state == new->br_state && LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN) state |= BMAP_LEFT_CONTIG; /* * Check and set flags if this segment has a right neighbor. * Don't set contiguous if the combined extent would be too large. * Also check for all-three-contiguous being too large. */ if (bma->idx < bma->ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) { state |= BMAP_RIGHT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx + 1), &RIGHT); if (isnullstartblock(RIGHT.br_startblock)) state |= BMAP_RIGHT_DELAY; } if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) && new_endoff == RIGHT.br_startoff && new->br_startblock + new->br_blockcount == RIGHT.br_startblock && new->br_state == RIGHT.br_state && new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN && ((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING)) != (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING) || LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN)) state |= BMAP_RIGHT_CONTIG; error = 0; /* * Switch out based on the FILLING and CONTIG state bits. */ switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) { case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG: /* * Filling in all of a previously delayed allocation extent. * The left and right neighbors are both contiguous with new. */ bma->idx--; trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx), LEFT.br_blockcount + PREV.br_blockcount + RIGHT.br_blockcount); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_iext_remove(bma->ip, bma->idx + 1, 2, state); bma->ip->i_d.di_nextents--; if (bma->cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff, RIGHT.br_startblock, RIGHT.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_btree_delete(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_btree_decrement(bma->cur, 0, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount + PREV.br_blockcount + RIGHT.br_blockcount, LEFT.br_state); if (error) goto done; } break; case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG: /* * Filling in all of a previously delayed allocation extent. * The left neighbor is contiguous, the right is not. */ bma->idx--; trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx), LEFT.br_blockcount + PREV.br_blockcount); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_iext_remove(bma->ip, bma->idx + 1, 1, state); if (bma->cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount + PREV.br_blockcount, LEFT.br_state); if (error) goto done; } break; case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG: /* * Filling in all of a previously delayed allocation extent. * The right neighbor is contiguous, the left is not. */ trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_startblock(ep, new->br_startblock); xfs_bmbt_set_blockcount(ep, PREV.br_blockcount + RIGHT.br_blockcount); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_iext_remove(bma->ip, bma->idx + 1, 1, state); if (bma->cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff, RIGHT.br_startblock, RIGHT.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, PREV.br_startoff, new->br_startblock, PREV.br_blockcount + RIGHT.br_blockcount, PREV.br_state); if (error) goto done; } break; case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING: /* * Filling in all of a previously delayed allocation extent. * Neither the left nor right neighbors are contiguous with * the new one. */ trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_startblock(ep, new->br_startblock); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); bma->ip->i_d.di_nextents++; if (bma->cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); bma->cur->bc_rec.b.br_state = XFS_EXT_NORM; error = xfs_btree_insert(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } break; case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG: /* * Filling in the first part of a previous delayed allocation. * The left neighbor is contiguous. */ trace_xfs_bmap_pre_update(bma->ip, bma->idx - 1, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx - 1), LEFT.br_blockcount + new->br_blockcount); xfs_bmbt_set_startoff(ep, PREV.br_startoff + new->br_blockcount); trace_xfs_bmap_post_update(bma->ip, bma->idx - 1, state, _THIS_IP_); temp = PREV.br_blockcount - new->br_blockcount; trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, temp); if (bma->cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount + new->br_blockcount, LEFT.br_state); if (error) goto done; } da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp), startblockval(PREV.br_startblock)); xfs_bmbt_set_startblock(ep, nullstartblock(da_new)); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); bma->idx--; break; case BMAP_LEFT_FILLING: /* * Filling in the first part of a previous delayed allocation. * The left neighbor is not contiguous. */ trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_startoff(ep, new_endoff); temp = PREV.br_blockcount - new->br_blockcount; xfs_bmbt_set_blockcount(ep, temp); xfs_iext_insert(bma->ip, bma->idx, 1, new, state); bma->ip->i_d.di_nextents++; if (bma->cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); bma->cur->bc_rec.b.br_state = XFS_EXT_NORM; error = xfs_btree_insert(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) { error = xfs_bmap_extents_to_btree(bma->tp, bma->ip, bma->firstblock, bma->flist, &bma->cur, 1, &tmp_rval, XFS_DATA_FORK); rval |= tmp_rval; if (error) goto done; } da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp), startblockval(PREV.br_startblock) - (bma->cur ? bma->cur->bc_private.b.allocated : 0)); ep = xfs_iext_get_ext(ifp, bma->idx + 1); xfs_bmbt_set_startblock(ep, nullstartblock(da_new)); trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_); break; case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG: /* * Filling in the last part of a previous delayed allocation. * The right neighbor is contiguous with the new allocation. */ temp = PREV.br_blockcount - new->br_blockcount; trace_xfs_bmap_pre_update(bma->ip, bma->idx + 1, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, temp); xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx + 1), new->br_startoff, new->br_startblock, new->br_blockcount + RIGHT.br_blockcount, RIGHT.br_state); trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_); if (bma->cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff, RIGHT.br_startblock, RIGHT.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount + RIGHT.br_blockcount, RIGHT.br_state); if (error) goto done; } da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp), startblockval(PREV.br_startblock)); trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_startblock(ep, nullstartblock(da_new)); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); bma->idx++; break; case BMAP_RIGHT_FILLING: /* * Filling in the last part of a previous delayed allocation. * The right neighbor is not contiguous. */ temp = PREV.br_blockcount - new->br_blockcount; trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, temp); xfs_iext_insert(bma->ip, bma->idx + 1, 1, new, state); bma->ip->i_d.di_nextents++; if (bma->cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); bma->cur->bc_rec.b.br_state = XFS_EXT_NORM; error = xfs_btree_insert(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) { error = xfs_bmap_extents_to_btree(bma->tp, bma->ip, bma->firstblock, bma->flist, &bma->cur, 1, &tmp_rval, XFS_DATA_FORK); rval |= tmp_rval; if (error) goto done; } da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp), startblockval(PREV.br_startblock) - (bma->cur ? bma->cur->bc_private.b.allocated : 0)); ep = xfs_iext_get_ext(ifp, bma->idx); xfs_bmbt_set_startblock(ep, nullstartblock(da_new)); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); bma->idx++; break; case 0: /* * Filling in the middle part of a previous delayed allocation. * Contiguity is impossible here. * This case is avoided almost all the time. * * We start with a delayed allocation: * * +ddddddddddddddddddddddddddddddddddddddddddddddddddddddd+ * PREV @ idx * * and we are allocating: * +rrrrrrrrrrrrrrrrr+ * new * * and we set it up for insertion as: * +ddddddddddddddddddd+rrrrrrrrrrrrrrrrr+ddddddddddddddddd+ * new * PREV @ idx LEFT RIGHT * inserted at idx + 1 */ temp = new->br_startoff - PREV.br_startoff; temp2 = PREV.br_startoff + PREV.br_blockcount - new_endoff; trace_xfs_bmap_pre_update(bma->ip, bma->idx, 0, _THIS_IP_); xfs_bmbt_set_blockcount(ep, temp); /* truncate PREV */ LEFT = *new; RIGHT.br_state = PREV.br_state; RIGHT.br_startblock = nullstartblock( (int)xfs_bmap_worst_indlen(bma->ip, temp2)); RIGHT.br_startoff = new_endoff; RIGHT.br_blockcount = temp2; /* insert LEFT (r[0]) and RIGHT (r[1]) at the same time */ xfs_iext_insert(bma->ip, bma->idx + 1, 2, &LEFT, state); bma->ip->i_d.di_nextents++; if (bma->cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); bma->cur->bc_rec.b.br_state = XFS_EXT_NORM; error = xfs_btree_insert(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) { error = xfs_bmap_extents_to_btree(bma->tp, bma->ip, bma->firstblock, bma->flist, &bma->cur, 1, &tmp_rval, XFS_DATA_FORK); rval |= tmp_rval; if (error) goto done; } temp = xfs_bmap_worst_indlen(bma->ip, temp); temp2 = xfs_bmap_worst_indlen(bma->ip, temp2); diff = (int)(temp + temp2 - startblockval(PREV.br_startblock) - (bma->cur ? bma->cur->bc_private.b.allocated : 0)); if (diff > 0) { error = xfs_icsb_modify_counters(bma->ip->i_mount, XFS_SBS_FDBLOCKS, -((int64_t)diff), 0); ASSERT(!error); if (error) goto done; } ep = xfs_iext_get_ext(ifp, bma->idx); xfs_bmbt_set_startblock(ep, nullstartblock((int)temp)); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); trace_xfs_bmap_pre_update(bma->ip, bma->idx + 2, state, _THIS_IP_); xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, bma->idx + 2), nullstartblock((int)temp2)); trace_xfs_bmap_post_update(bma->ip, bma->idx + 2, state, _THIS_IP_); bma->idx++; da_new = temp + temp2; break; case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG: case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG: case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: case BMAP_LEFT_CONTIG: case BMAP_RIGHT_CONTIG: /* * These cases are all impossible. */ ASSERT(0); } /* convert to a btree if necessary */ if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) { int tmp_logflags; /* partial log flag return val */ ASSERT(bma->cur == NULL); error = xfs_bmap_extents_to_btree(bma->tp, bma->ip, bma->firstblock, bma->flist, &bma->cur, da_old > 0, &tmp_logflags, XFS_DATA_FORK); bma->logflags |= tmp_logflags; if (error) goto done; } /* adjust for changes in reserved delayed indirect blocks */ if (da_old || da_new) { temp = da_new; if (bma->cur) temp += bma->cur->bc_private.b.allocated; ASSERT(temp <= da_old); if (temp < da_old) xfs_icsb_modify_counters(bma->ip->i_mount, XFS_SBS_FDBLOCKS, (int64_t)(da_old - temp), 0); } /* clear out the allocated field, done with it now in any case. */ if (bma->cur) bma->cur->bc_private.b.allocated = 0; xfs_bmap_check_leaf_extents(bma->cur, bma->ip, XFS_DATA_FORK); done: bma->logflags |= rval; return error; #undef LEFT #undef RIGHT #undef PREV } /* * Convert an unwritten allocation to a real allocation or vice versa. */ STATIC int /* error */ xfs_bmap_add_extent_unwritten_real( struct xfs_trans *tp, xfs_inode_t *ip, /* incore inode pointer */ xfs_extnum_t *idx, /* extent number to update/insert */ xfs_btree_cur_t **curp, /* if *curp is null, not a btree */ xfs_bmbt_irec_t *new, /* new data to add to file extents */ xfs_fsblock_t *first, /* pointer to firstblock variable */ xfs_bmap_free_t *flist, /* list of extents to be freed */ int *logflagsp) /* inode logging flags */ { xfs_btree_cur_t *cur; /* btree cursor */ xfs_bmbt_rec_host_t *ep; /* extent entry for idx */ int error; /* error return value */ int i; /* temp state */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_fileoff_t new_endoff; /* end offset of new entry */ xfs_exntst_t newext; /* new extent state */ xfs_exntst_t oldext; /* old extent state */ xfs_bmbt_irec_t r[3]; /* neighbor extent entries */ /* left is 0, right is 1, prev is 2 */ int rval=0; /* return value (logging flags) */ int state = 0;/* state bits, accessed thru macros */ *logflagsp = 0; cur = *curp; ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK); ASSERT(*idx >= 0); ASSERT(*idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec)); ASSERT(!isnullstartblock(new->br_startblock)); XFS_STATS_INC(xs_add_exlist); #define LEFT r[0] #define RIGHT r[1] #define PREV r[2] /* * Set up a bunch of variables to make the tests simpler. */ error = 0; ep = xfs_iext_get_ext(ifp, *idx); xfs_bmbt_get_all(ep, &PREV); newext = new->br_state; oldext = (newext == XFS_EXT_UNWRITTEN) ? XFS_EXT_NORM : XFS_EXT_UNWRITTEN; ASSERT(PREV.br_state == oldext); new_endoff = new->br_startoff + new->br_blockcount; ASSERT(PREV.br_startoff <= new->br_startoff); ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff); /* * Set flags determining what part of the previous oldext allocation * extent is being replaced by a newext allocation. */ if (PREV.br_startoff == new->br_startoff) state |= BMAP_LEFT_FILLING; if (PREV.br_startoff + PREV.br_blockcount == new_endoff) state |= BMAP_RIGHT_FILLING; /* * Check and set flags if this segment has a left neighbor. * Don't set contiguous if the combined extent would be too large. */ if (*idx > 0) { state |= BMAP_LEFT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &LEFT); if (isnullstartblock(LEFT.br_startblock)) state |= BMAP_LEFT_DELAY; } if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) && LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff && LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock && LEFT.br_state == newext && LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN) state |= BMAP_LEFT_CONTIG; /* * Check and set flags if this segment has a right neighbor. * Don't set contiguous if the combined extent would be too large. * Also check for all-three-contiguous being too large. */ if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) { state |= BMAP_RIGHT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx + 1), &RIGHT); if (isnullstartblock(RIGHT.br_startblock)) state |= BMAP_RIGHT_DELAY; } if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) && new_endoff == RIGHT.br_startoff && new->br_startblock + new->br_blockcount == RIGHT.br_startblock && newext == RIGHT.br_state && new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN && ((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING)) != (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING) || LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN)) state |= BMAP_RIGHT_CONTIG; /* * Switch out based on the FILLING and CONTIG state bits. */ switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) { case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG: /* * Setting all of a previous oldext extent to newext. * The left and right neighbors are both contiguous with new. */ --*idx; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), LEFT.br_blockcount + PREV.br_blockcount + RIGHT.br_blockcount); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); xfs_iext_remove(ip, *idx + 1, 2, state); ip->i_d.di_nextents -= 2; if (cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff, RIGHT.br_startblock, RIGHT.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_delete(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_decrement(cur, 0, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_delete(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_decrement(cur, 0, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount + PREV.br_blockcount + RIGHT.br_blockcount, LEFT.br_state))) goto done; } break; case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG: /* * Setting all of a previous oldext extent to newext. * The left neighbor is contiguous, the right is not. */ --*idx; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), LEFT.br_blockcount + PREV.br_blockcount); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); xfs_iext_remove(ip, *idx + 1, 1, state); ip->i_d.di_nextents--; if (cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_delete(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_decrement(cur, 0, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount + PREV.br_blockcount, LEFT.br_state))) goto done; } break; case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG: /* * Setting all of a previous oldext extent to newext. * The right neighbor is contiguous, the left is not. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, PREV.br_blockcount + RIGHT.br_blockcount); xfs_bmbt_set_state(ep, newext); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); xfs_iext_remove(ip, *idx + 1, 1, state); ip->i_d.di_nextents--; if (cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff, RIGHT.br_startblock, RIGHT.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_delete(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_btree_decrement(cur, 0, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, new->br_startoff, new->br_startblock, new->br_blockcount + RIGHT.br_blockcount, newext))) goto done; } break; case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING: /* * Setting all of a previous oldext extent to newext. * Neither the left nor right neighbors are contiguous with * the new one. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_state(ep, newext); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); if (cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, new->br_startoff, new->br_startblock, new->br_blockcount, newext))) goto done; } break; case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG: /* * Setting the first part of a previous oldext extent to newext. * The left neighbor is contiguous. */ trace_xfs_bmap_pre_update(ip, *idx - 1, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx - 1), LEFT.br_blockcount + new->br_blockcount); xfs_bmbt_set_startoff(ep, PREV.br_startoff + new->br_blockcount); trace_xfs_bmap_post_update(ip, *idx - 1, state, _THIS_IP_); trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_startblock(ep, new->br_startblock + new->br_blockcount); xfs_bmbt_set_blockcount(ep, PREV.br_blockcount - new->br_blockcount); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); --*idx; if (cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, PREV.br_startoff + new->br_blockcount, PREV.br_startblock + new->br_blockcount, PREV.br_blockcount - new->br_blockcount, oldext))) goto done; if ((error = xfs_btree_decrement(cur, 0, &i))) goto done; error = xfs_bmbt_update(cur, LEFT.br_startoff, LEFT.br_startblock, LEFT.br_blockcount + new->br_blockcount, LEFT.br_state); if (error) goto done; } break; case BMAP_LEFT_FILLING: /* * Setting the first part of a previous oldext extent to newext. * The left neighbor is not contiguous. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); ASSERT(ep && xfs_bmbt_get_state(ep) == oldext); xfs_bmbt_set_startoff(ep, new_endoff); xfs_bmbt_set_blockcount(ep, PREV.br_blockcount - new->br_blockcount); xfs_bmbt_set_startblock(ep, new->br_startblock + new->br_blockcount); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); xfs_iext_insert(ip, *idx, 1, new, state); ip->i_d.di_nextents++; if (cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, PREV.br_startoff + new->br_blockcount, PREV.br_startblock + new->br_blockcount, PREV.br_blockcount - new->br_blockcount, oldext))) goto done; cur->bc_rec.b = *new; if ((error = xfs_btree_insert(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } break; case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG: /* * Setting the last part of a previous oldext extent to newext. * The right neighbor is contiguous with the new allocation. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, PREV.br_blockcount - new->br_blockcount); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); ++*idx; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx), new->br_startoff, new->br_startblock, new->br_blockcount + RIGHT.br_blockcount, newext); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); if (cur == NULL) rval = XFS_ILOG_DEXT; else { rval = 0; if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount - new->br_blockcount, oldext))) goto done; if ((error = xfs_btree_increment(cur, 0, &i))) goto done; if ((error = xfs_bmbt_update(cur, new->br_startoff, new->br_startblock, new->br_blockcount + RIGHT.br_blockcount, newext))) goto done; } break; case BMAP_RIGHT_FILLING: /* * Setting the last part of a previous oldext extent to newext. * The right neighbor is not contiguous. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, PREV.br_blockcount - new->br_blockcount); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); ++*idx; xfs_iext_insert(ip, *idx, 1, new, state); ip->i_d.di_nextents++; if (cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); if ((error = xfs_bmbt_update(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount - new->br_blockcount, oldext))) goto done; if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); cur->bc_rec.b.br_state = XFS_EXT_NORM; if ((error = xfs_btree_insert(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } break; case 0: /* * Setting the middle part of a previous oldext extent to * newext. Contiguity is impossible here. * One extent becomes three extents. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, new->br_startoff - PREV.br_startoff); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); r[0] = *new; r[1].br_startoff = new_endoff; r[1].br_blockcount = PREV.br_startoff + PREV.br_blockcount - new_endoff; r[1].br_startblock = new->br_startblock + new->br_blockcount; r[1].br_state = oldext; ++*idx; xfs_iext_insert(ip, *idx, 2, &r[0], state); ip->i_d.di_nextents += 2; if (cur == NULL) rval = XFS_ILOG_CORE | XFS_ILOG_DEXT; else { rval = XFS_ILOG_CORE; if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff, PREV.br_startblock, PREV.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); /* new right extent - oldext */ if ((error = xfs_bmbt_update(cur, r[1].br_startoff, r[1].br_startblock, r[1].br_blockcount, r[1].br_state))) goto done; /* new left extent - oldext */ cur->bc_rec.b = PREV; cur->bc_rec.b.br_blockcount = new->br_startoff - PREV.br_startoff; if ((error = xfs_btree_insert(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); /* * Reset the cursor to the position of the new extent * we are about to insert as we can't trust it after * the previous insert. */ if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); /* new middle extent - newext */ cur->bc_rec.b.br_state = new->br_state; if ((error = xfs_btree_insert(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } break; case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG: case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG: case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: case BMAP_LEFT_CONTIG: case BMAP_RIGHT_CONTIG: /* * These cases are all impossible. */ ASSERT(0); } /* convert to a btree if necessary */ if (xfs_bmap_needs_btree(ip, XFS_DATA_FORK)) { int tmp_logflags; /* partial log flag return val */ ASSERT(cur == NULL); error = xfs_bmap_extents_to_btree(tp, ip, first, flist, &cur, 0, &tmp_logflags, XFS_DATA_FORK); *logflagsp |= tmp_logflags; if (error) goto done; } /* clear out the allocated field, done with it now in any case. */ if (cur) { cur->bc_private.b.allocated = 0; *curp = cur; } xfs_bmap_check_leaf_extents(*curp, ip, XFS_DATA_FORK); done: *logflagsp |= rval; return error; #undef LEFT #undef RIGHT #undef PREV } /* * Convert a hole to a delayed allocation. */ STATIC void xfs_bmap_add_extent_hole_delay( xfs_inode_t *ip, /* incore inode pointer */ xfs_extnum_t *idx, /* extent number to update/insert */ xfs_bmbt_irec_t *new) /* new data to add to file extents */ { xfs_ifork_t *ifp; /* inode fork pointer */ xfs_bmbt_irec_t left; /* left neighbor extent entry */ xfs_filblks_t newlen=0; /* new indirect size */ xfs_filblks_t oldlen=0; /* old indirect size */ xfs_bmbt_irec_t right; /* right neighbor extent entry */ int state; /* state bits, accessed thru macros */ xfs_filblks_t temp=0; /* temp for indirect calculations */ ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK); state = 0; ASSERT(isnullstartblock(new->br_startblock)); /* * Check and set flags if this segment has a left neighbor */ if (*idx > 0) { state |= BMAP_LEFT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &left); if (isnullstartblock(left.br_startblock)) state |= BMAP_LEFT_DELAY; } /* * Check and set flags if the current (right) segment exists. * If it doesn't exist, we're converting the hole at end-of-file. */ if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) { state |= BMAP_RIGHT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx), &right); if (isnullstartblock(right.br_startblock)) state |= BMAP_RIGHT_DELAY; } /* * Set contiguity flags on the left and right neighbors. * Don't let extents get too large, even if the pieces are contiguous. */ if ((state & BMAP_LEFT_VALID) && (state & BMAP_LEFT_DELAY) && left.br_startoff + left.br_blockcount == new->br_startoff && left.br_blockcount + new->br_blockcount <= MAXEXTLEN) state |= BMAP_LEFT_CONTIG; if ((state & BMAP_RIGHT_VALID) && (state & BMAP_RIGHT_DELAY) && new->br_startoff + new->br_blockcount == right.br_startoff && new->br_blockcount + right.br_blockcount <= MAXEXTLEN && (!(state & BMAP_LEFT_CONTIG) || (left.br_blockcount + new->br_blockcount + right.br_blockcount <= MAXEXTLEN))) state |= BMAP_RIGHT_CONTIG; /* * Switch out based on the contiguity flags. */ switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) { case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: /* * New allocation is contiguous with delayed allocations * on the left and on the right. * Merge all three into a single extent record. */ --*idx; temp = left.br_blockcount + new->br_blockcount + right.br_blockcount; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp); oldlen = startblockval(left.br_startblock) + startblockval(new->br_startblock) + startblockval(right.br_startblock); newlen = xfs_bmap_worst_indlen(ip, temp); xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx), nullstartblock((int)newlen)); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); xfs_iext_remove(ip, *idx + 1, 1, state); break; case BMAP_LEFT_CONTIG: /* * New allocation is contiguous with a delayed allocation * on the left. * Merge the new allocation with the left neighbor. */ --*idx; temp = left.br_blockcount + new->br_blockcount; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp); oldlen = startblockval(left.br_startblock) + startblockval(new->br_startblock); newlen = xfs_bmap_worst_indlen(ip, temp); xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx), nullstartblock((int)newlen)); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); break; case BMAP_RIGHT_CONTIG: /* * New allocation is contiguous with a delayed allocation * on the right. * Merge the new allocation with the right neighbor. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); temp = new->br_blockcount + right.br_blockcount; oldlen = startblockval(new->br_startblock) + startblockval(right.br_startblock); newlen = xfs_bmap_worst_indlen(ip, temp); xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx), new->br_startoff, nullstartblock((int)newlen), temp, right.br_state); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); break; case 0: /* * New allocation is not contiguous with another * delayed allocation. * Insert a new entry. */ oldlen = newlen = 0; xfs_iext_insert(ip, *idx, 1, new, state); break; } if (oldlen != newlen) { ASSERT(oldlen > newlen); xfs_icsb_modify_counters(ip->i_mount, XFS_SBS_FDBLOCKS, (int64_t)(oldlen - newlen), 0); /* * Nothing to do for disk quota accounting here. */ } } /* * Convert a hole to a real allocation. */ STATIC int /* error */ xfs_bmap_add_extent_hole_real( struct xfs_bmalloca *bma, int whichfork) { struct xfs_bmbt_irec *new = &bma->got; int error; /* error return value */ int i; /* temp state */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_bmbt_irec_t left; /* left neighbor extent entry */ xfs_bmbt_irec_t right; /* right neighbor extent entry */ int rval=0; /* return value (logging flags) */ int state; /* state bits, accessed thru macros */ ifp = XFS_IFORK_PTR(bma->ip, whichfork); ASSERT(bma->idx >= 0); ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec)); ASSERT(!isnullstartblock(new->br_startblock)); ASSERT(!bma->cur || !(bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL)); XFS_STATS_INC(xs_add_exlist); state = 0; if (whichfork == XFS_ATTR_FORK) state |= BMAP_ATTRFORK; /* * Check and set flags if this segment has a left neighbor. */ if (bma->idx > 0) { state |= BMAP_LEFT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &left); if (isnullstartblock(left.br_startblock)) state |= BMAP_LEFT_DELAY; } /* * Check and set flags if this segment has a current value. * Not true if we're inserting into the "hole" at eof. */ if (bma->idx < ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) { state |= BMAP_RIGHT_VALID; xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &right); if (isnullstartblock(right.br_startblock)) state |= BMAP_RIGHT_DELAY; } /* * We're inserting a real allocation between "left" and "right". * Set the contiguity flags. Don't let extents get too large. */ if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) && left.br_startoff + left.br_blockcount == new->br_startoff && left.br_startblock + left.br_blockcount == new->br_startblock && left.br_state == new->br_state && left.br_blockcount + new->br_blockcount <= MAXEXTLEN) state |= BMAP_LEFT_CONTIG; if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) && new->br_startoff + new->br_blockcount == right.br_startoff && new->br_startblock + new->br_blockcount == right.br_startblock && new->br_state == right.br_state && new->br_blockcount + right.br_blockcount <= MAXEXTLEN && (!(state & BMAP_LEFT_CONTIG) || left.br_blockcount + new->br_blockcount + right.br_blockcount <= MAXEXTLEN)) state |= BMAP_RIGHT_CONTIG; error = 0; /* * Select which case we're in here, and implement it. */ switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) { case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG: /* * New allocation is contiguous with real allocations on the * left and on the right. * Merge all three into a single extent record. */ --bma->idx; trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx), left.br_blockcount + new->br_blockcount + right.br_blockcount); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_iext_remove(bma->ip, bma->idx + 1, 1, state); XFS_IFORK_NEXT_SET(bma->ip, whichfork, XFS_IFORK_NEXTENTS(bma->ip, whichfork) - 1); if (bma->cur == NULL) { rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork); } else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, right.br_startoff, right.br_startblock, right.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_btree_delete(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_btree_decrement(bma->cur, 0, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, left.br_startoff, left.br_startblock, left.br_blockcount + new->br_blockcount + right.br_blockcount, left.br_state); if (error) goto done; } break; case BMAP_LEFT_CONTIG: /* * New allocation is contiguous with a real allocation * on the left. * Merge the new allocation with the left neighbor. */ --bma->idx; trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx), left.br_blockcount + new->br_blockcount); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); if (bma->cur == NULL) { rval = xfs_ilog_fext(whichfork); } else { rval = 0; error = xfs_bmbt_lookup_eq(bma->cur, left.br_startoff, left.br_startblock, left.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, left.br_startoff, left.br_startblock, left.br_blockcount + new->br_blockcount, left.br_state); if (error) goto done; } break; case BMAP_RIGHT_CONTIG: /* * New allocation is contiguous with a real allocation * on the right. * Merge the new allocation with the right neighbor. */ trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_); xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx), new->br_startoff, new->br_startblock, new->br_blockcount + right.br_blockcount, right.br_state); trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_); if (bma->cur == NULL) { rval = xfs_ilog_fext(whichfork); } else { rval = 0; error = xfs_bmbt_lookup_eq(bma->cur, right.br_startoff, right.br_startblock, right.br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); error = xfs_bmbt_update(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount + right.br_blockcount, right.br_state); if (error) goto done; } break; case 0: /* * New allocation is not contiguous with another * real allocation. * Insert a new entry. */ xfs_iext_insert(bma->ip, bma->idx, 1, new, state); XFS_IFORK_NEXT_SET(bma->ip, whichfork, XFS_IFORK_NEXTENTS(bma->ip, whichfork) + 1); if (bma->cur == NULL) { rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork); } else { rval = XFS_ILOG_CORE; error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff, new->br_startblock, new->br_blockcount, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 0, done); bma->cur->bc_rec.b.br_state = new->br_state; error = xfs_btree_insert(bma->cur, &i); if (error) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } break; } /* convert to a btree if necessary */ if (xfs_bmap_needs_btree(bma->ip, whichfork)) { int tmp_logflags; /* partial log flag return val */ ASSERT(bma->cur == NULL); error = xfs_bmap_extents_to_btree(bma->tp, bma->ip, bma->firstblock, bma->flist, &bma->cur, 0, &tmp_logflags, whichfork); bma->logflags |= tmp_logflags; if (error) goto done; } /* clear out the allocated field, done with it now in any case. */ if (bma->cur) bma->cur->bc_private.b.allocated = 0; xfs_bmap_check_leaf_extents(bma->cur, bma->ip, whichfork); done: bma->logflags |= rval; return error; } /* * Adjust the size of the new extent based on di_extsize and rt extsize. */ STATIC int xfs_bmap_extsize_align( xfs_mount_t *mp, xfs_bmbt_irec_t *gotp, /* next extent pointer */ xfs_bmbt_irec_t *prevp, /* previous extent pointer */ xfs_extlen_t extsz, /* align to this extent size */ int rt, /* is this a realtime inode? */ int eof, /* is extent at end-of-file? */ int delay, /* creating delalloc extent? */ int convert, /* overwriting unwritten extent? */ xfs_fileoff_t *offp, /* in/out: aligned offset */ xfs_extlen_t *lenp) /* in/out: aligned length */ { xfs_fileoff_t orig_off; /* original offset */ xfs_extlen_t orig_alen; /* original length */ xfs_fileoff_t orig_end; /* original off+len */ xfs_fileoff_t nexto; /* next file offset */ xfs_fileoff_t prevo; /* previous file offset */ xfs_fileoff_t align_off; /* temp for offset */ xfs_extlen_t align_alen; /* temp for length */ xfs_extlen_t temp; /* temp for calculations */ if (convert) return 0; orig_off = align_off = *offp; orig_alen = align_alen = *lenp; orig_end = orig_off + orig_alen; /* * If this request overlaps an existing extent, then don't * attempt to perform any additional alignment. */ if (!delay && !eof && (orig_off >= gotp->br_startoff) && (orig_end <= gotp->br_startoff + gotp->br_blockcount)) { return 0; } /* * If the file offset is unaligned vs. the extent size * we need to align it. This will be possible unless * the file was previously written with a kernel that didn't * perform this alignment, or if a truncate shot us in the * foot. */ temp = do_mod(orig_off, extsz); if (temp) { align_alen += temp; align_off -= temp; } /* * Same adjustment for the end of the requested area. */ if ((temp = (align_alen % extsz))) { align_alen += extsz - temp; } /* * If the previous block overlaps with this proposed allocation * then move the start forward without adjusting the length. */ if (prevp->br_startoff != NULLFILEOFF) { if (prevp->br_startblock == HOLESTARTBLOCK) prevo = prevp->br_startoff; else prevo = prevp->br_startoff + prevp->br_blockcount; } else prevo = 0; if (align_off != orig_off && align_off < prevo) align_off = prevo; /* * If the next block overlaps with this proposed allocation * then move the start back without adjusting the length, * but not before offset 0. * This may of course make the start overlap previous block, * and if we hit the offset 0 limit then the next block * can still overlap too. */ if (!eof && gotp->br_startoff != NULLFILEOFF) { if ((delay && gotp->br_startblock == HOLESTARTBLOCK) || (!delay && gotp->br_startblock == DELAYSTARTBLOCK)) nexto = gotp->br_startoff + gotp->br_blockcount; else nexto = gotp->br_startoff; } else nexto = NULLFILEOFF; if (!eof && align_off + align_alen != orig_end && align_off + align_alen > nexto) align_off = nexto > align_alen ? nexto - align_alen : 0; /* * If we're now overlapping the next or previous extent that * means we can't fit an extsz piece in this hole. Just move * the start forward to the first valid spot and set * the length so we hit the end. */ if (align_off != orig_off && align_off < prevo) align_off = prevo; if (align_off + align_alen != orig_end && align_off + align_alen > nexto && nexto != NULLFILEOFF) { ASSERT(nexto > prevo); align_alen = nexto - align_off; } /* * If realtime, and the result isn't a multiple of the realtime * extent size we need to remove blocks until it is. */ if (rt && (temp = (align_alen % mp->m_sb.sb_rextsize))) { /* * We're not covering the original request, or * we won't be able to once we fix the length. */ if (orig_off < align_off || orig_end > align_off + align_alen || align_alen - temp < orig_alen) return XFS_ERROR(EINVAL); /* * Try to fix it by moving the start up. */ if (align_off + temp <= orig_off) { align_alen -= temp; align_off += temp; } /* * Try to fix it by moving the end in. */ else if (align_off + align_alen - temp >= orig_end) align_alen -= temp; /* * Set the start to the minimum then trim the length. */ else { align_alen -= orig_off - align_off; align_off = orig_off; align_alen -= align_alen % mp->m_sb.sb_rextsize; } /* * Result doesn't cover the request, fail it. */ if (orig_off < align_off || orig_end > align_off + align_alen) return XFS_ERROR(EINVAL); } else { ASSERT(orig_off >= align_off); ASSERT(orig_end <= align_off + align_alen); } #ifdef DEBUG if (!eof && gotp->br_startoff != NULLFILEOFF) ASSERT(align_off + align_alen <= gotp->br_startoff); if (prevp->br_startoff != NULLFILEOFF) ASSERT(align_off >= prevp->br_startoff + prevp->br_blockcount); #endif *lenp = align_alen; *offp = align_off; return 0; } #define XFS_ALLOC_GAP_UNITS 4 STATIC void xfs_bmap_adjacent( xfs_bmalloca_t *ap) /* bmap alloc argument struct */ { xfs_fsblock_t adjust; /* adjustment to block numbers */ xfs_agnumber_t fb_agno; /* ag number of ap->firstblock */ xfs_mount_t *mp; /* mount point structure */ int nullfb; /* true if ap->firstblock isn't set */ int rt; /* true if inode is realtime */ #define ISVALID(x,y) \ (rt ? \ (x) < mp->m_sb.sb_rblocks : \ XFS_FSB_TO_AGNO(mp, x) == XFS_FSB_TO_AGNO(mp, y) && \ XFS_FSB_TO_AGNO(mp, x) < mp->m_sb.sb_agcount && \ XFS_FSB_TO_AGBNO(mp, x) < mp->m_sb.sb_agblocks) mp = ap->ip->i_mount; nullfb = *ap->firstblock == NULLFSBLOCK; rt = XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata; fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock); /* * If allocating at eof, and there's a previous real block, * try to use its last block as our starting point. */ if (ap->eof && ap->prev.br_startoff != NULLFILEOFF && !isnullstartblock(ap->prev.br_startblock) && ISVALID(ap->prev.br_startblock + ap->prev.br_blockcount, ap->prev.br_startblock)) { ap->blkno = ap->prev.br_startblock + ap->prev.br_blockcount; /* * Adjust for the gap between prevp and us. */ adjust = ap->offset - (ap->prev.br_startoff + ap->prev.br_blockcount); if (adjust && ISVALID(ap->blkno + adjust, ap->prev.br_startblock)) ap->blkno += adjust; } /* * If not at eof, then compare the two neighbor blocks. * Figure out whether either one gives us a good starting point, * and pick the better one. */ else if (!ap->eof) { xfs_fsblock_t gotbno; /* right side block number */ xfs_fsblock_t gotdiff=0; /* right side difference */ xfs_fsblock_t prevbno; /* left side block number */ xfs_fsblock_t prevdiff=0; /* left side difference */ /* * If there's a previous (left) block, select a requested * start block based on it. */ if (ap->prev.br_startoff != NULLFILEOFF && !isnullstartblock(ap->prev.br_startblock) && (prevbno = ap->prev.br_startblock + ap->prev.br_blockcount) && ISVALID(prevbno, ap->prev.br_startblock)) { /* * Calculate gap to end of previous block. */ adjust = prevdiff = ap->offset - (ap->prev.br_startoff + ap->prev.br_blockcount); /* * Figure the startblock based on the previous block's * end and the gap size. * Heuristic! * If the gap is large relative to the piece we're * allocating, or using it gives us an invalid block * number, then just use the end of the previous block. */ if (prevdiff <= XFS_ALLOC_GAP_UNITS * ap->length && ISVALID(prevbno + prevdiff, ap->prev.br_startblock)) prevbno += adjust; else prevdiff += adjust; /* * If the firstblock forbids it, can't use it, * must use default. */ if (!rt && !nullfb && XFS_FSB_TO_AGNO(mp, prevbno) != fb_agno) prevbno = NULLFSBLOCK; } /* * No previous block or can't follow it, just default. */ else prevbno = NULLFSBLOCK; /* * If there's a following (right) block, select a requested * start block based on it. */ if (!isnullstartblock(ap->got.br_startblock)) { /* * Calculate gap to start of next block. */ adjust = gotdiff = ap->got.br_startoff - ap->offset; /* * Figure the startblock based on the next block's * start and the gap size. */ gotbno = ap->got.br_startblock; /* * Heuristic! * If the gap is large relative to the piece we're * allocating, or using it gives us an invalid block * number, then just use the start of the next block * offset by our length. */ if (gotdiff <= XFS_ALLOC_GAP_UNITS * ap->length && ISVALID(gotbno - gotdiff, gotbno)) gotbno -= adjust; else if (ISVALID(gotbno - ap->length, gotbno)) { gotbno -= ap->length; gotdiff += adjust - ap->length; } else gotdiff += adjust; /* * If the firstblock forbids it, can't use it, * must use default. */ if (!rt && !nullfb && XFS_FSB_TO_AGNO(mp, gotbno) != fb_agno) gotbno = NULLFSBLOCK; } /* * No next block, just default. */ else gotbno = NULLFSBLOCK; /* * If both valid, pick the better one, else the only good * one, else ap->blkno is already set (to 0 or the inode block). */ if (prevbno != NULLFSBLOCK && gotbno != NULLFSBLOCK) ap->blkno = prevdiff <= gotdiff ? prevbno : gotbno; else if (prevbno != NULLFSBLOCK) ap->blkno = prevbno; else if (gotbno != NULLFSBLOCK) ap->blkno = gotbno; } #undef ISVALID } STATIC int xfs_bmap_rtalloc( xfs_bmalloca_t *ap) /* bmap alloc argument struct */ { xfs_alloctype_t atype = 0; /* type for allocation routines */ int error; /* error return value */ xfs_mount_t *mp; /* mount point structure */ xfs_extlen_t prod = 0; /* product factor for allocators */ xfs_extlen_t ralen = 0; /* realtime allocation length */ xfs_extlen_t align; /* minimum allocation alignment */ xfs_rtblock_t rtb; mp = ap->ip->i_mount; align = xfs_get_extsz_hint(ap->ip); prod = align / mp->m_sb.sb_rextsize; error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev, align, 1, ap->eof, 0, ap->conv, &ap->offset, &ap->length); if (error) return error; ASSERT(ap->length); ASSERT(ap->length % mp->m_sb.sb_rextsize == 0); /* * If the offset & length are not perfectly aligned * then kill prod, it will just get us in trouble. */ if (do_mod(ap->offset, align) || ap->length % align) prod = 1; /* * Set ralen to be the actual requested length in rtextents. */ ralen = ap->length / mp->m_sb.sb_rextsize; /* * If the old value was close enough to MAXEXTLEN that * we rounded up to it, cut it back so it's valid again. * Note that if it's a really large request (bigger than * MAXEXTLEN), we don't hear about that number, and can't * adjust the starting point to match it. */ if (ralen * mp->m_sb.sb_rextsize >= MAXEXTLEN) ralen = MAXEXTLEN / mp->m_sb.sb_rextsize; /* * Lock out other modifications to the RT bitmap inode. */ xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL); xfs_trans_ijoin(ap->tp, mp->m_rbmip, XFS_ILOCK_EXCL); /* * If it's an allocation to an empty file at offset 0, * pick an extent that will space things out in the rt area. */ if (ap->eof && ap->offset == 0) { xfs_rtblock_t uninitialized_var(rtx); /* realtime extent no */ error = xfs_rtpick_extent(mp, ap->tp, ralen, &rtx); if (error) return error; ap->blkno = rtx * mp->m_sb.sb_rextsize; } else { ap->blkno = 0; } xfs_bmap_adjacent(ap); /* * Realtime allocation, done through xfs_rtallocate_extent. */ atype = ap->blkno == 0 ? XFS_ALLOCTYPE_ANY_AG : XFS_ALLOCTYPE_NEAR_BNO; do_div(ap->blkno, mp->m_sb.sb_rextsize); rtb = ap->blkno; ap->length = ralen; if ((error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1, ap->length, &ralen, atype, ap->wasdel, prod, &rtb))) return error; if (rtb == NULLFSBLOCK && prod > 1 && (error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1, ap->length, &ralen, atype, ap->wasdel, 1, &rtb))) return error; ap->blkno = rtb; if (ap->blkno != NULLFSBLOCK) { ap->blkno *= mp->m_sb.sb_rextsize; ralen *= mp->m_sb.sb_rextsize; ap->length = ralen; ap->ip->i_d.di_nblocks += ralen; xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE); if (ap->wasdel) ap->ip->i_delayed_blks -= ralen; /* * Adjust the disk quota also. This was reserved * earlier. */ xfs_trans_mod_dquot_byino(ap->tp, ap->ip, ap->wasdel ? XFS_TRANS_DQ_DELRTBCOUNT : XFS_TRANS_DQ_RTBCOUNT, (long) ralen); } else { ap->length = 0; } return 0; } STATIC int xfs_bmap_btalloc_nullfb( struct xfs_bmalloca *ap, struct xfs_alloc_arg *args, xfs_extlen_t *blen) { struct xfs_mount *mp = ap->ip->i_mount; struct xfs_perag *pag; xfs_agnumber_t ag, startag; int notinit = 0; int error; if (ap->userdata && xfs_inode_is_filestream(ap->ip)) args->type = XFS_ALLOCTYPE_NEAR_BNO; else args->type = XFS_ALLOCTYPE_START_BNO; args->total = ap->total; /* * Search for an allocation group with a single extent large enough * for the request. If one isn't found, then adjust the minimum * allocation size to the largest space found. */ startag = ag = XFS_FSB_TO_AGNO(mp, args->fsbno); if (startag == NULLAGNUMBER) startag = ag = 0; pag = xfs_perag_get(mp, ag); while (*blen < args->maxlen) { if (!pag->pagf_init) { error = xfs_alloc_pagf_init(mp, args->tp, ag, XFS_ALLOC_FLAG_TRYLOCK); if (error) { xfs_perag_put(pag); return error; } } /* * See xfs_alloc_fix_freelist... */ if (pag->pagf_init) { xfs_extlen_t longest; longest = xfs_alloc_longest_free_extent(mp, pag); if (*blen < longest) *blen = longest; } else notinit = 1; if (xfs_inode_is_filestream(ap->ip)) { if (*blen >= args->maxlen) break; if (ap->userdata) { /* * If startag is an invalid AG, we've * come here once before and * xfs_filestream_new_ag picked the * best currently available. * * Don't continue looping, since we * could loop forever. */ if (startag == NULLAGNUMBER) break; error = xfs_filestream_new_ag(ap, &ag); xfs_perag_put(pag); if (error) return error; /* loop again to set 'blen'*/ startag = NULLAGNUMBER; pag = xfs_perag_get(mp, ag); continue; } } if (++ag == mp->m_sb.sb_agcount) ag = 0; if (ag == startag) break; xfs_perag_put(pag); pag = xfs_perag_get(mp, ag); } xfs_perag_put(pag); /* * Since the above loop did a BUF_TRYLOCK, it is * possible that there is space for this request. */ if (notinit || *blen < ap->minlen) args->minlen = ap->minlen; /* * If the best seen length is less than the request * length, use the best as the minimum. */ else if (*blen < args->maxlen) args->minlen = *blen; /* * Otherwise we've seen an extent as big as maxlen, * use that as the minimum. */ else args->minlen = args->maxlen; /* * set the failure fallback case to look in the selected * AG as the stream may have moved. */ if (xfs_inode_is_filestream(ap->ip)) ap->blkno = args->fsbno = XFS_AGB_TO_FSB(mp, ag, 0); return 0; } STATIC int xfs_bmap_btalloc( xfs_bmalloca_t *ap) /* bmap alloc argument struct */ { xfs_mount_t *mp; /* mount point structure */ xfs_alloctype_t atype = 0; /* type for allocation routines */ xfs_extlen_t align; /* minimum allocation alignment */ xfs_agnumber_t fb_agno; /* ag number of ap->firstblock */ xfs_agnumber_t ag; xfs_alloc_arg_t args; xfs_extlen_t blen; xfs_extlen_t nextminlen = 0; int nullfb; /* true if ap->firstblock isn't set */ int isaligned; int tryagain; int error; ASSERT(ap->length); mp = ap->ip->i_mount; align = ap->userdata ? xfs_get_extsz_hint(ap->ip) : 0; if (unlikely(align)) { error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev, align, 0, ap->eof, 0, ap->conv, &ap->offset, &ap->length); ASSERT(!error); ASSERT(ap->length); } nullfb = *ap->firstblock == NULLFSBLOCK; fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock); if (nullfb) { if (ap->userdata && xfs_inode_is_filestream(ap->ip)) { ag = xfs_filestream_lookup_ag(ap->ip); ag = (ag != NULLAGNUMBER) ? ag : 0; ap->blkno = XFS_AGB_TO_FSB(mp, ag, 0); } else { ap->blkno = XFS_INO_TO_FSB(mp, ap->ip->i_ino); } } else ap->blkno = *ap->firstblock; xfs_bmap_adjacent(ap); /* * If allowed, use ap->blkno; otherwise must use firstblock since * it's in the right allocation group. */ if (nullfb || XFS_FSB_TO_AGNO(mp, ap->blkno) == fb_agno) ; else ap->blkno = *ap->firstblock; /* * Normal allocation, done through xfs_alloc_vextent. */ tryagain = isaligned = 0; args.tp = ap->tp; args.mp = mp; args.fsbno = ap->blkno; /* Trim the allocation back to the maximum an AG can fit. */ args.maxlen = MIN(ap->length, XFS_ALLOC_AG_MAX_USABLE(mp)); args.firstblock = *ap->firstblock; blen = 0; if (nullfb) { error = xfs_bmap_btalloc_nullfb(ap, &args, &blen); if (error) return error; } else if (ap->flist->xbf_low) { if (xfs_inode_is_filestream(ap->ip)) args.type = XFS_ALLOCTYPE_FIRST_AG; else args.type = XFS_ALLOCTYPE_START_BNO; args.total = args.minlen = ap->minlen; } else { args.type = XFS_ALLOCTYPE_NEAR_BNO; args.total = ap->total; args.minlen = ap->minlen; } /* apply extent size hints if obtained earlier */ if (unlikely(align)) { args.prod = align; if ((args.mod = (xfs_extlen_t)do_mod(ap->offset, args.prod))) args.mod = (xfs_extlen_t)(args.prod - args.mod); } else if (mp->m_sb.sb_blocksize >= PAGE_CACHE_SIZE) { args.prod = 1; args.mod = 0; } else { args.prod = PAGE_CACHE_SIZE >> mp->m_sb.sb_blocklog; if ((args.mod = (xfs_extlen_t)(do_mod(ap->offset, args.prod)))) args.mod = (xfs_extlen_t)(args.prod - args.mod); } /* * If we are not low on available data blocks, and the * underlying logical volume manager is a stripe, and * the file offset is zero then try to allocate data * blocks on stripe unit boundary. * NOTE: ap->aeof is only set if the allocation length * is >= the stripe unit and the allocation offset is * at the end of file. */ if (!ap->flist->xbf_low && ap->aeof) { if (!ap->offset) { args.alignment = mp->m_dalign; atype = args.type; isaligned = 1; /* * Adjust for alignment */ if (blen > args.alignment && blen <= args.maxlen) args.minlen = blen - args.alignment; args.minalignslop = 0; } else { /* * First try an exact bno allocation. * If it fails then do a near or start bno * allocation with alignment turned on. */ atype = args.type; tryagain = 1; args.type = XFS_ALLOCTYPE_THIS_BNO; args.alignment = 1; /* * Compute the minlen+alignment for the * next case. Set slop so that the value * of minlen+alignment+slop doesn't go up * between the calls. */ if (blen > mp->m_dalign && blen <= args.maxlen) nextminlen = blen - mp->m_dalign; else nextminlen = args.minlen; if (nextminlen + mp->m_dalign > args.minlen + 1) args.minalignslop = nextminlen + mp->m_dalign - args.minlen - 1; else args.minalignslop = 0; } } else { args.alignment = 1; args.minalignslop = 0; } args.minleft = ap->minleft; args.wasdel = ap->wasdel; args.isfl = 0; args.userdata = ap->userdata; if ((error = xfs_alloc_vextent(&args))) return error; if (tryagain && args.fsbno == NULLFSBLOCK) { /* * Exact allocation failed. Now try with alignment * turned on. */ args.type = atype; args.fsbno = ap->blkno; args.alignment = mp->m_dalign; args.minlen = nextminlen; args.minalignslop = 0; isaligned = 1; if ((error = xfs_alloc_vextent(&args))) return error; } if (isaligned && args.fsbno == NULLFSBLOCK) { /* * allocation failed, so turn off alignment and * try again. */ args.type = atype; args.fsbno = ap->blkno; args.alignment = 0; if ((error = xfs_alloc_vextent(&args))) return error; } if (args.fsbno == NULLFSBLOCK && nullfb && args.minlen > ap->minlen) { args.minlen = ap->minlen; args.type = XFS_ALLOCTYPE_START_BNO; args.fsbno = ap->blkno; if ((error = xfs_alloc_vextent(&args))) return error; } if (args.fsbno == NULLFSBLOCK && nullfb) { args.fsbno = 0; args.type = XFS_ALLOCTYPE_FIRST_AG; args.total = ap->minlen; args.minleft = 0; if ((error = xfs_alloc_vextent(&args))) return error; ap->flist->xbf_low = 1; } if (args.fsbno != NULLFSBLOCK) { /* * check the allocation happened at the same or higher AG than * the first block that was allocated. */ ASSERT(*ap->firstblock == NULLFSBLOCK || XFS_FSB_TO_AGNO(mp, *ap->firstblock) == XFS_FSB_TO_AGNO(mp, args.fsbno) || (ap->flist->xbf_low && XFS_FSB_TO_AGNO(mp, *ap->firstblock) < XFS_FSB_TO_AGNO(mp, args.fsbno))); ap->blkno = args.fsbno; if (*ap->firstblock == NULLFSBLOCK) *ap->firstblock = args.fsbno; ASSERT(nullfb || fb_agno == args.agno || (ap->flist->xbf_low && fb_agno < args.agno)); ap->length = args.len; ap->ip->i_d.di_nblocks += args.len; xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE); if (ap->wasdel) ap->ip->i_delayed_blks -= args.len; /* * Adjust the disk quota also. This was reserved * earlier. */ xfs_trans_mod_dquot_byino(ap->tp, ap->ip, ap->wasdel ? XFS_TRANS_DQ_DELBCOUNT : XFS_TRANS_DQ_BCOUNT, (long) args.len); } else { ap->blkno = NULLFSBLOCK; ap->length = 0; } return 0; } /* * xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file. * It figures out where to ask the underlying allocator to put the new extent. */ STATIC int xfs_bmap_alloc( xfs_bmalloca_t *ap) /* bmap alloc argument struct */ { if (XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata) return xfs_bmap_rtalloc(ap); return xfs_bmap_btalloc(ap); } /* * Transform a btree format file with only one leaf node, where the * extents list will fit in the inode, into an extents format file. * Since the file extents are already in-core, all we have to do is * give up the space for the btree root and pitch the leaf block. */ STATIC int /* error */ xfs_bmap_btree_to_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_btree_cur_t *cur, /* btree cursor */ int *logflagsp, /* inode logging flags */ int whichfork) /* data or attr fork */ { /* REFERENCED */ struct xfs_btree_block *cblock;/* child btree block */ xfs_fsblock_t cbno; /* child block number */ xfs_buf_t *cbp; /* child block's buffer */ int error; /* error return value */ xfs_ifork_t *ifp; /* inode fork data */ xfs_mount_t *mp; /* mount point structure */ __be64 *pp; /* ptr to block address */ struct xfs_btree_block *rblock;/* root btree block */ mp = ip->i_mount; ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT(ifp->if_flags & XFS_IFEXTENTS); ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE); rblock = ifp->if_broot; ASSERT(be16_to_cpu(rblock->bb_level) == 1); ASSERT(be16_to_cpu(rblock->bb_numrecs) == 1); ASSERT(xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0) == 1); pp = XFS_BMAP_BROOT_PTR_ADDR(mp, rblock, 1, ifp->if_broot_bytes); cbno = be64_to_cpu(*pp); *logflagsp = 0; #ifdef DEBUG if ((error = xfs_btree_check_lptr(cur, cbno, 1))) return error; #endif if ((error = xfs_btree_read_bufl(mp, tp, cbno, 0, &cbp, XFS_BMAP_BTREE_REF))) return error; cblock = XFS_BUF_TO_BLOCK(cbp); if ((error = xfs_btree_check_block(cur, cblock, 0, cbp))) return error; xfs_bmap_add_free(cbno, 1, cur->bc_private.b.flist, mp); ip->i_d.di_nblocks--; xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, -1L); xfs_trans_binval(tp, cbp); if (cur->bc_bufs[0] == cbp) cur->bc_bufs[0] = NULL; xfs_iroot_realloc(ip, -1, whichfork); ASSERT(ifp->if_broot == NULL); ASSERT((ifp->if_flags & XFS_IFBROOT) == 0); XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS); *logflagsp = XFS_ILOG_CORE | xfs_ilog_fext(whichfork); return 0; } /* * Called by xfs_bmapi to update file extent records and the btree * after removing space (or undoing a delayed allocation). */ STATIC int /* error */ xfs_bmap_del_extent( xfs_inode_t *ip, /* incore inode pointer */ xfs_trans_t *tp, /* current transaction pointer */ xfs_extnum_t *idx, /* extent number to update/delete */ xfs_bmap_free_t *flist, /* list of extents to be freed */ xfs_btree_cur_t *cur, /* if null, not a btree */ xfs_bmbt_irec_t *del, /* data to remove from extents */ int *logflagsp, /* inode logging flags */ int whichfork) /* data or attr fork */ { xfs_filblks_t da_new; /* new delay-alloc indirect blocks */ xfs_filblks_t da_old; /* old delay-alloc indirect blocks */ xfs_fsblock_t del_endblock=0; /* first block past del */ xfs_fileoff_t del_endoff; /* first offset past del */ int delay; /* current block is delayed allocated */ int do_fx; /* free extent at end of routine */ xfs_bmbt_rec_host_t *ep; /* current extent entry pointer */ int error; /* error return value */ int flags; /* inode logging flags */ xfs_bmbt_irec_t got; /* current extent entry */ xfs_fileoff_t got_endoff; /* first offset past got */ int i; /* temp state */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_mount_t *mp; /* mount structure */ xfs_filblks_t nblks; /* quota/sb block count */ xfs_bmbt_irec_t new; /* new record to be inserted */ /* REFERENCED */ uint qfield; /* quota field to update */ xfs_filblks_t temp; /* for indirect length calculations */ xfs_filblks_t temp2; /* for indirect length calculations */ int state = 0; XFS_STATS_INC(xs_del_exlist); if (whichfork == XFS_ATTR_FORK) state |= BMAP_ATTRFORK; mp = ip->i_mount; ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT((*idx >= 0) && (*idx < ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))); ASSERT(del->br_blockcount > 0); ep = xfs_iext_get_ext(ifp, *idx); xfs_bmbt_get_all(ep, &got); ASSERT(got.br_startoff <= del->br_startoff); del_endoff = del->br_startoff + del->br_blockcount; got_endoff = got.br_startoff + got.br_blockcount; ASSERT(got_endoff >= del_endoff); delay = isnullstartblock(got.br_startblock); ASSERT(isnullstartblock(del->br_startblock) == delay); flags = 0; qfield = 0; error = 0; /* * If deleting a real allocation, must free up the disk space. */ if (!delay) { flags = XFS_ILOG_CORE; /* * Realtime allocation. Free it and record di_nblocks update. */ if (whichfork == XFS_DATA_FORK && XFS_IS_REALTIME_INODE(ip)) { xfs_fsblock_t bno; xfs_filblks_t len; ASSERT(do_mod(del->br_blockcount, mp->m_sb.sb_rextsize) == 0); ASSERT(do_mod(del->br_startblock, mp->m_sb.sb_rextsize) == 0); bno = del->br_startblock; len = del->br_blockcount; do_div(bno, mp->m_sb.sb_rextsize); do_div(len, mp->m_sb.sb_rextsize); error = xfs_rtfree_extent(tp, bno, (xfs_extlen_t)len); if (error) goto done; do_fx = 0; nblks = len * mp->m_sb.sb_rextsize; qfield = XFS_TRANS_DQ_RTBCOUNT; } /* * Ordinary allocation. */ else { do_fx = 1; nblks = del->br_blockcount; qfield = XFS_TRANS_DQ_BCOUNT; } /* * Set up del_endblock and cur for later. */ del_endblock = del->br_startblock + del->br_blockcount; if (cur) { if ((error = xfs_bmbt_lookup_eq(cur, got.br_startoff, got.br_startblock, got.br_blockcount, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); } da_old = da_new = 0; } else { da_old = startblockval(got.br_startblock); da_new = 0; nblks = 0; do_fx = 0; } /* * Set flag value to use in switch statement. * Left-contig is 2, right-contig is 1. */ switch (((got.br_startoff == del->br_startoff) << 1) | (got_endoff == del_endoff)) { case 3: /* * Matches the whole extent. Delete the entry. */ xfs_iext_remove(ip, *idx, 1, whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0); --*idx; if (delay) break; XFS_IFORK_NEXT_SET(ip, whichfork, XFS_IFORK_NEXTENTS(ip, whichfork) - 1); flags |= XFS_ILOG_CORE; if (!cur) { flags |= xfs_ilog_fext(whichfork); break; } if ((error = xfs_btree_delete(cur, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); break; case 2: /* * Deleting the first part of the extent. */ trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_startoff(ep, del_endoff); temp = got.br_blockcount - del->br_blockcount; xfs_bmbt_set_blockcount(ep, temp); if (delay) { temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp), da_old); xfs_bmbt_set_startblock(ep, nullstartblock((int)temp)); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); da_new = temp; break; } xfs_bmbt_set_startblock(ep, del_endblock); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); if (!cur) { flags |= xfs_ilog_fext(whichfork); break; } if ((error = xfs_bmbt_update(cur, del_endoff, del_endblock, got.br_blockcount - del->br_blockcount, got.br_state))) goto done; break; case 1: /* * Deleting the last part of the extent. */ temp = got.br_blockcount - del->br_blockcount; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, temp); if (delay) { temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp), da_old); xfs_bmbt_set_startblock(ep, nullstartblock((int)temp)); trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); da_new = temp; break; } trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); if (!cur) { flags |= xfs_ilog_fext(whichfork); break; } if ((error = xfs_bmbt_update(cur, got.br_startoff, got.br_startblock, got.br_blockcount - del->br_blockcount, got.br_state))) goto done; break; case 0: /* * Deleting the middle of the extent. */ temp = del->br_startoff - got.br_startoff; trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_); xfs_bmbt_set_blockcount(ep, temp); new.br_startoff = del_endoff; temp2 = got_endoff - del_endoff; new.br_blockcount = temp2; new.br_state = got.br_state; if (!delay) { new.br_startblock = del_endblock; flags |= XFS_ILOG_CORE; if (cur) { if ((error = xfs_bmbt_update(cur, got.br_startoff, got.br_startblock, temp, got.br_state))) goto done; if ((error = xfs_btree_increment(cur, 0, &i))) goto done; cur->bc_rec.b = new; error = xfs_btree_insert(cur, &i); if (error && error != ENOSPC) goto done; /* * If get no-space back from btree insert, * it tried a split, and we have a zero * block reservation. * Fix up our state and return the error. */ if (error == ENOSPC) { /* * Reset the cursor, don't trust * it after any insert operation. */ if ((error = xfs_bmbt_lookup_eq(cur, got.br_startoff, got.br_startblock, temp, &i))) goto done; XFS_WANT_CORRUPTED_GOTO(i == 1, done); /* * Update the btree record back * to the original value. */ if ((error = xfs_bmbt_update(cur, got.br_startoff, got.br_startblock, got.br_blockcount, got.br_state))) goto done; /* * Reset the extent record back * to the original value. */ xfs_bmbt_set_blockcount(ep, got.br_blockcount); flags = 0; error = XFS_ERROR(ENOSPC); goto done; } XFS_WANT_CORRUPTED_GOTO(i == 1, done); } else flags |= xfs_ilog_fext(whichfork); XFS_IFORK_NEXT_SET(ip, whichfork, XFS_IFORK_NEXTENTS(ip, whichfork) + 1); } else { ASSERT(whichfork == XFS_DATA_FORK); temp = xfs_bmap_worst_indlen(ip, temp); xfs_bmbt_set_startblock(ep, nullstartblock((int)temp)); temp2 = xfs_bmap_worst_indlen(ip, temp2); new.br_startblock = nullstartblock((int)temp2); da_new = temp + temp2; while (da_new > da_old) { if (temp) { temp--; da_new--; xfs_bmbt_set_startblock(ep, nullstartblock((int)temp)); } if (da_new == da_old) break; if (temp2) { temp2--; da_new--; new.br_startblock = nullstartblock((int)temp2); } } } trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_); xfs_iext_insert(ip, *idx + 1, 1, &new, state); ++*idx; break; } /* * If we need to, add to list of extents to delete. */ if (do_fx) xfs_bmap_add_free(del->br_startblock, del->br_blockcount, flist, mp); /* * Adjust inode # blocks in the file. */ if (nblks) ip->i_d.di_nblocks -= nblks; /* * Adjust quota data. */ if (qfield) xfs_trans_mod_dquot_byino(tp, ip, qfield, (long)-nblks); /* * Account for change in delayed indirect blocks. * Nothing to do for disk quota accounting here. */ ASSERT(da_old >= da_new); if (da_old > da_new) { xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, (int64_t)(da_old - da_new), 0); } done: *logflagsp = flags; return error; } /* * Remove the entry "free" from the free item list. Prev points to the * previous entry, unless "free" is the head of the list. */ STATIC void xfs_bmap_del_free( xfs_bmap_free_t *flist, /* free item list header */ xfs_bmap_free_item_t *prev, /* previous item on list, if any */ xfs_bmap_free_item_t *free) /* list item to be freed */ { if (prev) prev->xbfi_next = free->xbfi_next; else flist->xbf_first = free->xbfi_next; flist->xbf_count--; kmem_zone_free(xfs_bmap_free_item_zone, free); } /* * Convert an extents-format file into a btree-format file. * The new file will have a root block (in the inode) and a single child block. */ STATIC int /* error */ xfs_bmap_extents_to_btree( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first-block-allocated */ xfs_bmap_free_t *flist, /* blocks freed in xaction */ xfs_btree_cur_t **curp, /* cursor returned to caller */ int wasdel, /* converting a delayed alloc */ int *logflagsp, /* inode logging flags */ int whichfork) /* data or attr fork */ { struct xfs_btree_block *ablock; /* allocated (child) bt block */ xfs_buf_t *abp; /* buffer for ablock */ xfs_alloc_arg_t args; /* allocation arguments */ xfs_bmbt_rec_t *arp; /* child record pointer */ struct xfs_btree_block *block; /* btree root block */ xfs_btree_cur_t *cur; /* bmap btree cursor */ xfs_bmbt_rec_host_t *ep; /* extent record pointer */ int error; /* error return value */ xfs_extnum_t i, cnt; /* extent record index */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_bmbt_key_t *kp; /* root block key pointer */ xfs_mount_t *mp; /* mount structure */ xfs_extnum_t nextents; /* number of file extents */ xfs_bmbt_ptr_t *pp; /* root block address pointer */ ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS); /* * Make space in the inode incore. */ xfs_iroot_realloc(ip, 1, whichfork); ifp->if_flags |= XFS_IFBROOT; /* * Fill in the root. */ block = ifp->if_broot; block->bb_magic = cpu_to_be32(XFS_BMAP_MAGIC); block->bb_level = cpu_to_be16(1); block->bb_numrecs = cpu_to_be16(1); block->bb_u.l.bb_leftsib = cpu_to_be64(NULLDFSBNO); block->bb_u.l.bb_rightsib = cpu_to_be64(NULLDFSBNO); /* * Need a cursor. Can't allocate until bb_level is filled in. */ mp = ip->i_mount; cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork); cur->bc_private.b.firstblock = *firstblock; cur->bc_private.b.flist = flist; cur->bc_private.b.flags = wasdel ? XFS_BTCUR_BPRV_WASDEL : 0; /* * Convert to a btree with two levels, one record in root. */ XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_BTREE); args.tp = tp; args.mp = mp; args.firstblock = *firstblock; if (*firstblock == NULLFSBLOCK) { args.type = XFS_ALLOCTYPE_START_BNO; args.fsbno = XFS_INO_TO_FSB(mp, ip->i_ino); } else if (flist->xbf_low) { args.type = XFS_ALLOCTYPE_START_BNO; args.fsbno = *firstblock; } else { args.type = XFS_ALLOCTYPE_NEAR_BNO; args.fsbno = *firstblock; } args.minlen = args.maxlen = args.prod = 1; args.total = args.minleft = args.alignment = args.mod = args.isfl = args.minalignslop = 0; args.wasdel = wasdel; *logflagsp = 0; if ((error = xfs_alloc_vextent(&args))) { xfs_iroot_realloc(ip, -1, whichfork); xfs_btree_del_cursor(cur, XFS_BTREE_ERROR); return error; } /* * Allocation can't fail, the space was reserved. */ ASSERT(args.fsbno != NULLFSBLOCK); ASSERT(*firstblock == NULLFSBLOCK || args.agno == XFS_FSB_TO_AGNO(mp, *firstblock) || (flist->xbf_low && args.agno > XFS_FSB_TO_AGNO(mp, *firstblock))); *firstblock = cur->bc_private.b.firstblock = args.fsbno; cur->bc_private.b.allocated++; ip->i_d.di_nblocks++; xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, 1L); abp = xfs_btree_get_bufl(mp, tp, args.fsbno, 0); /* * Fill in the child block. */ ablock = XFS_BUF_TO_BLOCK(abp); ablock->bb_magic = cpu_to_be32(XFS_BMAP_MAGIC); ablock->bb_level = 0; ablock->bb_u.l.bb_leftsib = cpu_to_be64(NULLDFSBNO); ablock->bb_u.l.bb_rightsib = cpu_to_be64(NULLDFSBNO); arp = XFS_BMBT_REC_ADDR(mp, ablock, 1); nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); for (cnt = i = 0; i < nextents; i++) { ep = xfs_iext_get_ext(ifp, i); if (!isnullstartblock(xfs_bmbt_get_startblock(ep))) { arp->l0 = cpu_to_be64(ep->l0); arp->l1 = cpu_to_be64(ep->l1); arp++; cnt++; } } ASSERT(cnt == XFS_IFORK_NEXTENTS(ip, whichfork)); xfs_btree_set_numrecs(ablock, cnt); /* * Fill in the root key and pointer. */ kp = XFS_BMBT_KEY_ADDR(mp, block, 1); arp = XFS_BMBT_REC_ADDR(mp, ablock, 1); kp->br_startoff = cpu_to_be64(xfs_bmbt_disk_get_startoff(arp)); pp = XFS_BMBT_PTR_ADDR(mp, block, 1, xfs_bmbt_get_maxrecs(cur, be16_to_cpu(block->bb_level))); *pp = cpu_to_be64(args.fsbno); /* * Do all this logging at the end so that * the root is at the right level. */ xfs_btree_log_block(cur, abp, XFS_BB_ALL_BITS); xfs_btree_log_recs(cur, abp, 1, be16_to_cpu(ablock->bb_numrecs)); ASSERT(*curp == NULL); *curp = cur; *logflagsp = XFS_ILOG_CORE | xfs_ilog_fbroot(whichfork); return 0; } /* * Calculate the default attribute fork offset for newly created inodes. */ uint xfs_default_attroffset( struct xfs_inode *ip) { struct xfs_mount *mp = ip->i_mount; uint offset; if (mp->m_sb.sb_inodesize == 256) { offset = XFS_LITINO(mp) - XFS_BMDR_SPACE_CALC(MINABTPTRS); } else { offset = XFS_BMDR_SPACE_CALC(6 * MINABTPTRS); } ASSERT(offset < XFS_LITINO(mp)); return offset; } /* * Helper routine to reset inode di_forkoff field when switching * attribute fork from local to extent format - we reset it where * possible to make space available for inline data fork extents. */ STATIC void xfs_bmap_forkoff_reset( xfs_mount_t *mp, xfs_inode_t *ip, int whichfork) { if (whichfork == XFS_ATTR_FORK && ip->i_d.di_format != XFS_DINODE_FMT_DEV && ip->i_d.di_format != XFS_DINODE_FMT_UUID && ip->i_d.di_format != XFS_DINODE_FMT_BTREE) { uint dfl_forkoff = xfs_default_attroffset(ip) >> 3; if (dfl_forkoff > ip->i_d.di_forkoff) ip->i_d.di_forkoff = dfl_forkoff; } } /* * Convert a local file to an extents file. * This code is out of bounds for data forks of regular files, * since the file data needs to get logged so things will stay consistent. * (The bmap-level manipulations are ok, though). */ STATIC int /* error */ xfs_bmap_local_to_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode pointer */ xfs_fsblock_t *firstblock, /* first block allocated in xaction */ xfs_extlen_t total, /* total blocks needed by transaction */ int *logflagsp, /* inode logging flags */ int whichfork) /* data or attr fork */ { int error; /* error return value */ int flags; /* logging flags returned */ xfs_ifork_t *ifp; /* inode fork pointer */ /* * We don't want to deal with the case of keeping inode data inline yet. * So sending the data fork of a regular inode is invalid. */ ASSERT(!(S_ISREG(ip->i_d.di_mode) && whichfork == XFS_DATA_FORK)); ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL); flags = 0; error = 0; if (ifp->if_bytes) { xfs_alloc_arg_t args; /* allocation arguments */ xfs_buf_t *bp; /* buffer for extent block */ xfs_bmbt_rec_host_t *ep;/* extent record pointer */ args.tp = tp; args.mp = ip->i_mount; args.firstblock = *firstblock; ASSERT((ifp->if_flags & (XFS_IFINLINE|XFS_IFEXTENTS|XFS_IFEXTIREC)) == XFS_IFINLINE); /* * Allocate a block. We know we need only one, since the * file currently fits in an inode. */ if (*firstblock == NULLFSBLOCK) { args.fsbno = XFS_INO_TO_FSB(args.mp, ip->i_ino); args.type = XFS_ALLOCTYPE_START_BNO; } else { args.fsbno = *firstblock; args.type = XFS_ALLOCTYPE_NEAR_BNO; } args.total = total; args.mod = args.minleft = args.alignment = args.wasdel = args.isfl = args.minalignslop = 0; args.minlen = args.maxlen = args.prod = 1; if ((error = xfs_alloc_vextent(&args))) goto done; /* * Can't fail, the space was reserved. */ ASSERT(args.fsbno != NULLFSBLOCK); ASSERT(args.len == 1); *firstblock = args.fsbno; bp = xfs_btree_get_bufl(args.mp, tp, args.fsbno, 0); memcpy(bp->b_addr, ifp->if_u1.if_data, ifp->if_bytes); xfs_trans_log_buf(tp, bp, 0, ifp->if_bytes - 1); xfs_bmap_forkoff_reset(args.mp, ip, whichfork); xfs_idata_realloc(ip, -ifp->if_bytes, whichfork); xfs_iext_add(ifp, 0, 1); ep = xfs_iext_get_ext(ifp, 0); xfs_bmbt_set_allf(ep, 0, args.fsbno, 1, XFS_EXT_NORM); trace_xfs_bmap_post_update(ip, 0, whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0, _THIS_IP_); XFS_IFORK_NEXT_SET(ip, whichfork, 1); ip->i_d.di_nblocks = 1; xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, 1L); flags |= xfs_ilog_fext(whichfork); } else { ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) == 0); xfs_bmap_forkoff_reset(ip->i_mount, ip, whichfork); } ifp->if_flags &= ~XFS_IFINLINE; ifp->if_flags |= XFS_IFEXTENTS; XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS); flags |= XFS_ILOG_CORE; done: *logflagsp = flags; return error; } /* * Search the extent records for the entry containing block bno. * If bno lies in a hole, point to the next entry. If bno lies * past eof, *eofp will be set, and *prevp will contain the last * entry (null if none). Else, *lastxp will be set to the index * of the found entry; *gotp will contain the entry. */ STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */ xfs_bmap_search_multi_extents( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_fileoff_t bno, /* block number searched for */ int *eofp, /* out: end of file found */ xfs_extnum_t *lastxp, /* out: last extent index */ xfs_bmbt_irec_t *gotp, /* out: extent entry found */ xfs_bmbt_irec_t *prevp) /* out: previous extent entry found */ { xfs_bmbt_rec_host_t *ep; /* extent record pointer */ xfs_extnum_t lastx; /* last extent index */ /* * Initialize the extent entry structure to catch access to * uninitialized br_startblock field. */ gotp->br_startoff = 0xffa5a5a5a5a5a5a5LL; gotp->br_blockcount = 0xa55a5a5a5a5a5a5aLL; gotp->br_state = XFS_EXT_INVALID; #if XFS_BIG_BLKNOS gotp->br_startblock = 0xffffa5a5a5a5a5a5LL; #else gotp->br_startblock = 0xffffa5a5; #endif prevp->br_startoff = NULLFILEOFF; ep = xfs_iext_bno_to_ext(ifp, bno, &lastx); if (lastx > 0) { xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx - 1), prevp); } if (lastx < (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))) { xfs_bmbt_get_all(ep, gotp); *eofp = 0; } else { if (lastx > 0) { *gotp = *prevp; } *eofp = 1; ep = NULL; } *lastxp = lastx; return ep; } /* * Search the extents list for the inode, for the extent containing bno. * If bno lies in a hole, point to the next entry. If bno lies past eof, * *eofp will be set, and *prevp will contain the last entry (null if none). * Else, *lastxp will be set to the index of the found * entry; *gotp will contain the entry. */ STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */ xfs_bmap_search_extents( xfs_inode_t *ip, /* incore inode pointer */ xfs_fileoff_t bno, /* block number searched for */ int fork, /* data or attr fork */ int *eofp, /* out: end of file found */ xfs_extnum_t *lastxp, /* out: last extent index */ xfs_bmbt_irec_t *gotp, /* out: extent entry found */ xfs_bmbt_irec_t *prevp) /* out: previous extent entry found */ { xfs_ifork_t *ifp; /* inode fork pointer */ xfs_bmbt_rec_host_t *ep; /* extent record pointer */ XFS_STATS_INC(xs_look_exlist); ifp = XFS_IFORK_PTR(ip, fork); ep = xfs_bmap_search_multi_extents(ifp, bno, eofp, lastxp, gotp, prevp); if (unlikely(!(gotp->br_startblock) && (*lastxp != NULLEXTNUM) && !(XFS_IS_REALTIME_INODE(ip) && fork == XFS_DATA_FORK))) { xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO, "Access to block zero in inode %llu " "start_block: %llx start_off: %llx " "blkcnt: %llx extent-state: %x lastx: %x\n", (unsigned long long)ip->i_ino, (unsigned long long)gotp->br_startblock, (unsigned long long)gotp->br_startoff, (unsigned long long)gotp->br_blockcount, gotp->br_state, *lastxp); *lastxp = NULLEXTNUM; *eofp = 1; return NULL; } return ep; } /* * Compute the worst-case number of indirect blocks that will be used * for ip's delayed extent of length "len". */ STATIC xfs_filblks_t xfs_bmap_worst_indlen( xfs_inode_t *ip, /* incore inode pointer */ xfs_filblks_t len) /* delayed extent length */ { int level; /* btree level number */ int maxrecs; /* maximum record count at this level */ xfs_mount_t *mp; /* mount structure */ xfs_filblks_t rval; /* return value */ mp = ip->i_mount; maxrecs = mp->m_bmap_dmxr[0]; for (level = 0, rval = 0; level < XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK); level++) { len += maxrecs - 1; do_div(len, maxrecs); rval += len; if (len == 1) return rval + XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK) - level - 1; if (level == 0) maxrecs = mp->m_bmap_dmxr[1]; } return rval; } /* * Convert inode from non-attributed to attributed. * Must not be in a transaction, ip must not be locked. */ int /* error code */ xfs_bmap_add_attrfork( xfs_inode_t *ip, /* incore inode pointer */ int size, /* space new attribute needs */ int rsvd) /* xact may use reserved blks */ { xfs_fsblock_t firstblock; /* 1st block/ag allocated */ xfs_bmap_free_t flist; /* freed extent records */ xfs_mount_t *mp; /* mount structure */ xfs_trans_t *tp; /* transaction pointer */ int blks; /* space reservation */ int version = 1; /* superblock attr version */ int committed; /* xaction was committed */ int logflags; /* logging flags */ int error; /* error return value */ ASSERT(XFS_IFORK_Q(ip) == 0); mp = ip->i_mount; ASSERT(!XFS_NOT_DQATTACHED(mp, ip)); tp = xfs_trans_alloc(mp, XFS_TRANS_ADDAFORK); blks = XFS_ADDAFORK_SPACE_RES(mp); if (rsvd) tp->t_flags |= XFS_TRANS_RESERVE; if ((error = xfs_trans_reserve(tp, blks, XFS_ADDAFORK_LOG_RES(mp), 0, XFS_TRANS_PERM_LOG_RES, XFS_ADDAFORK_LOG_COUNT))) goto error0; xfs_ilock(ip, XFS_ILOCK_EXCL); error = xfs_trans_reserve_quota_nblks(tp, ip, blks, 0, rsvd ? XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES : XFS_QMOPT_RES_REGBLKS); if (error) { xfs_iunlock(ip, XFS_ILOCK_EXCL); xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES); return error; } if (XFS_IFORK_Q(ip)) goto error1; if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS) { /* * For inodes coming from pre-6.2 filesystems. */ ASSERT(ip->i_d.di_aformat == 0); ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS; } ASSERT(ip->i_d.di_anextents == 0); xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); switch (ip->i_d.di_format) { case XFS_DINODE_FMT_DEV: ip->i_d.di_forkoff = roundup(sizeof(xfs_dev_t), 8) >> 3; break; case XFS_DINODE_FMT_UUID: ip->i_d.di_forkoff = roundup(sizeof(uuid_t), 8) >> 3; break; case XFS_DINODE_FMT_LOCAL: case XFS_DINODE_FMT_EXTENTS: case XFS_DINODE_FMT_BTREE: ip->i_d.di_forkoff = xfs_attr_shortform_bytesfit(ip, size); if (!ip->i_d.di_forkoff) ip->i_d.di_forkoff = xfs_default_attroffset(ip) >> 3; else if (mp->m_flags & XFS_MOUNT_ATTR2) version = 2; break; default: ASSERT(0); error = XFS_ERROR(EINVAL); goto error1; } ASSERT(ip->i_afp == NULL); ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP); ip->i_afp->if_flags = XFS_IFEXTENTS; logflags = 0; xfs_bmap_init(&flist, &firstblock); switch (ip->i_d.di_format) { case XFS_DINODE_FMT_LOCAL: error = xfs_bmap_add_attrfork_local(tp, ip, &firstblock, &flist, &logflags); break; case XFS_DINODE_FMT_EXTENTS: error = xfs_bmap_add_attrfork_extents(tp, ip, &firstblock, &flist, &logflags); break; case XFS_DINODE_FMT_BTREE: error = xfs_bmap_add_attrfork_btree(tp, ip, &firstblock, &flist, &logflags); break; default: error = 0; break; } if (logflags) xfs_trans_log_inode(tp, ip, logflags); if (error) goto error2; if (!xfs_sb_version_hasattr(&mp->m_sb) || (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2)) { __int64_t sbfields = 0; spin_lock(&mp->m_sb_lock); if (!xfs_sb_version_hasattr(&mp->m_sb)) { xfs_sb_version_addattr(&mp->m_sb); sbfields |= XFS_SB_VERSIONNUM; } if (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2) { xfs_sb_version_addattr2(&mp->m_sb); sbfields |= (XFS_SB_VERSIONNUM | XFS_SB_FEATURES2); } if (sbfields) { spin_unlock(&mp->m_sb_lock); xfs_mod_sb(tp, sbfields); } else spin_unlock(&mp->m_sb_lock); } error = xfs_bmap_finish(&tp, &flist, &committed); if (error) goto error2; return xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES); error2: xfs_bmap_cancel(&flist); error1: xfs_iunlock(ip, XFS_ILOCK_EXCL); error0: xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT); return error; } /* * Add the extent to the list of extents to be free at transaction end. * The list is maintained sorted (by block number). */ /* ARGSUSED */ void xfs_bmap_add_free( xfs_fsblock_t bno, /* fs block number of extent */ xfs_filblks_t len, /* length of extent */ xfs_bmap_free_t *flist, /* list of extents */ xfs_mount_t *mp) /* mount point structure */ { xfs_bmap_free_item_t *cur; /* current (next) element */ xfs_bmap_free_item_t *new; /* new element */ xfs_bmap_free_item_t *prev; /* previous element */ #ifdef DEBUG xfs_agnumber_t agno; xfs_agblock_t agbno; ASSERT(bno != NULLFSBLOCK); ASSERT(len > 0); ASSERT(len <= MAXEXTLEN); ASSERT(!isnullstartblock(bno)); agno = XFS_FSB_TO_AGNO(mp, bno); agbno = XFS_FSB_TO_AGBNO(mp, bno); ASSERT(agno < mp->m_sb.sb_agcount); ASSERT(agbno < mp->m_sb.sb_agblocks); ASSERT(len < mp->m_sb.sb_agblocks); ASSERT(agbno + len <= mp->m_sb.sb_agblocks); #endif ASSERT(xfs_bmap_free_item_zone != NULL); new = kmem_zone_alloc(xfs_bmap_free_item_zone, KM_SLEEP); new->xbfi_startblock = bno; new->xbfi_blockcount = (xfs_extlen_t)len; for (prev = NULL, cur = flist->xbf_first; cur != NULL; prev = cur, cur = cur->xbfi_next) { if (cur->xbfi_startblock >= bno) break; } if (prev) prev->xbfi_next = new; else flist->xbf_first = new; new->xbfi_next = cur; flist->xbf_count++; } /* * Compute and fill in the value of the maximum depth of a bmap btree * in this filesystem. Done once, during mount. */ void xfs_bmap_compute_maxlevels( xfs_mount_t *mp, /* file system mount structure */ int whichfork) /* data or attr fork */ { int level; /* btree level */ uint maxblocks; /* max blocks at this level */ uint maxleafents; /* max leaf entries possible */ int maxrootrecs; /* max records in root block */ int minleafrecs; /* min records in leaf block */ int minnoderecs; /* min records in node block */ int sz; /* root block size */ /* * The maximum number of extents in a file, hence the maximum * number of leaf entries, is controlled by the type of di_nextents * (a signed 32-bit number, xfs_extnum_t), or by di_anextents * (a signed 16-bit number, xfs_aextnum_t). * * Note that we can no longer assume that if we are in ATTR1 that * the fork offset of all the inodes will be * (xfs_default_attroffset(ip) >> 3) because we could have mounted * with ATTR2 and then mounted back with ATTR1, keeping the * di_forkoff's fixed but probably at various positions. Therefore, * for both ATTR1 and ATTR2 we have to assume the worst case scenario * of a minimum size available. */ if (whichfork == XFS_DATA_FORK) { maxleafents = MAXEXTNUM; sz = XFS_BMDR_SPACE_CALC(MINDBTPTRS); } else { maxleafents = MAXAEXTNUM; sz = XFS_BMDR_SPACE_CALC(MINABTPTRS); } maxrootrecs = xfs_bmdr_maxrecs(mp, sz, 0); minleafrecs = mp->m_bmap_dmnr[0]; minnoderecs = mp->m_bmap_dmnr[1]; maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs; for (level = 1; maxblocks > 1; level++) { if (maxblocks <= maxrootrecs) maxblocks = 1; else maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs; } mp->m_bm_maxlevels[whichfork] = level; } /* * Routine to be called at transaction's end by xfs_bmapi, xfs_bunmapi * caller. Frees all the extents that need freeing, which must be done * last due to locking considerations. We never free any extents in * the first transaction. * * Return 1 if the given transaction was committed and a new one * started, and 0 otherwise in the committed parameter. */ int /* error */ xfs_bmap_finish( xfs_trans_t **tp, /* transaction pointer addr */ xfs_bmap_free_t *flist, /* i/o: list extents to free */ int *committed) /* xact committed or not */ { xfs_efd_log_item_t *efd; /* extent free data */ xfs_efi_log_item_t *efi; /* extent free intention */ int error; /* error return value */ xfs_bmap_free_item_t *free; /* free extent item */ unsigned int logres; /* new log reservation */ unsigned int logcount; /* new log count */ xfs_mount_t *mp; /* filesystem mount structure */ xfs_bmap_free_item_t *next; /* next item on free list */ xfs_trans_t *ntp; /* new transaction pointer */ ASSERT((*tp)->t_flags & XFS_TRANS_PERM_LOG_RES); if (flist->xbf_count == 0) { *committed = 0; return 0; } ntp = *tp; efi = xfs_trans_get_efi(ntp, flist->xbf_count); for (free = flist->xbf_first; free; free = free->xbfi_next) xfs_trans_log_efi_extent(ntp, efi, free->xbfi_startblock, free->xbfi_blockcount); logres = ntp->t_log_res; logcount = ntp->t_log_count; ntp = xfs_trans_dup(*tp); error = xfs_trans_commit(*tp, 0); *tp = ntp; *committed = 1; /* * We have a new transaction, so we should return committed=1, * even though we're returning an error. */ if (error) return error; /* * transaction commit worked ok so we can drop the extra ticket * reference that we gained in xfs_trans_dup() */ xfs_log_ticket_put(ntp->t_ticket); if ((error = xfs_trans_reserve(ntp, 0, logres, 0, XFS_TRANS_PERM_LOG_RES, logcount))) return error; efd = xfs_trans_get_efd(ntp, efi, flist->xbf_count); for (free = flist->xbf_first; free != NULL; free = next) { next = free->xbfi_next; if ((error = xfs_free_extent(ntp, free->xbfi_startblock, free->xbfi_blockcount))) { /* * The bmap free list will be cleaned up at a * higher level. The EFI will be canceled when * this transaction is aborted. * Need to force shutdown here to make sure it * happens, since this transaction may not be * dirty yet. */ mp = ntp->t_mountp; if (!XFS_FORCED_SHUTDOWN(mp)) xfs_force_shutdown(mp, (error == EFSCORRUPTED) ? SHUTDOWN_CORRUPT_INCORE : SHUTDOWN_META_IO_ERROR); return error; } xfs_trans_log_efd_extent(ntp, efd, free->xbfi_startblock, free->xbfi_blockcount); xfs_bmap_del_free(flist, NULL, free); } return 0; } /* * Free up any items left in the list. */ void xfs_bmap_cancel( xfs_bmap_free_t *flist) /* list of bmap_free_items */ { xfs_bmap_free_item_t *free; /* free list item */ xfs_bmap_free_item_t *next; if (flist->xbf_count == 0) return; ASSERT(flist->xbf_first != NULL); for (free = flist->xbf_first; free; free = next) { next = free->xbfi_next; xfs_bmap_del_free(flist, NULL, free); } ASSERT(flist->xbf_count == 0); } /* * Returns the file-relative block number of the first unused block(s) * in the file with at least "len" logically contiguous blocks free. * This is the lowest-address hole if the file has holes, else the first block * past the end of file. * Return 0 if the file is currently local (in-inode). */ int /* error */ xfs_bmap_first_unused( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode */ xfs_extlen_t len, /* size of hole to find */ xfs_fileoff_t *first_unused, /* unused block */ int whichfork) /* data or attr fork */ { int error; /* error return value */ int idx; /* extent record index */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_fileoff_t lastaddr; /* last block number seen */ xfs_fileoff_t lowest; /* lowest useful block */ xfs_fileoff_t max; /* starting useful block */ xfs_fileoff_t off; /* offset for this block */ xfs_extnum_t nextents; /* number of extent entries */ ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE || XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS || XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL); if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) { *first_unused = 0; return 0; } ifp = XFS_IFORK_PTR(ip, whichfork); if (!(ifp->if_flags & XFS_IFEXTENTS) && (error = xfs_iread_extents(tp, ip, whichfork))) return error; lowest = *first_unused; nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); for (idx = 0, lastaddr = 0, max = lowest; idx < nextents; idx++) { xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, idx); off = xfs_bmbt_get_startoff(ep); /* * See if the hole before this extent will work. */ if (off >= lowest + len && off - max >= len) { *first_unused = max; return 0; } lastaddr = off + xfs_bmbt_get_blockcount(ep); max = XFS_FILEOFF_MAX(lastaddr, lowest); } *first_unused = max; return 0; } /* * Returns the file-relative block number of the last block + 1 before * last_block (input value) in the file. * This is not based on i_size, it is based on the extent records. * Returns 0 for local files, as they do not have extent records. */ int /* error */ xfs_bmap_last_before( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode */ xfs_fileoff_t *last_block, /* last block */ int whichfork) /* data or attr fork */ { xfs_fileoff_t bno; /* input file offset */ int eof; /* hit end of file */ xfs_bmbt_rec_host_t *ep; /* pointer to last extent */ int error; /* error return value */ xfs_bmbt_irec_t got; /* current extent value */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_extnum_t lastx; /* last extent used */ xfs_bmbt_irec_t prev; /* previous extent value */ if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL) return XFS_ERROR(EIO); if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) { *last_block = 0; return 0; } ifp = XFS_IFORK_PTR(ip, whichfork); if (!(ifp->if_flags & XFS_IFEXTENTS) && (error = xfs_iread_extents(tp, ip, whichfork))) return error; bno = *last_block - 1; ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got, &prev); if (eof || xfs_bmbt_get_startoff(ep) > bno) { if (prev.br_startoff == NULLFILEOFF) *last_block = 0; else *last_block = prev.br_startoff + prev.br_blockcount; } /* * Otherwise *last_block is already the right answer. */ return 0; } STATIC int xfs_bmap_last_extent( struct xfs_trans *tp, struct xfs_inode *ip, int whichfork, struct xfs_bmbt_irec *rec, int *is_empty) { struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, whichfork); int error; int nextents; if (!(ifp->if_flags & XFS_IFEXTENTS)) { error = xfs_iread_extents(tp, ip, whichfork); if (error) return error; } nextents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t); if (nextents == 0) { *is_empty = 1; return 0; } xfs_bmbt_get_all(xfs_iext_get_ext(ifp, nextents - 1), rec); *is_empty = 0; return 0; } /* * Check the last inode extent to determine whether this allocation will result * in blocks being allocated at the end of the file. When we allocate new data * blocks at the end of the file which do not start at the previous data block, * we will try to align the new blocks at stripe unit boundaries. * * Returns 0 in bma->aeof if the file (fork) is empty as any new write will be * at, or past the EOF. */ STATIC int xfs_bmap_isaeof( struct xfs_bmalloca *bma, int whichfork) { struct xfs_bmbt_irec rec; int is_empty; int error; bma->aeof = 0; error = xfs_bmap_last_extent(NULL, bma->ip, whichfork, &rec, &is_empty); if (error || is_empty) return error; /* * Check if we are allocation or past the last extent, or at least into * the last delayed allocated extent. */ bma->aeof = bma->offset >= rec.br_startoff + rec.br_blockcount || (bma->offset >= rec.br_startoff && isnullstartblock(rec.br_startblock)); return 0; } /* * Check if the endoff is outside the last extent. If so the caller will grow * the allocation to a stripe unit boundary. All offsets are considered outside * the end of file for an empty fork, so 1 is returned in *eof in that case. */ int xfs_bmap_eof( struct xfs_inode *ip, xfs_fileoff_t endoff, int whichfork, int *eof) { struct xfs_bmbt_irec rec; int error; error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, eof); if (error || *eof) return error; *eof = endoff >= rec.br_startoff + rec.br_blockcount; return 0; } /* * Returns the file-relative block number of the first block past eof in * the file. This is not based on i_size, it is based on the extent records. * Returns 0 for local files, as they do not have extent records. */ int xfs_bmap_last_offset( struct xfs_trans *tp, struct xfs_inode *ip, xfs_fileoff_t *last_block, int whichfork) { struct xfs_bmbt_irec rec; int is_empty; int error; *last_block = 0; if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) return 0; if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS) return XFS_ERROR(EIO); error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, &is_empty); if (error || is_empty) return error; *last_block = rec.br_startoff + rec.br_blockcount; return 0; } /* * Returns whether the selected fork of the inode has exactly one * block or not. For the data fork we check this matches di_size, * implying the file's range is 0..bsize-1. */ int /* 1=>1 block, 0=>otherwise */ xfs_bmap_one_block( xfs_inode_t *ip, /* incore inode */ int whichfork) /* data or attr fork */ { xfs_bmbt_rec_host_t *ep; /* ptr to fork's extent */ xfs_ifork_t *ifp; /* inode fork pointer */ int rval; /* return value */ xfs_bmbt_irec_t s; /* internal version of extent */ #ifndef DEBUG if (whichfork == XFS_DATA_FORK) return XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize; #endif /* !DEBUG */ if (XFS_IFORK_NEXTENTS(ip, whichfork) != 1) return 0; if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS) return 0; ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT(ifp->if_flags & XFS_IFEXTENTS); ep = xfs_iext_get_ext(ifp, 0); xfs_bmbt_get_all(ep, &s); rval = s.br_startoff == 0 && s.br_blockcount == 1; if (rval && whichfork == XFS_DATA_FORK) ASSERT(XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize); return rval; } STATIC int xfs_bmap_sanity_check( struct xfs_mount *mp, struct xfs_buf *bp, int level) { struct xfs_btree_block *block = XFS_BUF_TO_BLOCK(bp); if (block->bb_magic != cpu_to_be32(XFS_BMAP_MAGIC) || be16_to_cpu(block->bb_level) != level || be16_to_cpu(block->bb_numrecs) == 0 || be16_to_cpu(block->bb_numrecs) > mp->m_bmap_dmxr[level != 0]) return 0; return 1; } /* * Read in the extents to if_extents. * All inode fields are set up by caller, we just traverse the btree * and copy the records in. If the file system cannot contain unwritten * extents, the records are checked for no "state" flags. */ int /* error */ xfs_bmap_read_extents( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode */ int whichfork) /* data or attr fork */ { struct xfs_btree_block *block; /* current btree block */ xfs_fsblock_t bno; /* block # of "block" */ xfs_buf_t *bp; /* buffer for "block" */ int error; /* error return value */ xfs_exntfmt_t exntf; /* XFS_EXTFMT_NOSTATE, if checking */ xfs_extnum_t i, j; /* index into the extents list */ xfs_ifork_t *ifp; /* fork structure */ int level; /* btree level, for checking */ xfs_mount_t *mp; /* file system mount structure */ __be64 *pp; /* pointer to block address */ /* REFERENCED */ xfs_extnum_t room; /* number of entries there's room for */ bno = NULLFSBLOCK; mp = ip->i_mount; ifp = XFS_IFORK_PTR(ip, whichfork); exntf = (whichfork != XFS_DATA_FORK) ? XFS_EXTFMT_NOSTATE : XFS_EXTFMT_INODE(ip); block = ifp->if_broot; /* * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out. */ level = be16_to_cpu(block->bb_level); ASSERT(level > 0); pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes); bno = be64_to_cpu(*pp); ASSERT(bno != NULLDFSBNO); ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount); ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks); /* * Go down the tree until leaf level is reached, following the first * pointer (leftmost) at each level. */ while (level-- > 0) { if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF))) return error; block = XFS_BUF_TO_BLOCK(bp); XFS_WANT_CORRUPTED_GOTO( xfs_bmap_sanity_check(mp, bp, level), error0); if (level == 0) break; pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]); bno = be64_to_cpu(*pp); XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, bno), error0); xfs_trans_brelse(tp, bp); } /* * Here with bp and block set to the leftmost leaf node in the tree. */ room = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); i = 0; /* * Loop over all leaf nodes. Copy information to the extent records. */ for (;;) { xfs_bmbt_rec_t *frp; xfs_fsblock_t nextbno; xfs_extnum_t num_recs; xfs_extnum_t start; num_recs = xfs_btree_get_numrecs(block); if (unlikely(i + num_recs > room)) { ASSERT(i + num_recs <= room); xfs_warn(ip->i_mount, "corrupt dinode %Lu, (btree extents).", (unsigned long long) ip->i_ino); XFS_CORRUPTION_ERROR("xfs_bmap_read_extents(1)", XFS_ERRLEVEL_LOW, ip->i_mount, block); goto error0; } XFS_WANT_CORRUPTED_GOTO( xfs_bmap_sanity_check(mp, bp, 0), error0); /* * Read-ahead the next leaf block, if any. */ nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib); if (nextbno != NULLFSBLOCK) xfs_btree_reada_bufl(mp, nextbno, 1); /* * Copy records into the extent records. */ frp = XFS_BMBT_REC_ADDR(mp, block, 1); start = i; for (j = 0; j < num_recs; j++, i++, frp++) { xfs_bmbt_rec_host_t *trp = xfs_iext_get_ext(ifp, i); trp->l0 = be64_to_cpu(frp->l0); trp->l1 = be64_to_cpu(frp->l1); } if (exntf == XFS_EXTFMT_NOSTATE) { /* * Check all attribute bmap btree records and * any "older" data bmap btree records for a * set bit in the "extent flag" position. */ if (unlikely(xfs_check_nostate_extents(ifp, start, num_recs))) { XFS_ERROR_REPORT("xfs_bmap_read_extents(2)", XFS_ERRLEVEL_LOW, ip->i_mount); goto error0; } } xfs_trans_brelse(tp, bp); bno = nextbno; /* * If we've reached the end, stop. */ if (bno == NULLFSBLOCK) break; if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF))) return error; block = XFS_BUF_TO_BLOCK(bp); } ASSERT(i == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))); ASSERT(i == XFS_IFORK_NEXTENTS(ip, whichfork)); XFS_BMAP_TRACE_EXLIST(ip, i, whichfork); return 0; error0: xfs_trans_brelse(tp, bp); return XFS_ERROR(EFSCORRUPTED); } #ifdef DEBUG /* * Add bmap trace insert entries for all the contents of the extent records. */ void xfs_bmap_trace_exlist( xfs_inode_t *ip, /* incore inode pointer */ xfs_extnum_t cnt, /* count of entries in the list */ int whichfork, /* data or attr fork */ unsigned long caller_ip) { xfs_extnum_t idx; /* extent record index */ xfs_ifork_t *ifp; /* inode fork pointer */ int state = 0; if (whichfork == XFS_ATTR_FORK) state |= BMAP_ATTRFORK; ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT(cnt == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))); for (idx = 0; idx < cnt; idx++) trace_xfs_extlist(ip, idx, whichfork, caller_ip); } /* * Validate that the bmbt_irecs being returned from bmapi are valid * given the callers original parameters. Specifically check the * ranges of the returned irecs to ensure that they only extent beyond * the given parameters if the XFS_BMAPI_ENTIRE flag was set. */ STATIC void xfs_bmap_validate_ret( xfs_fileoff_t bno, xfs_filblks_t len, int flags, xfs_bmbt_irec_t *mval, int nmap, int ret_nmap) { int i; /* index to map values */ ASSERT(ret_nmap <= nmap); for (i = 0; i < ret_nmap; i++) { ASSERT(mval[i].br_blockcount > 0); if (!(flags & XFS_BMAPI_ENTIRE)) { ASSERT(mval[i].br_startoff >= bno); ASSERT(mval[i].br_blockcount <= len); ASSERT(mval[i].br_startoff + mval[i].br_blockcount <= bno + len); } else { ASSERT(mval[i].br_startoff < bno + len); ASSERT(mval[i].br_startoff + mval[i].br_blockcount > bno); } ASSERT(i == 0 || mval[i - 1].br_startoff + mval[i - 1].br_blockcount == mval[i].br_startoff); ASSERT(mval[i].br_startblock != DELAYSTARTBLOCK && mval[i].br_startblock != HOLESTARTBLOCK); ASSERT(mval[i].br_state == XFS_EXT_NORM || mval[i].br_state == XFS_EXT_UNWRITTEN); } } #endif /* DEBUG */ /* * Trim the returned map to the required bounds */ STATIC void xfs_bmapi_trim_map( struct xfs_bmbt_irec *mval, struct xfs_bmbt_irec *got, xfs_fileoff_t *bno, xfs_filblks_t len, xfs_fileoff_t obno, xfs_fileoff_t end, int n, int flags) { if ((flags & XFS_BMAPI_ENTIRE) || got->br_startoff + got->br_blockcount <= obno) { *mval = *got; if (isnullstartblock(got->br_startblock)) mval->br_startblock = DELAYSTARTBLOCK; return; } if (obno > *bno) *bno = obno; ASSERT((*bno >= obno) || (n == 0)); ASSERT(*bno < end); mval->br_startoff = *bno; if (isnullstartblock(got->br_startblock)) mval->br_startblock = DELAYSTARTBLOCK; else mval->br_startblock = got->br_startblock + (*bno - got->br_startoff); /* * Return the minimum of what we got and what we asked for for * the length. We can use the len variable here because it is * modified below and we could have been there before coming * here if the first part of the allocation didn't overlap what * was asked for. */ mval->br_blockcount = XFS_FILBLKS_MIN(end - *bno, got->br_blockcount - (*bno - got->br_startoff)); mval->br_state = got->br_state; ASSERT(mval->br_blockcount <= len); return; } /* * Update and validate the extent map to return */ STATIC void xfs_bmapi_update_map( struct xfs_bmbt_irec **map, xfs_fileoff_t *bno, xfs_filblks_t *len, xfs_fileoff_t obno, xfs_fileoff_t end, int *n, int flags) { xfs_bmbt_irec_t *mval = *map; ASSERT((flags & XFS_BMAPI_ENTIRE) || ((mval->br_startoff + mval->br_blockcount) <= end)); ASSERT((flags & XFS_BMAPI_ENTIRE) || (mval->br_blockcount <= *len) || (mval->br_startoff < obno)); *bno = mval->br_startoff + mval->br_blockcount; *len = end - *bno; if (*n > 0 && mval->br_startoff == mval[-1].br_startoff) { /* update previous map with new information */ ASSERT(mval->br_startblock == mval[-1].br_startblock); ASSERT(mval->br_blockcount > mval[-1].br_blockcount); ASSERT(mval->br_state == mval[-1].br_state); mval[-1].br_blockcount = mval->br_blockcount; mval[-1].br_state = mval->br_state; } else if (*n > 0 && mval->br_startblock != DELAYSTARTBLOCK && mval[-1].br_startblock != DELAYSTARTBLOCK && mval[-1].br_startblock != HOLESTARTBLOCK && mval->br_startblock == mval[-1].br_startblock + mval[-1].br_blockcount && ((flags & XFS_BMAPI_IGSTATE) || mval[-1].br_state == mval->br_state)) { ASSERT(mval->br_startoff == mval[-1].br_startoff + mval[-1].br_blockcount); mval[-1].br_blockcount += mval->br_blockcount; } else if (*n > 0 && mval->br_startblock == DELAYSTARTBLOCK && mval[-1].br_startblock == DELAYSTARTBLOCK && mval->br_startoff == mval[-1].br_startoff + mval[-1].br_blockcount) { mval[-1].br_blockcount += mval->br_blockcount; mval[-1].br_state = mval->br_state; } else if (!((*n == 0) && ((mval->br_startoff + mval->br_blockcount) <= obno))) { mval++; (*n)++; } *map = mval; } /* * Map file blocks to filesystem blocks without allocation. */ int xfs_bmapi_read( struct xfs_inode *ip, xfs_fileoff_t bno, xfs_filblks_t len, struct xfs_bmbt_irec *mval, int *nmap, int flags) { struct xfs_mount *mp = ip->i_mount; struct xfs_ifork *ifp; struct xfs_bmbt_irec got; struct xfs_bmbt_irec prev; xfs_fileoff_t obno; xfs_fileoff_t end; xfs_extnum_t lastx; int error; int eof; int n = 0; int whichfork = (flags & XFS_BMAPI_ATTRFORK) ? XFS_ATTR_FORK : XFS_DATA_FORK; ASSERT(*nmap >= 1); ASSERT(!(flags & ~(XFS_BMAPI_ATTRFORK|XFS_BMAPI_ENTIRE| XFS_BMAPI_IGSTATE))); if (unlikely(XFS_TEST_ERROR( (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE), mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) { XFS_ERROR_REPORT("xfs_bmapi_read", XFS_ERRLEVEL_LOW, mp); return XFS_ERROR(EFSCORRUPTED); } if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); XFS_STATS_INC(xs_blk_mapr); ifp = XFS_IFORK_PTR(ip, whichfork); if (!(ifp->if_flags & XFS_IFEXTENTS)) { error = xfs_iread_extents(NULL, ip, whichfork); if (error) return error; } xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got, &prev); end = bno + len; obno = bno; while (bno < end && n < *nmap) { /* Reading past eof, act as though there's a hole up to end. */ if (eof) got.br_startoff = end; if (got.br_startoff > bno) { /* Reading in a hole. */ mval->br_startoff = bno; mval->br_startblock = HOLESTARTBLOCK; mval->br_blockcount = XFS_FILBLKS_MIN(len, got.br_startoff - bno); mval->br_state = XFS_EXT_NORM; bno += mval->br_blockcount; len -= mval->br_blockcount; mval++; n++; continue; } /* set up the extent map to return. */ xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags); xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags); /* If we're done, stop now. */ if (bno >= end || n >= *nmap) break; /* Else go on to the next record. */ if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)) xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got); else eof = 1; } *nmap = n; return 0; } STATIC int xfs_bmapi_reserve_delalloc( struct xfs_inode *ip, xfs_fileoff_t aoff, xfs_filblks_t len, struct xfs_bmbt_irec *got, struct xfs_bmbt_irec *prev, xfs_extnum_t *lastx, int eof) { struct xfs_mount *mp = ip->i_mount; struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK); xfs_extlen_t alen; xfs_extlen_t indlen; char rt = XFS_IS_REALTIME_INODE(ip); xfs_extlen_t extsz; int error; alen = XFS_FILBLKS_MIN(len, MAXEXTLEN); if (!eof) alen = XFS_FILBLKS_MIN(alen, got->br_startoff - aoff); /* Figure out the extent size, adjust alen */ extsz = xfs_get_extsz_hint(ip); if (extsz) { /* * Make sure we don't exceed a single extent length when we * align the extent by reducing length we are going to * allocate by the maximum amount extent size aligment may * require. */ alen = XFS_FILBLKS_MIN(len, MAXEXTLEN - (2 * extsz - 1)); error = xfs_bmap_extsize_align(mp, got, prev, extsz, rt, eof, 1, 0, &aoff, &alen); ASSERT(!error); } if (rt) extsz = alen / mp->m_sb.sb_rextsize; /* * Make a transaction-less quota reservation for delayed allocation * blocks. This number gets adjusted later. We return if we haven't * allocated blocks already inside this loop. */ error = xfs_trans_reserve_quota_nblks(NULL, ip, (long)alen, 0, rt ? XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS); if (error) return error; /* * Split changing sb for alen and indlen since they could be coming * from different places. */ indlen = (xfs_extlen_t)xfs_bmap_worst_indlen(ip, alen); ASSERT(indlen > 0); if (rt) { error = xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS, -((int64_t)extsz), 0); } else { error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, -((int64_t)alen), 0); } if (error) goto out_unreserve_quota; error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, -((int64_t)indlen), 0); if (error) goto out_unreserve_blocks; ip->i_delayed_blks += alen; got->br_startoff = aoff; got->br_startblock = nullstartblock(indlen); got->br_blockcount = alen; got->br_state = XFS_EXT_NORM; xfs_bmap_add_extent_hole_delay(ip, lastx, got); /* * Update our extent pointer, given that xfs_bmap_add_extent_hole_delay * might have merged it into one of the neighbouring ones. */ xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *lastx), got); ASSERT(got->br_startoff <= aoff); ASSERT(got->br_startoff + got->br_blockcount >= aoff + alen); ASSERT(isnullstartblock(got->br_startblock)); ASSERT(got->br_state == XFS_EXT_NORM); return 0; out_unreserve_blocks: if (rt) xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS, extsz, 0); else xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, alen, 0); out_unreserve_quota: if (XFS_IS_QUOTA_ON(mp)) xfs_trans_unreserve_quota_nblks(NULL, ip, alen, 0, rt ? XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS); return error; } /* * Map file blocks to filesystem blocks, adding delayed allocations as needed. */ int xfs_bmapi_delay( struct xfs_inode *ip, /* incore inode */ xfs_fileoff_t bno, /* starting file offs. mapped */ xfs_filblks_t len, /* length to map in file */ struct xfs_bmbt_irec *mval, /* output: map values */ int *nmap, /* i/o: mval size/count */ int flags) /* XFS_BMAPI_... */ { struct xfs_mount *mp = ip->i_mount; struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK); struct xfs_bmbt_irec got; /* current file extent record */ struct xfs_bmbt_irec prev; /* previous file extent record */ xfs_fileoff_t obno; /* old block number (offset) */ xfs_fileoff_t end; /* end of mapped file region */ xfs_extnum_t lastx; /* last useful extent number */ int eof; /* we've hit the end of extents */ int n = 0; /* current extent index */ int error = 0; ASSERT(*nmap >= 1); ASSERT(*nmap <= XFS_BMAP_MAX_NMAP); ASSERT(!(flags & ~XFS_BMAPI_ENTIRE)); if (unlikely(XFS_TEST_ERROR( (XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_EXTENTS && XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_BTREE), mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) { XFS_ERROR_REPORT("xfs_bmapi_delay", XFS_ERRLEVEL_LOW, mp); return XFS_ERROR(EFSCORRUPTED); } if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); XFS_STATS_INC(xs_blk_mapw); if (!(ifp->if_flags & XFS_IFEXTENTS)) { error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK); if (error) return error; } xfs_bmap_search_extents(ip, bno, XFS_DATA_FORK, &eof, &lastx, &got, &prev); end = bno + len; obno = bno; while (bno < end && n < *nmap) { if (eof || got.br_startoff > bno) { error = xfs_bmapi_reserve_delalloc(ip, bno, len, &got, &prev, &lastx, eof); if (error) { if (n == 0) { *nmap = 0; return error; } break; } } /* set up the extent map to return. */ xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags); xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags); /* If we're done, stop now. */ if (bno >= end || n >= *nmap) break; /* Else go on to the next record. */ prev = got; if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)) xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got); else eof = 1; } *nmap = n; return 0; } STATIC int xfs_bmapi_allocate( struct xfs_bmalloca *bma, int flags) { struct xfs_mount *mp = bma->ip->i_mount; int whichfork = (flags & XFS_BMAPI_ATTRFORK) ? XFS_ATTR_FORK : XFS_DATA_FORK; struct xfs_ifork *ifp = XFS_IFORK_PTR(bma->ip, whichfork); int tmp_logflags = 0; int error; int rt; ASSERT(bma->length > 0); rt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(bma->ip); /* * For the wasdelay case, we could also just allocate the stuff asked * for in this bmap call but that wouldn't be as good. */ if (bma->wasdel) { bma->length = (xfs_extlen_t)bma->got.br_blockcount; bma->offset = bma->got.br_startoff; if (bma->idx != NULLEXTNUM && bma->idx) { xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &bma->prev); } } else { bma->length = XFS_FILBLKS_MIN(bma->length, MAXEXTLEN); if (!bma->eof) bma->length = XFS_FILBLKS_MIN(bma->length, bma->got.br_startoff - bma->offset); } /* * Indicate if this is the first user data in the file, or just any * user data. */ if (!(flags & XFS_BMAPI_METADATA)) { bma->userdata = (bma->offset == 0) ? XFS_ALLOC_INITIAL_USER_DATA : XFS_ALLOC_USERDATA; } bma->minlen = (flags & XFS_BMAPI_CONTIG) ? bma->length : 1; /* * Only want to do the alignment at the eof if it is userdata and * allocation length is larger than a stripe unit. */ if (mp->m_dalign && bma->length >= mp->m_dalign && !(flags & XFS_BMAPI_METADATA) && whichfork == XFS_DATA_FORK) { error = xfs_bmap_isaeof(bma, whichfork); if (error) return error; } error = xfs_bmap_alloc(bma); if (error) return error; if (bma->flist->xbf_low) bma->minleft = 0; if (bma->cur) bma->cur->bc_private.b.firstblock = *bma->firstblock; if (bma->blkno == NULLFSBLOCK) return 0; if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) { bma->cur = xfs_bmbt_init_cursor(mp, bma->tp, bma->ip, whichfork); bma->cur->bc_private.b.firstblock = *bma->firstblock; bma->cur->bc_private.b.flist = bma->flist; } /* * Bump the number of extents we've allocated * in this call. */ bma->nallocs++; if (bma->cur) bma->cur->bc_private.b.flags = bma->wasdel ? XFS_BTCUR_BPRV_WASDEL : 0; bma->got.br_startoff = bma->offset; bma->got.br_startblock = bma->blkno; bma->got.br_blockcount = bma->length; bma->got.br_state = XFS_EXT_NORM; /* * A wasdelay extent has been initialized, so shouldn't be flagged * as unwritten. */ if (!bma->wasdel && (flags & XFS_BMAPI_PREALLOC) && xfs_sb_version_hasextflgbit(&mp->m_sb)) bma->got.br_state = XFS_EXT_UNWRITTEN; if (bma->wasdel) error = xfs_bmap_add_extent_delay_real(bma); else error = xfs_bmap_add_extent_hole_real(bma, whichfork); bma->logflags |= tmp_logflags; if (error) return error; /* * Update our extent pointer, given that xfs_bmap_add_extent_delay_real * or xfs_bmap_add_extent_hole_real might have merged it into one of * the neighbouring ones. */ xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got); ASSERT(bma->got.br_startoff <= bma->offset); ASSERT(bma->got.br_startoff + bma->got.br_blockcount >= bma->offset + bma->length); ASSERT(bma->got.br_state == XFS_EXT_NORM || bma->got.br_state == XFS_EXT_UNWRITTEN); return 0; } STATIC int xfs_bmapi_convert_unwritten( struct xfs_bmalloca *bma, struct xfs_bmbt_irec *mval, xfs_filblks_t len, int flags) { int whichfork = (flags & XFS_BMAPI_ATTRFORK) ? XFS_ATTR_FORK : XFS_DATA_FORK; struct xfs_ifork *ifp = XFS_IFORK_PTR(bma->ip, whichfork); int tmp_logflags = 0; int error; /* check if we need to do unwritten->real conversion */ if (mval->br_state == XFS_EXT_UNWRITTEN && (flags & XFS_BMAPI_PREALLOC)) return 0; /* check if we need to do real->unwritten conversion */ if (mval->br_state == XFS_EXT_NORM && (flags & (XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT)) != (XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT)) return 0; /* * Modify (by adding) the state flag, if writing. */ ASSERT(mval->br_blockcount <= len); if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) { bma->cur = xfs_bmbt_init_cursor(bma->ip->i_mount, bma->tp, bma->ip, whichfork); bma->cur->bc_private.b.firstblock = *bma->firstblock; bma->cur->bc_private.b.flist = bma->flist; } mval->br_state = (mval->br_state == XFS_EXT_UNWRITTEN) ? XFS_EXT_NORM : XFS_EXT_UNWRITTEN; error = xfs_bmap_add_extent_unwritten_real(bma->tp, bma->ip, &bma->idx, &bma->cur, mval, bma->firstblock, bma->flist, &tmp_logflags); bma->logflags |= tmp_logflags; if (error) return error; /* * Update our extent pointer, given that * xfs_bmap_add_extent_unwritten_real might have merged it into one * of the neighbouring ones. */ xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got); /* * We may have combined previously unwritten space with written space, * so generate another request. */ if (mval->br_blockcount < len) return EAGAIN; return 0; } /* * Map file blocks to filesystem blocks, and allocate blocks or convert the * extent state if necessary. Details behaviour is controlled by the flags * parameter. Only allocates blocks from a single allocation group, to avoid * locking problems. * * The returned value in "firstblock" from the first call in a transaction * must be remembered and presented to subsequent calls in "firstblock". * An upper bound for the number of blocks to be allocated is supplied to * the first call in "total"; if no allocation group has that many free * blocks then the call will fail (return NULLFSBLOCK in "firstblock"). */ int xfs_bmapi_write( struct xfs_trans *tp, /* transaction pointer */ struct xfs_inode *ip, /* incore inode */ xfs_fileoff_t bno, /* starting file offs. mapped */ xfs_filblks_t len, /* length to map in file */ int flags, /* XFS_BMAPI_... */ xfs_fsblock_t *firstblock, /* first allocated block controls a.g. for allocs */ xfs_extlen_t total, /* total blocks needed */ struct xfs_bmbt_irec *mval, /* output: map values */ int *nmap, /* i/o: mval size/count */ struct xfs_bmap_free *flist) /* i/o: list extents to free */ { struct xfs_mount *mp = ip->i_mount; struct xfs_ifork *ifp; struct xfs_bmalloca bma = { 0 }; /* args for xfs_bmap_alloc */ xfs_fileoff_t end; /* end of mapped file region */ int eof; /* after the end of extents */ int error; /* error return */ int n; /* current extent index */ xfs_fileoff_t obno; /* old block number (offset) */ int whichfork; /* data or attr fork */ char inhole; /* current location is hole in file */ char wasdelay; /* old extent was delayed */ #ifdef DEBUG xfs_fileoff_t orig_bno; /* original block number value */ int orig_flags; /* original flags arg value */ xfs_filblks_t orig_len; /* original value of len arg */ struct xfs_bmbt_irec *orig_mval; /* original value of mval */ int orig_nmap; /* original value of *nmap */ orig_bno = bno; orig_len = len; orig_flags = flags; orig_mval = mval; orig_nmap = *nmap; #endif ASSERT(*nmap >= 1); ASSERT(*nmap <= XFS_BMAP_MAX_NMAP); ASSERT(!(flags & XFS_BMAPI_IGSTATE)); ASSERT(tp != NULL); ASSERT(len > 0); whichfork = (flags & XFS_BMAPI_ATTRFORK) ? XFS_ATTR_FORK : XFS_DATA_FORK; if (unlikely(XFS_TEST_ERROR( (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL), mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) { XFS_ERROR_REPORT("xfs_bmapi_write", XFS_ERRLEVEL_LOW, mp); return XFS_ERROR(EFSCORRUPTED); } if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); ifp = XFS_IFORK_PTR(ip, whichfork); XFS_STATS_INC(xs_blk_mapw); if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) { error = xfs_bmap_local_to_extents(tp, ip, firstblock, total, &bma.logflags, whichfork); if (error) goto error0; } if (*firstblock == NULLFSBLOCK) { if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE) bma.minleft = be16_to_cpu(ifp->if_broot->bb_level) + 1; else bma.minleft = 1; } else { bma.minleft = 0; } if (!(ifp->if_flags & XFS_IFEXTENTS)) { error = xfs_iread_extents(tp, ip, whichfork); if (error) goto error0; } xfs_bmap_search_extents(ip, bno, whichfork, &eof, &bma.idx, &bma.got, &bma.prev); n = 0; end = bno + len; obno = bno; bma.tp = tp; bma.ip = ip; bma.total = total; bma.userdata = 0; bma.flist = flist; bma.firstblock = firstblock; while (bno < end && n < *nmap) { inhole = eof || bma.got.br_startoff > bno; wasdelay = !inhole && isnullstartblock(bma.got.br_startblock); /* * First, deal with the hole before the allocated space * that we found, if any. */ if (inhole || wasdelay) { bma.eof = eof; bma.conv = !!(flags & XFS_BMAPI_CONVERT); bma.wasdel = wasdelay; bma.offset = bno; /* * There's a 32/64 bit type mismatch between the * allocation length request (which can be 64 bits in * length) and the bma length request, which is * xfs_extlen_t and therefore 32 bits. Hence we have to * check for 32-bit overflows and handle them here. */ if (len > (xfs_filblks_t)MAXEXTLEN) bma.length = MAXEXTLEN; else bma.length = len; ASSERT(len > 0); ASSERT(bma.length > 0); error = xfs_bmapi_allocate(&bma, flags); if (error) goto error0; if (bma.blkno == NULLFSBLOCK) break; } /* Deal with the allocated space we found. */ xfs_bmapi_trim_map(mval, &bma.got, &bno, len, obno, end, n, flags); /* Execute unwritten extent conversion if necessary */ error = xfs_bmapi_convert_unwritten(&bma, mval, len, flags); if (error == EAGAIN) continue; if (error) goto error0; /* update the extent map to return */ xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags); /* * If we're done, stop now. Stop when we've allocated * XFS_BMAP_MAX_NMAP extents no matter what. Otherwise * the transaction may get too big. */ if (bno >= end || n >= *nmap || bma.nallocs >= *nmap) break; /* Else go on to the next record. */ bma.prev = bma.got; if (++bma.idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)) { xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma.idx), &bma.got); } else eof = 1; } *nmap = n; /* * Transform from btree to extents, give it cur. */ if (xfs_bmap_wants_extents(ip, whichfork)) { int tmp_logflags = 0; ASSERT(bma.cur); error = xfs_bmap_btree_to_extents(tp, ip, bma.cur, &tmp_logflags, whichfork); bma.logflags |= tmp_logflags; if (error) goto error0; } ASSERT(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE || XFS_IFORK_NEXTENTS(ip, whichfork) > XFS_IFORK_MAXEXT(ip, whichfork)); error = 0; error0: /* * Log everything. Do this after conversion, there's no point in * logging the extent records if we've converted to btree format. */ if ((bma.logflags & xfs_ilog_fext(whichfork)) && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS) bma.logflags &= ~xfs_ilog_fext(whichfork); else if ((bma.logflags & xfs_ilog_fbroot(whichfork)) && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) bma.logflags &= ~xfs_ilog_fbroot(whichfork); /* * Log whatever the flags say, even if error. Otherwise we might miss * detecting a case where the data is changed, there's an error, * and it's not logged so we don't shutdown when we should. */ if (bma.logflags) xfs_trans_log_inode(tp, ip, bma.logflags); if (bma.cur) { if (!error) { ASSERT(*firstblock == NULLFSBLOCK || XFS_FSB_TO_AGNO(mp, *firstblock) == XFS_FSB_TO_AGNO(mp, bma.cur->bc_private.b.firstblock) || (flist->xbf_low && XFS_FSB_TO_AGNO(mp, *firstblock) < XFS_FSB_TO_AGNO(mp, bma.cur->bc_private.b.firstblock))); *firstblock = bma.cur->bc_private.b.firstblock; } xfs_btree_del_cursor(bma.cur, error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR); } if (!error) xfs_bmap_validate_ret(orig_bno, orig_len, orig_flags, orig_mval, orig_nmap, *nmap); return error; } /* * Unmap (remove) blocks from a file. * If nexts is nonzero then the number of extents to remove is limited to * that value. If not all extents in the block range can be removed then * *done is set. */ int /* error */ xfs_bunmapi( xfs_trans_t *tp, /* transaction pointer */ struct xfs_inode *ip, /* incore inode */ xfs_fileoff_t bno, /* starting offset to unmap */ xfs_filblks_t len, /* length to unmap in file */ int flags, /* misc flags */ xfs_extnum_t nexts, /* number of extents max */ xfs_fsblock_t *firstblock, /* first allocated block controls a.g. for allocs */ xfs_bmap_free_t *flist, /* i/o: list extents to free */ int *done) /* set if not done yet */ { xfs_btree_cur_t *cur; /* bmap btree cursor */ xfs_bmbt_irec_t del; /* extent being deleted */ int eof; /* is deleting at eof */ xfs_bmbt_rec_host_t *ep; /* extent record pointer */ int error; /* error return value */ xfs_extnum_t extno; /* extent number in list */ xfs_bmbt_irec_t got; /* current extent record */ xfs_ifork_t *ifp; /* inode fork pointer */ int isrt; /* freeing in rt area */ xfs_extnum_t lastx; /* last extent index used */ int logflags; /* transaction logging flags */ xfs_extlen_t mod; /* rt extent offset */ xfs_mount_t *mp; /* mount structure */ xfs_extnum_t nextents; /* number of file extents */ xfs_bmbt_irec_t prev; /* previous extent record */ xfs_fileoff_t start; /* first file offset deleted */ int tmp_logflags; /* partial logging flags */ int wasdel; /* was a delayed alloc extent */ int whichfork; /* data or attribute fork */ xfs_fsblock_t sum; trace_xfs_bunmap(ip, bno, len, flags, _RET_IP_); whichfork = (flags & XFS_BMAPI_ATTRFORK) ? XFS_ATTR_FORK : XFS_DATA_FORK; ifp = XFS_IFORK_PTR(ip, whichfork); if (unlikely( XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) { XFS_ERROR_REPORT("xfs_bunmapi", XFS_ERRLEVEL_LOW, ip->i_mount); return XFS_ERROR(EFSCORRUPTED); } mp = ip->i_mount; if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); ASSERT(len > 0); ASSERT(nexts >= 0); if (!(ifp->if_flags & XFS_IFEXTENTS) && (error = xfs_iread_extents(tp, ip, whichfork))) return error; nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); if (nextents == 0) { *done = 1; return 0; } XFS_STATS_INC(xs_blk_unmap); isrt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip); start = bno; bno = start + len - 1; ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got, &prev); /* * Check to see if the given block number is past the end of the * file, back up to the last block if so... */ if (eof) { ep = xfs_iext_get_ext(ifp, --lastx); xfs_bmbt_get_all(ep, &got); bno = got.br_startoff + got.br_blockcount - 1; } logflags = 0; if (ifp->if_flags & XFS_IFBROOT) { ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE); cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork); cur->bc_private.b.firstblock = *firstblock; cur->bc_private.b.flist = flist; cur->bc_private.b.flags = 0; } else cur = NULL; if (isrt) { /* * Synchronize by locking the bitmap inode. */ xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL); xfs_trans_ijoin(tp, mp->m_rbmip, XFS_ILOCK_EXCL); } extno = 0; while (bno != (xfs_fileoff_t)-1 && bno >= start && lastx >= 0 && (nexts == 0 || extno < nexts)) { /* * Is the found extent after a hole in which bno lives? * Just back up to the previous extent, if so. */ if (got.br_startoff > bno) { if (--lastx < 0) break; ep = xfs_iext_get_ext(ifp, lastx); xfs_bmbt_get_all(ep, &got); } /* * Is the last block of this extent before the range * we're supposed to delete? If so, we're done. */ bno = XFS_FILEOFF_MIN(bno, got.br_startoff + got.br_blockcount - 1); if (bno < start) break; /* * Then deal with the (possibly delayed) allocated space * we found. */ ASSERT(ep != NULL); del = got; wasdel = isnullstartblock(del.br_startblock); if (got.br_startoff < start) { del.br_startoff = start; del.br_blockcount -= start - got.br_startoff; if (!wasdel) del.br_startblock += start - got.br_startoff; } if (del.br_startoff + del.br_blockcount > bno + 1) del.br_blockcount = bno + 1 - del.br_startoff; sum = del.br_startblock + del.br_blockcount; if (isrt && (mod = do_mod(sum, mp->m_sb.sb_rextsize))) { /* * Realtime extent not lined up at the end. * The extent could have been split into written * and unwritten pieces, or we could just be * unmapping part of it. But we can't really * get rid of part of a realtime extent. */ if (del.br_state == XFS_EXT_UNWRITTEN || !xfs_sb_version_hasextflgbit(&mp->m_sb)) { /* * This piece is unwritten, or we're not * using unwritten extents. Skip over it. */ ASSERT(bno >= mod); bno -= mod > del.br_blockcount ? del.br_blockcount : mod; if (bno < got.br_startoff) { if (--lastx >= 0) xfs_bmbt_get_all(xfs_iext_get_ext( ifp, lastx), &got); } continue; } /* * It's written, turn it unwritten. * This is better than zeroing it. */ ASSERT(del.br_state == XFS_EXT_NORM); ASSERT(xfs_trans_get_block_res(tp) > 0); /* * If this spans a realtime extent boundary, * chop it back to the start of the one we end at. */ if (del.br_blockcount > mod) { del.br_startoff += del.br_blockcount - mod; del.br_startblock += del.br_blockcount - mod; del.br_blockcount = mod; } del.br_state = XFS_EXT_UNWRITTEN; error = xfs_bmap_add_extent_unwritten_real(tp, ip, &lastx, &cur, &del, firstblock, flist, &logflags); if (error) goto error0; goto nodelete; } if (isrt && (mod = do_mod(del.br_startblock, mp->m_sb.sb_rextsize))) { /* * Realtime extent is lined up at the end but not * at the front. We'll get rid of full extents if * we can. */ mod = mp->m_sb.sb_rextsize - mod; if (del.br_blockcount > mod) { del.br_blockcount -= mod; del.br_startoff += mod; del.br_startblock += mod; } else if ((del.br_startoff == start && (del.br_state == XFS_EXT_UNWRITTEN || xfs_trans_get_block_res(tp) == 0)) || !xfs_sb_version_hasextflgbit(&mp->m_sb)) { /* * Can't make it unwritten. There isn't * a full extent here so just skip it. */ ASSERT(bno >= del.br_blockcount); bno -= del.br_blockcount; if (got.br_startoff > bno) { if (--lastx >= 0) { ep = xfs_iext_get_ext(ifp, lastx); xfs_bmbt_get_all(ep, &got); } } continue; } else if (del.br_state == XFS_EXT_UNWRITTEN) { /* * This one is already unwritten. * It must have a written left neighbor. * Unwrite the killed part of that one and * try again. */ ASSERT(lastx > 0); xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx - 1), &prev); ASSERT(prev.br_state == XFS_EXT_NORM); ASSERT(!isnullstartblock(prev.br_startblock)); ASSERT(del.br_startblock == prev.br_startblock + prev.br_blockcount); if (prev.br_startoff < start) { mod = start - prev.br_startoff; prev.br_blockcount -= mod; prev.br_startblock += mod; prev.br_startoff = start; } prev.br_state = XFS_EXT_UNWRITTEN; lastx--; error = xfs_bmap_add_extent_unwritten_real(tp, ip, &lastx, &cur, &prev, firstblock, flist, &logflags); if (error) goto error0; goto nodelete; } else { ASSERT(del.br_state == XFS_EXT_NORM); del.br_state = XFS_EXT_UNWRITTEN; error = xfs_bmap_add_extent_unwritten_real(tp, ip, &lastx, &cur, &del, firstblock, flist, &logflags); if (error) goto error0; goto nodelete; } } if (wasdel) { ASSERT(startblockval(del.br_startblock) > 0); /* Update realtime/data freespace, unreserve quota */ if (isrt) { xfs_filblks_t rtexts; rtexts = XFS_FSB_TO_B(mp, del.br_blockcount); do_div(rtexts, mp->m_sb.sb_rextsize); xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS, (int64_t)rtexts, 0); (void)xfs_trans_reserve_quota_nblks(NULL, ip, -((long)del.br_blockcount), 0, XFS_QMOPT_RES_RTBLKS); } else { xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, (int64_t)del.br_blockcount, 0); (void)xfs_trans_reserve_quota_nblks(NULL, ip, -((long)del.br_blockcount), 0, XFS_QMOPT_RES_REGBLKS); } ip->i_delayed_blks -= del.br_blockcount; if (cur) cur->bc_private.b.flags |= XFS_BTCUR_BPRV_WASDEL; } else if (cur) cur->bc_private.b.flags &= ~XFS_BTCUR_BPRV_WASDEL; /* * If it's the case where the directory code is running * with no block reservation, and the deleted block is in * the middle of its extent, and the resulting insert * of an extent would cause transformation to btree format, * then reject it. The calling code will then swap * blocks around instead. * We have to do this now, rather than waiting for the * conversion to btree format, since the transaction * will be dirty. */ if (!wasdel && xfs_trans_get_block_res(tp) == 0 && XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS && XFS_IFORK_NEXTENTS(ip, whichfork) >= /* Note the >= */ XFS_IFORK_MAXEXT(ip, whichfork) && del.br_startoff > got.br_startoff && del.br_startoff + del.br_blockcount < got.br_startoff + got.br_blockcount) { error = XFS_ERROR(ENOSPC); goto error0; } error = xfs_bmap_del_extent(ip, tp, &lastx, flist, cur, &del, &tmp_logflags, whichfork); logflags |= tmp_logflags; if (error) goto error0; bno = del.br_startoff - 1; nodelete: /* * If not done go on to the next (previous) record. */ if (bno != (xfs_fileoff_t)-1 && bno >= start) { if (lastx >= 0) { ep = xfs_iext_get_ext(ifp, lastx); if (xfs_bmbt_get_startoff(ep) > bno) { if (--lastx >= 0) ep = xfs_iext_get_ext(ifp, lastx); } xfs_bmbt_get_all(ep, &got); } extno++; } } *done = bno == (xfs_fileoff_t)-1 || bno < start || lastx < 0; /* * Convert to a btree if necessary. */ if (xfs_bmap_needs_btree(ip, whichfork)) { ASSERT(cur == NULL); error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist, &cur, 0, &tmp_logflags, whichfork); logflags |= tmp_logflags; if (error) goto error0; } /* * transform from btree to extents, give it cur */ else if (xfs_bmap_wants_extents(ip, whichfork)) { ASSERT(cur != NULL); error = xfs_bmap_btree_to_extents(tp, ip, cur, &tmp_logflags, whichfork); logflags |= tmp_logflags; if (error) goto error0; } /* * transform from extents to local? */ error = 0; error0: /* * Log everything. Do this after conversion, there's no point in * logging the extent records if we've converted to btree format. */ if ((logflags & xfs_ilog_fext(whichfork)) && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS) logflags &= ~xfs_ilog_fext(whichfork); else if ((logflags & xfs_ilog_fbroot(whichfork)) && XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) logflags &= ~xfs_ilog_fbroot(whichfork); /* * Log inode even in the error case, if the transaction * is dirty we'll need to shut down the filesystem. */ if (logflags) xfs_trans_log_inode(tp, ip, logflags); if (cur) { if (!error) { *firstblock = cur->bc_private.b.firstblock; cur->bc_private.b.allocated = 0; } xfs_btree_del_cursor(cur, error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR); } return error; } /* * returns 1 for success, 0 if we failed to map the extent. */ STATIC int xfs_getbmapx_fix_eof_hole( xfs_inode_t *ip, /* xfs incore inode pointer */ struct getbmapx *out, /* output structure */ int prealloced, /* this is a file with * preallocated data space */ __int64_t end, /* last block requested */ xfs_fsblock_t startblock) { __int64_t fixlen; xfs_mount_t *mp; /* file system mount point */ xfs_ifork_t *ifp; /* inode fork pointer */ xfs_extnum_t lastx; /* last extent pointer */ xfs_fileoff_t fileblock; if (startblock == HOLESTARTBLOCK) { mp = ip->i_mount; out->bmv_block = -1; fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, XFS_ISIZE(ip))); fixlen -= out->bmv_offset; if (prealloced && out->bmv_offset + out->bmv_length == end) { /* Came to hole at EOF. Trim it. */ if (fixlen <= 0) return 0; out->bmv_length = fixlen; } } else { if (startblock == DELAYSTARTBLOCK) out->bmv_block = -2; else out->bmv_block = xfs_fsb_to_db(ip, startblock); fileblock = XFS_BB_TO_FSB(ip->i_mount, out->bmv_offset); ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK); if (xfs_iext_bno_to_ext(ifp, fileblock, &lastx) && (lastx == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))-1)) out->bmv_oflags |= BMV_OF_LAST; } return 1; } /* * Get inode's extents as described in bmv, and format for output. * Calls formatter to fill the user's buffer until all extents * are mapped, until the passed-in bmv->bmv_count slots have * been filled, or until the formatter short-circuits the loop, * if it is tracking filled-in extents on its own. */ int /* error code */ xfs_getbmap( xfs_inode_t *ip, struct getbmapx *bmv, /* user bmap structure */ xfs_bmap_format_t formatter, /* format to user */ void *arg) /* formatter arg */ { __int64_t bmvend; /* last block requested */ int error = 0; /* return value */ __int64_t fixlen; /* length for -1 case */ int i; /* extent number */ int lock; /* lock state */ xfs_bmbt_irec_t *map; /* buffer for user's data */ xfs_mount_t *mp; /* file system mount point */ int nex; /* # of user extents can do */ int nexleft; /* # of user extents left */ int subnex; /* # of bmapi's can do */ int nmap; /* number of map entries */ struct getbmapx *out; /* output structure */ int whichfork; /* data or attr fork */ int prealloced; /* this is a file with * preallocated data space */ int iflags; /* interface flags */ int bmapi_flags; /* flags for xfs_bmapi */ int cur_ext = 0; mp = ip->i_mount; iflags = bmv->bmv_iflags; whichfork = iflags & BMV_IF_ATTRFORK ? XFS_ATTR_FORK : XFS_DATA_FORK; if (whichfork == XFS_ATTR_FORK) { if (XFS_IFORK_Q(ip)) { if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS && ip->i_d.di_aformat != XFS_DINODE_FMT_BTREE && ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL) return XFS_ERROR(EINVAL); } else if (unlikely( ip->i_d.di_aformat != 0 && ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS)) { XFS_ERROR_REPORT("xfs_getbmap", XFS_ERRLEVEL_LOW, ip->i_mount); return XFS_ERROR(EFSCORRUPTED); } prealloced = 0; fixlen = 1LL << 32; } else { if (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS && ip->i_d.di_format != XFS_DINODE_FMT_BTREE && ip->i_d.di_format != XFS_DINODE_FMT_LOCAL) return XFS_ERROR(EINVAL); if (xfs_get_extsz_hint(ip) || ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC|XFS_DIFLAG_APPEND)){ prealloced = 1; fixlen = XFS_MAXIOFFSET(mp); } else { prealloced = 0; fixlen = XFS_ISIZE(ip); } } if (bmv->bmv_length == -1) { fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, fixlen)); bmv->bmv_length = max_t(__int64_t, fixlen - bmv->bmv_offset, 0); } else if (bmv->bmv_length == 0) { bmv->bmv_entries = 0; return 0; } else if (bmv->bmv_length < 0) { return XFS_ERROR(EINVAL); } nex = bmv->bmv_count - 1; if (nex <= 0) return XFS_ERROR(EINVAL); bmvend = bmv->bmv_offset + bmv->bmv_length; if (bmv->bmv_count > ULONG_MAX / sizeof(struct getbmapx)) return XFS_ERROR(ENOMEM); out = kmem_zalloc(bmv->bmv_count * sizeof(struct getbmapx), KM_MAYFAIL); if (!out) { out = kmem_zalloc_large(bmv->bmv_count * sizeof(struct getbmapx)); if (!out) return XFS_ERROR(ENOMEM); } xfs_ilock(ip, XFS_IOLOCK_SHARED); if (whichfork == XFS_DATA_FORK && !(iflags & BMV_IF_DELALLOC)) { if (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_d.di_size) { error = xfs_flush_pages(ip, 0, -1, 0, FI_REMAPF); if (error) goto out_unlock_iolock; } /* * even after flushing the inode, there can still be delalloc * blocks on the inode beyond EOF due to speculative * preallocation. These are not removed until the release * function is called or the inode is inactivated. Hence we * cannot assert here that ip->i_delayed_blks == 0. */ } lock = xfs_ilock_map_shared(ip); /* * Don't let nex be bigger than the number of extents * we can have assuming alternating holes and real extents. */ if (nex > XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1) nex = XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1; bmapi_flags = xfs_bmapi_aflag(whichfork); if (!(iflags & BMV_IF_PREALLOC)) bmapi_flags |= XFS_BMAPI_IGSTATE; /* * Allocate enough space to handle "subnex" maps at a time. */ error = ENOMEM; subnex = 16; map = kmem_alloc(subnex * sizeof(*map), KM_MAYFAIL | KM_NOFS); if (!map) goto out_unlock_ilock; bmv->bmv_entries = 0; if (XFS_IFORK_NEXTENTS(ip, whichfork) == 0 && (whichfork == XFS_ATTR_FORK || !(iflags & BMV_IF_DELALLOC))) { error = 0; goto out_free_map; } nexleft = nex; do { nmap = (nexleft > subnex) ? subnex : nexleft; error = xfs_bmapi_read(ip, XFS_BB_TO_FSBT(mp, bmv->bmv_offset), XFS_BB_TO_FSB(mp, bmv->bmv_length), map, &nmap, bmapi_flags); if (error) goto out_free_map; ASSERT(nmap <= subnex); for (i = 0; i < nmap && nexleft && bmv->bmv_length; i++) { out[cur_ext].bmv_oflags = 0; if (map[i].br_state == XFS_EXT_UNWRITTEN) out[cur_ext].bmv_oflags |= BMV_OF_PREALLOC; else if (map[i].br_startblock == DELAYSTARTBLOCK) out[cur_ext].bmv_oflags |= BMV_OF_DELALLOC; out[cur_ext].bmv_offset = XFS_FSB_TO_BB(mp, map[i].br_startoff); out[cur_ext].bmv_length = XFS_FSB_TO_BB(mp, map[i].br_blockcount); out[cur_ext].bmv_unused1 = 0; out[cur_ext].bmv_unused2 = 0; ASSERT(((iflags & BMV_IF_DELALLOC) != 0) || (map[i].br_startblock != DELAYSTARTBLOCK)); if (map[i].br_startblock == HOLESTARTBLOCK && whichfork == XFS_ATTR_FORK) { /* came to the end of attribute fork */ out[cur_ext].bmv_oflags |= BMV_OF_LAST; goto out_free_map; } if (!xfs_getbmapx_fix_eof_hole(ip, &out[cur_ext], prealloced, bmvend, map[i].br_startblock)) goto out_free_map; bmv->bmv_offset = out[cur_ext].bmv_offset + out[cur_ext].bmv_length; bmv->bmv_length = max_t(__int64_t, 0, bmvend - bmv->bmv_offset); /* * In case we don't want to return the hole, * don't increase cur_ext so that we can reuse * it in the next loop. */ if ((iflags & BMV_IF_NO_HOLES) && map[i].br_startblock == HOLESTARTBLOCK) { memset(&out[cur_ext], 0, sizeof(out[cur_ext])); continue; } nexleft--; bmv->bmv_entries++; cur_ext++; } } while (nmap && nexleft && bmv->bmv_length); out_free_map: kmem_free(map); out_unlock_ilock: xfs_iunlock_map_shared(ip, lock); out_unlock_iolock: xfs_iunlock(ip, XFS_IOLOCK_SHARED); for (i = 0; i < cur_ext; i++) { int full = 0; /* user array is full */ /* format results & advance arg */ error = formatter(&arg, &out[i], &full); if (error || full) break; } if (is_vmalloc_addr(out)) kmem_free_large(out); else kmem_free(out); return error; } #ifdef DEBUG STATIC struct xfs_buf * xfs_bmap_get_bp( struct xfs_btree_cur *cur, xfs_fsblock_t bno) { struct xfs_log_item_desc *lidp; int i; if (!cur) return NULL; for (i = 0; i < XFS_BTREE_MAXLEVELS; i++) { if (!cur->bc_bufs[i]) break; if (XFS_BUF_ADDR(cur->bc_bufs[i]) == bno) return cur->bc_bufs[i]; } /* Chase down all the log items to see if the bp is there */ list_for_each_entry(lidp, &cur->bc_tp->t_items, lid_trans) { struct xfs_buf_log_item *bip; bip = (struct xfs_buf_log_item *)lidp->lid_item; if (bip->bli_item.li_type == XFS_LI_BUF && XFS_BUF_ADDR(bip->bli_buf) == bno) return bip->bli_buf; } return NULL; } STATIC void xfs_check_block( struct xfs_btree_block *block, xfs_mount_t *mp, int root, short sz) { int i, j, dmxr; __be64 *pp, *thispa; /* pointer to block address */ xfs_bmbt_key_t *prevp, *keyp; ASSERT(be16_to_cpu(block->bb_level) > 0); prevp = NULL; for( i = 1; i <= xfs_btree_get_numrecs(block); i++) { dmxr = mp->m_bmap_dmxr[0]; keyp = XFS_BMBT_KEY_ADDR(mp, block, i); if (prevp) { ASSERT(be64_to_cpu(prevp->br_startoff) < be64_to_cpu(keyp->br_startoff)); } prevp = keyp; /* * Compare the block numbers to see if there are dups. */ if (root) pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, i, sz); else pp = XFS_BMBT_PTR_ADDR(mp, block, i, dmxr); for (j = i+1; j <= be16_to_cpu(block->bb_numrecs); j++) { if (root) thispa = XFS_BMAP_BROOT_PTR_ADDR(mp, block, j, sz); else thispa = XFS_BMBT_PTR_ADDR(mp, block, j, dmxr); if (*thispa == *pp) { xfs_warn(mp, "%s: thispa(%d) == pp(%d) %Ld", __func__, j, i, (unsigned long long)be64_to_cpu(*thispa)); panic("%s: ptrs are equal in node\n", __func__); } } } } /* * Check that the extents for the inode ip are in the right order in all * btree leaves. */ STATIC void xfs_bmap_check_leaf_extents( xfs_btree_cur_t *cur, /* btree cursor or null */ xfs_inode_t *ip, /* incore inode pointer */ int whichfork) /* data or attr fork */ { struct xfs_btree_block *block; /* current btree block */ xfs_fsblock_t bno; /* block # of "block" */ xfs_buf_t *bp; /* buffer for "block" */ int error; /* error return value */ xfs_extnum_t i=0, j; /* index into the extents list */ xfs_ifork_t *ifp; /* fork structure */ int level; /* btree level, for checking */ xfs_mount_t *mp; /* file system mount structure */ __be64 *pp; /* pointer to block address */ xfs_bmbt_rec_t *ep; /* pointer to current extent */ xfs_bmbt_rec_t last = {0, 0}; /* last extent in prev block */ xfs_bmbt_rec_t *nextp; /* pointer to next extent */ int bp_release = 0; if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) { return; } bno = NULLFSBLOCK; mp = ip->i_mount; ifp = XFS_IFORK_PTR(ip, whichfork); block = ifp->if_broot; /* * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out. */ level = be16_to_cpu(block->bb_level); ASSERT(level > 0); xfs_check_block(block, mp, 1, ifp->if_broot_bytes); pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes); bno = be64_to_cpu(*pp); ASSERT(bno != NULLDFSBNO); ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount); ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks); /* * Go down the tree until leaf level is reached, following the first * pointer (leftmost) at each level. */ while (level-- > 0) { /* See if buf is in cur first */ bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno)); if (bp) { bp_release = 0; } else { bp_release = 1; } if (!bp && (error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp, XFS_BMAP_BTREE_REF))) goto error_norelse; block = XFS_BUF_TO_BLOCK(bp); XFS_WANT_CORRUPTED_GOTO( xfs_bmap_sanity_check(mp, bp, level), error0); if (level == 0) break; /* * Check this block for basic sanity (increasing keys and * no duplicate blocks). */ xfs_check_block(block, mp, 0, 0); pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]); bno = be64_to_cpu(*pp); XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, bno), error0); if (bp_release) { bp_release = 0; xfs_trans_brelse(NULL, bp); } } /* * Here with bp and block set to the leftmost leaf node in the tree. */ i = 0; /* * Loop over all leaf nodes checking that all extents are in the right order. */ for (;;) { xfs_fsblock_t nextbno; xfs_extnum_t num_recs; num_recs = xfs_btree_get_numrecs(block); /* * Read-ahead the next leaf block, if any. */ nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib); /* * Check all the extents to make sure they are OK. * If we had a previous block, the last entry should * conform with the first entry in this one. */ ep = XFS_BMBT_REC_ADDR(mp, block, 1); if (i) { ASSERT(xfs_bmbt_disk_get_startoff(&last) + xfs_bmbt_disk_get_blockcount(&last) <= xfs_bmbt_disk_get_startoff(ep)); } for (j = 1; j < num_recs; j++) { nextp = XFS_BMBT_REC_ADDR(mp, block, j + 1); ASSERT(xfs_bmbt_disk_get_startoff(ep) + xfs_bmbt_disk_get_blockcount(ep) <= xfs_bmbt_disk_get_startoff(nextp)); ep = nextp; } last = *ep; i += num_recs; if (bp_release) { bp_release = 0; xfs_trans_brelse(NULL, bp); } bno = nextbno; /* * If we've reached the end, stop. */ if (bno == NULLFSBLOCK) break; bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno)); if (bp) { bp_release = 0; } else { bp_release = 1; } if (!bp && (error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp, XFS_BMAP_BTREE_REF))) goto error_norelse; block = XFS_BUF_TO_BLOCK(bp); } if (bp_release) { bp_release = 0; xfs_trans_brelse(NULL, bp); } return; error0: xfs_warn(mp, "%s: at error0", __func__); if (bp_release) xfs_trans_brelse(NULL, bp); error_norelse: xfs_warn(mp, "%s: BAD after btree leaves for %d extents", __func__, i); panic("%s: CORRUPTED BTREE OR SOMETHING", __func__); return; } #endif /* * Count fsblocks of the given fork. */ int /* error */ xfs_bmap_count_blocks( xfs_trans_t *tp, /* transaction pointer */ xfs_inode_t *ip, /* incore inode */ int whichfork, /* data or attr fork */ int *count) /* out: count of blocks */ { struct xfs_btree_block *block; /* current btree block */ xfs_fsblock_t bno; /* block # of "block" */ xfs_ifork_t *ifp; /* fork structure */ int level; /* btree level, for checking */ xfs_mount_t *mp; /* file system mount structure */ __be64 *pp; /* pointer to block address */ bno = NULLFSBLOCK; mp = ip->i_mount; ifp = XFS_IFORK_PTR(ip, whichfork); if ( XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ) { xfs_bmap_count_leaves(ifp, 0, ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t), count); return 0; } /* * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out. */ block = ifp->if_broot; level = be16_to_cpu(block->bb_level); ASSERT(level > 0); pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes); bno = be64_to_cpu(*pp); ASSERT(bno != NULLDFSBNO); ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount); ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks); if (unlikely(xfs_bmap_count_tree(mp, tp, ifp, bno, level, count) < 0)) { XFS_ERROR_REPORT("xfs_bmap_count_blocks(2)", XFS_ERRLEVEL_LOW, mp); return XFS_ERROR(EFSCORRUPTED); } return 0; } /* * Recursively walks each level of a btree * to count total fsblocks is use. */ STATIC int /* error */ xfs_bmap_count_tree( xfs_mount_t *mp, /* file system mount point */ xfs_trans_t *tp, /* transaction pointer */ xfs_ifork_t *ifp, /* inode fork pointer */ xfs_fsblock_t blockno, /* file system block number */ int levelin, /* level in btree */ int *count) /* Count of blocks */ { int error; xfs_buf_t *bp, *nbp; int level = levelin; __be64 *pp; xfs_fsblock_t bno = blockno; xfs_fsblock_t nextbno; struct xfs_btree_block *block, *nextblock; int numrecs; if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF))) return error; *count += 1; block = XFS_BUF_TO_BLOCK(bp); if (--level) { /* Not at node above leaves, count this level of nodes */ nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib); while (nextbno != NULLFSBLOCK) { if ((error = xfs_btree_read_bufl(mp, tp, nextbno, 0, &nbp, XFS_BMAP_BTREE_REF))) return error; *count += 1; nextblock = XFS_BUF_TO_BLOCK(nbp); nextbno = be64_to_cpu(nextblock->bb_u.l.bb_rightsib); xfs_trans_brelse(tp, nbp); } /* Dive to the next level */ pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]); bno = be64_to_cpu(*pp); if (unlikely((error = xfs_bmap_count_tree(mp, tp, ifp, bno, level, count)) < 0)) { xfs_trans_brelse(tp, bp); XFS_ERROR_REPORT("xfs_bmap_count_tree(1)", XFS_ERRLEVEL_LOW, mp); return XFS_ERROR(EFSCORRUPTED); } xfs_trans_brelse(tp, bp); } else { /* count all level 1 nodes and their leaves */ for (;;) { nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib); numrecs = be16_to_cpu(block->bb_numrecs); xfs_bmap_disk_count_leaves(mp, block, numrecs, count); xfs_trans_brelse(tp, bp); if (nextbno == NULLFSBLOCK) break; bno = nextbno; if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF))) return error; *count += 1; block = XFS_BUF_TO_BLOCK(bp); } } return 0; } /* * Count leaf blocks given a range of extent records. */ STATIC void xfs_bmap_count_leaves( xfs_ifork_t *ifp, xfs_extnum_t idx, int numrecs, int *count) { int b; for (b = 0; b < numrecs; b++) { xfs_bmbt_rec_host_t *frp = xfs_iext_get_ext(ifp, idx + b); *count += xfs_bmbt_get_blockcount(frp); } } /* * Count leaf blocks given a range of extent records originally * in btree format. */ STATIC void xfs_bmap_disk_count_leaves( struct xfs_mount *mp, struct xfs_btree_block *block, int numrecs, int *count) { int b; xfs_bmbt_rec_t *frp; for (b = 1; b <= numrecs; b++) { frp = XFS_BMBT_REC_ADDR(mp, block, b); *count += xfs_bmbt_disk_get_blockcount(frp); } } /* * dead simple method of punching delalyed allocation blocks from a range in * the inode. Walks a block at a time so will be slow, but is only executed in * rare error cases so the overhead is not critical. This will alays punch out * both the start and end blocks, even if the ranges only partially overlap * them, so it is up to the caller to ensure that partial blocks are not * passed in. */ int xfs_bmap_punch_delalloc_range( struct xfs_inode *ip, xfs_fileoff_t start_fsb, xfs_fileoff_t length) { xfs_fileoff_t remaining = length; int error = 0; ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL)); do { int done; xfs_bmbt_irec_t imap; int nimaps = 1; xfs_fsblock_t firstblock; xfs_bmap_free_t flist; /* * Map the range first and check that it is a delalloc extent * before trying to unmap the range. Otherwise we will be * trying to remove a real extent (which requires a * transaction) or a hole, which is probably a bad idea... */ error = xfs_bmapi_read(ip, start_fsb, 1, &imap, &nimaps, XFS_BMAPI_ENTIRE); if (error) { /* something screwed, just bail */ if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) { xfs_alert(ip->i_mount, "Failed delalloc mapping lookup ino %lld fsb %lld.", ip->i_ino, start_fsb); } break; } if (!nimaps) { /* nothing there */ goto next_block; } if (imap.br_startblock != DELAYSTARTBLOCK) { /* been converted, ignore */ goto next_block; } WARN_ON(imap.br_blockcount == 0); /* * Note: while we initialise the firstblock/flist pair, they * should never be used because blocks should never be * allocated or freed for a delalloc extent and hence we need * don't cancel or finish them after the xfs_bunmapi() call. */ xfs_bmap_init(&flist, &firstblock); error = xfs_bunmapi(NULL, ip, start_fsb, 1, 0, 1, &firstblock, &flist, &done); if (error) break; ASSERT(!flist.xbf_count && !flist.xbf_first); next_block: start_fsb++; remaining--; } while(remaining > 0); return error; }
gpl-2.0
haoyangw/android_kernel_xiaomi_dior
drivers/md/dm-thin-metadata.c
4808
32017
/* * Copyright (C) 2011 Red Hat, Inc. * * This file is released under the GPL. */ #include "dm-thin-metadata.h" #include "persistent-data/dm-btree.h" #include "persistent-data/dm-space-map.h" #include "persistent-data/dm-space-map-disk.h" #include "persistent-data/dm-transaction-manager.h" #include <linux/list.h> #include <linux/device-mapper.h> #include <linux/workqueue.h> /*-------------------------------------------------------------------------- * As far as the metadata goes, there is: * * - A superblock in block zero, taking up fewer than 512 bytes for * atomic writes. * * - A space map managing the metadata blocks. * * - A space map managing the data blocks. * * - A btree mapping our internal thin dev ids onto struct disk_device_details. * * - A hierarchical btree, with 2 levels which effectively maps (thin * dev id, virtual block) -> block_time. Block time is a 64-bit * field holding the time in the low 24 bits, and block in the top 48 * bits. * * BTrees consist solely of btree_nodes, that fill a block. Some are * internal nodes, as such their values are a __le64 pointing to other * nodes. Leaf nodes can store data of any reasonable size (ie. much * smaller than the block size). The nodes consist of the header, * followed by an array of keys, followed by an array of values. We have * to binary search on the keys so they're all held together to help the * cpu cache. * * Space maps have 2 btrees: * * - One maps a uint64_t onto a struct index_entry. Which points to a * bitmap block, and has some details about how many free entries there * are etc. * * - The bitmap blocks have a header (for the checksum). Then the rest * of the block is pairs of bits. With the meaning being: * * 0 - ref count is 0 * 1 - ref count is 1 * 2 - ref count is 2 * 3 - ref count is higher than 2 * * - If the count is higher than 2 then the ref count is entered in a * second btree that directly maps the block_address to a uint32_t ref * count. * * The space map metadata variant doesn't have a bitmaps btree. Instead * it has one single blocks worth of index_entries. This avoids * recursive issues with the bitmap btree needing to allocate space in * order to insert. With a small data block size such as 64k the * metadata support data devices that are hundreds of terrabytes. * * The space maps allocate space linearly from front to back. Space that * is freed in a transaction is never recycled within that transaction. * To try and avoid fragmenting _free_ space the allocator always goes * back and fills in gaps. * * All metadata io is in THIN_METADATA_BLOCK_SIZE sized/aligned chunks * from the block manager. *--------------------------------------------------------------------------*/ #define DM_MSG_PREFIX "thin metadata" #define THIN_SUPERBLOCK_MAGIC 27022010 #define THIN_SUPERBLOCK_LOCATION 0 #define THIN_VERSION 1 #define THIN_METADATA_CACHE_SIZE 64 #define SECTOR_TO_BLOCK_SHIFT 3 /* This should be plenty */ #define SPACE_MAP_ROOT_SIZE 128 /* * Little endian on-disk superblock and device details. */ struct thin_disk_superblock { __le32 csum; /* Checksum of superblock except for this field. */ __le32 flags; __le64 blocknr; /* This block number, dm_block_t. */ __u8 uuid[16]; __le64 magic; __le32 version; __le32 time; __le64 trans_id; /* * Root held by userspace transactions. */ __le64 held_root; __u8 data_space_map_root[SPACE_MAP_ROOT_SIZE]; __u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE]; /* * 2-level btree mapping (dev_id, (dev block, time)) -> data block */ __le64 data_mapping_root; /* * Device detail root mapping dev_id -> device_details */ __le64 device_details_root; __le32 data_block_size; /* In 512-byte sectors. */ __le32 metadata_block_size; /* In 512-byte sectors. */ __le64 metadata_nr_blocks; __le32 compat_flags; __le32 compat_ro_flags; __le32 incompat_flags; } __packed; struct disk_device_details { __le64 mapped_blocks; __le64 transaction_id; /* When created. */ __le32 creation_time; __le32 snapshotted_time; } __packed; struct dm_pool_metadata { struct hlist_node hash; struct block_device *bdev; struct dm_block_manager *bm; struct dm_space_map *metadata_sm; struct dm_space_map *data_sm; struct dm_transaction_manager *tm; struct dm_transaction_manager *nb_tm; /* * Two-level btree. * First level holds thin_dev_t. * Second level holds mappings. */ struct dm_btree_info info; /* * Non-blocking version of the above. */ struct dm_btree_info nb_info; /* * Just the top level for deleting whole devices. */ struct dm_btree_info tl_info; /* * Just the bottom level for creating new devices. */ struct dm_btree_info bl_info; /* * Describes the device details btree. */ struct dm_btree_info details_info; struct rw_semaphore root_lock; uint32_t time; int need_commit; dm_block_t root; dm_block_t details_root; struct list_head thin_devices; uint64_t trans_id; unsigned long flags; sector_t data_block_size; }; struct dm_thin_device { struct list_head list; struct dm_pool_metadata *pmd; dm_thin_id id; int open_count; int changed; uint64_t mapped_blocks; uint64_t transaction_id; uint32_t creation_time; uint32_t snapshotted_time; }; /*---------------------------------------------------------------- * superblock validator *--------------------------------------------------------------*/ #define SUPERBLOCK_CSUM_XOR 160774 static void sb_prepare_for_write(struct dm_block_validator *v, struct dm_block *b, size_t block_size) { struct thin_disk_superblock *disk_super = dm_block_data(b); disk_super->blocknr = cpu_to_le64(dm_block_location(b)); disk_super->csum = cpu_to_le32(dm_bm_checksum(&disk_super->flags, block_size - sizeof(__le32), SUPERBLOCK_CSUM_XOR)); } static int sb_check(struct dm_block_validator *v, struct dm_block *b, size_t block_size) { struct thin_disk_superblock *disk_super = dm_block_data(b); __le32 csum_le; if (dm_block_location(b) != le64_to_cpu(disk_super->blocknr)) { DMERR("sb_check failed: blocknr %llu: " "wanted %llu", le64_to_cpu(disk_super->blocknr), (unsigned long long)dm_block_location(b)); return -ENOTBLK; } if (le64_to_cpu(disk_super->magic) != THIN_SUPERBLOCK_MAGIC) { DMERR("sb_check failed: magic %llu: " "wanted %llu", le64_to_cpu(disk_super->magic), (unsigned long long)THIN_SUPERBLOCK_MAGIC); return -EILSEQ; } csum_le = cpu_to_le32(dm_bm_checksum(&disk_super->flags, block_size - sizeof(__le32), SUPERBLOCK_CSUM_XOR)); if (csum_le != disk_super->csum) { DMERR("sb_check failed: csum %u: wanted %u", le32_to_cpu(csum_le), le32_to_cpu(disk_super->csum)); return -EILSEQ; } return 0; } static struct dm_block_validator sb_validator = { .name = "superblock", .prepare_for_write = sb_prepare_for_write, .check = sb_check }; /*---------------------------------------------------------------- * Methods for the btree value types *--------------------------------------------------------------*/ static uint64_t pack_block_time(dm_block_t b, uint32_t t) { return (b << 24) | t; } static void unpack_block_time(uint64_t v, dm_block_t *b, uint32_t *t) { *b = v >> 24; *t = v & ((1 << 24) - 1); } static void data_block_inc(void *context, void *value_le) { struct dm_space_map *sm = context; __le64 v_le; uint64_t b; uint32_t t; memcpy(&v_le, value_le, sizeof(v_le)); unpack_block_time(le64_to_cpu(v_le), &b, &t); dm_sm_inc_block(sm, b); } static void data_block_dec(void *context, void *value_le) { struct dm_space_map *sm = context; __le64 v_le; uint64_t b; uint32_t t; memcpy(&v_le, value_le, sizeof(v_le)); unpack_block_time(le64_to_cpu(v_le), &b, &t); dm_sm_dec_block(sm, b); } static int data_block_equal(void *context, void *value1_le, void *value2_le) { __le64 v1_le, v2_le; uint64_t b1, b2; uint32_t t; memcpy(&v1_le, value1_le, sizeof(v1_le)); memcpy(&v2_le, value2_le, sizeof(v2_le)); unpack_block_time(le64_to_cpu(v1_le), &b1, &t); unpack_block_time(le64_to_cpu(v2_le), &b2, &t); return b1 == b2; } static void subtree_inc(void *context, void *value) { struct dm_btree_info *info = context; __le64 root_le; uint64_t root; memcpy(&root_le, value, sizeof(root_le)); root = le64_to_cpu(root_le); dm_tm_inc(info->tm, root); } static void subtree_dec(void *context, void *value) { struct dm_btree_info *info = context; __le64 root_le; uint64_t root; memcpy(&root_le, value, sizeof(root_le)); root = le64_to_cpu(root_le); if (dm_btree_del(info, root)) DMERR("btree delete failed\n"); } static int subtree_equal(void *context, void *value1_le, void *value2_le) { __le64 v1_le, v2_le; memcpy(&v1_le, value1_le, sizeof(v1_le)); memcpy(&v2_le, value2_le, sizeof(v2_le)); return v1_le == v2_le; } /*----------------------------------------------------------------*/ static int superblock_all_zeroes(struct dm_block_manager *bm, int *result) { int r; unsigned i; struct dm_block *b; __le64 *data_le, zero = cpu_to_le64(0); unsigned block_size = dm_bm_block_size(bm) / sizeof(__le64); /* * We can't use a validator here - it may be all zeroes. */ r = dm_bm_read_lock(bm, THIN_SUPERBLOCK_LOCATION, NULL, &b); if (r) return r; data_le = dm_block_data(b); *result = 1; for (i = 0; i < block_size; i++) { if (data_le[i] != zero) { *result = 0; break; } } return dm_bm_unlock(b); } static int init_pmd(struct dm_pool_metadata *pmd, struct dm_block_manager *bm, dm_block_t nr_blocks, int create) { int r; struct dm_space_map *sm, *data_sm; struct dm_transaction_manager *tm; struct dm_block *sblock; if (create) { r = dm_tm_create_with_sm(bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &tm, &sm, &sblock); if (r < 0) { DMERR("tm_create_with_sm failed"); return r; } data_sm = dm_sm_disk_create(tm, nr_blocks); if (IS_ERR(data_sm)) { DMERR("sm_disk_create failed"); dm_tm_unlock(tm, sblock); r = PTR_ERR(data_sm); goto bad; } } else { struct thin_disk_superblock *disk_super = NULL; size_t space_map_root_offset = offsetof(struct thin_disk_superblock, metadata_space_map_root); r = dm_tm_open_with_sm(bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, space_map_root_offset, SPACE_MAP_ROOT_SIZE, &tm, &sm, &sblock); if (r < 0) { DMERR("tm_open_with_sm failed"); return r; } disk_super = dm_block_data(sblock); data_sm = dm_sm_disk_open(tm, disk_super->data_space_map_root, sizeof(disk_super->data_space_map_root)); if (IS_ERR(data_sm)) { DMERR("sm_disk_open failed"); r = PTR_ERR(data_sm); goto bad; } } r = dm_tm_unlock(tm, sblock); if (r < 0) { DMERR("couldn't unlock superblock"); goto bad_data_sm; } pmd->bm = bm; pmd->metadata_sm = sm; pmd->data_sm = data_sm; pmd->tm = tm; pmd->nb_tm = dm_tm_create_non_blocking_clone(tm); if (!pmd->nb_tm) { DMERR("could not create clone tm"); r = -ENOMEM; goto bad_data_sm; } pmd->info.tm = tm; pmd->info.levels = 2; pmd->info.value_type.context = pmd->data_sm; pmd->info.value_type.size = sizeof(__le64); pmd->info.value_type.inc = data_block_inc; pmd->info.value_type.dec = data_block_dec; pmd->info.value_type.equal = data_block_equal; memcpy(&pmd->nb_info, &pmd->info, sizeof(pmd->nb_info)); pmd->nb_info.tm = pmd->nb_tm; pmd->tl_info.tm = tm; pmd->tl_info.levels = 1; pmd->tl_info.value_type.context = &pmd->info; pmd->tl_info.value_type.size = sizeof(__le64); pmd->tl_info.value_type.inc = subtree_inc; pmd->tl_info.value_type.dec = subtree_dec; pmd->tl_info.value_type.equal = subtree_equal; pmd->bl_info.tm = tm; pmd->bl_info.levels = 1; pmd->bl_info.value_type.context = pmd->data_sm; pmd->bl_info.value_type.size = sizeof(__le64); pmd->bl_info.value_type.inc = data_block_inc; pmd->bl_info.value_type.dec = data_block_dec; pmd->bl_info.value_type.equal = data_block_equal; pmd->details_info.tm = tm; pmd->details_info.levels = 1; pmd->details_info.value_type.context = NULL; pmd->details_info.value_type.size = sizeof(struct disk_device_details); pmd->details_info.value_type.inc = NULL; pmd->details_info.value_type.dec = NULL; pmd->details_info.value_type.equal = NULL; pmd->root = 0; init_rwsem(&pmd->root_lock); pmd->time = 0; pmd->need_commit = 0; pmd->details_root = 0; pmd->trans_id = 0; pmd->flags = 0; INIT_LIST_HEAD(&pmd->thin_devices); return 0; bad_data_sm: dm_sm_destroy(data_sm); bad: dm_tm_destroy(tm); dm_sm_destroy(sm); return r; } static int __begin_transaction(struct dm_pool_metadata *pmd) { int r; u32 features; struct thin_disk_superblock *disk_super; struct dm_block *sblock; /* * __maybe_commit_transaction() resets these */ WARN_ON(pmd->need_commit); /* * We re-read the superblock every time. Shouldn't need to do this * really. */ r = dm_bm_read_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) return r; disk_super = dm_block_data(sblock); pmd->time = le32_to_cpu(disk_super->time); pmd->root = le64_to_cpu(disk_super->data_mapping_root); pmd->details_root = le64_to_cpu(disk_super->device_details_root); pmd->trans_id = le64_to_cpu(disk_super->trans_id); pmd->flags = le32_to_cpu(disk_super->flags); pmd->data_block_size = le32_to_cpu(disk_super->data_block_size); features = le32_to_cpu(disk_super->incompat_flags) & ~THIN_FEATURE_INCOMPAT_SUPP; if (features) { DMERR("could not access metadata due to " "unsupported optional features (%lx).", (unsigned long)features); r = -EINVAL; goto out; } /* * Check for read-only metadata to skip the following RDWR checks. */ if (get_disk_ro(pmd->bdev->bd_disk)) goto out; features = le32_to_cpu(disk_super->compat_ro_flags) & ~THIN_FEATURE_COMPAT_RO_SUPP; if (features) { DMERR("could not access metadata RDWR due to " "unsupported optional features (%lx).", (unsigned long)features); r = -EINVAL; } out: dm_bm_unlock(sblock); return r; } static int __write_changed_details(struct dm_pool_metadata *pmd) { int r; struct dm_thin_device *td, *tmp; struct disk_device_details details; uint64_t key; list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) { if (!td->changed) continue; key = td->id; details.mapped_blocks = cpu_to_le64(td->mapped_blocks); details.transaction_id = cpu_to_le64(td->transaction_id); details.creation_time = cpu_to_le32(td->creation_time); details.snapshotted_time = cpu_to_le32(td->snapshotted_time); __dm_bless_for_disk(&details); r = dm_btree_insert(&pmd->details_info, pmd->details_root, &key, &details, &pmd->details_root); if (r) return r; if (td->open_count) td->changed = 0; else { list_del(&td->list); kfree(td); } pmd->need_commit = 1; } return 0; } static int __commit_transaction(struct dm_pool_metadata *pmd) { /* * FIXME: Associated pool should be made read-only on failure. */ int r; size_t metadata_len, data_len; struct thin_disk_superblock *disk_super; struct dm_block *sblock; /* * We need to know if the thin_disk_superblock exceeds a 512-byte sector. */ BUILD_BUG_ON(sizeof(struct thin_disk_superblock) > 512); r = __write_changed_details(pmd); if (r < 0) goto out; if (!pmd->need_commit) goto out; r = dm_sm_commit(pmd->data_sm); if (r < 0) goto out; r = dm_tm_pre_commit(pmd->tm); if (r < 0) goto out; r = dm_sm_root_size(pmd->metadata_sm, &metadata_len); if (r < 0) goto out; r = dm_sm_root_size(pmd->data_sm, &data_len); if (r < 0) goto out; r = dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) goto out; disk_super = dm_block_data(sblock); disk_super->time = cpu_to_le32(pmd->time); disk_super->data_mapping_root = cpu_to_le64(pmd->root); disk_super->device_details_root = cpu_to_le64(pmd->details_root); disk_super->trans_id = cpu_to_le64(pmd->trans_id); disk_super->flags = cpu_to_le32(pmd->flags); r = dm_sm_copy_root(pmd->metadata_sm, &disk_super->metadata_space_map_root, metadata_len); if (r < 0) goto out_locked; r = dm_sm_copy_root(pmd->data_sm, &disk_super->data_space_map_root, data_len); if (r < 0) goto out_locked; r = dm_tm_commit(pmd->tm, sblock); if (!r) pmd->need_commit = 0; out: return r; out_locked: dm_bm_unlock(sblock); return r; } struct dm_pool_metadata *dm_pool_metadata_open(struct block_device *bdev, sector_t data_block_size) { int r; struct thin_disk_superblock *disk_super; struct dm_pool_metadata *pmd; sector_t bdev_size = i_size_read(bdev->bd_inode) >> SECTOR_SHIFT; struct dm_block_manager *bm; int create; struct dm_block *sblock; pmd = kmalloc(sizeof(*pmd), GFP_KERNEL); if (!pmd) { DMERR("could not allocate metadata struct"); return ERR_PTR(-ENOMEM); } /* * Max hex locks: * 3 for btree insert + * 2 for btree lookup used within space map */ bm = dm_block_manager_create(bdev, THIN_METADATA_BLOCK_SIZE, THIN_METADATA_CACHE_SIZE, 5); if (!bm) { DMERR("could not create block manager"); kfree(pmd); return ERR_PTR(-ENOMEM); } r = superblock_all_zeroes(bm, &create); if (r) { dm_block_manager_destroy(bm); kfree(pmd); return ERR_PTR(r); } r = init_pmd(pmd, bm, 0, create); if (r) { dm_block_manager_destroy(bm); kfree(pmd); return ERR_PTR(r); } pmd->bdev = bdev; if (!create) { r = __begin_transaction(pmd); if (r < 0) goto bad; return pmd; } /* * Create. */ r = dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) goto bad; if (bdev_size > THIN_METADATA_MAX_SECTORS) bdev_size = THIN_METADATA_MAX_SECTORS; disk_super = dm_block_data(sblock); disk_super->magic = cpu_to_le64(THIN_SUPERBLOCK_MAGIC); disk_super->version = cpu_to_le32(THIN_VERSION); disk_super->time = 0; disk_super->metadata_block_size = cpu_to_le32(THIN_METADATA_BLOCK_SIZE >> SECTOR_SHIFT); disk_super->metadata_nr_blocks = cpu_to_le64(bdev_size >> SECTOR_TO_BLOCK_SHIFT); disk_super->data_block_size = cpu_to_le32(data_block_size); r = dm_bm_unlock(sblock); if (r < 0) goto bad; r = dm_btree_empty(&pmd->info, &pmd->root); if (r < 0) goto bad; r = dm_btree_empty(&pmd->details_info, &pmd->details_root); if (r < 0) { DMERR("couldn't create devices root"); goto bad; } pmd->flags = 0; pmd->need_commit = 1; r = dm_pool_commit_metadata(pmd); if (r < 0) { DMERR("%s: dm_pool_commit_metadata() failed, error = %d", __func__, r); goto bad; } return pmd; bad: if (dm_pool_metadata_close(pmd) < 0) DMWARN("%s: dm_pool_metadata_close() failed.", __func__); return ERR_PTR(r); } int dm_pool_metadata_close(struct dm_pool_metadata *pmd) { int r; unsigned open_devices = 0; struct dm_thin_device *td, *tmp; down_read(&pmd->root_lock); list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) { if (td->open_count) open_devices++; else { list_del(&td->list); kfree(td); } } up_read(&pmd->root_lock); if (open_devices) { DMERR("attempt to close pmd when %u device(s) are still open", open_devices); return -EBUSY; } r = __commit_transaction(pmd); if (r < 0) DMWARN("%s: __commit_transaction() failed, error = %d", __func__, r); dm_tm_destroy(pmd->tm); dm_tm_destroy(pmd->nb_tm); dm_block_manager_destroy(pmd->bm); dm_sm_destroy(pmd->metadata_sm); dm_sm_destroy(pmd->data_sm); kfree(pmd); return 0; } /* * __open_device: Returns @td corresponding to device with id @dev, * creating it if @create is set and incrementing @td->open_count. * On failure, @td is undefined. */ static int __open_device(struct dm_pool_metadata *pmd, dm_thin_id dev, int create, struct dm_thin_device **td) { int r, changed = 0; struct dm_thin_device *td2; uint64_t key = dev; struct disk_device_details details_le; /* * If the device is already open, return it. */ list_for_each_entry(td2, &pmd->thin_devices, list) if (td2->id == dev) { /* * May not create an already-open device. */ if (create) return -EEXIST; td2->open_count++; *td = td2; return 0; } /* * Check the device exists. */ r = dm_btree_lookup(&pmd->details_info, pmd->details_root, &key, &details_le); if (r) { if (r != -ENODATA || !create) return r; /* * Create new device. */ changed = 1; details_le.mapped_blocks = 0; details_le.transaction_id = cpu_to_le64(pmd->trans_id); details_le.creation_time = cpu_to_le32(pmd->time); details_le.snapshotted_time = cpu_to_le32(pmd->time); } *td = kmalloc(sizeof(**td), GFP_NOIO); if (!*td) return -ENOMEM; (*td)->pmd = pmd; (*td)->id = dev; (*td)->open_count = 1; (*td)->changed = changed; (*td)->mapped_blocks = le64_to_cpu(details_le.mapped_blocks); (*td)->transaction_id = le64_to_cpu(details_le.transaction_id); (*td)->creation_time = le32_to_cpu(details_le.creation_time); (*td)->snapshotted_time = le32_to_cpu(details_le.snapshotted_time); list_add(&(*td)->list, &pmd->thin_devices); return 0; } static void __close_device(struct dm_thin_device *td) { --td->open_count; } static int __create_thin(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; dm_block_t dev_root; uint64_t key = dev; struct disk_device_details details_le; struct dm_thin_device *td; __le64 value; r = dm_btree_lookup(&pmd->details_info, pmd->details_root, &key, &details_le); if (!r) return -EEXIST; /* * Create an empty btree for the mappings. */ r = dm_btree_empty(&pmd->bl_info, &dev_root); if (r) return r; /* * Insert it into the main mapping tree. */ value = cpu_to_le64(dev_root); __dm_bless_for_disk(&value); r = dm_btree_insert(&pmd->tl_info, pmd->root, &key, &value, &pmd->root); if (r) { dm_btree_del(&pmd->bl_info, dev_root); return r; } r = __open_device(pmd, dev, 1, &td); if (r) { dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_del(&pmd->bl_info, dev_root); return r; } __close_device(td); return r; } int dm_pool_create_thin(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; down_write(&pmd->root_lock); r = __create_thin(pmd, dev); up_write(&pmd->root_lock); return r; } static int __set_snapshot_details(struct dm_pool_metadata *pmd, struct dm_thin_device *snap, dm_thin_id origin, uint32_t time) { int r; struct dm_thin_device *td; r = __open_device(pmd, origin, 0, &td); if (r) return r; td->changed = 1; td->snapshotted_time = time; snap->mapped_blocks = td->mapped_blocks; snap->snapshotted_time = time; __close_device(td); return 0; } static int __create_snap(struct dm_pool_metadata *pmd, dm_thin_id dev, dm_thin_id origin) { int r; dm_block_t origin_root; uint64_t key = origin, dev_key = dev; struct dm_thin_device *td; struct disk_device_details details_le; __le64 value; /* check this device is unused */ r = dm_btree_lookup(&pmd->details_info, pmd->details_root, &dev_key, &details_le); if (!r) return -EEXIST; /* find the mapping tree for the origin */ r = dm_btree_lookup(&pmd->tl_info, pmd->root, &key, &value); if (r) return r; origin_root = le64_to_cpu(value); /* clone the origin, an inc will do */ dm_tm_inc(pmd->tm, origin_root); /* insert into the main mapping tree */ value = cpu_to_le64(origin_root); __dm_bless_for_disk(&value); key = dev; r = dm_btree_insert(&pmd->tl_info, pmd->root, &key, &value, &pmd->root); if (r) { dm_tm_dec(pmd->tm, origin_root); return r; } pmd->time++; r = __open_device(pmd, dev, 1, &td); if (r) goto bad; r = __set_snapshot_details(pmd, td, origin, pmd->time); __close_device(td); if (r) goto bad; return 0; bad: dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_remove(&pmd->details_info, pmd->details_root, &key, &pmd->details_root); return r; } int dm_pool_create_snap(struct dm_pool_metadata *pmd, dm_thin_id dev, dm_thin_id origin) { int r; down_write(&pmd->root_lock); r = __create_snap(pmd, dev, origin); up_write(&pmd->root_lock); return r; } static int __delete_device(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; uint64_t key = dev; struct dm_thin_device *td; /* TODO: failure should mark the transaction invalid */ r = __open_device(pmd, dev, 0, &td); if (r) return r; if (td->open_count > 1) { __close_device(td); return -EBUSY; } list_del(&td->list); kfree(td); r = dm_btree_remove(&pmd->details_info, pmd->details_root, &key, &pmd->details_root); if (r) return r; r = dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); if (r) return r; pmd->need_commit = 1; return 0; } int dm_pool_delete_thin_device(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; down_write(&pmd->root_lock); r = __delete_device(pmd, dev); up_write(&pmd->root_lock); return r; } int dm_pool_set_metadata_transaction_id(struct dm_pool_metadata *pmd, uint64_t current_id, uint64_t new_id) { down_write(&pmd->root_lock); if (pmd->trans_id != current_id) { up_write(&pmd->root_lock); DMERR("mismatched transaction id"); return -EINVAL; } pmd->trans_id = new_id; pmd->need_commit = 1; up_write(&pmd->root_lock); return 0; } int dm_pool_get_metadata_transaction_id(struct dm_pool_metadata *pmd, uint64_t *result) { down_read(&pmd->root_lock); *result = pmd->trans_id; up_read(&pmd->root_lock); return 0; } static int __get_held_metadata_root(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; struct thin_disk_superblock *disk_super; struct dm_block *sblock; r = dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) return r; disk_super = dm_block_data(sblock); *result = le64_to_cpu(disk_super->held_root); return dm_bm_unlock(sblock); } int dm_pool_get_held_metadata_root(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = __get_held_metadata_root(pmd, result); up_read(&pmd->root_lock); return r; } int dm_pool_open_thin_device(struct dm_pool_metadata *pmd, dm_thin_id dev, struct dm_thin_device **td) { int r; down_write(&pmd->root_lock); r = __open_device(pmd, dev, 0, td); up_write(&pmd->root_lock); return r; } int dm_pool_close_thin_device(struct dm_thin_device *td) { down_write(&td->pmd->root_lock); __close_device(td); up_write(&td->pmd->root_lock); return 0; } dm_thin_id dm_thin_dev_id(struct dm_thin_device *td) { return td->id; } static int __snapshotted_since(struct dm_thin_device *td, uint32_t time) { return td->snapshotted_time > time; } int dm_thin_find_block(struct dm_thin_device *td, dm_block_t block, int can_block, struct dm_thin_lookup_result *result) { int r; uint64_t block_time = 0; __le64 value; struct dm_pool_metadata *pmd = td->pmd; dm_block_t keys[2] = { td->id, block }; if (can_block) { down_read(&pmd->root_lock); r = dm_btree_lookup(&pmd->info, pmd->root, keys, &value); if (!r) block_time = le64_to_cpu(value); up_read(&pmd->root_lock); } else if (down_read_trylock(&pmd->root_lock)) { r = dm_btree_lookup(&pmd->nb_info, pmd->root, keys, &value); if (!r) block_time = le64_to_cpu(value); up_read(&pmd->root_lock); } else return -EWOULDBLOCK; if (!r) { dm_block_t exception_block; uint32_t exception_time; unpack_block_time(block_time, &exception_block, &exception_time); result->block = exception_block; result->shared = __snapshotted_since(td, exception_time); } return r; } static int __insert(struct dm_thin_device *td, dm_block_t block, dm_block_t data_block) { int r, inserted; __le64 value; struct dm_pool_metadata *pmd = td->pmd; dm_block_t keys[2] = { td->id, block }; pmd->need_commit = 1; value = cpu_to_le64(pack_block_time(data_block, pmd->time)); __dm_bless_for_disk(&value); r = dm_btree_insert_notify(&pmd->info, pmd->root, keys, &value, &pmd->root, &inserted); if (r) return r; if (inserted) { td->mapped_blocks++; td->changed = 1; } return 0; } int dm_thin_insert_block(struct dm_thin_device *td, dm_block_t block, dm_block_t data_block) { int r; down_write(&td->pmd->root_lock); r = __insert(td, block, data_block); up_write(&td->pmd->root_lock); return r; } static int __remove(struct dm_thin_device *td, dm_block_t block) { int r; struct dm_pool_metadata *pmd = td->pmd; dm_block_t keys[2] = { td->id, block }; r = dm_btree_remove(&pmd->info, pmd->root, keys, &pmd->root); if (r) return r; td->mapped_blocks--; td->changed = 1; pmd->need_commit = 1; return 0; } int dm_thin_remove_block(struct dm_thin_device *td, dm_block_t block) { int r; down_write(&td->pmd->root_lock); r = __remove(td, block); up_write(&td->pmd->root_lock); return r; } int dm_pool_alloc_data_block(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_write(&pmd->root_lock); r = dm_sm_new_block(pmd->data_sm, result); pmd->need_commit = 1; up_write(&pmd->root_lock); return r; } int dm_pool_commit_metadata(struct dm_pool_metadata *pmd) { int r; down_write(&pmd->root_lock); r = __commit_transaction(pmd); if (r <= 0) goto out; /* * Open the next transaction. */ r = __begin_transaction(pmd); out: up_write(&pmd->root_lock); return r; } int dm_pool_get_free_block_count(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_free(pmd->data_sm, result); up_read(&pmd->root_lock); return r; } int dm_pool_get_free_metadata_block_count(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_free(pmd->metadata_sm, result); up_read(&pmd->root_lock); return r; } int dm_pool_get_metadata_dev_size(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_blocks(pmd->metadata_sm, result); up_read(&pmd->root_lock); return r; } int dm_pool_get_data_block_size(struct dm_pool_metadata *pmd, sector_t *result) { down_read(&pmd->root_lock); *result = pmd->data_block_size; up_read(&pmd->root_lock); return 0; } int dm_pool_get_data_dev_size(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_blocks(pmd->data_sm, result); up_read(&pmd->root_lock); return r; } int dm_thin_get_mapped_count(struct dm_thin_device *td, dm_block_t *result) { struct dm_pool_metadata *pmd = td->pmd; down_read(&pmd->root_lock); *result = td->mapped_blocks; up_read(&pmd->root_lock); return 0; } static int __highest_block(struct dm_thin_device *td, dm_block_t *result) { int r; __le64 value_le; dm_block_t thin_root; struct dm_pool_metadata *pmd = td->pmd; r = dm_btree_lookup(&pmd->tl_info, pmd->root, &td->id, &value_le); if (r) return r; thin_root = le64_to_cpu(value_le); return dm_btree_find_highest_key(&pmd->bl_info, thin_root, result); } int dm_thin_get_highest_mapped_block(struct dm_thin_device *td, dm_block_t *result) { int r; struct dm_pool_metadata *pmd = td->pmd; down_read(&pmd->root_lock); r = __highest_block(td, result); up_read(&pmd->root_lock); return r; } static int __resize_data_dev(struct dm_pool_metadata *pmd, dm_block_t new_count) { int r; dm_block_t old_count; r = dm_sm_get_nr_blocks(pmd->data_sm, &old_count); if (r) return r; if (new_count == old_count) return 0; if (new_count < old_count) { DMERR("cannot reduce size of data device"); return -EINVAL; } r = dm_sm_extend(pmd->data_sm, new_count - old_count); if (!r) pmd->need_commit = 1; return r; } int dm_pool_resize_data_dev(struct dm_pool_metadata *pmd, dm_block_t new_count) { int r; down_write(&pmd->root_lock); r = __resize_data_dev(pmd, new_count); up_write(&pmd->root_lock); return r; }
gpl-2.0
windyyuan/linux
drivers/isdn/hisax/sportster.c
4808
6498
/* $Id: sportster.c,v 1.16.2.4 2004/01/13 23:48:39 keil Exp $ * * low level stuff for USR Sportster internal TA * * Author Karsten Keil * Copyright by Karsten Keil <keil@isdn4linux.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Thanks to Christian "naddy" Weisgerber (3Com, US Robotics) for documentation * * */ #include <linux/init.h> #include "hisax.h" #include "isac.h" #include "hscx.h" #include "isdnl1.h" static const char *sportster_revision = "$Revision: 1.16.2.4 $"; #define byteout(addr, val) outb(val, addr) #define bytein(addr) inb(addr) #define SPORTSTER_ISAC 0xC000 #define SPORTSTER_HSCXA 0x0000 #define SPORTSTER_HSCXB 0x4000 #define SPORTSTER_RES_IRQ 0x8000 #define SPORTSTER_RESET 0x80 #define SPORTSTER_INTE 0x40 static inline int calc_off(unsigned int base, unsigned int off) { return (base + ((off & 0xfc) << 8) + ((off & 3) << 1)); } static inline void read_fifo(unsigned int adr, u_char *data, int size) { insb(adr, data, size); } static void write_fifo(unsigned int adr, u_char *data, int size) { outsb(adr, data, size); } /* Interface functions */ static u_char ReadISAC(struct IsdnCardState *cs, u_char offset) { return (bytein(calc_off(cs->hw.spt.isac, offset))); } static void WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value) { byteout(calc_off(cs->hw.spt.isac, offset), value); } static void ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size) { read_fifo(cs->hw.spt.isac, data, size); } static void WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size) { write_fifo(cs->hw.spt.isac, data, size); } static u_char ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset) { return (bytein(calc_off(cs->hw.spt.hscx[hscx], offset))); } static void WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value) { byteout(calc_off(cs->hw.spt.hscx[hscx], offset), value); } /* * fast interrupt HSCX stuff goes here */ #define READHSCX(cs, nr, reg) bytein(calc_off(cs->hw.spt.hscx[nr], reg)) #define WRITEHSCX(cs, nr, reg, data) byteout(calc_off(cs->hw.spt.hscx[nr], reg), data) #define READHSCXFIFO(cs, nr, ptr, cnt) read_fifo(cs->hw.spt.hscx[nr], ptr, cnt) #define WRITEHSCXFIFO(cs, nr, ptr, cnt) write_fifo(cs->hw.spt.hscx[nr], ptr, cnt) #include "hscx_irq.c" static irqreturn_t sportster_interrupt(int intno, void *dev_id) { struct IsdnCardState *cs = dev_id; u_char val; u_long flags; spin_lock_irqsave(&cs->lock, flags); val = READHSCX(cs, 1, HSCX_ISTA); Start_HSCX: if (val) hscx_int_main(cs, val); val = ReadISAC(cs, ISAC_ISTA); Start_ISAC: if (val) isac_interrupt(cs, val); val = READHSCX(cs, 1, HSCX_ISTA); if (val) { if (cs->debug & L1_DEB_HSCX) debugl1(cs, "HSCX IntStat after IntRoutine"); goto Start_HSCX; } val = ReadISAC(cs, ISAC_ISTA); if (val) { if (cs->debug & L1_DEB_ISAC) debugl1(cs, "ISAC IntStat after IntRoutine"); goto Start_ISAC; } /* get a new irq impulse if there any pending */ bytein(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ + 1); spin_unlock_irqrestore(&cs->lock, flags); return IRQ_HANDLED; } static void release_io_sportster(struct IsdnCardState *cs) { int i, adr; byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, 0); for (i = 0; i < 64; i++) { adr = cs->hw.spt.cfg_reg + i * 1024; release_region(adr, 8); } } static void reset_sportster(struct IsdnCardState *cs) { cs->hw.spt.res_irq |= SPORTSTER_RESET; /* Reset On */ byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, cs->hw.spt.res_irq); mdelay(10); cs->hw.spt.res_irq &= ~SPORTSTER_RESET; /* Reset Off */ byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, cs->hw.spt.res_irq); mdelay(10); } static int Sportster_card_msg(struct IsdnCardState *cs, int mt, void *arg) { u_long flags; switch (mt) { case CARD_RESET: spin_lock_irqsave(&cs->lock, flags); reset_sportster(cs); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_RELEASE: release_io_sportster(cs); return (0); case CARD_INIT: spin_lock_irqsave(&cs->lock, flags); reset_sportster(cs); inithscxisac(cs, 1); cs->hw.spt.res_irq |= SPORTSTER_INTE; /* IRQ On */ byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, cs->hw.spt.res_irq); inithscxisac(cs, 2); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_TEST: return (0); } return (0); } static int get_io_range(struct IsdnCardState *cs) { int i, j, adr; for (i = 0; i < 64; i++) { adr = cs->hw.spt.cfg_reg + i * 1024; if (!request_region(adr, 8, "sportster")) { printk(KERN_WARNING "HiSax: USR Sportster config port " "%x-%x already in use\n", adr, adr + 8); break; } } if (i == 64) return (1); else { for (j = 0; j < i; j++) { adr = cs->hw.spt.cfg_reg + j * 1024; release_region(adr, 8); } return (0); } } int setup_sportster(struct IsdnCard *card) { struct IsdnCardState *cs = card->cs; char tmp[64]; strcpy(tmp, sportster_revision); printk(KERN_INFO "HiSax: USR Sportster driver Rev. %s\n", HiSax_getrev(tmp)); if (cs->typ != ISDN_CTYPE_SPORTSTER) return (0); cs->hw.spt.cfg_reg = card->para[1]; cs->irq = card->para[0]; if (!get_io_range(cs)) return (0); cs->hw.spt.isac = cs->hw.spt.cfg_reg + SPORTSTER_ISAC; cs->hw.spt.hscx[0] = cs->hw.spt.cfg_reg + SPORTSTER_HSCXA; cs->hw.spt.hscx[1] = cs->hw.spt.cfg_reg + SPORTSTER_HSCXB; switch (cs->irq) { case 5: cs->hw.spt.res_irq = 1; break; case 7: cs->hw.spt.res_irq = 2; break; case 10:cs->hw.spt.res_irq = 3; break; case 11:cs->hw.spt.res_irq = 4; break; case 12:cs->hw.spt.res_irq = 5; break; case 14:cs->hw.spt.res_irq = 6; break; case 15:cs->hw.spt.res_irq = 7; break; default:release_io_sportster(cs); printk(KERN_WARNING "Sportster: wrong IRQ\n"); return (0); } printk(KERN_INFO "HiSax: USR Sportster config irq:%d cfg:0x%X\n", cs->irq, cs->hw.spt.cfg_reg); setup_isac(cs); cs->readisac = &ReadISAC; cs->writeisac = &WriteISAC; cs->readisacfifo = &ReadISACfifo; cs->writeisacfifo = &WriteISACfifo; cs->BC_Read_Reg = &ReadHSCX; cs->BC_Write_Reg = &WriteHSCX; cs->BC_Send_Data = &hscx_fill_fifo; cs->cardmsg = &Sportster_card_msg; cs->irq_func = &sportster_interrupt; ISACVersion(cs, "Sportster:"); if (HscxVersion(cs, "Sportster:")) { printk(KERN_WARNING "Sportster: wrong HSCX versions check IO address\n"); release_io_sportster(cs); return (0); } return (1); }
gpl-2.0
Arc-Team/android_kernel_htc_a11
fs/xfs/xfs_itable.c
4808
20030
/* * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * 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. 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_types.h" #include "xfs_bit.h" #include "xfs_log.h" #include "xfs_inum.h" #include "xfs_trans.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_mount.h" #include "xfs_bmap_btree.h" #include "xfs_alloc_btree.h" #include "xfs_ialloc_btree.h" #include "xfs_dinode.h" #include "xfs_inode.h" #include "xfs_ialloc.h" #include "xfs_itable.h" #include "xfs_error.h" #include "xfs_btree.h" #include "xfs_trace.h" STATIC int xfs_internal_inum( xfs_mount_t *mp, xfs_ino_t ino) { return (ino == mp->m_sb.sb_rbmino || ino == mp->m_sb.sb_rsumino || (xfs_sb_version_hasquota(&mp->m_sb) && (ino == mp->m_sb.sb_uquotino || ino == mp->m_sb.sb_gquotino))); } /* * Return stat information for one inode. * Return 0 if ok, else errno. */ int xfs_bulkstat_one_int( struct xfs_mount *mp, /* mount point for filesystem */ xfs_ino_t ino, /* inode to get data for */ void __user *buffer, /* buffer to place output in */ int ubsize, /* size of buffer */ bulkstat_one_fmt_pf formatter, /* formatter, copy to user */ int *ubused, /* bytes used by me */ int *stat) /* BULKSTAT_RV_... */ { struct xfs_icdinode *dic; /* dinode core info pointer */ struct xfs_inode *ip; /* incore inode pointer */ struct xfs_bstat *buf; /* return buffer */ int error = 0; /* error value */ *stat = BULKSTAT_RV_NOTHING; if (!buffer || xfs_internal_inum(mp, ino)) return XFS_ERROR(EINVAL); buf = kmem_alloc(sizeof(*buf), KM_SLEEP | KM_MAYFAIL); if (!buf) return XFS_ERROR(ENOMEM); error = xfs_iget(mp, NULL, ino, (XFS_IGET_DONTCACHE | XFS_IGET_UNTRUSTED), XFS_ILOCK_SHARED, &ip); if (error) { *stat = BULKSTAT_RV_NOTHING; goto out_free; } ASSERT(ip != NULL); ASSERT(ip->i_imap.im_blkno != 0); dic = &ip->i_d; /* xfs_iget returns the following without needing * further change. */ buf->bs_nlink = dic->di_nlink; buf->bs_projid_lo = dic->di_projid_lo; buf->bs_projid_hi = dic->di_projid_hi; buf->bs_ino = ino; buf->bs_mode = dic->di_mode; buf->bs_uid = dic->di_uid; buf->bs_gid = dic->di_gid; buf->bs_size = dic->di_size; buf->bs_atime.tv_sec = dic->di_atime.t_sec; buf->bs_atime.tv_nsec = dic->di_atime.t_nsec; buf->bs_mtime.tv_sec = dic->di_mtime.t_sec; buf->bs_mtime.tv_nsec = dic->di_mtime.t_nsec; buf->bs_ctime.tv_sec = dic->di_ctime.t_sec; buf->bs_ctime.tv_nsec = dic->di_ctime.t_nsec; buf->bs_xflags = xfs_ip2xflags(ip); buf->bs_extsize = dic->di_extsize << mp->m_sb.sb_blocklog; buf->bs_extents = dic->di_nextents; buf->bs_gen = dic->di_gen; memset(buf->bs_pad, 0, sizeof(buf->bs_pad)); buf->bs_dmevmask = dic->di_dmevmask; buf->bs_dmstate = dic->di_dmstate; buf->bs_aextents = dic->di_anextents; buf->bs_forkoff = XFS_IFORK_BOFF(ip); switch (dic->di_format) { case XFS_DINODE_FMT_DEV: buf->bs_rdev = ip->i_df.if_u2.if_rdev; buf->bs_blksize = BLKDEV_IOSIZE; buf->bs_blocks = 0; break; case XFS_DINODE_FMT_LOCAL: case XFS_DINODE_FMT_UUID: buf->bs_rdev = 0; buf->bs_blksize = mp->m_sb.sb_blocksize; buf->bs_blocks = 0; break; case XFS_DINODE_FMT_EXTENTS: case XFS_DINODE_FMT_BTREE: buf->bs_rdev = 0; buf->bs_blksize = mp->m_sb.sb_blocksize; buf->bs_blocks = dic->di_nblocks + ip->i_delayed_blks; break; } xfs_iunlock(ip, XFS_ILOCK_SHARED); IRELE(ip); error = formatter(buffer, ubsize, ubused, buf); if (!error) *stat = BULKSTAT_RV_DIDONE; out_free: kmem_free(buf); return error; } /* Return 0 on success or positive error */ STATIC int xfs_bulkstat_one_fmt( void __user *ubuffer, int ubsize, int *ubused, const xfs_bstat_t *buffer) { if (ubsize < sizeof(*buffer)) return XFS_ERROR(ENOMEM); if (copy_to_user(ubuffer, buffer, sizeof(*buffer))) return XFS_ERROR(EFAULT); if (ubused) *ubused = sizeof(*buffer); return 0; } int xfs_bulkstat_one( xfs_mount_t *mp, /* mount point for filesystem */ xfs_ino_t ino, /* inode number to get data for */ void __user *buffer, /* buffer to place output in */ int ubsize, /* size of buffer */ int *ubused, /* bytes used by me */ int *stat) /* BULKSTAT_RV_... */ { return xfs_bulkstat_one_int(mp, ino, buffer, ubsize, xfs_bulkstat_one_fmt, ubused, stat); } #define XFS_BULKSTAT_UBLEFT(ubleft) ((ubleft) >= statstruct_size) /* * Return stat information in bulk (by-inode) for the filesystem. */ int /* error status */ xfs_bulkstat( xfs_mount_t *mp, /* mount point for filesystem */ xfs_ino_t *lastinop, /* last inode returned */ int *ubcountp, /* size of buffer/count returned */ bulkstat_one_pf formatter, /* func that'd fill a single buf */ size_t statstruct_size, /* sizeof struct filling */ char __user *ubuffer, /* buffer with inode stats */ int *done) /* 1 if there are more stats to get */ { xfs_agblock_t agbno=0;/* allocation group block number */ xfs_buf_t *agbp; /* agi header buffer */ xfs_agi_t *agi; /* agi header data */ xfs_agino_t agino; /* inode # in allocation group */ xfs_agnumber_t agno; /* allocation group number */ int chunkidx; /* current index into inode chunk */ int clustidx; /* current index into inode cluster */ xfs_btree_cur_t *cur; /* btree cursor for ialloc btree */ int end_of_ag; /* set if we've seen the ag end */ int error; /* error code */ int fmterror;/* bulkstat formatter result */ int i; /* loop index */ int icount; /* count of inodes good in irbuf */ size_t irbsize; /* size of irec buffer in bytes */ xfs_ino_t ino; /* inode number (filesystem) */ xfs_inobt_rec_incore_t *irbp; /* current irec buffer pointer */ xfs_inobt_rec_incore_t *irbuf; /* start of irec buffer */ xfs_inobt_rec_incore_t *irbufend; /* end of good irec buffer entries */ xfs_ino_t lastino; /* last inode number returned */ int nbcluster; /* # of blocks in a cluster */ int nicluster; /* # of inodes in a cluster */ int nimask; /* mask for inode clusters */ int nirbuf; /* size of irbuf */ int rval; /* return value error code */ int tmp; /* result value from btree calls */ int ubcount; /* size of user's buffer */ int ubleft; /* bytes left in user's buffer */ char __user *ubufp; /* pointer into user's buffer */ int ubelem; /* spaces used in user's buffer */ int ubused; /* bytes used by formatter */ xfs_buf_t *bp; /* ptr to on-disk inode cluster buf */ /* * Get the last inode value, see if there's nothing to do. */ ino = (xfs_ino_t)*lastinop; lastino = ino; agno = XFS_INO_TO_AGNO(mp, ino); agino = XFS_INO_TO_AGINO(mp, ino); if (agno >= mp->m_sb.sb_agcount || ino != XFS_AGINO_TO_INO(mp, agno, agino)) { *done = 1; *ubcountp = 0; return 0; } if (!ubcountp || *ubcountp <= 0) { return EINVAL; } ubcount = *ubcountp; /* statstruct's */ ubleft = ubcount * statstruct_size; /* bytes */ *ubcountp = ubelem = 0; *done = 0; fmterror = 0; ubufp = ubuffer; nicluster = mp->m_sb.sb_blocksize >= XFS_INODE_CLUSTER_SIZE(mp) ? mp->m_sb.sb_inopblock : (XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_inodelog); nimask = ~(nicluster - 1); nbcluster = nicluster >> mp->m_sb.sb_inopblog; irbuf = kmem_zalloc_greedy(&irbsize, PAGE_SIZE, PAGE_SIZE * 4); if (!irbuf) return ENOMEM; nirbuf = irbsize / sizeof(*irbuf); /* * Loop over the allocation groups, starting from the last * inode returned; 0 means start of the allocation group. */ rval = 0; while (XFS_BULKSTAT_UBLEFT(ubleft) && agno < mp->m_sb.sb_agcount) { cond_resched(); bp = NULL; error = xfs_ialloc_read_agi(mp, NULL, agno, &agbp); if (error) { /* * Skip this allocation group and go to the next one. */ agno++; agino = 0; continue; } agi = XFS_BUF_TO_AGI(agbp); /* * Allocate and initialize a btree cursor for ialloc btree. */ cur = xfs_inobt_init_cursor(mp, NULL, agbp, agno); irbp = irbuf; irbufend = irbuf + nirbuf; end_of_ag = 0; /* * If we're returning in the middle of an allocation group, * we need to get the remainder of the chunk we're in. */ if (agino > 0) { xfs_inobt_rec_incore_t r; /* * Lookup the inode chunk that this inode lives in. */ error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE, &tmp); if (!error && /* no I/O error */ tmp && /* lookup succeeded */ /* got the record, should always work */ !(error = xfs_inobt_get_rec(cur, &r, &i)) && i == 1 && /* this is the right chunk */ agino < r.ir_startino + XFS_INODES_PER_CHUNK && /* lastino was not last in chunk */ (chunkidx = agino - r.ir_startino + 1) < XFS_INODES_PER_CHUNK && /* there are some left allocated */ xfs_inobt_maskn(chunkidx, XFS_INODES_PER_CHUNK - chunkidx) & ~r.ir_free) { /* * Grab the chunk record. Mark all the * uninteresting inodes (because they're * before our start point) free. */ for (i = 0; i < chunkidx; i++) { if (XFS_INOBT_MASK(i) & ~r.ir_free) r.ir_freecount++; } r.ir_free |= xfs_inobt_maskn(0, chunkidx); irbp->ir_startino = r.ir_startino; irbp->ir_freecount = r.ir_freecount; irbp->ir_free = r.ir_free; irbp++; agino = r.ir_startino + XFS_INODES_PER_CHUNK; icount = XFS_INODES_PER_CHUNK - r.ir_freecount; } else { /* * If any of those tests failed, bump the * inode number (just in case). */ agino++; icount = 0; } /* * In any case, increment to the next record. */ if (!error) error = xfs_btree_increment(cur, 0, &tmp); } else { /* * Start of ag. Lookup the first inode chunk. */ error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &tmp); icount = 0; } /* * Loop through inode btree records in this ag, * until we run out of inodes or space in the buffer. */ while (irbp < irbufend && icount < ubcount) { xfs_inobt_rec_incore_t r; /* * Loop as long as we're unable to read the * inode btree. */ while (error) { agino += XFS_INODES_PER_CHUNK; if (XFS_AGINO_TO_AGBNO(mp, agino) >= be32_to_cpu(agi->agi_length)) break; error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_GE, &tmp); cond_resched(); } /* * If ran off the end of the ag either with an error, * or the normal way, set end and stop collecting. */ if (error) { end_of_ag = 1; break; } error = xfs_inobt_get_rec(cur, &r, &i); if (error || i == 0) { end_of_ag = 1; break; } /* * If this chunk has any allocated inodes, save it. * Also start read-ahead now for this chunk. */ if (r.ir_freecount < XFS_INODES_PER_CHUNK) { /* * Loop over all clusters in the next chunk. * Do a readahead if there are any allocated * inodes in that cluster. */ agbno = XFS_AGINO_TO_AGBNO(mp, r.ir_startino); for (chunkidx = 0; chunkidx < XFS_INODES_PER_CHUNK; chunkidx += nicluster, agbno += nbcluster) { if (xfs_inobt_maskn(chunkidx, nicluster) & ~r.ir_free) xfs_btree_reada_bufs(mp, agno, agbno, nbcluster); } irbp->ir_startino = r.ir_startino; irbp->ir_freecount = r.ir_freecount; irbp->ir_free = r.ir_free; irbp++; icount += XFS_INODES_PER_CHUNK - r.ir_freecount; } /* * Set agino to after this chunk and bump the cursor. */ agino = r.ir_startino + XFS_INODES_PER_CHUNK; error = xfs_btree_increment(cur, 0, &tmp); cond_resched(); } /* * Drop the btree buffers and the agi buffer. * We can't hold any of the locks these represent * when calling iget. */ xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR); xfs_buf_relse(agbp); /* * Now format all the good inodes into the user's buffer. */ irbufend = irbp; for (irbp = irbuf; irbp < irbufend && XFS_BULKSTAT_UBLEFT(ubleft); irbp++) { /* * Now process this chunk of inodes. */ for (agino = irbp->ir_startino, chunkidx = clustidx = 0; XFS_BULKSTAT_UBLEFT(ubleft) && irbp->ir_freecount < XFS_INODES_PER_CHUNK; chunkidx++, clustidx++, agino++) { ASSERT(chunkidx < XFS_INODES_PER_CHUNK); /* * Recompute agbno if this is the * first inode of the cluster. * * Careful with clustidx. There can be * multiple clusters per chunk, a single * cluster per chunk or a cluster that has * inodes represented from several different * chunks (if blocksize is large). * * Because of this, the starting clustidx is * initialized to zero in this loop but must * later be reset after reading in the cluster * buffer. */ if ((chunkidx & (nicluster - 1)) == 0) { agbno = XFS_AGINO_TO_AGBNO(mp, irbp->ir_startino) + ((chunkidx & nimask) >> mp->m_sb.sb_inopblog); } ino = XFS_AGINO_TO_INO(mp, agno, agino); /* * Skip if this inode is free. */ if (XFS_INOBT_MASK(chunkidx) & irbp->ir_free) { lastino = ino; continue; } /* * Count used inodes as free so we can tell * when the chunk is used up. */ irbp->ir_freecount++; /* * Get the inode and fill in a single buffer. */ ubused = statstruct_size; error = formatter(mp, ino, ubufp, ubleft, &ubused, &fmterror); if (fmterror == BULKSTAT_RV_NOTHING) { if (error && error != ENOENT && error != EINVAL) { ubleft = 0; rval = error; break; } lastino = ino; continue; } if (fmterror == BULKSTAT_RV_GIVEUP) { ubleft = 0; ASSERT(error); rval = error; break; } if (ubufp) ubufp += ubused; ubleft -= ubused; ubelem++; lastino = ino; } cond_resched(); } if (bp) xfs_buf_relse(bp); /* * Set up for the next loop iteration. */ if (XFS_BULKSTAT_UBLEFT(ubleft)) { if (end_of_ag) { agno++; agino = 0; } else agino = XFS_INO_TO_AGINO(mp, lastino); } else break; } /* * Done, we're either out of filesystem or space to put the data. */ kmem_free_large(irbuf); *ubcountp = ubelem; /* * Found some inodes, return them now and return the error next time. */ if (ubelem) rval = 0; if (agno >= mp->m_sb.sb_agcount) { /* * If we ran out of filesystem, mark lastino as off * the end of the filesystem, so the next call * will return immediately. */ *lastinop = (xfs_ino_t)XFS_AGINO_TO_INO(mp, agno, 0); *done = 1; } else *lastinop = (xfs_ino_t)lastino; return rval; } /* * Return stat information in bulk (by-inode) for the filesystem. * Special case for non-sequential one inode bulkstat. */ int /* error status */ xfs_bulkstat_single( xfs_mount_t *mp, /* mount point for filesystem */ xfs_ino_t *lastinop, /* inode to return */ char __user *buffer, /* buffer with inode stats */ int *done) /* 1 if there are more stats to get */ { int count; /* count value for bulkstat call */ int error; /* return value */ xfs_ino_t ino; /* filesystem inode number */ int res; /* result from bs1 */ /* * note that requesting valid inode numbers which are not allocated * to inodes will most likely cause xfs_itobp to generate warning * messages about bad magic numbers. This is ok. The fact that * the inode isn't actually an inode is handled by the * error check below. Done this way to make the usual case faster * at the expense of the error case. */ ino = (xfs_ino_t)*lastinop; error = xfs_bulkstat_one(mp, ino, buffer, sizeof(xfs_bstat_t), 0, &res); if (error) { /* * Special case way failed, do it the "long" way * to see if that works. */ (*lastinop)--; count = 1; if (xfs_bulkstat(mp, lastinop, &count, xfs_bulkstat_one, sizeof(xfs_bstat_t), buffer, done)) return error; if (count == 0 || (xfs_ino_t)*lastinop != ino) return error == EFSCORRUPTED ? XFS_ERROR(EINVAL) : error; else return 0; } *done = 0; return 0; } int xfs_inumbers_fmt( void __user *ubuffer, /* buffer to write to */ const xfs_inogrp_t *buffer, /* buffer to read from */ long count, /* # of elements to read */ long *written) /* # of bytes written */ { if (copy_to_user(ubuffer, buffer, count * sizeof(*buffer))) return -EFAULT; *written = count * sizeof(*buffer); return 0; } /* * Return inode number table for the filesystem. */ int /* error status */ xfs_inumbers( xfs_mount_t *mp, /* mount point for filesystem */ xfs_ino_t *lastino, /* last inode returned */ int *count, /* size of buffer/count returned */ void __user *ubuffer,/* buffer with inode descriptions */ inumbers_fmt_pf formatter) { xfs_buf_t *agbp; xfs_agino_t agino; xfs_agnumber_t agno; int bcount; xfs_inogrp_t *buffer; int bufidx; xfs_btree_cur_t *cur; int error; xfs_inobt_rec_incore_t r; int i; xfs_ino_t ino; int left; int tmp; ino = (xfs_ino_t)*lastino; agno = XFS_INO_TO_AGNO(mp, ino); agino = XFS_INO_TO_AGINO(mp, ino); left = *count; *count = 0; bcount = MIN(left, (int)(PAGE_SIZE / sizeof(*buffer))); buffer = kmem_alloc(bcount * sizeof(*buffer), KM_SLEEP); error = bufidx = 0; cur = NULL; agbp = NULL; while (left > 0 && agno < mp->m_sb.sb_agcount) { if (agbp == NULL) { error = xfs_ialloc_read_agi(mp, NULL, agno, &agbp); if (error) { /* * If we can't read the AGI of this ag, * then just skip to the next one. */ ASSERT(cur == NULL); agbp = NULL; agno++; agino = 0; continue; } cur = xfs_inobt_init_cursor(mp, NULL, agbp, agno); error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_GE, &tmp); if (error) { xfs_btree_del_cursor(cur, XFS_BTREE_ERROR); cur = NULL; xfs_buf_relse(agbp); agbp = NULL; /* * Move up the last inode in the current * chunk. The lookup_ge will always get * us the first inode in the next chunk. */ agino += XFS_INODES_PER_CHUNK - 1; continue; } } error = xfs_inobt_get_rec(cur, &r, &i); if (error || i == 0) { xfs_buf_relse(agbp); agbp = NULL; xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR); cur = NULL; agno++; agino = 0; continue; } agino = r.ir_startino + XFS_INODES_PER_CHUNK - 1; buffer[bufidx].xi_startino = XFS_AGINO_TO_INO(mp, agno, r.ir_startino); buffer[bufidx].xi_alloccount = XFS_INODES_PER_CHUNK - r.ir_freecount; buffer[bufidx].xi_allocmask = ~r.ir_free; bufidx++; left--; if (bufidx == bcount) { long written; if (formatter(ubuffer, buffer, bufidx, &written)) { error = XFS_ERROR(EFAULT); break; } ubuffer += written; *count += bufidx; bufidx = 0; } if (left) { error = xfs_btree_increment(cur, 0, &tmp); if (error) { xfs_btree_del_cursor(cur, XFS_BTREE_ERROR); cur = NULL; xfs_buf_relse(agbp); agbp = NULL; /* * The agino value has already been bumped. * Just try to skip up to it. */ agino += XFS_INODES_PER_CHUNK; continue; } } } if (!error) { if (bufidx) { long written; if (formatter(ubuffer, buffer, bufidx, &written)) error = XFS_ERROR(EFAULT); else *count += bufidx; } *lastino = XFS_AGINO_TO_INO(mp, agno, agino); } kmem_free(buffer); if (cur) xfs_btree_del_cursor(cur, (error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR)); if (agbp) xfs_buf_relse(agbp); return error; }
gpl-2.0
CyanogenMod/sony-kernel-u8500
drivers/leds/leds-rb532.c
4808
1761
/* * LEDs driver for the "User LED" on Routerboard532 * * Copyright (C) 2009 Phil Sutter <n0-1@freewrt.org> * * Based on leds-cobalt-qube.c by Florian Fainelly and * rb-diag.c (my own standalone driver for both LED and * button of Routerboard532). */ #include <linux/leds.h> #include <linux/module.h> #include <linux/platform_device.h> #include <asm/mach-rc32434/gpio.h> #include <asm/mach-rc32434/rb.h> static void rb532_led_set(struct led_classdev *cdev, enum led_brightness brightness) { if (brightness) set_latch_u5(LO_ULED, 0); else set_latch_u5(0, LO_ULED); } static enum led_brightness rb532_led_get(struct led_classdev *cdev) { return (get_latch_u5() & LO_ULED) ? LED_FULL : LED_OFF; } static struct led_classdev rb532_uled = { .name = "uled", .brightness_set = rb532_led_set, .brightness_get = rb532_led_get, .default_trigger = "nand-disk", }; static int __devinit rb532_led_probe(struct platform_device *pdev) { return led_classdev_register(&pdev->dev, &rb532_uled); } static int __devexit rb532_led_remove(struct platform_device *pdev) { led_classdev_unregister(&rb532_uled); return 0; } static struct platform_driver rb532_led_driver = { .probe = rb532_led_probe, .remove = __devexit_p(rb532_led_remove), .driver = { .name = "rb532-led", .owner = THIS_MODULE, }, }; static int __init rb532_led_init(void) { return platform_driver_register(&rb532_led_driver); } static void __exit rb532_led_exit(void) { platform_driver_unregister(&rb532_led_driver); } module_init(rb532_led_init); module_exit(rb532_led_exit); MODULE_ALIAS("platform:rb532-led"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("User LED support for Routerboard532"); MODULE_AUTHOR("Phil Sutter <n0-1@freewrt.org>");
gpl-2.0
TEAM-Gummy/android_kernel_lg_g2
drivers/usb/serial/keyspan_pda.c
4808
22262
/* * USB Keyspan PDA / Xircom / Entregra Converter driver * * Copyright (C) 1999 - 2001 Greg Kroah-Hartman <greg@kroah.com> * Copyright (C) 1999, 2000 Brian Warner <warner@lothar.com> * Copyright (C) 2000 Al Borchers <borchers@steinerpoint.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. * * See Documentation/usb/usb-serial.txt for more information on using this * driver */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/workqueue.h> #include <linux/firmware.h> #include <linux/ihex.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> static bool debug; /* make a simple define to handle if we are compiling keyspan_pda or xircom support */ #if defined(CONFIG_USB_SERIAL_KEYSPAN_PDA) || defined(CONFIG_USB_SERIAL_KEYSPAN_PDA_MODULE) #define KEYSPAN #else #undef KEYSPAN #endif #if defined(CONFIG_USB_SERIAL_XIRCOM) || defined(CONFIG_USB_SERIAL_XIRCOM_MODULE) #define XIRCOM #else #undef XIRCOM #endif /* * Version Information */ #define DRIVER_VERSION "v1.1" #define DRIVER_AUTHOR "Brian Warner <warner@lothar.com>" #define DRIVER_DESC "USB Keyspan PDA Converter driver" struct keyspan_pda_private { int tx_room; int tx_throttled; struct work_struct wakeup_work; struct work_struct unthrottle_work; struct usb_serial *serial; struct usb_serial_port *port; }; #define KEYSPAN_VENDOR_ID 0x06cd #define KEYSPAN_PDA_FAKE_ID 0x0103 #define KEYSPAN_PDA_ID 0x0104 /* no clue */ /* For Xircom PGSDB9 and older Entregra version of the same device */ #define XIRCOM_VENDOR_ID 0x085a #define XIRCOM_FAKE_ID 0x8027 #define ENTREGRA_VENDOR_ID 0x1645 #define ENTREGRA_FAKE_ID 0x8093 static const struct usb_device_id id_table_combined[] = { #ifdef KEYSPAN { USB_DEVICE(KEYSPAN_VENDOR_ID, KEYSPAN_PDA_FAKE_ID) }, #endif #ifdef XIRCOM { USB_DEVICE(XIRCOM_VENDOR_ID, XIRCOM_FAKE_ID) }, { USB_DEVICE(ENTREGRA_VENDOR_ID, ENTREGRA_FAKE_ID) }, #endif { USB_DEVICE(KEYSPAN_VENDOR_ID, KEYSPAN_PDA_ID) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table_combined); static struct usb_driver keyspan_pda_driver = { .name = "keyspan_pda", .probe = usb_serial_probe, .disconnect = usb_serial_disconnect, .id_table = id_table_combined, }; static const struct usb_device_id id_table_std[] = { { USB_DEVICE(KEYSPAN_VENDOR_ID, KEYSPAN_PDA_ID) }, { } /* Terminating entry */ }; #ifdef KEYSPAN static const struct usb_device_id id_table_fake[] = { { USB_DEVICE(KEYSPAN_VENDOR_ID, KEYSPAN_PDA_FAKE_ID) }, { } /* Terminating entry */ }; #endif #ifdef XIRCOM static const struct usb_device_id id_table_fake_xircom[] = { { USB_DEVICE(XIRCOM_VENDOR_ID, XIRCOM_FAKE_ID) }, { USB_DEVICE(ENTREGRA_VENDOR_ID, ENTREGRA_FAKE_ID) }, { } }; #endif static void keyspan_pda_wakeup_write(struct work_struct *work) { struct keyspan_pda_private *priv = container_of(work, struct keyspan_pda_private, wakeup_work); struct usb_serial_port *port = priv->port; struct tty_struct *tty = tty_port_tty_get(&port->port); if (tty) tty_wakeup(tty); tty_kref_put(tty); } static void keyspan_pda_request_unthrottle(struct work_struct *work) { struct keyspan_pda_private *priv = container_of(work, struct keyspan_pda_private, unthrottle_work); struct usb_serial *serial = priv->serial; int result; dbg(" request_unthrottle"); /* ask the device to tell us when the tx buffer becomes sufficiently empty */ result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0), 7, /* request_unthrottle */ USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT, 16, /* value: threshold */ 0, /* index */ NULL, 0, 2000); if (result < 0) dbg("%s - error %d from usb_control_msg", __func__, result); } static void keyspan_pda_rx_interrupt(struct urb *urb) { struct usb_serial_port *port = urb->context; struct tty_struct *tty; unsigned char *data = urb->transfer_buffer; int retval; int status = urb->status; struct keyspan_pda_private *priv; priv = usb_get_serial_port_data(port); switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dbg("%s - urb shutting down with status: %d", __func__, status); return; default: dbg("%s - nonzero urb status received: %d", __func__, status); goto exit; } /* see if the message is data or a status interrupt */ switch (data[0]) { case 0: tty = tty_port_tty_get(&port->port); /* rest of message is rx data */ if (tty && urb->actual_length) { tty_insert_flip_string(tty, data + 1, urb->actual_length - 1); tty_flip_buffer_push(tty); } tty_kref_put(tty); break; case 1: /* status interrupt */ dbg(" rx int, d1=%d, d2=%d", data[1], data[2]); switch (data[1]) { case 1: /* modemline change */ break; case 2: /* tx unthrottle interrupt */ priv->tx_throttled = 0; /* queue up a wakeup at scheduler time */ schedule_work(&priv->wakeup_work); break; default: break; } break; default: break; } exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&port->dev, "%s - usb_submit_urb failed with result %d", __func__, retval); } static void keyspan_pda_rx_throttle(struct tty_struct *tty) { /* stop receiving characters. We just turn off the URB request, and let chars pile up in the device. If we're doing hardware flowcontrol, the device will signal the other end when its buffer fills up. If we're doing XON/XOFF, this would be a good time to send an XOFF, although it might make sense to foist that off upon the device too. */ struct usb_serial_port *port = tty->driver_data; dbg("keyspan_pda_rx_throttle port %d", port->number); usb_kill_urb(port->interrupt_in_urb); } static void keyspan_pda_rx_unthrottle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; /* just restart the receive interrupt URB */ dbg("keyspan_pda_rx_unthrottle port %d", port->number); if (usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL)) dbg(" usb_submit_urb(read urb) failed"); } static speed_t keyspan_pda_setbaud(struct usb_serial *serial, speed_t baud) { int rc; int bindex; switch (baud) { case 110: bindex = 0; break; case 300: bindex = 1; break; case 1200: bindex = 2; break; case 2400: bindex = 3; break; case 4800: bindex = 4; break; case 9600: bindex = 5; break; case 19200: bindex = 6; break; case 38400: bindex = 7; break; case 57600: bindex = 8; break; case 115200: bindex = 9; break; default: bindex = 5; /* Default to 9600 */ baud = 9600; } /* rather than figure out how to sleep while waiting for this to complete, I just use the "legacy" API. */ rc = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0), 0, /* set baud */ USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT, /* type */ bindex, /* value */ 0, /* index */ NULL, /* &data */ 0, /* size */ 2000); /* timeout */ if (rc < 0) return 0; return baud; } static void keyspan_pda_break_ctl(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct usb_serial *serial = port->serial; int value; int result; if (break_state == -1) value = 1; /* start break */ else value = 0; /* clear break */ result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0), 4, /* set break */ USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT, value, 0, NULL, 0, 2000); if (result < 0) dbg("%s - error %d from usb_control_msg", __func__, result); /* there is something funky about this.. the TCSBRK that 'cu' performs ought to translate into a break_ctl(-1),break_ctl(0) pair HZ/4 seconds apart, but it feels like the break sent isn't as long as it is on /dev/ttyS0 */ } static void keyspan_pda_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct usb_serial *serial = port->serial; speed_t speed; /* cflag specifies lots of stuff: number of stop bits, parity, number of data bits, baud. What can the device actually handle?: CSTOPB (1 stop bit or 2) PARENB (parity) CSIZE (5bit .. 8bit) There is minimal hw support for parity (a PSW bit seems to hold the parity of whatever is in the accumulator). The UART either deals with 10 bits (start, 8 data, stop) or 11 bits (start, 8 data, 1 special, stop). So, with firmware changes, we could do: 8N1: 10 bit 8N2: 11 bit, extra bit always (mark?) 8[EOMS]1: 11 bit, extra bit is parity 7[EOMS]1: 10 bit, b0/b7 is parity 7[EOMS]2: 11 bit, b0/b7 is parity, extra bit always (mark?) HW flow control is dictated by the tty->termios->c_cflags & CRTSCTS bit. For now, just do baud. */ speed = tty_get_baud_rate(tty); speed = keyspan_pda_setbaud(serial, speed); if (speed == 0) { dbg("can't handle requested baud rate"); /* It hasn't changed so.. */ speed = tty_termios_baud_rate(old_termios); } /* Only speed can change so copy the old h/w parameters then encode the new speed */ tty_termios_copy_hw(tty->termios, old_termios); tty_encode_baud_rate(tty, speed, speed); } /* modem control pins: DTR and RTS are outputs and can be controlled. DCD, RI, DSR, CTS are inputs and can be read. All outputs can also be read. The byte passed is: DTR(b7) DCD RI DSR CTS RTS(b2) unused unused */ static int keyspan_pda_get_modem_info(struct usb_serial *serial, unsigned char *value) { int rc; u8 *data; data = kmalloc(1, GFP_KERNEL); if (!data) return -ENOMEM; rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), 3, /* get pins */ USB_TYPE_VENDOR|USB_RECIP_INTERFACE|USB_DIR_IN, 0, 0, data, 1, 2000); if (rc >= 0) *value = *data; kfree(data); return rc; } static int keyspan_pda_set_modem_info(struct usb_serial *serial, unsigned char value) { int rc; rc = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0), 3, /* set pins */ USB_TYPE_VENDOR|USB_RECIP_INTERFACE|USB_DIR_OUT, value, 0, NULL, 0, 2000); return rc; } static int keyspan_pda_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct usb_serial *serial = port->serial; int rc; unsigned char status; int value; rc = keyspan_pda_get_modem_info(serial, &status); if (rc < 0) return rc; value = ((status & (1<<7)) ? TIOCM_DTR : 0) | ((status & (1<<6)) ? TIOCM_CAR : 0) | ((status & (1<<5)) ? TIOCM_RNG : 0) | ((status & (1<<4)) ? TIOCM_DSR : 0) | ((status & (1<<3)) ? TIOCM_CTS : 0) | ((status & (1<<2)) ? TIOCM_RTS : 0); return value; } static int keyspan_pda_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct usb_serial_port *port = tty->driver_data; struct usb_serial *serial = port->serial; int rc; unsigned char status; rc = keyspan_pda_get_modem_info(serial, &status); if (rc < 0) return rc; if (set & TIOCM_RTS) status |= (1<<2); if (set & TIOCM_DTR) status |= (1<<7); if (clear & TIOCM_RTS) status &= ~(1<<2); if (clear & TIOCM_DTR) status &= ~(1<<7); rc = keyspan_pda_set_modem_info(serial, status); return rc; } static int keyspan_pda_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *buf, int count) { struct usb_serial *serial = port->serial; int request_unthrottle = 0; int rc = 0; struct keyspan_pda_private *priv; priv = usb_get_serial_port_data(port); /* guess how much room is left in the device's ring buffer, and if we want to send more than that, check first, updating our notion of what is left. If our write will result in no room left, ask the device to give us an interrupt when the room available rises above a threshold, and hold off all writers (eventually, those using select() or poll() too) until we receive that unthrottle interrupt. Block if we can't write anything at all, otherwise write as much as we can. */ dbg("keyspan_pda_write(%d)", count); if (count == 0) { dbg(" write request of 0 bytes"); return 0; } /* we might block because of: the TX urb is in-flight (wait until it completes) the device is full (wait until it says there is room) */ spin_lock_bh(&port->lock); if (!test_bit(0, &port->write_urbs_free) || priv->tx_throttled) { spin_unlock_bh(&port->lock); return 0; } clear_bit(0, &port->write_urbs_free); spin_unlock_bh(&port->lock); /* At this point the URB is in our control, nobody else can submit it again (the only sudden transition was the one from EINPROGRESS to finished). Also, the tx process is not throttled. So we are ready to write. */ count = (count > port->bulk_out_size) ? port->bulk_out_size : count; /* Check if we might overrun the Tx buffer. If so, ask the device how much room it really has. This is done only on scheduler time, since usb_control_msg() sleeps. */ if (count > priv->tx_room && !in_interrupt()) { u8 *room; room = kmalloc(1, GFP_KERNEL); if (!room) { rc = -ENOMEM; goto exit; } rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), 6, /* write_room */ USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_IN, 0, /* value: 0 means "remaining room" */ 0, /* index */ room, 1, 2000); if (rc > 0) { dbg(" roomquery says %d", *room); priv->tx_room = *room; } kfree(room); if (rc < 0) { dbg(" roomquery failed"); goto exit; } if (rc == 0) { dbg(" roomquery returned 0 bytes"); rc = -EIO; /* device didn't return any data */ goto exit; } } if (count > priv->tx_room) { /* we're about to completely fill the Tx buffer, so we'll be throttled afterwards. */ count = priv->tx_room; request_unthrottle = 1; } if (count) { /* now transfer data */ memcpy(port->write_urb->transfer_buffer, buf, count); /* send the data out the bulk port */ port->write_urb->transfer_buffer_length = count; priv->tx_room -= count; rc = usb_submit_urb(port->write_urb, GFP_ATOMIC); if (rc) { dbg(" usb_submit_urb(write bulk) failed"); goto exit; } } else { /* There wasn't any room left, so we are throttled until the buffer empties a bit */ request_unthrottle = 1; } if (request_unthrottle) { priv->tx_throttled = 1; /* block writers */ schedule_work(&priv->unthrottle_work); } rc = count; exit: if (rc < 0) set_bit(0, &port->write_urbs_free); return rc; } static void keyspan_pda_write_bulk_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct keyspan_pda_private *priv; set_bit(0, &port->write_urbs_free); priv = usb_get_serial_port_data(port); /* queue up a wakeup at scheduler time */ schedule_work(&priv->wakeup_work); } static int keyspan_pda_write_room(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct keyspan_pda_private *priv; priv = usb_get_serial_port_data(port); /* used by n_tty.c for processing of tabs and such. Giving it our conservative guess is probably good enough, but needs testing by running a console through the device. */ return priv->tx_room; } static int keyspan_pda_chars_in_buffer(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct keyspan_pda_private *priv; unsigned long flags; int ret = 0; priv = usb_get_serial_port_data(port); /* when throttled, return at least WAKEUP_CHARS to tell select() (via n_tty.c:normal_poll() ) that we're not writeable. */ spin_lock_irqsave(&port->lock, flags); if (!test_bit(0, &port->write_urbs_free) || priv->tx_throttled) ret = 256; spin_unlock_irqrestore(&port->lock, flags); return ret; } static void keyspan_pda_dtr_rts(struct usb_serial_port *port, int on) { struct usb_serial *serial = port->serial; if (serial->dev) { if (on) keyspan_pda_set_modem_info(serial, (1<<7) | (1<< 2)); else keyspan_pda_set_modem_info(serial, 0); } } static int keyspan_pda_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; u8 *room; int rc = 0; struct keyspan_pda_private *priv; /* find out how much room is in the Tx ring */ room = kmalloc(1, GFP_KERNEL); if (!room) return -ENOMEM; rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), 6, /* write_room */ USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_IN, 0, /* value */ 0, /* index */ room, 1, 2000); if (rc < 0) { dbg("%s - roomquery failed", __func__); goto error; } if (rc == 0) { dbg("%s - roomquery returned 0 bytes", __func__); rc = -EIO; goto error; } priv = usb_get_serial_port_data(port); priv->tx_room = *room; priv->tx_throttled = *room ? 0 : 1; /*Start reading from the device*/ rc = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (rc) { dbg("%s - usb_submit_urb(read int) failed", __func__); goto error; } error: kfree(room); return rc; } static void keyspan_pda_close(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; if (serial->dev) { /* shutdown our bulk reads and writes */ usb_kill_urb(port->write_urb); usb_kill_urb(port->interrupt_in_urb); } } /* download the firmware to a "fake" device (pre-renumeration) */ static int keyspan_pda_fake_startup(struct usb_serial *serial) { int response; const char *fw_name; const struct ihex_binrec *record; const struct firmware *fw; /* download the firmware here ... */ response = ezusb_set_reset(serial, 1); if (0) { ; } #ifdef KEYSPAN else if (le16_to_cpu(serial->dev->descriptor.idVendor) == KEYSPAN_VENDOR_ID) fw_name = "keyspan_pda/keyspan_pda.fw"; #endif #ifdef XIRCOM else if ((le16_to_cpu(serial->dev->descriptor.idVendor) == XIRCOM_VENDOR_ID) || (le16_to_cpu(serial->dev->descriptor.idVendor) == ENTREGRA_VENDOR_ID)) fw_name = "keyspan_pda/xircom_pgs.fw"; #endif else { dev_err(&serial->dev->dev, "%s: unknown vendor, aborting.\n", __func__); return -ENODEV; } if (request_ihex_firmware(&fw, fw_name, &serial->dev->dev)) { dev_err(&serial->dev->dev, "failed to load firmware \"%s\"\n", fw_name); return -ENOENT; } record = (const struct ihex_binrec *)fw->data; while (record) { response = ezusb_writememory(serial, be32_to_cpu(record->addr), (unsigned char *)record->data, be16_to_cpu(record->len), 0xa0); if (response < 0) { dev_err(&serial->dev->dev, "ezusb_writememory failed " "for Keyspan PDA firmware (%d %04X %p %d)\n", response, be32_to_cpu(record->addr), record->data, be16_to_cpu(record->len)); break; } record = ihex_next_binrec(record); } release_firmware(fw); /* bring device out of reset. Renumeration will occur in a moment and the new device will bind to the real driver */ response = ezusb_set_reset(serial, 0); /* we want this device to fail to have a driver assigned to it. */ return 1; } #ifdef KEYSPAN MODULE_FIRMWARE("keyspan_pda/keyspan_pda.fw"); #endif #ifdef XIRCOM MODULE_FIRMWARE("keyspan_pda/xircom_pgs.fw"); #endif static int keyspan_pda_startup(struct usb_serial *serial) { struct keyspan_pda_private *priv; /* allocate the private data structures for all ports. Well, for all one ports. */ priv = kmalloc(sizeof(struct keyspan_pda_private), GFP_KERNEL); if (!priv) return 1; /* error */ usb_set_serial_port_data(serial->port[0], priv); init_waitqueue_head(&serial->port[0]->write_wait); INIT_WORK(&priv->wakeup_work, keyspan_pda_wakeup_write); INIT_WORK(&priv->unthrottle_work, keyspan_pda_request_unthrottle); priv->serial = serial; priv->port = serial->port[0]; return 0; } static void keyspan_pda_release(struct usb_serial *serial) { dbg("%s", __func__); kfree(usb_get_serial_port_data(serial->port[0])); } #ifdef KEYSPAN static struct usb_serial_driver keyspan_pda_fake_device = { .driver = { .owner = THIS_MODULE, .name = "keyspan_pda_pre", }, .description = "Keyspan PDA - (prerenumeration)", .id_table = id_table_fake, .num_ports = 1, .attach = keyspan_pda_fake_startup, }; #endif #ifdef XIRCOM static struct usb_serial_driver xircom_pgs_fake_device = { .driver = { .owner = THIS_MODULE, .name = "xircom_no_firm", }, .description = "Xircom / Entregra PGS - (prerenumeration)", .id_table = id_table_fake_xircom, .num_ports = 1, .attach = keyspan_pda_fake_startup, }; #endif static struct usb_serial_driver keyspan_pda_device = { .driver = { .owner = THIS_MODULE, .name = "keyspan_pda", }, .description = "Keyspan PDA", .id_table = id_table_std, .num_ports = 1, .dtr_rts = keyspan_pda_dtr_rts, .open = keyspan_pda_open, .close = keyspan_pda_close, .write = keyspan_pda_write, .write_room = keyspan_pda_write_room, .write_bulk_callback = keyspan_pda_write_bulk_callback, .read_int_callback = keyspan_pda_rx_interrupt, .chars_in_buffer = keyspan_pda_chars_in_buffer, .throttle = keyspan_pda_rx_throttle, .unthrottle = keyspan_pda_rx_unthrottle, .set_termios = keyspan_pda_set_termios, .break_ctl = keyspan_pda_break_ctl, .tiocmget = keyspan_pda_tiocmget, .tiocmset = keyspan_pda_tiocmset, .attach = keyspan_pda_startup, .release = keyspan_pda_release, }; static struct usb_serial_driver * const serial_drivers[] = { &keyspan_pda_device, #ifdef KEYSPAN &keyspan_pda_fake_device, #endif #ifdef XIRCOM &xircom_pgs_fake_device, #endif NULL }; module_usb_serial_driver(keyspan_pda_driver, serial_drivers); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); module_param(debug, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug, "Debug enabled or not");
gpl-2.0
drewx2/android_kernel_htc_dlx
sound/soc/codecs/ak4104.c
4808
6152
/* * AK4104 ALSA SoC (ASoC) driver * * Copyright (c) 2009 Daniel Mack <daniel@caiaq.de> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/soc.h> #include <sound/initval.h> #include <linux/spi/spi.h> #include <sound/asoundef.h> /* AK4104 registers addresses */ #define AK4104_REG_CONTROL1 0x00 #define AK4104_REG_RESERVED 0x01 #define AK4104_REG_CONTROL2 0x02 #define AK4104_REG_TX 0x03 #define AK4104_REG_CHN_STATUS(x) ((x) + 0x04) #define AK4104_NUM_REGS 10 #define AK4104_REG_MASK 0x1f #define AK4104_READ 0xc0 #define AK4104_WRITE 0xe0 #define AK4104_RESERVED_VAL 0x5b /* Bit masks for AK4104 registers */ #define AK4104_CONTROL1_RSTN (1 << 0) #define AK4104_CONTROL1_PW (1 << 1) #define AK4104_CONTROL1_DIF0 (1 << 2) #define AK4104_CONTROL1_DIF1 (1 << 3) #define AK4104_CONTROL2_SEL0 (1 << 0) #define AK4104_CONTROL2_SEL1 (1 << 1) #define AK4104_CONTROL2_MODE (1 << 2) #define AK4104_TX_TXE (1 << 0) #define AK4104_TX_V (1 << 1) #define DRV_NAME "ak4104-codec" struct ak4104_private { struct regmap *regmap; }; static int ak4104_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int format) { struct snd_soc_codec *codec = codec_dai->codec; int val = 0; int ret; /* set DAI format */ switch (format & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_RIGHT_J: break; case SND_SOC_DAIFMT_LEFT_J: val |= AK4104_CONTROL1_DIF0; break; case SND_SOC_DAIFMT_I2S: val |= AK4104_CONTROL1_DIF0 | AK4104_CONTROL1_DIF1; break; default: dev_err(codec->dev, "invalid dai format\n"); return -EINVAL; } /* This device can only be slave */ if ((format & SND_SOC_DAIFMT_MASTER_MASK) != SND_SOC_DAIFMT_CBS_CFS) return -EINVAL; ret = snd_soc_update_bits(codec, AK4104_REG_CONTROL1, AK4104_CONTROL1_DIF0 | AK4104_CONTROL1_DIF1, val); if (ret < 0) return ret; return 0; } static int ak4104_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; int val = 0; /* set the IEC958 bits: consumer mode, no copyright bit */ val |= IEC958_AES0_CON_NOT_COPYRIGHT; snd_soc_write(codec, AK4104_REG_CHN_STATUS(0), val); val = 0; switch (params_rate(params)) { case 44100: val |= IEC958_AES3_CON_FS_44100; break; case 48000: val |= IEC958_AES3_CON_FS_48000; break; case 32000: val |= IEC958_AES3_CON_FS_32000; break; default: dev_err(codec->dev, "unsupported sampling rate\n"); return -EINVAL; } return snd_soc_write(codec, AK4104_REG_CHN_STATUS(3), val); } static const struct snd_soc_dai_ops ak4101_dai_ops = { .hw_params = ak4104_hw_params, .set_fmt = ak4104_set_dai_fmt, }; static struct snd_soc_dai_driver ak4104_dai = { .name = "ak4104-hifi", .playback = { .stream_name = "Playback", .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_192000, .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_LE }, .ops = &ak4101_dai_ops, }; static int ak4104_probe(struct snd_soc_codec *codec) { struct ak4104_private *ak4104 = snd_soc_codec_get_drvdata(codec); int ret; codec->control_data = ak4104->regmap; ret = snd_soc_codec_set_cache_io(codec, 8, 8, SND_SOC_REGMAP); if (ret != 0) return ret; /* set power-up and non-reset bits */ ret = snd_soc_update_bits(codec, AK4104_REG_CONTROL1, AK4104_CONTROL1_PW | AK4104_CONTROL1_RSTN, AK4104_CONTROL1_PW | AK4104_CONTROL1_RSTN); if (ret < 0) return ret; /* enable transmitter */ ret = snd_soc_update_bits(codec, AK4104_REG_TX, AK4104_TX_TXE, AK4104_TX_TXE); if (ret < 0) return ret; return 0; } static int ak4104_remove(struct snd_soc_codec *codec) { snd_soc_update_bits(codec, AK4104_REG_CONTROL1, AK4104_CONTROL1_PW | AK4104_CONTROL1_RSTN, 0); return 0; } static struct snd_soc_codec_driver soc_codec_device_ak4104 = { .probe = ak4104_probe, .remove = ak4104_remove, }; static const struct regmap_config ak4104_regmap = { .reg_bits = 8, .val_bits = 8, .max_register = AK4104_NUM_REGS - 1, .read_flag_mask = AK4104_READ, .write_flag_mask = AK4104_WRITE, .cache_type = REGCACHE_RBTREE, }; static int ak4104_spi_probe(struct spi_device *spi) { struct ak4104_private *ak4104; unsigned int val; int ret; spi->bits_per_word = 8; spi->mode = SPI_MODE_0; ret = spi_setup(spi); if (ret < 0) return ret; ak4104 = devm_kzalloc(&spi->dev, sizeof(struct ak4104_private), GFP_KERNEL); if (ak4104 == NULL) return -ENOMEM; ak4104->regmap = regmap_init_spi(spi, &ak4104_regmap); if (IS_ERR(ak4104->regmap)) { ret = PTR_ERR(ak4104->regmap); return ret; } /* read the 'reserved' register - according to the datasheet, it * should contain 0x5b. Not a good way to verify the presence of * the device, but there is no hardware ID register. */ ret = regmap_read(ak4104->regmap, AK4104_REG_RESERVED, &val); if (ret != 0) goto err; if (val != AK4104_RESERVED_VAL) { ret = -ENODEV; goto err; } spi_set_drvdata(spi, ak4104); ret = snd_soc_register_codec(&spi->dev, &soc_codec_device_ak4104, &ak4104_dai, 1); if (ret != 0) goto err; return 0; err: regmap_exit(ak4104->regmap); return ret; } static int __devexit ak4104_spi_remove(struct spi_device *spi) { struct ak4104_private *ak4101 = spi_get_drvdata(spi); regmap_exit(ak4101->regmap); snd_soc_unregister_codec(&spi->dev); return 0; } static struct spi_driver ak4104_spi_driver = { .driver = { .name = DRV_NAME, .owner = THIS_MODULE, }, .probe = ak4104_spi_probe, .remove = __devexit_p(ak4104_spi_remove), }; module_spi_driver(ak4104_spi_driver); MODULE_AUTHOR("Daniel Mack <daniel@caiaq.de>"); MODULE_DESCRIPTION("Asahi Kasei AK4104 ALSA SoC driver"); MODULE_LICENSE("GPL");
gpl-2.0
cristianomatos/android_kernel_motorola_msm8226
drivers/power/max8903_charger.c
5064
9292
/* * max8903_charger.c - Maxim 8903 USB/Adapter Charger Driver * * Copyright (C) 2011 Samsung Electronics * MyungJoo Ham <myungjoo.ham@samsung.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/gpio.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/power_supply.h> #include <linux/platform_device.h> #include <linux/power/max8903_charger.h> struct max8903_data { struct max8903_pdata pdata; struct device *dev; struct power_supply psy; bool fault; bool usb_in; bool ta_in; }; static enum power_supply_property max8903_charger_props[] = { POWER_SUPPLY_PROP_STATUS, /* Charger status output */ POWER_SUPPLY_PROP_ONLINE, /* External power source */ POWER_SUPPLY_PROP_HEALTH, /* Fault or OK */ }; static int max8903_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max8903_data *data = container_of(psy, struct max8903_data, psy); switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = POWER_SUPPLY_STATUS_UNKNOWN; if (data->pdata.chg) { if (gpio_get_value(data->pdata.chg) == 0) val->intval = POWER_SUPPLY_STATUS_CHARGING; else if (data->usb_in || data->ta_in) val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; else val->intval = POWER_SUPPLY_STATUS_DISCHARGING; } break; case POWER_SUPPLY_PROP_ONLINE: val->intval = 0; if (data->usb_in || data->ta_in) val->intval = 1; break; case POWER_SUPPLY_PROP_HEALTH: val->intval = POWER_SUPPLY_HEALTH_GOOD; if (data->fault) val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; break; default: return -EINVAL; } return 0; } static irqreturn_t max8903_dcin(int irq, void *_data) { struct max8903_data *data = _data; struct max8903_pdata *pdata = &data->pdata; bool ta_in; enum power_supply_type old_type; ta_in = gpio_get_value(pdata->dok) ? false : true; if (ta_in == data->ta_in) return IRQ_HANDLED; data->ta_in = ta_in; /* Set Current-Limit-Mode 1:DC 0:USB */ if (pdata->dcm) gpio_set_value(pdata->dcm, ta_in ? 1 : 0); /* Charger Enable / Disable (cen is negated) */ if (pdata->cen) gpio_set_value(pdata->cen, ta_in ? 0 : (data->usb_in ? 0 : 1)); dev_dbg(data->dev, "TA(DC-IN) Charger %s.\n", ta_in ? "Connected" : "Disconnected"); old_type = data->psy.type; if (data->ta_in) data->psy.type = POWER_SUPPLY_TYPE_MAINS; else if (data->usb_in) data->psy.type = POWER_SUPPLY_TYPE_USB; else data->psy.type = POWER_SUPPLY_TYPE_BATTERY; if (old_type != data->psy.type) power_supply_changed(&data->psy); return IRQ_HANDLED; } static irqreturn_t max8903_usbin(int irq, void *_data) { struct max8903_data *data = _data; struct max8903_pdata *pdata = &data->pdata; bool usb_in; enum power_supply_type old_type; usb_in = gpio_get_value(pdata->uok) ? false : true; if (usb_in == data->usb_in) return IRQ_HANDLED; data->usb_in = usb_in; /* Do not touch Current-Limit-Mode */ /* Charger Enable / Disable (cen is negated) */ if (pdata->cen) gpio_set_value(pdata->cen, usb_in ? 0 : (data->ta_in ? 0 : 1)); dev_dbg(data->dev, "USB Charger %s.\n", usb_in ? "Connected" : "Disconnected"); old_type = data->psy.type; if (data->ta_in) data->psy.type = POWER_SUPPLY_TYPE_MAINS; else if (data->usb_in) data->psy.type = POWER_SUPPLY_TYPE_USB; else data->psy.type = POWER_SUPPLY_TYPE_BATTERY; if (old_type != data->psy.type) power_supply_changed(&data->psy); return IRQ_HANDLED; } static irqreturn_t max8903_fault(int irq, void *_data) { struct max8903_data *data = _data; struct max8903_pdata *pdata = &data->pdata; bool fault; fault = gpio_get_value(pdata->flt) ? false : true; if (fault == data->fault) return IRQ_HANDLED; data->fault = fault; if (fault) dev_err(data->dev, "Charger suffers a fault and stops.\n"); else dev_err(data->dev, "Charger recovered from a fault.\n"); return IRQ_HANDLED; } static __devinit int max8903_probe(struct platform_device *pdev) { struct max8903_data *data; struct device *dev = &pdev->dev; struct max8903_pdata *pdata = pdev->dev.platform_data; int ret = 0; int gpio; int ta_in = 0; int usb_in = 0; data = kzalloc(sizeof(struct max8903_data), GFP_KERNEL); if (data == NULL) { dev_err(dev, "Cannot allocate memory.\n"); return -ENOMEM; } memcpy(&data->pdata, pdata, sizeof(struct max8903_pdata)); data->dev = dev; platform_set_drvdata(pdev, data); if (pdata->dc_valid == false && pdata->usb_valid == false) { dev_err(dev, "No valid power sources.\n"); ret = -EINVAL; goto err; } if (pdata->dc_valid) { if (pdata->dok && gpio_is_valid(pdata->dok) && pdata->dcm && gpio_is_valid(pdata->dcm)) { gpio = pdata->dok; /* PULL_UPed Interrupt */ ta_in = gpio_get_value(gpio) ? 0 : 1; gpio = pdata->dcm; /* Output */ gpio_set_value(gpio, ta_in); } else { dev_err(dev, "When DC is wired, DOK and DCM should" " be wired as well.\n"); ret = -EINVAL; goto err; } } else { if (pdata->dcm) { if (gpio_is_valid(pdata->dcm)) gpio_set_value(pdata->dcm, 0); else { dev_err(dev, "Invalid pin: dcm.\n"); ret = -EINVAL; goto err; } } } if (pdata->usb_valid) { if (pdata->uok && gpio_is_valid(pdata->uok)) { gpio = pdata->uok; usb_in = gpio_get_value(gpio) ? 0 : 1; } else { dev_err(dev, "When USB is wired, UOK should be wired." "as well.\n"); ret = -EINVAL; goto err; } } if (pdata->cen) { if (gpio_is_valid(pdata->cen)) { gpio_set_value(pdata->cen, (ta_in || usb_in) ? 0 : 1); } else { dev_err(dev, "Invalid pin: cen.\n"); ret = -EINVAL; goto err; } } if (pdata->chg) { if (!gpio_is_valid(pdata->chg)) { dev_err(dev, "Invalid pin: chg.\n"); ret = -EINVAL; goto err; } } if (pdata->flt) { if (!gpio_is_valid(pdata->flt)) { dev_err(dev, "Invalid pin: flt.\n"); ret = -EINVAL; goto err; } } if (pdata->usus) { if (!gpio_is_valid(pdata->usus)) { dev_err(dev, "Invalid pin: usus.\n"); ret = -EINVAL; goto err; } } data->fault = false; data->ta_in = ta_in; data->usb_in = usb_in; data->psy.name = "max8903_charger"; data->psy.type = (ta_in) ? POWER_SUPPLY_TYPE_MAINS : ((usb_in) ? POWER_SUPPLY_TYPE_USB : POWER_SUPPLY_TYPE_BATTERY); data->psy.get_property = max8903_get_property; data->psy.properties = max8903_charger_props; data->psy.num_properties = ARRAY_SIZE(max8903_charger_props); ret = power_supply_register(dev, &data->psy); if (ret) { dev_err(dev, "failed: power supply register.\n"); goto err; } if (pdata->dc_valid) { ret = request_threaded_irq(gpio_to_irq(pdata->dok), NULL, max8903_dcin, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "MAX8903 DC IN", data); if (ret) { dev_err(dev, "Cannot request irq %d for DC (%d)\n", gpio_to_irq(pdata->dok), ret); goto err_psy; } } if (pdata->usb_valid) { ret = request_threaded_irq(gpio_to_irq(pdata->uok), NULL, max8903_usbin, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "MAX8903 USB IN", data); if (ret) { dev_err(dev, "Cannot request irq %d for USB (%d)\n", gpio_to_irq(pdata->uok), ret); goto err_dc_irq; } } if (pdata->flt) { ret = request_threaded_irq(gpio_to_irq(pdata->flt), NULL, max8903_fault, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "MAX8903 Fault", data); if (ret) { dev_err(dev, "Cannot request irq %d for Fault (%d)\n", gpio_to_irq(pdata->flt), ret); goto err_usb_irq; } } return 0; err_usb_irq: if (pdata->usb_valid) free_irq(gpio_to_irq(pdata->uok), data); err_dc_irq: if (pdata->dc_valid) free_irq(gpio_to_irq(pdata->dok), data); err_psy: power_supply_unregister(&data->psy); err: kfree(data); return ret; } static __devexit int max8903_remove(struct platform_device *pdev) { struct max8903_data *data = platform_get_drvdata(pdev); if (data) { struct max8903_pdata *pdata = &data->pdata; if (pdata->flt) free_irq(gpio_to_irq(pdata->flt), data); if (pdata->usb_valid) free_irq(gpio_to_irq(pdata->uok), data); if (pdata->dc_valid) free_irq(gpio_to_irq(pdata->dok), data); power_supply_unregister(&data->psy); kfree(data); } return 0; } static struct platform_driver max8903_driver = { .probe = max8903_probe, .remove = __devexit_p(max8903_remove), .driver = { .name = "max8903-charger", .owner = THIS_MODULE, }, }; module_platform_driver(max8903_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("MAX8903 Charger Driver"); MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>"); MODULE_ALIAS("platform:max8903-charger");
gpl-2.0
Eliminater74/D851_20G_Kernel_Stock
drivers/gpio/gpio-xilinx.c
5064
7155
/* * Xilinx gpio driver * * Copyright 2008 Xilinx, 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. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/errno.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/of_platform.h> #include <linux/of_gpio.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/slab.h> /* Register Offset Definitions */ #define XGPIO_DATA_OFFSET (0x0) /* Data register */ #define XGPIO_TRI_OFFSET (0x4) /* I/O direction register */ struct xgpio_instance { struct of_mm_gpio_chip mmchip; u32 gpio_state; /* GPIO state shadow register */ u32 gpio_dir; /* GPIO direction shadow register */ spinlock_t gpio_lock; /* Lock used for synchronization */ }; /** * xgpio_get - Read the specified signal of the GPIO device. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * * This function reads the specified signal of the GPIO device. It returns 0 if * the signal clear, 1 if signal is set or negative value on error. */ static int xgpio_get(struct gpio_chip *gc, unsigned int gpio) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); return (in_be32(mm_gc->regs + XGPIO_DATA_OFFSET) >> gpio) & 1; } /** * xgpio_set - Write the specified signal of the GPIO device. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * @val: Value to be written to specified signal. * * This function writes the specified value in to the specified signal of the * GPIO device. */ static void xgpio_set(struct gpio_chip *gc, unsigned int gpio, int val) { unsigned long flags; struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); spin_lock_irqsave(&chip->gpio_lock, flags); /* Write to GPIO signal and set its direction to output */ if (val) chip->gpio_state |= 1 << gpio; else chip->gpio_state &= ~(1 << gpio); out_be32(mm_gc->regs + XGPIO_DATA_OFFSET, chip->gpio_state); spin_unlock_irqrestore(&chip->gpio_lock, flags); } /** * xgpio_dir_in - Set the direction of the specified GPIO signal as input. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * * This function sets the direction of specified GPIO signal as input. * It returns 0 if direction of GPIO signals is set as input otherwise it * returns negative error value. */ static int xgpio_dir_in(struct gpio_chip *gc, unsigned int gpio) { unsigned long flags; struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); spin_lock_irqsave(&chip->gpio_lock, flags); /* Set the GPIO bit in shadow register and set direction as input */ chip->gpio_dir |= (1 << gpio); out_be32(mm_gc->regs + XGPIO_TRI_OFFSET, chip->gpio_dir); spin_unlock_irqrestore(&chip->gpio_lock, flags); return 0; } /** * xgpio_dir_out - Set the direction of the specified GPIO signal as output. * @gc: Pointer to gpio_chip device structure. * @gpio: GPIO signal number. * @val: Value to be written to specified signal. * * This function sets the direction of specified GPIO signal as output. If all * GPIO signals of GPIO chip is configured as input then it returns * error otherwise it returns 0. */ static int xgpio_dir_out(struct gpio_chip *gc, unsigned int gpio, int val) { unsigned long flags; struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); spin_lock_irqsave(&chip->gpio_lock, flags); /* Write state of GPIO signal */ if (val) chip->gpio_state |= 1 << gpio; else chip->gpio_state &= ~(1 << gpio); out_be32(mm_gc->regs + XGPIO_DATA_OFFSET, chip->gpio_state); /* Clear the GPIO bit in shadow register and set direction as output */ chip->gpio_dir &= (~(1 << gpio)); out_be32(mm_gc->regs + XGPIO_TRI_OFFSET, chip->gpio_dir); spin_unlock_irqrestore(&chip->gpio_lock, flags); return 0; } /** * xgpio_save_regs - Set initial values of GPIO pins * @mm_gc: pointer to memory mapped GPIO chip structure */ static void xgpio_save_regs(struct of_mm_gpio_chip *mm_gc) { struct xgpio_instance *chip = container_of(mm_gc, struct xgpio_instance, mmchip); out_be32(mm_gc->regs + XGPIO_DATA_OFFSET, chip->gpio_state); out_be32(mm_gc->regs + XGPIO_TRI_OFFSET, chip->gpio_dir); } /** * xgpio_of_probe - Probe method for the GPIO device. * @np: pointer to device tree node * * This function probes the GPIO device in the device tree. It initializes the * driver data structure. It returns 0, if the driver is bound to the GPIO * device, or a negative value if there is an error. */ static int __devinit xgpio_of_probe(struct device_node *np) { struct xgpio_instance *chip; int status = 0; const u32 *tree_info; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; /* Update GPIO state shadow register with default value */ tree_info = of_get_property(np, "xlnx,dout-default", NULL); if (tree_info) chip->gpio_state = be32_to_cpup(tree_info); /* Update GPIO direction shadow register with default value */ chip->gpio_dir = 0xFFFFFFFF; /* By default, all pins are inputs */ tree_info = of_get_property(np, "xlnx,tri-default", NULL); if (tree_info) chip->gpio_dir = be32_to_cpup(tree_info); /* Check device node and parent device node for device width */ chip->mmchip.gc.ngpio = 32; /* By default assume full GPIO controller */ tree_info = of_get_property(np, "xlnx,gpio-width", NULL); if (!tree_info) tree_info = of_get_property(np->parent, "xlnx,gpio-width", NULL); if (tree_info) chip->mmchip.gc.ngpio = be32_to_cpup(tree_info); spin_lock_init(&chip->gpio_lock); chip->mmchip.gc.direction_input = xgpio_dir_in; chip->mmchip.gc.direction_output = xgpio_dir_out; chip->mmchip.gc.get = xgpio_get; chip->mmchip.gc.set = xgpio_set; chip->mmchip.save_regs = xgpio_save_regs; /* Call the OF gpio helper to setup and register the GPIO device */ status = of_mm_gpiochip_add(np, &chip->mmchip); if (status) { kfree(chip); pr_err("%s: error in probe function with status %d\n", np->full_name, status); return status; } return 0; } static struct of_device_id xgpio_of_match[] __devinitdata = { { .compatible = "xlnx,xps-gpio-1.00.a", }, { /* end of list */ }, }; static int __init xgpio_init(void) { struct device_node *np; for_each_matching_node(np, xgpio_of_match) xgpio_of_probe(np); return 0; } /* Make sure we get initialized before anyone else tries to use us */ subsys_initcall(xgpio_init); /* No exit call at the moment as we cannot unregister of GPIO chips */ MODULE_AUTHOR("Xilinx, Inc."); MODULE_DESCRIPTION("Xilinx GPIO driver"); MODULE_LICENSE("GPL");
gpl-2.0
friedrich420/S6_UniKernel_v2
fs/ncpfs/getopt.c
12744
1903
/* * getopt.c */ #include <linux/kernel.h> #include <linux/string.h> #include <asm/errno.h> #include "getopt.h" /** * ncp_getopt - option parser * @caller: name of the caller, for error messages * @options: the options string * @opts: an array of &struct option entries controlling parser operations * @optopt: output; will contain the current option * @optarg: output; will contain the value (if one exists) * @value: output; may be NULL; will be overwritten with the integer value * of the current argument. * * Helper to parse options on the format used by mount ("a=b,c=d,e,f"). * Returns opts->val if a matching entry in the 'opts' array is found, * 0 when no more tokens are found, -1 if an error is encountered. */ int ncp_getopt(const char *caller, char **options, const struct ncp_option *opts, char **optopt, char **optarg, unsigned long *value) { char *token; char *val; do { if ((token = strsep(options, ",")) == NULL) return 0; } while (*token == '\0'); if (optopt) *optopt = token; if ((val = strchr (token, '=')) != NULL) { *val++ = 0; } *optarg = val; for (; opts->name; opts++) { if (!strcmp(opts->name, token)) { if (!val) { if (opts->has_arg & OPT_NOPARAM) { return opts->val; } printk(KERN_INFO "%s: the %s option requires an argument\n", caller, token); return -EINVAL; } if (opts->has_arg & OPT_INT) { char* v; *value = simple_strtoul(val, &v, 0); if (!*v) { return opts->val; } printk(KERN_INFO "%s: invalid numeric value in %s=%s\n", caller, token, val); return -EDOM; } if (opts->has_arg & OPT_STRING) { return opts->val; } printk(KERN_INFO "%s: unexpected argument %s to the %s option\n", caller, val, token); return -EINVAL; } } printk(KERN_INFO "%s: Unrecognized mount option %s\n", caller, token); return -EOPNOTSUPP; }
gpl-2.0
flar2/villec2-bulletproof
net/netfilter/xt_pkttype.c
13768
1686
/* (C) 1999-2001 Michal Ludvig <michal@logix.cz> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/skbuff.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/netfilter/xt_pkttype.h> #include <linux/netfilter/x_tables.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Michal Ludvig <michal@logix.cz>"); MODULE_DESCRIPTION("Xtables: link layer packet type match"); MODULE_ALIAS("ipt_pkttype"); MODULE_ALIAS("ip6t_pkttype"); static bool pkttype_mt(const struct sk_buff *skb, struct xt_action_param *par) { const struct xt_pkttype_info *info = par->matchinfo; u_int8_t type; if (skb->pkt_type != PACKET_LOOPBACK) type = skb->pkt_type; else if (par->family == NFPROTO_IPV4 && ipv4_is_multicast(ip_hdr(skb)->daddr)) type = PACKET_MULTICAST; else if (par->family == NFPROTO_IPV6 && ipv6_hdr(skb)->daddr.s6_addr[0] == 0xFF) type = PACKET_MULTICAST; else type = PACKET_BROADCAST; return (type == info->pkttype) ^ info->invert; } static struct xt_match pkttype_mt_reg __read_mostly = { .name = "pkttype", .revision = 0, .family = NFPROTO_UNSPEC, .match = pkttype_mt, .matchsize = sizeof(struct xt_pkttype_info), .me = THIS_MODULE, }; static int __init pkttype_mt_init(void) { return xt_register_match(&pkttype_mt_reg); } static void __exit pkttype_mt_exit(void) { xt_unregister_match(&pkttype_mt_reg); } module_init(pkttype_mt_init); module_exit(pkttype_mt_exit);
gpl-2.0
BAGAsss/mrmc
tools/depends/target/libcpluff/cpluff/console/cmdinput_readline.c
201
5498
/*------------------------------------------------------------------------- * C-Pluff, a plug-in framework for C * Copyright 2007 Johannes Lehtinen * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *-----------------------------------------------------------------------*/ // GNU readline based command line input #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <readline/readline.h> #include <readline/history.h> #include "console.h" static cp_plugin_info_t **plugins = NULL; static char *cp_console_compl_cmdgen(const char *text, int state) { static int counter; static int textlen; if (!state) { counter = 0; textlen = strlen(text); } while (commands[counter].name != NULL && strncmp(text, commands[counter].name, textlen)) { counter++; } if (commands[counter].name == NULL) { return NULL; } else { char *buffer = strdup(commands[counter].name); counter++; return buffer; } } static char *cp_console_compl_flagsgen(const char *text, int state) { static int counter; static int textlen; if (!state) { counter = 0; textlen = strlen(text); } while(load_flags[counter].name != NULL && strncmp(text, load_flags[counter].name, textlen)) { counter++; } if (load_flags[counter].name == NULL) { return NULL; } else { char *buffer = strdup(load_flags[counter].name); counter++; return buffer; } } static char *cp_console_compl_loggen(const char *text, int state) { static int counter; static int textlen; if (!state) { counter = 0; textlen = strlen(text); } while (log_levels[counter].name != NULL && strncmp(text, log_levels[counter].name, textlen)) { counter++; } if (log_levels[counter].name == NULL) { return NULL; } else { char *buffer = strdup(log_levels[counter].name); counter++; return buffer; } } static char *cp_console_compl_plugingen(const char *text, int state) { static int counter; static int textlen; if (!state) { counter = 0; textlen = strlen(text); if (plugins != NULL) { cp_release_info(context, plugins); } plugins = cp_get_plugins_info(context, NULL, NULL); } if (plugins != NULL) { while (plugins[counter] != NULL && strncmp(text, plugins[counter]->identifier, textlen)) { counter++; } if (plugins[counter] == NULL) { cp_release_info(context, plugins); plugins = NULL; return NULL; } else { char *buffer = strdup(plugins[counter]->identifier); counter++; return buffer; } } else { return NULL; } } static char **cp_console_completion(const char *text, int start, int end) { int cs, ce; char **matches = NULL; // Search for start and end of command for (cs = 0; cs < start && isspace(rl_line_buffer[cs]); cs++); for (ce = cs; ce <= start && !isspace(rl_line_buffer[ce]); ce++); // If no command entered yet, use command completion if (ce >= start) { matches = rl_completion_matches(text, cp_console_compl_cmdgen); rl_attempted_completion_over = 1; } // Otherwise check if known command and complete accordingly else { int j = 0; while (commands[j].name != NULL && strncmp(rl_line_buffer + cs, commands[j].name, ce - cs)) { j++; } if (commands[j].name != NULL) { switch(commands[j].arg_completion) { case CPC_COMPL_FILE: break; case CPC_COMPL_FLAG: matches = rl_completion_matches(text, cp_console_compl_flagsgen); rl_attempted_completion_over = 1; break; case CPC_COMPL_LOG_LEVEL: matches = rl_completion_matches(text, cp_console_compl_loggen); rl_attempted_completion_over = 1; break; case CPC_COMPL_PLUGIN: matches = rl_completion_matches(text, cp_console_compl_plugingen); rl_attempted_completion_over = 1; break; default: rl_attempted_completion_over = 1; break; } } else { rl_attempted_completion_over = 1; } } return matches; } CP_HIDDEN void cmdline_init(void) { rl_readline_name = PACKAGE_NAME; rl_attempted_completion_function = cp_console_completion; } CP_HIDDEN char *cmdline_input(const char *prompt) { static char *cmdline = NULL; // Free previously returned command line, if any if (cmdline != NULL) { free(cmdline); cmdline = NULL; } // Obtain new command line and record it for history cmdline = readline(prompt); if (cmdline != NULL && *cmdline != '\0') { add_history(cmdline); } return cmdline; } CP_HIDDEN void cmdline_destroy(void) { if (plugins != NULL) { cp_release_info(context, plugins); plugins = NULL; } }
gpl-2.0
CyanogenMod/android_kernel_motorola_msm8916
fs/nfs/nfs4state.c
457
59837
/* * fs/nfs/nfs4state.c * * Client-side XDR for NFSv4. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Kendrick Smith <kmsmith@umich.edu> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Implementation of the NFSv4 state model. For the time being, * this is minimal, but will be made much more complex in a * subsequent patch. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/nfs_fs.h> #include <linux/nfs_idmap.h> #include <linux/kthread.h> #include <linux/module.h> #include <linux/random.h> #include <linux/ratelimit.h> #include <linux/workqueue.h> #include <linux/bitops.h> #include <linux/jiffies.h> #include <linux/sunrpc/clnt.h> #include "nfs4_fs.h" #include "callback.h" #include "delegation.h" #include "internal.h" #include "nfs4session.h" #include "pnfs.h" #include "netns.h" #define NFSDBG_FACILITY NFSDBG_STATE #define OPENOWNER_POOL_SIZE 8 const nfs4_stateid zero_stateid; static DEFINE_MUTEX(nfs_clid_init_mutex); int nfs4_init_clientid(struct nfs_client *clp, struct rpc_cred *cred) { struct nfs4_setclientid_res clid = { .clientid = clp->cl_clientid, .confirm = clp->cl_confirm, }; unsigned short port; int status; struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id); if (test_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state)) goto do_confirm; port = nn->nfs_callback_tcpport; if (clp->cl_addr.ss_family == AF_INET6) port = nn->nfs_callback_tcpport6; status = nfs4_proc_setclientid(clp, NFS4_CALLBACK, port, cred, &clid); if (status != 0) goto out; clp->cl_clientid = clid.clientid; clp->cl_confirm = clid.confirm; set_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); do_confirm: status = nfs4_proc_setclientid_confirm(clp, &clid, cred); if (status != 0) goto out; clear_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); nfs4_schedule_state_renewal(clp); out: return status; } /** * nfs40_discover_server_trunking - Detect server IP address trunking (mv0) * * @clp: nfs_client under test * @result: OUT: found nfs_client, or clp * @cred: credential to use for trunking test * * Returns zero, a negative errno, or a negative NFS4ERR status. * If zero is returned, an nfs_client pointer is planted in * "result". * * Note: The returned client may not yet be marked ready. */ int nfs40_discover_server_trunking(struct nfs_client *clp, struct nfs_client **result, struct rpc_cred *cred) { struct nfs4_setclientid_res clid = { .clientid = clp->cl_clientid, .confirm = clp->cl_confirm, }; struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id); unsigned short port; int status; port = nn->nfs_callback_tcpport; if (clp->cl_addr.ss_family == AF_INET6) port = nn->nfs_callback_tcpport6; status = nfs4_proc_setclientid(clp, NFS4_CALLBACK, port, cred, &clid); if (status != 0) goto out; clp->cl_clientid = clid.clientid; clp->cl_confirm = clid.confirm; status = nfs40_walk_client_list(clp, result, cred); if (status == 0) { /* Sustain the lease, even if it's empty. If the clientid4 * goes stale it's of no use for trunking discovery. */ nfs4_schedule_state_renewal(*result); } out: return status; } struct rpc_cred *nfs4_get_machine_cred_locked(struct nfs_client *clp) { struct rpc_cred *cred = NULL; if (clp->cl_machine_cred != NULL) cred = get_rpccred(clp->cl_machine_cred); return cred; } static struct rpc_cred * nfs4_get_renew_cred_server_locked(struct nfs_server *server) { struct rpc_cred *cred = NULL; struct nfs4_state_owner *sp; struct rb_node *pos; for (pos = rb_first(&server->state_owners); pos != NULL; pos = rb_next(pos)) { sp = rb_entry(pos, struct nfs4_state_owner, so_server_node); if (list_empty(&sp->so_states)) continue; cred = get_rpccred(sp->so_cred); break; } return cred; } /** * nfs4_get_renew_cred_locked - Acquire credential for a renew operation * @clp: client state handle * * Returns an rpc_cred with reference count bumped, or NULL. * Caller must hold clp->cl_lock. */ struct rpc_cred *nfs4_get_renew_cred_locked(struct nfs_client *clp) { struct rpc_cred *cred = NULL; struct nfs_server *server; /* Use machine credentials if available */ cred = nfs4_get_machine_cred_locked(clp); if (cred != NULL) goto out; rcu_read_lock(); list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) { cred = nfs4_get_renew_cred_server_locked(server); if (cred != NULL) break; } rcu_read_unlock(); out: return cred; } #if defined(CONFIG_NFS_V4_1) static int nfs41_setup_state_renewal(struct nfs_client *clp) { int status; struct nfs_fsinfo fsinfo; if (!test_bit(NFS_CS_CHECK_LEASE_TIME, &clp->cl_res_state)) { nfs4_schedule_state_renewal(clp); return 0; } status = nfs4_proc_get_lease_time(clp, &fsinfo); if (status == 0) { /* Update lease time and schedule renewal */ spin_lock(&clp->cl_lock); clp->cl_lease_time = fsinfo.lease_time * HZ; clp->cl_last_renewal = jiffies; spin_unlock(&clp->cl_lock); nfs4_schedule_state_renewal(clp); } return status; } static void nfs4_end_drain_slot_table(struct nfs4_slot_table *tbl) { if (test_and_clear_bit(NFS4_SLOT_TBL_DRAINING, &tbl->slot_tbl_state)) { spin_lock(&tbl->slot_tbl_lock); nfs41_wake_slot_table(tbl); spin_unlock(&tbl->slot_tbl_lock); } } static void nfs4_end_drain_session(struct nfs_client *clp) { struct nfs4_session *ses = clp->cl_session; if (ses != NULL) { nfs4_end_drain_slot_table(&ses->bc_slot_table); nfs4_end_drain_slot_table(&ses->fc_slot_table); } } /* * Signal state manager thread if session fore channel is drained */ void nfs4_slot_tbl_drain_complete(struct nfs4_slot_table *tbl) { if (nfs4_slot_tbl_draining(tbl)) complete(&tbl->complete); } static int nfs4_drain_slot_tbl(struct nfs4_slot_table *tbl) { set_bit(NFS4_SLOT_TBL_DRAINING, &tbl->slot_tbl_state); spin_lock(&tbl->slot_tbl_lock); if (tbl->highest_used_slotid != NFS4_NO_SLOT) { INIT_COMPLETION(tbl->complete); spin_unlock(&tbl->slot_tbl_lock); return wait_for_completion_interruptible(&tbl->complete); } spin_unlock(&tbl->slot_tbl_lock); return 0; } static int nfs4_begin_drain_session(struct nfs_client *clp) { struct nfs4_session *ses = clp->cl_session; int ret = 0; /* back channel */ ret = nfs4_drain_slot_tbl(&ses->bc_slot_table); if (ret) return ret; /* fore channel */ return nfs4_drain_slot_tbl(&ses->fc_slot_table); } static void nfs41_finish_session_reset(struct nfs_client *clp) { clear_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); clear_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state); /* create_session negotiated new slot table */ clear_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state); nfs41_setup_state_renewal(clp); } int nfs41_init_clientid(struct nfs_client *clp, struct rpc_cred *cred) { int status; if (test_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state)) goto do_confirm; nfs4_begin_drain_session(clp); status = nfs4_proc_exchange_id(clp, cred); if (status != 0) goto out; set_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); do_confirm: status = nfs4_proc_create_session(clp, cred); if (status != 0) goto out; nfs41_finish_session_reset(clp); nfs_mark_client_ready(clp, NFS_CS_READY); out: return status; } /** * nfs41_discover_server_trunking - Detect server IP address trunking (mv1) * * @clp: nfs_client under test * @result: OUT: found nfs_client, or clp * @cred: credential to use for trunking test * * Returns NFS4_OK, a negative errno, or a negative NFS4ERR status. * If NFS4_OK is returned, an nfs_client pointer is planted in * "result". * * Note: The returned client may not yet be marked ready. */ int nfs41_discover_server_trunking(struct nfs_client *clp, struct nfs_client **result, struct rpc_cred *cred) { int status; status = nfs4_proc_exchange_id(clp, cred); if (status != NFS4_OK) return status; set_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); return nfs41_walk_client_list(clp, result, cred); } struct rpc_cred *nfs4_get_exchange_id_cred(struct nfs_client *clp) { struct rpc_cred *cred; spin_lock(&clp->cl_lock); cred = nfs4_get_machine_cred_locked(clp); spin_unlock(&clp->cl_lock); return cred; } #endif /* CONFIG_NFS_V4_1 */ static struct rpc_cred * nfs4_get_setclientid_cred_server(struct nfs_server *server) { struct nfs_client *clp = server->nfs_client; struct rpc_cred *cred = NULL; struct nfs4_state_owner *sp; struct rb_node *pos; spin_lock(&clp->cl_lock); pos = rb_first(&server->state_owners); if (pos != NULL) { sp = rb_entry(pos, struct nfs4_state_owner, so_server_node); cred = get_rpccred(sp->so_cred); } spin_unlock(&clp->cl_lock); return cred; } /** * nfs4_get_setclientid_cred - Acquire credential for a setclientid operation * @clp: client state handle * * Returns an rpc_cred with reference count bumped, or NULL. */ struct rpc_cred *nfs4_get_setclientid_cred(struct nfs_client *clp) { struct nfs_server *server; struct rpc_cred *cred; spin_lock(&clp->cl_lock); cred = nfs4_get_machine_cred_locked(clp); spin_unlock(&clp->cl_lock); if (cred != NULL) goto out; rcu_read_lock(); list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) { cred = nfs4_get_setclientid_cred_server(server); if (cred != NULL) break; } rcu_read_unlock(); out: return cred; } static struct nfs4_state_owner * nfs4_find_state_owner_locked(struct nfs_server *server, struct rpc_cred *cred) { struct rb_node **p = &server->state_owners.rb_node, *parent = NULL; struct nfs4_state_owner *sp; while (*p != NULL) { parent = *p; sp = rb_entry(parent, struct nfs4_state_owner, so_server_node); if (cred < sp->so_cred) p = &parent->rb_left; else if (cred > sp->so_cred) p = &parent->rb_right; else { if (!list_empty(&sp->so_lru)) list_del_init(&sp->so_lru); atomic_inc(&sp->so_count); return sp; } } return NULL; } static struct nfs4_state_owner * nfs4_insert_state_owner_locked(struct nfs4_state_owner *new) { struct nfs_server *server = new->so_server; struct rb_node **p = &server->state_owners.rb_node, *parent = NULL; struct nfs4_state_owner *sp; int err; while (*p != NULL) { parent = *p; sp = rb_entry(parent, struct nfs4_state_owner, so_server_node); if (new->so_cred < sp->so_cred) p = &parent->rb_left; else if (new->so_cred > sp->so_cred) p = &parent->rb_right; else { if (!list_empty(&sp->so_lru)) list_del_init(&sp->so_lru); atomic_inc(&sp->so_count); return sp; } } err = ida_get_new(&server->openowner_id, &new->so_seqid.owner_id); if (err) return ERR_PTR(err); rb_link_node(&new->so_server_node, parent, p); rb_insert_color(&new->so_server_node, &server->state_owners); return new; } static void nfs4_remove_state_owner_locked(struct nfs4_state_owner *sp) { struct nfs_server *server = sp->so_server; if (!RB_EMPTY_NODE(&sp->so_server_node)) rb_erase(&sp->so_server_node, &server->state_owners); ida_remove(&server->openowner_id, sp->so_seqid.owner_id); } static void nfs4_init_seqid_counter(struct nfs_seqid_counter *sc) { sc->create_time = ktime_get(); sc->flags = 0; sc->counter = 0; spin_lock_init(&sc->lock); INIT_LIST_HEAD(&sc->list); rpc_init_wait_queue(&sc->wait, "Seqid_waitqueue"); } static void nfs4_destroy_seqid_counter(struct nfs_seqid_counter *sc) { rpc_destroy_wait_queue(&sc->wait); } /* * nfs4_alloc_state_owner(): this is called on the OPEN or CREATE path to * create a new state_owner. * */ static struct nfs4_state_owner * nfs4_alloc_state_owner(struct nfs_server *server, struct rpc_cred *cred, gfp_t gfp_flags) { struct nfs4_state_owner *sp; sp = kzalloc(sizeof(*sp), gfp_flags); if (!sp) return NULL; sp->so_server = server; sp->so_cred = get_rpccred(cred); spin_lock_init(&sp->so_lock); INIT_LIST_HEAD(&sp->so_states); nfs4_init_seqid_counter(&sp->so_seqid); atomic_set(&sp->so_count, 1); INIT_LIST_HEAD(&sp->so_lru); seqcount_init(&sp->so_reclaim_seqcount); mutex_init(&sp->so_delegreturn_mutex); return sp; } static void nfs4_drop_state_owner(struct nfs4_state_owner *sp) { struct rb_node *rb_node = &sp->so_server_node; if (!RB_EMPTY_NODE(rb_node)) { struct nfs_server *server = sp->so_server; struct nfs_client *clp = server->nfs_client; spin_lock(&clp->cl_lock); if (!RB_EMPTY_NODE(rb_node)) { rb_erase(rb_node, &server->state_owners); RB_CLEAR_NODE(rb_node); } spin_unlock(&clp->cl_lock); } } static void nfs4_free_state_owner(struct nfs4_state_owner *sp) { nfs4_destroy_seqid_counter(&sp->so_seqid); put_rpccred(sp->so_cred); kfree(sp); } static void nfs4_gc_state_owners(struct nfs_server *server) { struct nfs_client *clp = server->nfs_client; struct nfs4_state_owner *sp, *tmp; unsigned long time_min, time_max; LIST_HEAD(doomed); spin_lock(&clp->cl_lock); time_max = jiffies; time_min = (long)time_max - (long)clp->cl_lease_time; list_for_each_entry_safe(sp, tmp, &server->state_owners_lru, so_lru) { /* NB: LRU is sorted so that oldest is at the head */ if (time_in_range(sp->so_expires, time_min, time_max)) break; list_move(&sp->so_lru, &doomed); nfs4_remove_state_owner_locked(sp); } spin_unlock(&clp->cl_lock); list_for_each_entry_safe(sp, tmp, &doomed, so_lru) { list_del(&sp->so_lru); nfs4_free_state_owner(sp); } } /** * nfs4_get_state_owner - Look up a state owner given a credential * @server: nfs_server to search * @cred: RPC credential to match * * Returns a pointer to an instantiated nfs4_state_owner struct, or NULL. */ struct nfs4_state_owner *nfs4_get_state_owner(struct nfs_server *server, struct rpc_cred *cred, gfp_t gfp_flags) { struct nfs_client *clp = server->nfs_client; struct nfs4_state_owner *sp, *new; spin_lock(&clp->cl_lock); sp = nfs4_find_state_owner_locked(server, cred); spin_unlock(&clp->cl_lock); if (sp != NULL) goto out; new = nfs4_alloc_state_owner(server, cred, gfp_flags); if (new == NULL) goto out; do { if (ida_pre_get(&server->openowner_id, gfp_flags) == 0) break; spin_lock(&clp->cl_lock); sp = nfs4_insert_state_owner_locked(new); spin_unlock(&clp->cl_lock); } while (sp == ERR_PTR(-EAGAIN)); if (sp != new) nfs4_free_state_owner(new); out: nfs4_gc_state_owners(server); return sp; } /** * nfs4_put_state_owner - Release a nfs4_state_owner * @sp: state owner data to release * * Note that we keep released state owners on an LRU * list. * This caches valid state owners so that they can be * reused, to avoid the OPEN_CONFIRM on minor version 0. * It also pins the uniquifier of dropped state owners for * a while, to ensure that those state owner names are * never reused. */ void nfs4_put_state_owner(struct nfs4_state_owner *sp) { struct nfs_server *server = sp->so_server; struct nfs_client *clp = server->nfs_client; if (!atomic_dec_and_lock(&sp->so_count, &clp->cl_lock)) return; sp->so_expires = jiffies; list_add_tail(&sp->so_lru, &server->state_owners_lru); spin_unlock(&clp->cl_lock); } /** * nfs4_purge_state_owners - Release all cached state owners * @server: nfs_server with cached state owners to release * * Called at umount time. Remaining state owners will be on * the LRU with ref count of zero. */ void nfs4_purge_state_owners(struct nfs_server *server) { struct nfs_client *clp = server->nfs_client; struct nfs4_state_owner *sp, *tmp; LIST_HEAD(doomed); spin_lock(&clp->cl_lock); list_for_each_entry_safe(sp, tmp, &server->state_owners_lru, so_lru) { list_move(&sp->so_lru, &doomed); nfs4_remove_state_owner_locked(sp); } spin_unlock(&clp->cl_lock); list_for_each_entry_safe(sp, tmp, &doomed, so_lru) { list_del(&sp->so_lru); nfs4_free_state_owner(sp); } } static struct nfs4_state * nfs4_alloc_open_state(void) { struct nfs4_state *state; state = kzalloc(sizeof(*state), GFP_NOFS); if (!state) return NULL; atomic_set(&state->count, 1); INIT_LIST_HEAD(&state->lock_states); spin_lock_init(&state->state_lock); seqlock_init(&state->seqlock); return state; } void nfs4_state_set_mode_locked(struct nfs4_state *state, fmode_t fmode) { if (state->state == fmode) return; /* NB! List reordering - see the reclaim code for why. */ if ((fmode & FMODE_WRITE) != (state->state & FMODE_WRITE)) { if (fmode & FMODE_WRITE) list_move(&state->open_states, &state->owner->so_states); else list_move_tail(&state->open_states, &state->owner->so_states); } state->state = fmode; } static struct nfs4_state * __nfs4_find_state_byowner(struct inode *inode, struct nfs4_state_owner *owner) { struct nfs_inode *nfsi = NFS_I(inode); struct nfs4_state *state; list_for_each_entry(state, &nfsi->open_states, inode_states) { if (state->owner != owner) continue; if (!nfs4_valid_open_stateid(state)) continue; if (atomic_inc_not_zero(&state->count)) return state; } return NULL; } static void nfs4_free_open_state(struct nfs4_state *state) { kfree(state); } struct nfs4_state * nfs4_get_open_state(struct inode *inode, struct nfs4_state_owner *owner) { struct nfs4_state *state, *new; struct nfs_inode *nfsi = NFS_I(inode); spin_lock(&inode->i_lock); state = __nfs4_find_state_byowner(inode, owner); spin_unlock(&inode->i_lock); if (state) goto out; new = nfs4_alloc_open_state(); spin_lock(&owner->so_lock); spin_lock(&inode->i_lock); state = __nfs4_find_state_byowner(inode, owner); if (state == NULL && new != NULL) { state = new; state->owner = owner; atomic_inc(&owner->so_count); list_add(&state->inode_states, &nfsi->open_states); ihold(inode); state->inode = inode; spin_unlock(&inode->i_lock); /* Note: The reclaim code dictates that we add stateless * and read-only stateids to the end of the list */ list_add_tail(&state->open_states, &owner->so_states); spin_unlock(&owner->so_lock); } else { spin_unlock(&inode->i_lock); spin_unlock(&owner->so_lock); if (new) nfs4_free_open_state(new); } out: return state; } void nfs4_put_open_state(struct nfs4_state *state) { struct inode *inode = state->inode; struct nfs4_state_owner *owner = state->owner; if (!atomic_dec_and_lock(&state->count, &owner->so_lock)) return; spin_lock(&inode->i_lock); list_del(&state->inode_states); list_del(&state->open_states); spin_unlock(&inode->i_lock); spin_unlock(&owner->so_lock); iput(inode); nfs4_free_open_state(state); nfs4_put_state_owner(owner); } /* * Close the current file. */ static void __nfs4_close(struct nfs4_state *state, fmode_t fmode, gfp_t gfp_mask, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; fmode_t newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (fmode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(state, gfp_mask, wait); } void nfs4_close_state(struct nfs4_state *state, fmode_t fmode) { __nfs4_close(state, fmode, GFP_NOFS, 0); } void nfs4_close_sync(struct nfs4_state *state, fmode_t fmode) { __nfs4_close(state, fmode, GFP_KERNEL, 1); } /* * Search the state->lock_states for an existing lock_owner * that is compatible with current->files */ static struct nfs4_lock_state * __nfs4_find_lock_state(struct nfs4_state *state, fl_owner_t fl_owner, pid_t fl_pid, unsigned int type) { struct nfs4_lock_state *pos; list_for_each_entry(pos, &state->lock_states, ls_locks) { if (type != NFS4_ANY_LOCK_TYPE && pos->ls_owner.lo_type != type) continue; switch (pos->ls_owner.lo_type) { case NFS4_POSIX_LOCK_TYPE: if (pos->ls_owner.lo_u.posix_owner != fl_owner) continue; break; case NFS4_FLOCK_LOCK_TYPE: if (pos->ls_owner.lo_u.flock_owner != fl_pid) continue; } atomic_inc(&pos->ls_count); return pos; } return NULL; } /* * Return a compatible lock_state. If no initialized lock_state structure * exists, return an uninitialized one. * */ static struct nfs4_lock_state *nfs4_alloc_lock_state(struct nfs4_state *state, fl_owner_t fl_owner, pid_t fl_pid, unsigned int type) { struct nfs4_lock_state *lsp; struct nfs_server *server = state->owner->so_server; lsp = kzalloc(sizeof(*lsp), GFP_NOFS); if (lsp == NULL) return NULL; nfs4_init_seqid_counter(&lsp->ls_seqid); atomic_set(&lsp->ls_count, 1); lsp->ls_state = state; lsp->ls_owner.lo_type = type; switch (lsp->ls_owner.lo_type) { case NFS4_FLOCK_LOCK_TYPE: lsp->ls_owner.lo_u.flock_owner = fl_pid; break; case NFS4_POSIX_LOCK_TYPE: lsp->ls_owner.lo_u.posix_owner = fl_owner; break; default: goto out_free; } lsp->ls_seqid.owner_id = ida_simple_get(&server->lockowner_id, 0, 0, GFP_NOFS); if (lsp->ls_seqid.owner_id < 0) goto out_free; INIT_LIST_HEAD(&lsp->ls_locks); return lsp; out_free: kfree(lsp); return NULL; } void nfs4_free_lock_state(struct nfs_server *server, struct nfs4_lock_state *lsp) { ida_simple_remove(&server->lockowner_id, lsp->ls_seqid.owner_id); nfs4_destroy_seqid_counter(&lsp->ls_seqid); kfree(lsp); } /* * Return a compatible lock_state. If no initialized lock_state structure * exists, return an uninitialized one. * */ static struct nfs4_lock_state *nfs4_get_lock_state(struct nfs4_state *state, fl_owner_t owner, pid_t pid, unsigned int type) { struct nfs4_lock_state *lsp, *new = NULL; for(;;) { spin_lock(&state->state_lock); lsp = __nfs4_find_lock_state(state, owner, pid, type); if (lsp != NULL) break; if (new != NULL) { list_add(&new->ls_locks, &state->lock_states); set_bit(LK_STATE_IN_USE, &state->flags); lsp = new; new = NULL; break; } spin_unlock(&state->state_lock); new = nfs4_alloc_lock_state(state, owner, pid, type); if (new == NULL) return NULL; } spin_unlock(&state->state_lock); if (new != NULL) nfs4_free_lock_state(state->owner->so_server, new); return lsp; } /* * Release reference to lock_state, and free it if we see that * it is no longer in use */ void nfs4_put_lock_state(struct nfs4_lock_state *lsp) { struct nfs_server *server; struct nfs4_state *state; if (lsp == NULL) return; state = lsp->ls_state; if (!atomic_dec_and_lock(&lsp->ls_count, &state->state_lock)) return; list_del(&lsp->ls_locks); if (list_empty(&state->lock_states)) clear_bit(LK_STATE_IN_USE, &state->flags); spin_unlock(&state->state_lock); server = state->owner->so_server; if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags)) { struct nfs_client *clp = server->nfs_client; clp->cl_mvops->free_lock_state(server, lsp); } else nfs4_free_lock_state(server, lsp); } static void nfs4_fl_copy_lock(struct file_lock *dst, struct file_lock *src) { struct nfs4_lock_state *lsp = src->fl_u.nfs4_fl.owner; dst->fl_u.nfs4_fl.owner = lsp; atomic_inc(&lsp->ls_count); } static void nfs4_fl_release_lock(struct file_lock *fl) { nfs4_put_lock_state(fl->fl_u.nfs4_fl.owner); } static const struct file_lock_operations nfs4_fl_lock_ops = { .fl_copy_lock = nfs4_fl_copy_lock, .fl_release_private = nfs4_fl_release_lock, }; int nfs4_set_lock_state(struct nfs4_state *state, struct file_lock *fl) { struct nfs4_lock_state *lsp; if (fl->fl_ops != NULL) return 0; if (fl->fl_flags & FL_POSIX) lsp = nfs4_get_lock_state(state, fl->fl_owner, 0, NFS4_POSIX_LOCK_TYPE); else if (fl->fl_flags & FL_FLOCK) lsp = nfs4_get_lock_state(state, NULL, fl->fl_pid, NFS4_FLOCK_LOCK_TYPE); else return -EINVAL; if (lsp == NULL) return -ENOMEM; fl->fl_u.nfs4_fl.owner = lsp; fl->fl_ops = &nfs4_fl_lock_ops; return 0; } static int nfs4_copy_lock_stateid(nfs4_stateid *dst, struct nfs4_state *state, const struct nfs_lockowner *lockowner) { struct nfs4_lock_state *lsp; fl_owner_t fl_owner; pid_t fl_pid; int ret = -ENOENT; if (lockowner == NULL) goto out; if (test_bit(LK_STATE_IN_USE, &state->flags) == 0) goto out; fl_owner = lockowner->l_owner; fl_pid = lockowner->l_pid; spin_lock(&state->state_lock); lsp = __nfs4_find_lock_state(state, fl_owner, fl_pid, NFS4_ANY_LOCK_TYPE); if (lsp != NULL && test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) != 0) { nfs4_stateid_copy(dst, &lsp->ls_stateid); ret = 0; smp_rmb(); if (!list_empty(&lsp->ls_seqid.list)) ret = -EWOULDBLOCK; } spin_unlock(&state->state_lock); nfs4_put_lock_state(lsp); out: return ret; } static int nfs4_copy_open_stateid(nfs4_stateid *dst, struct nfs4_state *state) { const nfs4_stateid *src; int ret; int seq; do { src = &zero_stateid; seq = read_seqbegin(&state->seqlock); if (test_bit(NFS_OPEN_STATE, &state->flags)) src = &state->open_stateid; nfs4_stateid_copy(dst, src); ret = 0; smp_rmb(); if (!list_empty(&state->owner->so_seqid.list)) ret = -EWOULDBLOCK; } while (read_seqretry(&state->seqlock, seq)); return ret; } /* * Byte-range lock aware utility to initialize the stateid of read/write * requests. */ int nfs4_select_rw_stateid(nfs4_stateid *dst, struct nfs4_state *state, fmode_t fmode, const struct nfs_lockowner *lockowner) { int ret = 0; if (nfs4_copy_delegation_stateid(dst, state->inode, fmode)) goto out; ret = nfs4_copy_lock_stateid(dst, state, lockowner); if (ret != -ENOENT) goto out; ret = nfs4_copy_open_stateid(dst, state); out: if (nfs_server_capable(state->inode, NFS_CAP_STATEID_NFSV41)) dst->seqid = 0; return ret; } struct nfs_seqid *nfs_alloc_seqid(struct nfs_seqid_counter *counter, gfp_t gfp_mask) { struct nfs_seqid *new; new = kmalloc(sizeof(*new), gfp_mask); if (new != NULL) { new->sequence = counter; INIT_LIST_HEAD(&new->list); new->task = NULL; } return new; } void nfs_release_seqid(struct nfs_seqid *seqid) { struct nfs_seqid_counter *sequence; if (list_empty(&seqid->list)) return; sequence = seqid->sequence; spin_lock(&sequence->lock); list_del_init(&seqid->list); if (!list_empty(&sequence->list)) { struct nfs_seqid *next; next = list_first_entry(&sequence->list, struct nfs_seqid, list); rpc_wake_up_queued_task(&sequence->wait, next->task); } spin_unlock(&sequence->lock); } void nfs_free_seqid(struct nfs_seqid *seqid) { nfs_release_seqid(seqid); kfree(seqid); } /* * Increment the seqid if the OPEN/OPEN_DOWNGRADE/CLOSE succeeded, or * failed with a seqid incrementing error - * see comments nfs_fs.h:seqid_mutating_error() */ static void nfs_increment_seqid(int status, struct nfs_seqid *seqid) { switch (status) { case 0: break; case -NFS4ERR_BAD_SEQID: if (seqid->sequence->flags & NFS_SEQID_CONFIRMED) return; pr_warn_ratelimited("NFS: v4 server returned a bad" " sequence-id error on an" " unconfirmed sequence %p!\n", seqid->sequence); case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_BADXDR: case -NFS4ERR_RESOURCE: case -NFS4ERR_NOFILEHANDLE: /* Non-seqid mutating errors */ return; }; /* * Note: no locking needed as we are guaranteed to be first * on the sequence list */ seqid->sequence->counter++; } void nfs_increment_open_seqid(int status, struct nfs_seqid *seqid) { struct nfs4_state_owner *sp = container_of(seqid->sequence, struct nfs4_state_owner, so_seqid); struct nfs_server *server = sp->so_server; if (status == -NFS4ERR_BAD_SEQID) nfs4_drop_state_owner(sp); if (!nfs4_has_session(server->nfs_client)) nfs_increment_seqid(status, seqid); } /* * Increment the seqid if the LOCK/LOCKU succeeded, or * failed with a seqid incrementing error - * see comments nfs_fs.h:seqid_mutating_error() */ void nfs_increment_lock_seqid(int status, struct nfs_seqid *seqid) { nfs_increment_seqid(status, seqid); } int nfs_wait_on_sequence(struct nfs_seqid *seqid, struct rpc_task *task) { struct nfs_seqid_counter *sequence = seqid->sequence; int status = 0; spin_lock(&sequence->lock); seqid->task = task; if (list_empty(&seqid->list)) list_add_tail(&seqid->list, &sequence->list); if (list_first_entry(&sequence->list, struct nfs_seqid, list) == seqid) goto unlock; rpc_sleep_on(&sequence->wait, task, NULL); status = -EAGAIN; unlock: spin_unlock(&sequence->lock); return status; } static int nfs4_run_state_manager(void *); static void nfs4_clear_state_manager_bit(struct nfs_client *clp) { smp_mb__before_atomic(); clear_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state); smp_mb__after_atomic(); wake_up_bit(&clp->cl_state, NFS4CLNT_MANAGER_RUNNING); rpc_wake_up(&clp->cl_rpcwaitq); } /* * Schedule the nfs_client asynchronous state management routine */ void nfs4_schedule_state_manager(struct nfs_client *clp) { struct task_struct *task; char buf[INET6_ADDRSTRLEN + sizeof("-manager") + 1]; if (test_and_set_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state) != 0) return; __module_get(THIS_MODULE); atomic_inc(&clp->cl_count); /* The rcu_read_lock() is not strictly necessary, as the state * manager is the only thread that ever changes the rpc_xprt * after it's initialized. At this point, we're single threaded. */ rcu_read_lock(); snprintf(buf, sizeof(buf), "%s-manager", rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_ADDR)); rcu_read_unlock(); task = kthread_run(nfs4_run_state_manager, clp, buf); if (IS_ERR(task)) { printk(KERN_ERR "%s: kthread_run: %ld\n", __func__, PTR_ERR(task)); nfs4_clear_state_manager_bit(clp); nfs_put_client(clp); module_put(THIS_MODULE); } } /* * Schedule a lease recovery attempt */ void nfs4_schedule_lease_recovery(struct nfs_client *clp) { if (!clp) return; if (!test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state)) set_bit(NFS4CLNT_CHECK_LEASE, &clp->cl_state); dprintk("%s: scheduling lease recovery for server %s\n", __func__, clp->cl_hostname); nfs4_schedule_state_manager(clp); } EXPORT_SYMBOL_GPL(nfs4_schedule_lease_recovery); int nfs4_wait_clnt_recover(struct nfs_client *clp) { int res; might_sleep(); res = wait_on_bit(&clp->cl_state, NFS4CLNT_MANAGER_RUNNING, nfs_wait_bit_killable, TASK_KILLABLE); if (res) return res; if (clp->cl_cons_state < 0) return clp->cl_cons_state; return 0; } int nfs4_client_recover_expired_lease(struct nfs_client *clp) { unsigned int loop; int ret; for (loop = NFS4_MAX_LOOP_ON_RECOVER; loop != 0; loop--) { ret = nfs4_wait_clnt_recover(clp); if (ret != 0) break; if (!test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) && !test_bit(NFS4CLNT_CHECK_LEASE,&clp->cl_state)) break; nfs4_schedule_state_manager(clp); ret = -EIO; } return ret; } /* * nfs40_handle_cb_pathdown - return all delegations after NFS4ERR_CB_PATH_DOWN * @clp: client to process * * Set the NFS4CLNT_LEASE_EXPIRED state in order to force a * resend of the SETCLIENTID and hence re-establish the * callback channel. Then return all existing delegations. */ static void nfs40_handle_cb_pathdown(struct nfs_client *clp) { set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state); nfs_expire_all_delegations(clp); dprintk("%s: handling CB_PATHDOWN recovery for server %s\n", __func__, clp->cl_hostname); } void nfs4_schedule_path_down_recovery(struct nfs_client *clp) { nfs40_handle_cb_pathdown(clp); nfs4_schedule_state_manager(clp); } static int nfs4_state_mark_reclaim_reboot(struct nfs_client *clp, struct nfs4_state *state) { set_bit(NFS_STATE_RECLAIM_REBOOT, &state->flags); /* Don't recover state that expired before the reboot */ if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags)) { clear_bit(NFS_STATE_RECLAIM_REBOOT, &state->flags); return 0; } set_bit(NFS_OWNER_RECLAIM_REBOOT, &state->owner->so_flags); set_bit(NFS4CLNT_RECLAIM_REBOOT, &clp->cl_state); return 1; } static int nfs4_state_mark_reclaim_nograce(struct nfs_client *clp, struct nfs4_state *state) { set_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags); clear_bit(NFS_STATE_RECLAIM_REBOOT, &state->flags); set_bit(NFS_OWNER_RECLAIM_NOGRACE, &state->owner->so_flags); set_bit(NFS4CLNT_RECLAIM_NOGRACE, &clp->cl_state); return 1; } int nfs4_schedule_stateid_recovery(const struct nfs_server *server, struct nfs4_state *state) { struct nfs_client *clp = server->nfs_client; if (!nfs4_valid_open_stateid(state)) return -EBADF; nfs4_state_mark_reclaim_nograce(clp, state); dprintk("%s: scheduling stateid recovery for server %s\n", __func__, clp->cl_hostname); nfs4_schedule_state_manager(clp); return 0; } EXPORT_SYMBOL_GPL(nfs4_schedule_stateid_recovery); void nfs_inode_find_state_and_recover(struct inode *inode, const nfs4_stateid *stateid) { struct nfs_client *clp = NFS_SERVER(inode)->nfs_client; struct nfs_inode *nfsi = NFS_I(inode); struct nfs_open_context *ctx; struct nfs4_state *state; bool found = false; spin_lock(&inode->i_lock); list_for_each_entry(ctx, &nfsi->open_files, list) { state = ctx->state; if (state == NULL) continue; if (!test_bit(NFS_DELEGATED_STATE, &state->flags)) continue; if (!nfs4_stateid_match(&state->stateid, stateid)) continue; nfs4_state_mark_reclaim_nograce(clp, state); found = true; } spin_unlock(&inode->i_lock); if (found) nfs4_schedule_state_manager(clp); } static void nfs4_state_mark_open_context_bad(struct nfs4_state *state) { struct inode *inode = state->inode; struct nfs_inode *nfsi = NFS_I(inode); struct nfs_open_context *ctx; spin_lock(&inode->i_lock); list_for_each_entry(ctx, &nfsi->open_files, list) { if (ctx->state != state) continue; set_bit(NFS_CONTEXT_BAD, &ctx->flags); } spin_unlock(&inode->i_lock); } static void nfs4_state_mark_recovery_failed(struct nfs4_state *state, int error) { set_bit(NFS_STATE_RECOVERY_FAILED, &state->flags); nfs4_state_mark_open_context_bad(state); } static int nfs4_reclaim_locks(struct nfs4_state *state, const struct nfs4_state_recovery_ops *ops) { struct inode *inode = state->inode; struct nfs_inode *nfsi = NFS_I(inode); struct file_lock *fl; int status = 0; if (inode->i_flock == NULL) return 0; /* Guard against delegation returns and new lock/unlock calls */ down_write(&nfsi->rwsem); /* Protect inode->i_flock using the BKL */ lock_flocks(); for (fl = inode->i_flock; fl != NULL; fl = fl->fl_next) { if (!(fl->fl_flags & (FL_POSIX|FL_FLOCK))) continue; if (nfs_file_open_context(fl->fl_file)->state != state) continue; unlock_flocks(); status = ops->recover_lock(state, fl); switch (status) { case 0: break; case -ESTALE: case -NFS4ERR_ADMIN_REVOKED: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_EXPIRED: case -NFS4ERR_NO_GRACE: case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_BADSESSION: case -NFS4ERR_BADSLOT: case -NFS4ERR_BAD_HIGH_SLOT: case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION: goto out; default: printk(KERN_ERR "NFS: %s: unhandled error %d. " "Zeroing state\n", __func__, status); case -ENOMEM: case -NFS4ERR_DENIED: case -NFS4ERR_RECLAIM_BAD: case -NFS4ERR_RECLAIM_CONFLICT: /* kill_proc(fl->fl_pid, SIGLOST, 1); */ status = 0; } lock_flocks(); } unlock_flocks(); out: up_write(&nfsi->rwsem); return status; } static int nfs4_reclaim_open_state(struct nfs4_state_owner *sp, const struct nfs4_state_recovery_ops *ops) { struct nfs4_state *state; struct nfs4_lock_state *lock; int status = 0; /* Note: we rely on the sp->so_states list being ordered * so that we always reclaim open(O_RDWR) and/or open(O_WRITE) * states first. * This is needed to ensure that the server won't give us any * read delegations that we have to return if, say, we are * recovering after a network partition or a reboot from a * server that doesn't support a grace period. */ spin_lock(&sp->so_lock); write_seqcount_begin(&sp->so_reclaim_seqcount); restart: list_for_each_entry(state, &sp->so_states, open_states) { if (!test_and_clear_bit(ops->state_flag_bit, &state->flags)) continue; if (!nfs4_valid_open_stateid(state)) continue; if (state->state == 0) continue; atomic_inc(&state->count); spin_unlock(&sp->so_lock); status = ops->recover_open(sp, state); if (status >= 0) { status = nfs4_reclaim_locks(state, ops); if (status >= 0) { spin_lock(&state->state_lock); list_for_each_entry(lock, &state->lock_states, ls_locks) { if (!test_bit(NFS_LOCK_INITIALIZED, &lock->ls_flags)) pr_warn_ratelimited("NFS: " "%s: Lock reclaim " "failed!\n", __func__); } spin_unlock(&state->state_lock); nfs4_put_open_state(state); spin_lock(&sp->so_lock); goto restart; } } switch (status) { default: printk(KERN_ERR "NFS: %s: unhandled error %d. " "Zeroing state\n", __func__, status); case -ENOENT: case -ENOMEM: case -ESTALE: /* * Open state on this file cannot be recovered * All we can do is revert to using the zero stateid. */ nfs4_state_mark_recovery_failed(state, status); break; case -EAGAIN: ssleep(1); case -NFS4ERR_ADMIN_REVOKED: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_RECLAIM_BAD: case -NFS4ERR_RECLAIM_CONFLICT: nfs4_state_mark_reclaim_nograce(sp->so_server->nfs_client, state); break; case -NFS4ERR_EXPIRED: case -NFS4ERR_NO_GRACE: nfs4_state_mark_reclaim_nograce(sp->so_server->nfs_client, state); case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_BADSESSION: case -NFS4ERR_BADSLOT: case -NFS4ERR_BAD_HIGH_SLOT: case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION: goto out_err; } nfs4_put_open_state(state); spin_lock(&sp->so_lock); goto restart; } write_seqcount_end(&sp->so_reclaim_seqcount); spin_unlock(&sp->so_lock); return 0; out_err: nfs4_put_open_state(state); spin_lock(&sp->so_lock); write_seqcount_end(&sp->so_reclaim_seqcount); spin_unlock(&sp->so_lock); return status; } static void nfs4_clear_open_state(struct nfs4_state *state) { struct nfs4_lock_state *lock; clear_bit(NFS_DELEGATED_STATE, &state->flags); clear_bit(NFS_O_RDONLY_STATE, &state->flags); clear_bit(NFS_O_WRONLY_STATE, &state->flags); clear_bit(NFS_O_RDWR_STATE, &state->flags); spin_lock(&state->state_lock); list_for_each_entry(lock, &state->lock_states, ls_locks) { lock->ls_seqid.flags = 0; clear_bit(NFS_LOCK_INITIALIZED, &lock->ls_flags); } spin_unlock(&state->state_lock); } static void nfs4_reset_seqids(struct nfs_server *server, int (*mark_reclaim)(struct nfs_client *clp, struct nfs4_state *state)) { struct nfs_client *clp = server->nfs_client; struct nfs4_state_owner *sp; struct rb_node *pos; struct nfs4_state *state; spin_lock(&clp->cl_lock); for (pos = rb_first(&server->state_owners); pos != NULL; pos = rb_next(pos)) { sp = rb_entry(pos, struct nfs4_state_owner, so_server_node); sp->so_seqid.flags = 0; spin_lock(&sp->so_lock); list_for_each_entry(state, &sp->so_states, open_states) { if (mark_reclaim(clp, state)) nfs4_clear_open_state(state); } spin_unlock(&sp->so_lock); } spin_unlock(&clp->cl_lock); } static void nfs4_state_mark_reclaim_helper(struct nfs_client *clp, int (*mark_reclaim)(struct nfs_client *clp, struct nfs4_state *state)) { struct nfs_server *server; rcu_read_lock(); list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) nfs4_reset_seqids(server, mark_reclaim); rcu_read_unlock(); } static void nfs4_state_start_reclaim_reboot(struct nfs_client *clp) { /* Mark all delegations for reclaim */ nfs_delegation_mark_reclaim(clp); nfs4_state_mark_reclaim_helper(clp, nfs4_state_mark_reclaim_reboot); } static void nfs4_reclaim_complete(struct nfs_client *clp, const struct nfs4_state_recovery_ops *ops) { /* Notify the server we're done reclaiming our state */ if (ops->reclaim_complete) (void)ops->reclaim_complete(clp); } static void nfs4_clear_reclaim_server(struct nfs_server *server) { struct nfs_client *clp = server->nfs_client; struct nfs4_state_owner *sp; struct rb_node *pos; struct nfs4_state *state; spin_lock(&clp->cl_lock); for (pos = rb_first(&server->state_owners); pos != NULL; pos = rb_next(pos)) { sp = rb_entry(pos, struct nfs4_state_owner, so_server_node); spin_lock(&sp->so_lock); list_for_each_entry(state, &sp->so_states, open_states) { if (!test_and_clear_bit(NFS_STATE_RECLAIM_REBOOT, &state->flags)) continue; nfs4_state_mark_reclaim_nograce(clp, state); } spin_unlock(&sp->so_lock); } spin_unlock(&clp->cl_lock); } static int nfs4_state_clear_reclaim_reboot(struct nfs_client *clp) { struct nfs_server *server; if (!test_and_clear_bit(NFS4CLNT_RECLAIM_REBOOT, &clp->cl_state)) return 0; rcu_read_lock(); list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) nfs4_clear_reclaim_server(server); rcu_read_unlock(); nfs_delegation_reap_unclaimed(clp); return 1; } static void nfs4_state_end_reclaim_reboot(struct nfs_client *clp) { if (!nfs4_state_clear_reclaim_reboot(clp)) return; nfs4_reclaim_complete(clp, clp->cl_mvops->reboot_recovery_ops); } static void nfs_delegation_clear_all(struct nfs_client *clp) { nfs_delegation_mark_reclaim(clp); nfs_delegation_reap_unclaimed(clp); } static void nfs4_state_start_reclaim_nograce(struct nfs_client *clp) { nfs_delegation_clear_all(clp); nfs4_state_mark_reclaim_helper(clp, nfs4_state_mark_reclaim_nograce); } static int nfs4_recovery_handle_error(struct nfs_client *clp, int error) { switch (error) { case 0: break; case -NFS4ERR_CB_PATH_DOWN: nfs40_handle_cb_pathdown(clp); break; case -NFS4ERR_NO_GRACE: nfs4_state_end_reclaim_reboot(clp); break; case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_LEASE_MOVED: set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state); nfs4_state_clear_reclaim_reboot(clp); nfs4_state_start_reclaim_reboot(clp); break; case -NFS4ERR_EXPIRED: set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state); nfs4_state_start_reclaim_nograce(clp); break; case -NFS4ERR_BADSESSION: case -NFS4ERR_BADSLOT: case -NFS4ERR_BAD_HIGH_SLOT: case -NFS4ERR_DEADSESSION: case -NFS4ERR_SEQ_FALSE_RETRY: case -NFS4ERR_SEQ_MISORDERED: set_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state); /* Zero session reset errors */ break; case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION: set_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state); break; default: dprintk("%s: failed to handle error %d for server %s\n", __func__, error, clp->cl_hostname); return error; } dprintk("%s: handled error %d for server %s\n", __func__, error, clp->cl_hostname); return 0; } static int nfs4_do_reclaim(struct nfs_client *clp, const struct nfs4_state_recovery_ops *ops) { struct nfs4_state_owner *sp; struct nfs_server *server; struct rb_node *pos; int status = 0; restart: rcu_read_lock(); list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) { nfs4_purge_state_owners(server); spin_lock(&clp->cl_lock); for (pos = rb_first(&server->state_owners); pos != NULL; pos = rb_next(pos)) { sp = rb_entry(pos, struct nfs4_state_owner, so_server_node); if (!test_and_clear_bit(ops->owner_flag_bit, &sp->so_flags)) continue; atomic_inc(&sp->so_count); spin_unlock(&clp->cl_lock); rcu_read_unlock(); status = nfs4_reclaim_open_state(sp, ops); if (status < 0) { set_bit(ops->owner_flag_bit, &sp->so_flags); nfs4_put_state_owner(sp); return nfs4_recovery_handle_error(clp, status); } nfs4_put_state_owner(sp); goto restart; } spin_unlock(&clp->cl_lock); } rcu_read_unlock(); return status; } static int nfs4_check_lease(struct nfs_client *clp) { struct rpc_cred *cred; const struct nfs4_state_maintenance_ops *ops = clp->cl_mvops->state_renewal_ops; int status; /* Is the client already known to have an expired lease? */ if (test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state)) return 0; spin_lock(&clp->cl_lock); cred = ops->get_state_renewal_cred_locked(clp); spin_unlock(&clp->cl_lock); if (cred == NULL) { cred = nfs4_get_setclientid_cred(clp); status = -ENOKEY; if (cred == NULL) goto out; } status = ops->renew_lease(clp, cred); put_rpccred(cred); if (status == -ETIMEDOUT) { set_bit(NFS4CLNT_CHECK_LEASE, &clp->cl_state); return 0; } out: return nfs4_recovery_handle_error(clp, status); } /* Set NFS4CLNT_LEASE_EXPIRED and reclaim reboot state for all v4.0 errors * and for recoverable errors on EXCHANGE_ID for v4.1 */ static int nfs4_handle_reclaim_lease_error(struct nfs_client *clp, int status) { switch (status) { case -NFS4ERR_SEQ_MISORDERED: if (test_and_set_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state)) return -ESERVERFAULT; /* Lease confirmation error: retry after purging the lease */ ssleep(1); clear_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); break; case -NFS4ERR_STALE_CLIENTID: clear_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); nfs4_state_clear_reclaim_reboot(clp); nfs4_state_start_reclaim_reboot(clp); break; case -NFS4ERR_CLID_INUSE: pr_err("NFS: Server %s reports our clientid is in use\n", clp->cl_hostname); nfs_mark_client_ready(clp, -EPERM); clear_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); return -EPERM; case -EACCES: case -NFS4ERR_DELAY: case -ETIMEDOUT: case -EAGAIN: ssleep(1); break; case -NFS4ERR_MINOR_VERS_MISMATCH: if (clp->cl_cons_state == NFS_CS_SESSION_INITING) nfs_mark_client_ready(clp, -EPROTONOSUPPORT); dprintk("%s: exit with error %d for server %s\n", __func__, -EPROTONOSUPPORT, clp->cl_hostname); return -EPROTONOSUPPORT; case -NFS4ERR_NOT_SAME: /* FixMe: implement recovery * in nfs4_exchange_id */ default: dprintk("%s: exit with error %d for server %s\n", __func__, status, clp->cl_hostname); return status; } set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state); dprintk("%s: handled error %d for server %s\n", __func__, status, clp->cl_hostname); return 0; } static int nfs4_establish_lease(struct nfs_client *clp) { struct rpc_cred *cred; const struct nfs4_state_recovery_ops *ops = clp->cl_mvops->reboot_recovery_ops; int status; cred = ops->get_clid_cred(clp); if (cred == NULL) return -ENOENT; status = ops->establish_clid(clp, cred); put_rpccred(cred); if (status != 0) return status; pnfs_destroy_all_layouts(clp); return 0; } /* * Returns zero or a negative errno. NFS4ERR values are converted * to local errno values. */ static int nfs4_reclaim_lease(struct nfs_client *clp) { int status; status = nfs4_establish_lease(clp); if (status < 0) return nfs4_handle_reclaim_lease_error(clp, status); if (test_and_clear_bit(NFS4CLNT_SERVER_SCOPE_MISMATCH, &clp->cl_state)) nfs4_state_start_reclaim_nograce(clp); if (!test_bit(NFS4CLNT_RECLAIM_NOGRACE, &clp->cl_state)) set_bit(NFS4CLNT_RECLAIM_REBOOT, &clp->cl_state); clear_bit(NFS4CLNT_CHECK_LEASE, &clp->cl_state); clear_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state); return 0; } static int nfs4_purge_lease(struct nfs_client *clp) { int status; status = nfs4_establish_lease(clp); if (status < 0) return nfs4_handle_reclaim_lease_error(clp, status); clear_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state); set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state); nfs4_state_start_reclaim_nograce(clp); return 0; } /** * nfs4_discover_server_trunking - Detect server IP address trunking * * @clp: nfs_client under test * @result: OUT: found nfs_client, or clp * * Returns zero or a negative errno. If zero is returned, * an nfs_client pointer is planted in "result". * * Note: since we are invoked in process context, and * not from inside the state manager, we cannot use * nfs4_handle_reclaim_lease_error(). */ int nfs4_discover_server_trunking(struct nfs_client *clp, struct nfs_client **result) { const struct nfs4_state_recovery_ops *ops = clp->cl_mvops->reboot_recovery_ops; struct rpc_clnt *clnt; struct rpc_cred *cred; int i, status; dprintk("NFS: %s: testing '%s'\n", __func__, clp->cl_hostname); clnt = clp->cl_rpcclient; i = 0; mutex_lock(&nfs_clid_init_mutex); again: status = -ENOENT; cred = ops->get_clid_cred(clp); if (cred == NULL) goto out_unlock; status = ops->detect_trunking(clp, result, cred); put_rpccred(cred); switch (status) { case 0: break; case -NFS4ERR_DELAY: case -ETIMEDOUT: case -EAGAIN: ssleep(1); case -NFS4ERR_STALE_CLIENTID: dprintk("NFS: %s after status %d, retrying\n", __func__, status); goto again; case -EACCES: if (i++) break; case -NFS4ERR_CLID_INUSE: case -NFS4ERR_WRONGSEC: clnt = rpc_clone_client_set_auth(clnt, RPC_AUTH_UNIX); if (IS_ERR(clnt)) { status = PTR_ERR(clnt); break; } /* Note: this is safe because we haven't yet marked the * client as ready, so we are the only user of * clp->cl_rpcclient */ clnt = xchg(&clp->cl_rpcclient, clnt); rpc_shutdown_client(clnt); clnt = clp->cl_rpcclient; goto again; case -NFS4ERR_MINOR_VERS_MISMATCH: status = -EPROTONOSUPPORT; break; case -EKEYEXPIRED: case -NFS4ERR_NOT_SAME: /* FixMe: implement recovery * in nfs4_exchange_id */ status = -EKEYEXPIRED; break; default: pr_warn("NFS: %s unhandled error %d. Exiting with error EIO\n", __func__, status); status = -EIO; } out_unlock: mutex_unlock(&nfs_clid_init_mutex); dprintk("NFS: %s: status = %d\n", __func__, status); return status; } #ifdef CONFIG_NFS_V4_1 void nfs4_schedule_session_recovery(struct nfs4_session *session, int err) { struct nfs_client *clp = session->clp; switch (err) { default: set_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state); break; case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION: set_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state); } nfs4_schedule_lease_recovery(clp); } EXPORT_SYMBOL_GPL(nfs4_schedule_session_recovery); static void nfs41_ping_server(struct nfs_client *clp) { /* Use CHECK_LEASE to ping the server with a SEQUENCE */ set_bit(NFS4CLNT_CHECK_LEASE, &clp->cl_state); nfs4_schedule_state_manager(clp); } void nfs41_server_notify_target_slotid_update(struct nfs_client *clp) { nfs41_ping_server(clp); } void nfs41_server_notify_highest_slotid_update(struct nfs_client *clp) { nfs41_ping_server(clp); } static void nfs4_reset_all_state(struct nfs_client *clp) { if (test_and_set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) == 0) { set_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state); clear_bit(NFS4CLNT_LEASE_CONFIRM, &clp->cl_state); nfs4_state_start_reclaim_nograce(clp); dprintk("%s: scheduling reset of all state for server %s!\n", __func__, clp->cl_hostname); nfs4_schedule_state_manager(clp); } } static void nfs41_handle_server_reboot(struct nfs_client *clp) { if (test_and_set_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) == 0) { nfs4_state_start_reclaim_reboot(clp); dprintk("%s: server %s rebooted!\n", __func__, clp->cl_hostname); nfs4_schedule_state_manager(clp); } } static void nfs41_handle_state_revoked(struct nfs_client *clp) { nfs4_reset_all_state(clp); dprintk("%s: state revoked on server %s\n", __func__, clp->cl_hostname); } static void nfs41_handle_recallable_state_revoked(struct nfs_client *clp) { /* This will need to handle layouts too */ nfs_expire_all_delegations(clp); dprintk("%s: Recallable state revoked on server %s!\n", __func__, clp->cl_hostname); } static void nfs41_handle_backchannel_fault(struct nfs_client *clp) { nfs_expire_all_delegations(clp); if (test_and_set_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state) == 0) nfs4_schedule_state_manager(clp); dprintk("%s: server %s declared a backchannel fault\n", __func__, clp->cl_hostname); } static void nfs41_handle_cb_path_down(struct nfs_client *clp) { if (test_and_set_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state) == 0) nfs4_schedule_state_manager(clp); } void nfs41_handle_sequence_flag_errors(struct nfs_client *clp, u32 flags) { if (!flags) return; dprintk("%s: \"%s\" (client ID %llx) flags=0x%08x\n", __func__, clp->cl_hostname, clp->cl_clientid, flags); if (flags & SEQ4_STATUS_RESTART_RECLAIM_NEEDED) nfs41_handle_server_reboot(clp); if (flags & (SEQ4_STATUS_EXPIRED_ALL_STATE_REVOKED | SEQ4_STATUS_EXPIRED_SOME_STATE_REVOKED | SEQ4_STATUS_ADMIN_STATE_REVOKED | SEQ4_STATUS_LEASE_MOVED)) nfs41_handle_state_revoked(clp); if (flags & SEQ4_STATUS_RECALLABLE_STATE_REVOKED) nfs41_handle_recallable_state_revoked(clp); if (flags & SEQ4_STATUS_BACKCHANNEL_FAULT) nfs41_handle_backchannel_fault(clp); else if (flags & (SEQ4_STATUS_CB_PATH_DOWN | SEQ4_STATUS_CB_PATH_DOWN_SESSION)) nfs41_handle_cb_path_down(clp); } static int nfs4_reset_session(struct nfs_client *clp) { struct rpc_cred *cred; int status; if (!nfs4_has_session(clp)) return 0; nfs4_begin_drain_session(clp); cred = nfs4_get_exchange_id_cred(clp); status = nfs4_proc_destroy_session(clp->cl_session, cred); switch (status) { case 0: case -NFS4ERR_BADSESSION: case -NFS4ERR_DEADSESSION: break; case -NFS4ERR_BACK_CHAN_BUSY: case -NFS4ERR_DELAY: set_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state); status = 0; ssleep(1); goto out; default: status = nfs4_recovery_handle_error(clp, status); goto out; } memset(clp->cl_session->sess_id.data, 0, NFS4_MAX_SESSIONID_LEN); status = nfs4_proc_create_session(clp, cred); if (status) { dprintk("%s: session reset failed with status %d for server %s!\n", __func__, status, clp->cl_hostname); status = nfs4_handle_reclaim_lease_error(clp, status); goto out; } nfs41_finish_session_reset(clp); dprintk("%s: session reset was successful for server %s!\n", __func__, clp->cl_hostname); out: if (cred) put_rpccred(cred); return status; } static int nfs4_bind_conn_to_session(struct nfs_client *clp) { struct rpc_cred *cred; int ret; if (!nfs4_has_session(clp)) return 0; nfs4_begin_drain_session(clp); cred = nfs4_get_exchange_id_cred(clp); ret = nfs4_proc_bind_conn_to_session(clp, cred); if (cred) put_rpccred(cred); clear_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state); switch (ret) { case 0: dprintk("%s: bind_conn_to_session was successful for server %s!\n", __func__, clp->cl_hostname); break; case -NFS4ERR_DELAY: ssleep(1); set_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state); break; default: return nfs4_recovery_handle_error(clp, ret); } return 0; } #else /* CONFIG_NFS_V4_1 */ static int nfs4_reset_session(struct nfs_client *clp) { return 0; } static int nfs4_end_drain_session(struct nfs_client *clp) { return 0; } static int nfs4_bind_conn_to_session(struct nfs_client *clp) { return 0; } #endif /* CONFIG_NFS_V4_1 */ static void nfs4_state_manager(struct nfs_client *clp) { int status = 0; const char *section = "", *section_sep = ""; /* Ensure exclusive access to NFSv4 state */ do { if (test_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state)) { section = "purge state"; status = nfs4_purge_lease(clp); if (status < 0) goto out_error; continue; } if (test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state)) { section = "lease expired"; /* We're going to have to re-establish a clientid */ status = nfs4_reclaim_lease(clp); if (status < 0) goto out_error; continue; } /* Initialize or reset the session */ if (test_and_clear_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state)) { section = "reset session"; status = nfs4_reset_session(clp); if (test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state)) continue; if (status < 0) goto out_error; } /* Send BIND_CONN_TO_SESSION */ if (test_and_clear_bit(NFS4CLNT_BIND_CONN_TO_SESSION, &clp->cl_state)) { section = "bind conn to session"; status = nfs4_bind_conn_to_session(clp); if (status < 0) goto out_error; continue; } if (test_and_clear_bit(NFS4CLNT_CHECK_LEASE, &clp->cl_state)) { section = "check lease"; status = nfs4_check_lease(clp); if (status < 0) goto out_error; continue; } /* First recover reboot state... */ if (test_bit(NFS4CLNT_RECLAIM_REBOOT, &clp->cl_state)) { section = "reclaim reboot"; status = nfs4_do_reclaim(clp, clp->cl_mvops->reboot_recovery_ops); if (test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) || test_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state)) continue; nfs4_state_end_reclaim_reboot(clp); if (test_bit(NFS4CLNT_RECLAIM_NOGRACE, &clp->cl_state)) continue; if (status < 0) goto out_error; } /* Now recover expired state... */ if (test_and_clear_bit(NFS4CLNT_RECLAIM_NOGRACE, &clp->cl_state)) { section = "reclaim nograce"; status = nfs4_do_reclaim(clp, clp->cl_mvops->nograce_recovery_ops); if (test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) || test_bit(NFS4CLNT_SESSION_RESET, &clp->cl_state) || test_bit(NFS4CLNT_RECLAIM_REBOOT, &clp->cl_state)) continue; if (status < 0) goto out_error; } nfs4_end_drain_session(clp); if (test_and_clear_bit(NFS4CLNT_DELEGRETURN, &clp->cl_state)) { nfs_client_return_marked_delegations(clp); continue; } nfs4_clear_state_manager_bit(clp); /* Did we race with an attempt to give us more work? */ if (clp->cl_state == 0) break; if (test_and_set_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state) != 0) break; } while (atomic_read(&clp->cl_count) > 1); return; out_error: if (strlen(section)) section_sep = ": "; pr_warn_ratelimited("NFS: state manager%s%s failed on NFSv4 server %s" " with error %d\n", section_sep, section, clp->cl_hostname, -status); ssleep(1); nfs4_end_drain_session(clp); nfs4_clear_state_manager_bit(clp); } static int nfs4_run_state_manager(void *ptr) { struct nfs_client *clp = ptr; allow_signal(SIGKILL); nfs4_state_manager(clp); nfs_put_client(clp); module_put_and_exit(0); return 0; } /* * Local variables: * c-basic-offset: 8 * End: */
gpl-2.0
enleightond/linux
drivers/net/ethernet/intel/ixgbe/ixgbe_dcb.c
969
11563
/******************************************************************************* Intel 10 Gigabit PCI Express Linux driver Copyright(c) 1999 - 2014 Intel Corporation. This program is free software; you can redistribute it and/or modify it under the terms and conditions of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". Contact Information: Linux NICS <linux.nics@intel.com> e1000-devel Mailing List <e1000-devel@lists.sourceforge.net> Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 *******************************************************************************/ #include "ixgbe.h" #include "ixgbe_type.h" #include "ixgbe_dcb.h" #include "ixgbe_dcb_82598.h" #include "ixgbe_dcb_82599.h" /** * ixgbe_ieee_credits - This calculates the ieee traffic class * credits from the configured bandwidth percentages. Credits * are the smallest unit programmable into the underlying * hardware. The IEEE 802.1Qaz specification do not use bandwidth * groups so this is much simplified from the CEE case. */ static s32 ixgbe_ieee_credits(__u8 *bw, __u16 *refill, __u16 *max, int max_frame) { int min_percent = 100; int min_credit, multiplier; int i; min_credit = ((max_frame / 2) + DCB_CREDIT_QUANTUM - 1) / DCB_CREDIT_QUANTUM; for (i = 0; i < MAX_TRAFFIC_CLASS; i++) { if (bw[i] < min_percent && bw[i]) min_percent = bw[i]; } multiplier = (min_credit / min_percent) + 1; /* Find out the hw credits for each TC */ for (i = 0; i < MAX_TRAFFIC_CLASS; i++) { int val = min(bw[i] * multiplier, MAX_CREDIT_REFILL); if (val < min_credit) val = min_credit; refill[i] = val; max[i] = bw[i] ? (bw[i] * MAX_CREDIT)/100 : min_credit; } return 0; } /** * ixgbe_dcb_calculate_tc_credits - Calculates traffic class credits * @ixgbe_dcb_config: Struct containing DCB settings. * @direction: Configuring either Tx or Rx. * * This function calculates the credits allocated to each traffic class. * It should be called only after the rules are checked by * ixgbe_dcb_check_config(). */ s32 ixgbe_dcb_calculate_tc_credits(struct ixgbe_hw *hw, struct ixgbe_dcb_config *dcb_config, int max_frame, u8 direction) { struct tc_bw_alloc *p; int min_credit; int min_multiplier; int min_percent = 100; /* Initialization values default for Tx settings */ u32 credit_refill = 0; u32 credit_max = 0; u16 link_percentage = 0; u8 bw_percent = 0; u8 i; if (!dcb_config) return DCB_ERR_CONFIG; min_credit = ((max_frame / 2) + DCB_CREDIT_QUANTUM - 1) / DCB_CREDIT_QUANTUM; /* Find smallest link percentage */ for (i = 0; i < MAX_TRAFFIC_CLASS; i++) { p = &dcb_config->tc_config[i].path[direction]; bw_percent = dcb_config->bw_percentage[direction][p->bwg_id]; link_percentage = p->bwg_percent; link_percentage = (link_percentage * bw_percent) / 100; if (link_percentage && link_percentage < min_percent) min_percent = link_percentage; } /* * The ratio between traffic classes will control the bandwidth * percentages seen on the wire. To calculate this ratio we use * a multiplier. It is required that the refill credits must be * larger than the max frame size so here we find the smallest * multiplier that will allow all bandwidth percentages to be * greater than the max frame size. */ min_multiplier = (min_credit / min_percent) + 1; /* Find out the link percentage for each TC first */ for (i = 0; i < MAX_TRAFFIC_CLASS; i++) { p = &dcb_config->tc_config[i].path[direction]; bw_percent = dcb_config->bw_percentage[direction][p->bwg_id]; link_percentage = p->bwg_percent; /* Must be careful of integer division for very small nums */ link_percentage = (link_percentage * bw_percent) / 100; if (p->bwg_percent > 0 && link_percentage == 0) link_percentage = 1; /* Save link_percentage for reference */ p->link_percent = (u8)link_percentage; /* Calculate credit refill ratio using multiplier */ credit_refill = min(link_percentage * min_multiplier, MAX_CREDIT_REFILL); p->data_credits_refill = (u16)credit_refill; /* Calculate maximum credit for the TC */ credit_max = (link_percentage * MAX_CREDIT) / 100; /* * Adjustment based on rule checking, if the percentage * of a TC is too small, the maximum credit may not be * enough to send out a jumbo frame in data plane arbitration. */ if (credit_max && (credit_max < min_credit)) credit_max = min_credit; if (direction == DCB_TX_CONFIG) { /* * Adjustment based on rule checking, if the * percentage of a TC is too small, the maximum * credit may not be enough to send out a TSO * packet in descriptor plane arbitration. */ if ((hw->mac.type == ixgbe_mac_82598EB) && credit_max && (credit_max < MINIMUM_CREDIT_FOR_TSO)) credit_max = MINIMUM_CREDIT_FOR_TSO; dcb_config->tc_config[i].desc_credits_max = (u16)credit_max; } p->data_credits_max = (u16)credit_max; } return 0; } void ixgbe_dcb_unpack_pfc(struct ixgbe_dcb_config *cfg, u8 *pfc_en) { struct tc_configuration *tc_config = &cfg->tc_config[0]; int tc; for (*pfc_en = 0, tc = 0; tc < MAX_TRAFFIC_CLASS; tc++) { if (tc_config[tc].dcb_pfc != pfc_disabled) *pfc_en |= 1 << tc; } } void ixgbe_dcb_unpack_refill(struct ixgbe_dcb_config *cfg, int direction, u16 *refill) { struct tc_configuration *tc_config = &cfg->tc_config[0]; int tc; for (tc = 0; tc < MAX_TRAFFIC_CLASS; tc++) refill[tc] = tc_config[tc].path[direction].data_credits_refill; } void ixgbe_dcb_unpack_max(struct ixgbe_dcb_config *cfg, u16 *max) { struct tc_configuration *tc_config = &cfg->tc_config[0]; int tc; for (tc = 0; tc < MAX_TRAFFIC_CLASS; tc++) max[tc] = tc_config[tc].desc_credits_max; } void ixgbe_dcb_unpack_bwgid(struct ixgbe_dcb_config *cfg, int direction, u8 *bwgid) { struct tc_configuration *tc_config = &cfg->tc_config[0]; int tc; for (tc = 0; tc < MAX_TRAFFIC_CLASS; tc++) bwgid[tc] = tc_config[tc].path[direction].bwg_id; } void ixgbe_dcb_unpack_prio(struct ixgbe_dcb_config *cfg, int direction, u8 *ptype) { struct tc_configuration *tc_config = &cfg->tc_config[0]; int tc; for (tc = 0; tc < MAX_TRAFFIC_CLASS; tc++) ptype[tc] = tc_config[tc].path[direction].prio_type; } u8 ixgbe_dcb_get_tc_from_up(struct ixgbe_dcb_config *cfg, int direction, u8 up) { struct tc_configuration *tc_config = &cfg->tc_config[0]; u8 prio_mask = 1 << up; u8 tc = cfg->num_tcs.pg_tcs; /* If tc is 0 then DCB is likely not enabled or supported */ if (!tc) return 0; /* * Test from maximum TC to 1 and report the first match we find. If * we find no match we can assume that the TC is 0 since the TC must * be set for all user priorities */ for (tc--; tc; tc--) { if (prio_mask & tc_config[tc].path[direction].up_to_tc_bitmap) break; } return tc; } void ixgbe_dcb_unpack_map(struct ixgbe_dcb_config *cfg, int direction, u8 *map) { u8 up; for (up = 0; up < MAX_USER_PRIORITY; up++) map[up] = ixgbe_dcb_get_tc_from_up(cfg, direction, up); } /** * ixgbe_dcb_hw_config - Config and enable DCB * @hw: pointer to hardware structure * @dcb_config: pointer to ixgbe_dcb_config structure * * Configure dcb settings and enable dcb mode. */ s32 ixgbe_dcb_hw_config(struct ixgbe_hw *hw, struct ixgbe_dcb_config *dcb_config) { u8 pfc_en; u8 ptype[MAX_TRAFFIC_CLASS]; u8 bwgid[MAX_TRAFFIC_CLASS]; u8 prio_tc[MAX_TRAFFIC_CLASS]; u16 refill[MAX_TRAFFIC_CLASS]; u16 max[MAX_TRAFFIC_CLASS]; /* Unpack CEE standard containers */ ixgbe_dcb_unpack_pfc(dcb_config, &pfc_en); ixgbe_dcb_unpack_refill(dcb_config, DCB_TX_CONFIG, refill); ixgbe_dcb_unpack_max(dcb_config, max); ixgbe_dcb_unpack_bwgid(dcb_config, DCB_TX_CONFIG, bwgid); ixgbe_dcb_unpack_prio(dcb_config, DCB_TX_CONFIG, ptype); ixgbe_dcb_unpack_map(dcb_config, DCB_TX_CONFIG, prio_tc); switch (hw->mac.type) { case ixgbe_mac_82598EB: return ixgbe_dcb_hw_config_82598(hw, pfc_en, refill, max, bwgid, ptype); case ixgbe_mac_82599EB: case ixgbe_mac_X540: case ixgbe_mac_X550: case ixgbe_mac_X550EM_x: return ixgbe_dcb_hw_config_82599(hw, pfc_en, refill, max, bwgid, ptype, prio_tc); default: break; } return 0; } /* Helper routines to abstract HW specifics from DCB netlink ops */ s32 ixgbe_dcb_hw_pfc_config(struct ixgbe_hw *hw, u8 pfc_en, u8 *prio_tc) { switch (hw->mac.type) { case ixgbe_mac_82598EB: return ixgbe_dcb_config_pfc_82598(hw, pfc_en); case ixgbe_mac_82599EB: case ixgbe_mac_X540: case ixgbe_mac_X550: case ixgbe_mac_X550EM_x: return ixgbe_dcb_config_pfc_82599(hw, pfc_en, prio_tc); default: break; } return -EINVAL; } s32 ixgbe_dcb_hw_ets(struct ixgbe_hw *hw, struct ieee_ets *ets, int max_frame) { __u16 refill[IEEE_8021QAZ_MAX_TCS], max[IEEE_8021QAZ_MAX_TCS]; __u8 prio_type[IEEE_8021QAZ_MAX_TCS]; int i; /* naively give each TC a bwg to map onto CEE hardware */ __u8 bwg_id[IEEE_8021QAZ_MAX_TCS] = {0, 1, 2, 3, 4, 5, 6, 7}; /* Map TSA onto CEE prio type */ for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) { switch (ets->tc_tsa[i]) { case IEEE_8021QAZ_TSA_STRICT: prio_type[i] = 2; break; case IEEE_8021QAZ_TSA_ETS: prio_type[i] = 0; break; default: /* Hardware only supports priority strict or * ETS transmission selection algorithms if * we receive some other value from dcbnl * throw an error */ return -EINVAL; } } ixgbe_ieee_credits(ets->tc_tx_bw, refill, max, max_frame); return ixgbe_dcb_hw_ets_config(hw, refill, max, bwg_id, prio_type, ets->prio_tc); } s32 ixgbe_dcb_hw_ets_config(struct ixgbe_hw *hw, u16 *refill, u16 *max, u8 *bwg_id, u8 *prio_type, u8 *prio_tc) { switch (hw->mac.type) { case ixgbe_mac_82598EB: ixgbe_dcb_config_rx_arbiter_82598(hw, refill, max, prio_type); ixgbe_dcb_config_tx_desc_arbiter_82598(hw, refill, max, bwg_id, prio_type); ixgbe_dcb_config_tx_data_arbiter_82598(hw, refill, max, bwg_id, prio_type); break; case ixgbe_mac_82599EB: case ixgbe_mac_X540: case ixgbe_mac_X550: case ixgbe_mac_X550EM_x: ixgbe_dcb_config_rx_arbiter_82599(hw, refill, max, bwg_id, prio_type, prio_tc); ixgbe_dcb_config_tx_desc_arbiter_82599(hw, refill, max, bwg_id, prio_type); ixgbe_dcb_config_tx_data_arbiter_82599(hw, refill, max, bwg_id, prio_type, prio_tc); break; default: break; } return 0; } static void ixgbe_dcb_read_rtrup2tc_82599(struct ixgbe_hw *hw, u8 *map) { u32 reg, i; reg = IXGBE_READ_REG(hw, IXGBE_RTRUP2TC); for (i = 0; i < MAX_USER_PRIORITY; i++) map[i] = IXGBE_RTRUP2TC_UP_MASK & (reg >> (i * IXGBE_RTRUP2TC_UP_SHIFT)); } void ixgbe_dcb_read_rtrup2tc(struct ixgbe_hw *hw, u8 *map) { switch (hw->mac.type) { case ixgbe_mac_82599EB: case ixgbe_mac_X540: case ixgbe_mac_X550: case ixgbe_mac_X550EM_x: ixgbe_dcb_read_rtrup2tc_82599(hw, map); break; default: break; } }
gpl-2.0
vishnuavula/ntb
drivers/hwmon/max6639.c
1737
18372
/* * max6639.c - Support for Maxim MAX6639 * * 2-Channel Temperature Monitor with Dual PWM Fan-Speed Controller * * Copyright (C) 2010, 2011 Roland Stigge <stigge@antcom.de> * * based on the initial MAX6639 support from semptian.net * by He Changqing <hechangqing@semptian.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/jiffies.h> #include <linux/i2c.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <linux/err.h> #include <linux/mutex.h> #include <linux/i2c/max6639.h> /* Addresses to scan */ static const unsigned short normal_i2c[] = { 0x2c, 0x2e, 0x2f, I2C_CLIENT_END }; /* The MAX6639 registers, valid channel numbers: 0, 1 */ #define MAX6639_REG_TEMP(ch) (0x00 + (ch)) #define MAX6639_REG_STATUS 0x02 #define MAX6639_REG_OUTPUT_MASK 0x03 #define MAX6639_REG_GCONFIG 0x04 #define MAX6639_REG_TEMP_EXT(ch) (0x05 + (ch)) #define MAX6639_REG_ALERT_LIMIT(ch) (0x08 + (ch)) #define MAX6639_REG_OT_LIMIT(ch) (0x0A + (ch)) #define MAX6639_REG_THERM_LIMIT(ch) (0x0C + (ch)) #define MAX6639_REG_FAN_CONFIG1(ch) (0x10 + (ch) * 4) #define MAX6639_REG_FAN_CONFIG2a(ch) (0x11 + (ch) * 4) #define MAX6639_REG_FAN_CONFIG2b(ch) (0x12 + (ch) * 4) #define MAX6639_REG_FAN_CONFIG3(ch) (0x13 + (ch) * 4) #define MAX6639_REG_FAN_CNT(ch) (0x20 + (ch)) #define MAX6639_REG_TARGET_CNT(ch) (0x22 + (ch)) #define MAX6639_REG_FAN_PPR(ch) (0x24 + (ch)) #define MAX6639_REG_TARGTDUTY(ch) (0x26 + (ch)) #define MAX6639_REG_FAN_START_TEMP(ch) (0x28 + (ch)) #define MAX6639_REG_DEVID 0x3D #define MAX6639_REG_MANUID 0x3E #define MAX6639_REG_DEVREV 0x3F /* Register bits */ #define MAX6639_GCONFIG_STANDBY 0x80 #define MAX6639_GCONFIG_POR 0x40 #define MAX6639_GCONFIG_DISABLE_TIMEOUT 0x20 #define MAX6639_GCONFIG_CH2_LOCAL 0x10 #define MAX6639_GCONFIG_PWM_FREQ_HI 0x08 #define MAX6639_FAN_CONFIG1_PWM 0x80 #define MAX6639_FAN_CONFIG3_THERM_FULL_SPEED 0x40 static const int rpm_ranges[] = { 2000, 4000, 8000, 16000 }; #define FAN_FROM_REG(val, rpm_range) ((val) == 0 || (val) == 255 ? \ 0 : (rpm_ranges[rpm_range] * 30) / (val)) #define TEMP_LIMIT_TO_REG(val) clamp_val((val) / 1000, 0, 255) /* * Client data (each client gets its own) */ struct max6639_data { struct i2c_client *client; struct mutex update_lock; char valid; /* !=0 if following fields are valid */ unsigned long last_updated; /* In jiffies */ /* Register values sampled regularly */ u16 temp[2]; /* Temperature, in 1/8 C, 0..255 C */ bool temp_fault[2]; /* Detected temperature diode failure */ u8 fan[2]; /* Register value: TACH count for fans >=30 */ u8 status; /* Detected channel alarms and fan failures */ /* Register values only written to */ u8 pwm[2]; /* Register value: Duty cycle 0..120 */ u8 temp_therm[2]; /* THERM Temperature, 0..255 C (->_max) */ u8 temp_alert[2]; /* ALERT Temperature, 0..255 C (->_crit) */ u8 temp_ot[2]; /* OT Temperature, 0..255 C (->_emergency) */ /* Register values initialized only once */ u8 ppr; /* Pulses per rotation 0..3 for 1..4 ppr */ u8 rpm_range; /* Index in above rpm_ranges table */ }; static struct max6639_data *max6639_update_device(struct device *dev) { struct max6639_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; struct max6639_data *ret = data; int i; int status_reg; mutex_lock(&data->update_lock); if (time_after(jiffies, data->last_updated + 2 * HZ) || !data->valid) { int res; dev_dbg(&client->dev, "Starting max6639 update\n"); status_reg = i2c_smbus_read_byte_data(client, MAX6639_REG_STATUS); if (status_reg < 0) { ret = ERR_PTR(status_reg); goto abort; } data->status = status_reg; for (i = 0; i < 2; i++) { res = i2c_smbus_read_byte_data(client, MAX6639_REG_FAN_CNT(i)); if (res < 0) { ret = ERR_PTR(res); goto abort; } data->fan[i] = res; res = i2c_smbus_read_byte_data(client, MAX6639_REG_TEMP_EXT(i)); if (res < 0) { ret = ERR_PTR(res); goto abort; } data->temp[i] = res >> 5; data->temp_fault[i] = res & 0x01; res = i2c_smbus_read_byte_data(client, MAX6639_REG_TEMP(i)); if (res < 0) { ret = ERR_PTR(res); goto abort; } data->temp[i] |= res << 3; } data->last_updated = jiffies; data->valid = 1; } abort: mutex_unlock(&data->update_lock); return ret; } static ssize_t show_temp_input(struct device *dev, struct device_attribute *dev_attr, char *buf) { long temp; struct max6639_data *data = max6639_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); if (IS_ERR(data)) return PTR_ERR(data); temp = data->temp[attr->index] * 125; return sprintf(buf, "%ld\n", temp); } static ssize_t show_temp_fault(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct max6639_data *data = max6639_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", data->temp_fault[attr->index]); } static ssize_t show_temp_max(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); return sprintf(buf, "%d\n", (data->temp_therm[attr->index] * 1000)); } static ssize_t set_temp_max(struct device *dev, struct device_attribute *dev_attr, const char *buf, size_t count) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; unsigned long val; int res; res = kstrtoul(buf, 10, &val); if (res) return res; mutex_lock(&data->update_lock); data->temp_therm[attr->index] = TEMP_LIMIT_TO_REG(val); i2c_smbus_write_byte_data(client, MAX6639_REG_THERM_LIMIT(attr->index), data->temp_therm[attr->index]); mutex_unlock(&data->update_lock); return count; } static ssize_t show_temp_crit(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); return sprintf(buf, "%d\n", (data->temp_alert[attr->index] * 1000)); } static ssize_t set_temp_crit(struct device *dev, struct device_attribute *dev_attr, const char *buf, size_t count) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; unsigned long val; int res; res = kstrtoul(buf, 10, &val); if (res) return res; mutex_lock(&data->update_lock); data->temp_alert[attr->index] = TEMP_LIMIT_TO_REG(val); i2c_smbus_write_byte_data(client, MAX6639_REG_ALERT_LIMIT(attr->index), data->temp_alert[attr->index]); mutex_unlock(&data->update_lock); return count; } static ssize_t show_temp_emergency(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); return sprintf(buf, "%d\n", (data->temp_ot[attr->index] * 1000)); } static ssize_t set_temp_emergency(struct device *dev, struct device_attribute *dev_attr, const char *buf, size_t count) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; unsigned long val; int res; res = kstrtoul(buf, 10, &val); if (res) return res; mutex_lock(&data->update_lock); data->temp_ot[attr->index] = TEMP_LIMIT_TO_REG(val); i2c_smbus_write_byte_data(client, MAX6639_REG_OT_LIMIT(attr->index), data->temp_ot[attr->index]); mutex_unlock(&data->update_lock); return count; } static ssize_t show_pwm(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); return sprintf(buf, "%d\n", data->pwm[attr->index] * 255 / 120); } static ssize_t set_pwm(struct device *dev, struct device_attribute *dev_attr, const char *buf, size_t count) { struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); struct max6639_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; unsigned long val; int res; res = kstrtoul(buf, 10, &val); if (res) return res; val = clamp_val(val, 0, 255); mutex_lock(&data->update_lock); data->pwm[attr->index] = (u8)(val * 120 / 255); i2c_smbus_write_byte_data(client, MAX6639_REG_TARGTDUTY(attr->index), data->pwm[attr->index]); mutex_unlock(&data->update_lock); return count; } static ssize_t show_fan_input(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct max6639_data *data = max6639_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[attr->index], data->rpm_range)); } static ssize_t show_alarm(struct device *dev, struct device_attribute *dev_attr, char *buf) { struct max6639_data *data = max6639_update_device(dev); struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", !!(data->status & (1 << attr->index))); } static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp_input, NULL, 0); static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp_input, NULL, 1); static SENSOR_DEVICE_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0); static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1); static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp_max, set_temp_max, 0); static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_temp_max, set_temp_max, 1); static SENSOR_DEVICE_ATTR(temp1_crit, S_IWUSR | S_IRUGO, show_temp_crit, set_temp_crit, 0); static SENSOR_DEVICE_ATTR(temp2_crit, S_IWUSR | S_IRUGO, show_temp_crit, set_temp_crit, 1); static SENSOR_DEVICE_ATTR(temp1_emergency, S_IWUSR | S_IRUGO, show_temp_emergency, set_temp_emergency, 0); static SENSOR_DEVICE_ATTR(temp2_emergency, S_IWUSR | S_IRUGO, show_temp_emergency, set_temp_emergency, 1); static SENSOR_DEVICE_ATTR(pwm1, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 0); static SENSOR_DEVICE_ATTR(pwm2, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 1); static SENSOR_DEVICE_ATTR(fan1_input, S_IRUGO, show_fan_input, NULL, 0); static SENSOR_DEVICE_ATTR(fan2_input, S_IRUGO, show_fan_input, NULL, 1); static SENSOR_DEVICE_ATTR(fan1_fault, S_IRUGO, show_alarm, NULL, 1); static SENSOR_DEVICE_ATTR(fan2_fault, S_IRUGO, show_alarm, NULL, 0); static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL, 3); static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_alarm, NULL, 2); static SENSOR_DEVICE_ATTR(temp1_crit_alarm, S_IRUGO, show_alarm, NULL, 7); static SENSOR_DEVICE_ATTR(temp2_crit_alarm, S_IRUGO, show_alarm, NULL, 6); static SENSOR_DEVICE_ATTR(temp1_emergency_alarm, S_IRUGO, show_alarm, NULL, 5); static SENSOR_DEVICE_ATTR(temp2_emergency_alarm, S_IRUGO, show_alarm, NULL, 4); static struct attribute *max6639_attrs[] = { &sensor_dev_attr_temp1_input.dev_attr.attr, &sensor_dev_attr_temp2_input.dev_attr.attr, &sensor_dev_attr_temp1_fault.dev_attr.attr, &sensor_dev_attr_temp2_fault.dev_attr.attr, &sensor_dev_attr_temp1_max.dev_attr.attr, &sensor_dev_attr_temp2_max.dev_attr.attr, &sensor_dev_attr_temp1_crit.dev_attr.attr, &sensor_dev_attr_temp2_crit.dev_attr.attr, &sensor_dev_attr_temp1_emergency.dev_attr.attr, &sensor_dev_attr_temp2_emergency.dev_attr.attr, &sensor_dev_attr_pwm1.dev_attr.attr, &sensor_dev_attr_pwm2.dev_attr.attr, &sensor_dev_attr_fan1_input.dev_attr.attr, &sensor_dev_attr_fan2_input.dev_attr.attr, &sensor_dev_attr_fan1_fault.dev_attr.attr, &sensor_dev_attr_fan2_fault.dev_attr.attr, &sensor_dev_attr_temp1_max_alarm.dev_attr.attr, &sensor_dev_attr_temp2_max_alarm.dev_attr.attr, &sensor_dev_attr_temp1_crit_alarm.dev_attr.attr, &sensor_dev_attr_temp2_crit_alarm.dev_attr.attr, &sensor_dev_attr_temp1_emergency_alarm.dev_attr.attr, &sensor_dev_attr_temp2_emergency_alarm.dev_attr.attr, NULL }; ATTRIBUTE_GROUPS(max6639); /* * returns respective index in rpm_ranges table * 1 by default on invalid range */ static int rpm_range_to_reg(int range) { int i; for (i = 0; i < ARRAY_SIZE(rpm_ranges); i++) { if (rpm_ranges[i] == range) return i; } return 1; /* default: 4000 RPM */ } static int max6639_init_client(struct i2c_client *client, struct max6639_data *data) { struct max6639_platform_data *max6639_info = dev_get_platdata(&client->dev); int i; int rpm_range = 1; /* default: 4000 RPM */ int err; /* Reset chip to default values, see below for GCONFIG setup */ err = i2c_smbus_write_byte_data(client, MAX6639_REG_GCONFIG, MAX6639_GCONFIG_POR); if (err) goto exit; /* Fans pulse per revolution is 2 by default */ if (max6639_info && max6639_info->ppr > 0 && max6639_info->ppr < 5) data->ppr = max6639_info->ppr; else data->ppr = 2; data->ppr -= 1; if (max6639_info) rpm_range = rpm_range_to_reg(max6639_info->rpm_range); data->rpm_range = rpm_range; for (i = 0; i < 2; i++) { /* Set Fan pulse per revolution */ err = i2c_smbus_write_byte_data(client, MAX6639_REG_FAN_PPR(i), data->ppr << 6); if (err) goto exit; /* Fans config PWM, RPM */ err = i2c_smbus_write_byte_data(client, MAX6639_REG_FAN_CONFIG1(i), MAX6639_FAN_CONFIG1_PWM | rpm_range); if (err) goto exit; /* Fans PWM polarity high by default */ if (max6639_info && max6639_info->pwm_polarity == 0) err = i2c_smbus_write_byte_data(client, MAX6639_REG_FAN_CONFIG2a(i), 0x00); else err = i2c_smbus_write_byte_data(client, MAX6639_REG_FAN_CONFIG2a(i), 0x02); if (err) goto exit; /* * /THERM full speed enable, * PWM frequency 25kHz, see also GCONFIG below */ err = i2c_smbus_write_byte_data(client, MAX6639_REG_FAN_CONFIG3(i), MAX6639_FAN_CONFIG3_THERM_FULL_SPEED | 0x03); if (err) goto exit; /* Max. temp. 80C/90C/100C */ data->temp_therm[i] = 80; data->temp_alert[i] = 90; data->temp_ot[i] = 100; err = i2c_smbus_write_byte_data(client, MAX6639_REG_THERM_LIMIT(i), data->temp_therm[i]); if (err) goto exit; err = i2c_smbus_write_byte_data(client, MAX6639_REG_ALERT_LIMIT(i), data->temp_alert[i]); if (err) goto exit; err = i2c_smbus_write_byte_data(client, MAX6639_REG_OT_LIMIT(i), data->temp_ot[i]); if (err) goto exit; /* PWM 120/120 (i.e. 100%) */ data->pwm[i] = 120; err = i2c_smbus_write_byte_data(client, MAX6639_REG_TARGTDUTY(i), data->pwm[i]); if (err) goto exit; } /* Start monitoring */ err = i2c_smbus_write_byte_data(client, MAX6639_REG_GCONFIG, MAX6639_GCONFIG_DISABLE_TIMEOUT | MAX6639_GCONFIG_CH2_LOCAL | MAX6639_GCONFIG_PWM_FREQ_HI); exit: return err; } /* Return 0 if detection is successful, -ENODEV otherwise */ static int max6639_detect(struct i2c_client *client, struct i2c_board_info *info) { struct i2c_adapter *adapter = client->adapter; int dev_id, manu_id; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -ENODEV; /* Actual detection via device and manufacturer ID */ dev_id = i2c_smbus_read_byte_data(client, MAX6639_REG_DEVID); manu_id = i2c_smbus_read_byte_data(client, MAX6639_REG_MANUID); if (dev_id != 0x58 || manu_id != 0x4D) return -ENODEV; strlcpy(info->type, "max6639", I2C_NAME_SIZE); return 0; } static int max6639_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct device *dev = &client->dev; struct max6639_data *data; struct device *hwmon_dev; int err; data = devm_kzalloc(dev, sizeof(struct max6639_data), GFP_KERNEL); if (!data) return -ENOMEM; data->client = client; mutex_init(&data->update_lock); /* Initialize the max6639 chip */ err = max6639_init_client(client, data); if (err < 0) return err; hwmon_dev = devm_hwmon_device_register_with_groups(dev, client->name, data, max6639_groups); return PTR_ERR_OR_ZERO(hwmon_dev); } #ifdef CONFIG_PM_SLEEP static int max6639_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); int data = i2c_smbus_read_byte_data(client, MAX6639_REG_GCONFIG); if (data < 0) return data; return i2c_smbus_write_byte_data(client, MAX6639_REG_GCONFIG, data | MAX6639_GCONFIG_STANDBY); } static int max6639_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); int data = i2c_smbus_read_byte_data(client, MAX6639_REG_GCONFIG); if (data < 0) return data; return i2c_smbus_write_byte_data(client, MAX6639_REG_GCONFIG, data & ~MAX6639_GCONFIG_STANDBY); } #endif /* CONFIG_PM_SLEEP */ static const struct i2c_device_id max6639_id[] = { {"max6639", 0}, { } }; MODULE_DEVICE_TABLE(i2c, max6639_id); static SIMPLE_DEV_PM_OPS(max6639_pm_ops, max6639_suspend, max6639_resume); static struct i2c_driver max6639_driver = { .class = I2C_CLASS_HWMON, .driver = { .name = "max6639", .pm = &max6639_pm_ops, }, .probe = max6639_probe, .id_table = max6639_id, .detect = max6639_detect, .address_list = normal_i2c, }; module_i2c_driver(max6639_driver); MODULE_AUTHOR("Roland Stigge <stigge@antcom.de>"); MODULE_DESCRIPTION("max6639 driver"); MODULE_LICENSE("GPL");
gpl-2.0
burstlam/kernel-35
drivers/staging/msm/mdp_dma.c
3017
15006
/* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/hrtimer.h> #include <mach/hardware.h> #include <linux/io.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/spinlock.h> #include <linux/fb.h> #include "mdp.h" #include "msm_fb.h" #include "mddihost.h" static uint32 mdp_last_dma2_update_width; static uint32 mdp_last_dma2_update_height; static uint32 mdp_curr_dma2_update_width; static uint32 mdp_curr_dma2_update_height; ktime_t mdp_dma2_last_update_time = { 0 }; int mdp_lcd_rd_cnt_offset_slow = 20; int mdp_lcd_rd_cnt_offset_fast = 20; int mdp_vsync_usec_wait_line_too_short = 5; uint32 mdp_dma2_update_time_in_usec; uint32 mdp_total_vdopkts; extern u32 msm_fb_debug_enabled; extern struct workqueue_struct *mdp_dma_wq; int vsync_start_y_adjust = 4; static void mdp_dma2_update_lcd(struct msm_fb_data_type *mfd) { MDPIBUF *iBuf = &mfd->ibuf; int mddi_dest = FALSE; uint32 outBpp = iBuf->bpp; uint32 dma2_cfg_reg; uint8 *src; uint32 mddi_ld_param; uint16 mddi_vdo_packet_reg; struct msm_fb_panel_data *pdata = (struct msm_fb_panel_data *)mfd->pdev->dev.platform_data; uint32 ystride = mfd->fbi->fix.line_length; dma2_cfg_reg = DMA_PACK_TIGHT | DMA_PACK_ALIGN_LSB | DMA_OUT_SEL_AHB | DMA_IBUF_NONCONTIGUOUS; #ifdef CONFIG_FB_MSM_MDP30 /* * Software workaround: On 7x25/7x27, the MDP will not * respond if dma_w is 1 pixel. Set the update width to * 2 pixels and adjust the x offset if needed. */ if (iBuf->dma_w == 1) { iBuf->dma_w = 2; if (iBuf->dma_x == (iBuf->ibuf_width - 2)) iBuf->dma_x--; } #endif if (mfd->fb_imgType == MDP_BGR_565) dma2_cfg_reg |= DMA_PACK_PATTERN_BGR; else dma2_cfg_reg |= DMA_PACK_PATTERN_RGB; if (outBpp == 4) dma2_cfg_reg |= DMA_IBUF_C3ALPHA_EN; if (outBpp == 2) dma2_cfg_reg |= DMA_IBUF_FORMAT_RGB565; mddi_ld_param = 0; mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if ((mfd->panel_info.type == MDDI_PANEL) || (mfd->panel_info.type == EXT_MDDI_PANEL)) { dma2_cfg_reg |= DMA_OUT_SEL_MDDI; mddi_dest = TRUE; if (mfd->panel_info.type == MDDI_PANEL) { mdp_total_vdopkts++; if (mfd->panel_info.pdest == DISPLAY_1) { dma2_cfg_reg |= DMA_MDDI_DMAOUT_LCD_SEL_PRIMARY; mddi_ld_param = 0; #ifdef MDDI_HOST_WINDOW_WORKAROUND mddi_window_adjust(mfd, iBuf->dma_x, iBuf->dma_w - 1, iBuf->dma_y, iBuf->dma_h - 1); #endif } else { dma2_cfg_reg |= DMA_MDDI_DMAOUT_LCD_SEL_SECONDARY; mddi_ld_param = 1; #ifdef MDDI_HOST_WINDOW_WORKAROUND mddi_window_adjust(mfd, iBuf->dma_x, iBuf->dma_w - 1, iBuf->dma_y, iBuf->dma_h - 1); #endif } } else { dma2_cfg_reg |= DMA_MDDI_DMAOUT_LCD_SEL_EXTERNAL; mddi_ld_param = 2; } } else { if (mfd->panel_info.pdest == DISPLAY_1) { dma2_cfg_reg |= DMA_AHBM_LCD_SEL_PRIMARY; outp32(MDP_EBI2_LCD0, mfd->data_port_phys); } else { dma2_cfg_reg |= DMA_AHBM_LCD_SEL_SECONDARY; outp32(MDP_EBI2_LCD1, mfd->data_port_phys); } } dma2_cfg_reg |= DMA_DITHER_EN; src = (uint8 *) iBuf->buf; /* starting input address */ src += iBuf->dma_x * outBpp + iBuf->dma_y * ystride; mdp_curr_dma2_update_width = iBuf->dma_w; mdp_curr_dma2_update_height = iBuf->dma_h; /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); #ifdef CONFIG_FB_MSM_MDP22 MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x0184, (iBuf->dma_h << 16 | iBuf->dma_w)); MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x0188, src); MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x018C, ystride); #else MDP_OUTP(MDP_BASE + 0x90004, (iBuf->dma_h << 16 | iBuf->dma_w)); MDP_OUTP(MDP_BASE + 0x90008, src); MDP_OUTP(MDP_BASE + 0x9000c, ystride); #endif if (mfd->panel_info.bpp == 18) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } if (mddi_dest) { #ifdef CONFIG_FB_MSM_MDP22 MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x0194, (iBuf->dma_y << 16) | iBuf->dma_x); MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x01a0, mddi_ld_param); MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x01a4, (MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg); #else MDP_OUTP(MDP_BASE + 0x90010, (iBuf->dma_y << 16) | iBuf->dma_x); MDP_OUTP(MDP_BASE + 0x00090, mddi_ld_param); MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg); #endif } else { /* setting EBI2 LCDC write window */ pdata->set_rect(iBuf->dma_x, iBuf->dma_y, iBuf->dma_w, iBuf->dma_h); } /* dma2 config register */ #ifdef MDP_HW_VSYNC MDP_OUTP(MDP_BASE + 0x90000, dma2_cfg_reg); if ((mfd->use_mdp_vsync) && (mfd->ibuf.vsync_enable) && (mfd->panel_info.lcd.vsync_enable)) { uint32 start_y; if (vsync_start_y_adjust <= iBuf->dma_y) start_y = iBuf->dma_y - vsync_start_y_adjust; else start_y = (mfd->total_lcd_lines - 1) - (vsync_start_y_adjust - iBuf->dma_y); /* * MDP VSYNC clock must be On by now so, we don't have to * re-enable it */ MDP_OUTP(MDP_BASE + 0x210, start_y); MDP_OUTP(MDP_BASE + 0x20c, 1); /* enable prim vsync */ } else { MDP_OUTP(MDP_BASE + 0x20c, 0); /* disable prim vsync */ } #else #ifdef CONFIG_FB_MSM_MDP22 MDP_OUTP(MDP_CMD_DEBUG_ACCESS_BASE + 0x0180, dma2_cfg_reg); #else MDP_OUTP(MDP_BASE + 0x90000, dma2_cfg_reg); #endif #endif /* MDP_HW_VSYNC */ /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } static ktime_t vt = { 0 }; int mdp_usec_diff_threshold = 100; int mdp_expected_usec_wait; enum hrtimer_restart mdp_dma2_vsync_hrtimer_handler(struct hrtimer *ht) { struct msm_fb_data_type *mfd = NULL; mfd = container_of(ht, struct msm_fb_data_type, dma_hrtimer); mdp_pipe_kickoff(MDP_DMA2_TERM, mfd); if (msm_fb_debug_enabled) { ktime_t t; int usec_diff; int actual_wait; t = ktime_get_real(); actual_wait = (t.tv.sec - vt.tv.sec) * 1000000 + (t.tv.nsec - vt.tv.nsec) / 1000; usec_diff = actual_wait - mdp_expected_usec_wait; if ((mdp_usec_diff_threshold < usec_diff) || (usec_diff < 0)) MSM_FB_DEBUG ("HRT Diff = %d usec Exp=%d usec Act=%d usec\n", usec_diff, mdp_expected_usec_wait, actual_wait); } return HRTIMER_NORESTART; } static void mdp_dma_schedule(struct msm_fb_data_type *mfd, uint32 term) { /* * dma2 configure VSYNC block * vsync supported on Primary LCD only for now */ int32 mdp_lcd_rd_cnt; uint32 usec_wait_time; uint32 start_y; /* * ToDo: if we can move HRT timer callback to workqueue, we can * move DMA2 power on under mdp_pipe_kickoff(). * This will save a power for hrt time wait. * However if the latency for context switch (hrt irq -> workqueue) * is too big, we will miss the vsync timing. */ if (term == MDP_DMA2_TERM) mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_dma2_update_time_in_usec = MDP_KTIME2USEC(mdp_dma2_last_update_time); if ((!mfd->ibuf.vsync_enable) || (!mfd->panel_info.lcd.vsync_enable) || (mfd->use_mdp_vsync)) { mdp_pipe_kickoff(term, mfd); return; } /* SW vsync logic starts here */ /* get current rd counter */ mdp_lcd_rd_cnt = mdp_get_lcd_line_counter(mfd); if (mdp_dma2_update_time_in_usec != 0) { uint32 num, den; /* * roi width boundary calculation to know the size of pixel * width that MDP can send faster or slower than LCD read * pointer */ num = mdp_last_dma2_update_width * mdp_last_dma2_update_height; den = (((mfd->panel_info.lcd.refx100 * mfd->total_lcd_lines) / 1000) * (mdp_dma2_update_time_in_usec / 100)) / 1000; if (den == 0) mfd->vsync_width_boundary[mdp_last_dma2_update_width] = mfd->panel_info.xres + 1; else mfd->vsync_width_boundary[mdp_last_dma2_update_width] = (int)(num / den); } if (mfd->vsync_width_boundary[mdp_last_dma2_update_width] > mdp_curr_dma2_update_width) { /* MDP wrp is faster than LCD rdp */ mdp_lcd_rd_cnt += mdp_lcd_rd_cnt_offset_fast; } else { /* MDP wrp is slower than LCD rdp */ mdp_lcd_rd_cnt -= mdp_lcd_rd_cnt_offset_slow; } if (mdp_lcd_rd_cnt < 0) mdp_lcd_rd_cnt = mfd->total_lcd_lines + mdp_lcd_rd_cnt; else if (mdp_lcd_rd_cnt > mfd->total_lcd_lines) mdp_lcd_rd_cnt = mdp_lcd_rd_cnt - mfd->total_lcd_lines - 1; /* get wrt pointer position */ start_y = mfd->ibuf.dma_y; /* measure line difference between start_y and rd counter */ if (start_y > mdp_lcd_rd_cnt) { /* * *100 for lcd_ref_hzx100 was already multiplied by 100 * *1000000 is for usec conversion */ if ((start_y - mdp_lcd_rd_cnt) <= mdp_vsync_usec_wait_line_too_short) usec_wait_time = 0; else usec_wait_time = ((start_y - mdp_lcd_rd_cnt) * 1000000) / ((mfd->total_lcd_lines * mfd->panel_info.lcd.refx100) / 100); } else { if ((start_y + (mfd->total_lcd_lines - mdp_lcd_rd_cnt)) <= mdp_vsync_usec_wait_line_too_short) usec_wait_time = 0; else usec_wait_time = ((start_y + (mfd->total_lcd_lines - mdp_lcd_rd_cnt)) * 1000000) / ((mfd->total_lcd_lines * mfd->panel_info.lcd.refx100) / 100); } mdp_last_dma2_update_width = mdp_curr_dma2_update_width; mdp_last_dma2_update_height = mdp_curr_dma2_update_height; if (usec_wait_time == 0) { mdp_pipe_kickoff(term, mfd); } else { ktime_t wait_time; wait_time.tv.sec = 0; wait_time.tv.nsec = usec_wait_time * 1000; if (msm_fb_debug_enabled) { vt = ktime_get_real(); mdp_expected_usec_wait = usec_wait_time; } hrtimer_start(&mfd->dma_hrtimer, wait_time, HRTIMER_MODE_REL); } } #ifdef MDDI_HOST_WINDOW_WORKAROUND void mdp_dma2_update(struct msm_fb_data_type *mfd) { MDPIBUF *iBuf; uint32 upper_height; if (mfd->panel.type == EXT_MDDI_PANEL) { mdp_dma2_update_sub(mfd); return; } iBuf = &mfd->ibuf; upper_height = (uint32) mddi_assign_pkt_height((uint16) iBuf->dma_w, (uint16) iBuf->dma_h, 18); if (upper_height >= iBuf->dma_h) { mdp_dma2_update_sub(mfd); } else { MDPIBUF lower_height; /* sending the upper region first */ lower_height = iBuf->dma_h - upper_height; iBuf->dma_h = upper_height; mdp_dma2_update_sub(mfd); /* sending the lower region second */ iBuf->dma_h = lower_height; iBuf->dma_y += lower_height; iBuf->vsync_enable = FALSE; mdp_dma2_update_sub(mfd); } } void mdp_dma2_update_sub(struct msm_fb_data_type *mfd) #else void mdp_dma2_update(struct msm_fb_data_type *mfd) #endif { down(&mfd->dma->mutex); if ((mfd) && (!mfd->dma->busy) && (mfd->panel_power_on)) { down(&mfd->sem); mfd->ibuf_flushed = TRUE; mdp_dma2_update_lcd(mfd); mdp_enable_irq(MDP_DMA2_TERM); mfd->dma->busy = TRUE; INIT_COMPLETION(mfd->dma->comp); /* schedule DMA to start */ mdp_dma_schedule(mfd, MDP_DMA2_TERM); up(&mfd->sem); /* wait until DMA finishes the current job */ wait_for_completion_killable(&mfd->dma->comp); mdp_disable_irq(MDP_DMA2_TERM); /* signal if pan function is waiting for the update completion */ if (mfd->pan_waiting) { mfd->pan_waiting = FALSE; complete(&mfd->pan_comp); } } up(&mfd->dma->mutex); } void mdp_lcd_update_workqueue_handler(struct work_struct *work) { struct msm_fb_data_type *mfd = NULL; mfd = container_of(work, struct msm_fb_data_type, dma_update_worker); if (mfd) mfd->dma_fnc(mfd); } void mdp_set_dma_pan_info(struct fb_info *info, struct mdp_dirty_region *dirty, boolean sync) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; MDPIBUF *iBuf; int bpp = info->var.bits_per_pixel / 8; down(&mfd->sem); iBuf = &mfd->ibuf; iBuf->buf = (uint8 *) info->fix.smem_start; iBuf->buf += info->var.xoffset * bpp + info->var.yoffset * info->fix.line_length; iBuf->ibuf_width = info->var.xres_virtual; iBuf->bpp = bpp; iBuf->vsync_enable = sync; if (dirty) { /* * ToDo: dirty region check inside var.xoffset+xres * <-> var.yoffset+yres */ iBuf->dma_x = dirty->xoffset % info->var.xres; iBuf->dma_y = dirty->yoffset % info->var.yres; iBuf->dma_w = dirty->width; iBuf->dma_h = dirty->height; } else { iBuf->dma_x = 0; iBuf->dma_y = 0; iBuf->dma_w = info->var.xres; iBuf->dma_h = info->var.yres; } mfd->ibuf_flushed = FALSE; up(&mfd->sem); } void mdp_set_offset_info(struct fb_info *info, uint32 addr, uint32 sync) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; MDPIBUF *iBuf; int bpp = info->var.bits_per_pixel / 8; down(&mfd->sem); iBuf = &mfd->ibuf; iBuf->ibuf_width = info->var.xres_virtual; iBuf->bpp = bpp; iBuf->vsync_enable = sync; iBuf->dma_x = 0; iBuf->dma_y = 0; iBuf->dma_w = info->var.xres; iBuf->dma_h = info->var.yres; iBuf->buf = (uint8 *) addr; mfd->ibuf_flushed = FALSE; up(&mfd->sem); } void mdp_dma_pan_update(struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; MDPIBUF *iBuf; iBuf = &mfd->ibuf; if (mfd->sw_currently_refreshing) { /* we need to wait for the pending update */ mfd->pan_waiting = TRUE; if (!mfd->ibuf_flushed) { wait_for_completion_killable(&mfd->pan_comp); } /* waiting for this update to complete */ mfd->pan_waiting = TRUE; wait_for_completion_killable(&mfd->pan_comp); } else mfd->dma_fnc(mfd); } void mdp_refresh_screen(unsigned long data) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)data; if ((mfd->sw_currently_refreshing) && (mfd->sw_refreshing_enable)) { init_timer(&mfd->refresh_timer); mfd->refresh_timer.function = mdp_refresh_screen; mfd->refresh_timer.data = data; if (mfd->dma->busy) /* come back in 1 msec */ mfd->refresh_timer.expires = jiffies + (HZ / 1000); else mfd->refresh_timer.expires = jiffies + mfd->refresh_timer_duration; add_timer(&mfd->refresh_timer); if (!mfd->dma->busy) { if (!queue_work(mdp_dma_wq, &mfd->dma_update_worker)) { MSM_FB_DEBUG("mdp_dma: can't queue_work! -> \ MDP/MDDI/LCD clock speed needs to be increased\n"); } } } else { if (!mfd->hw_refresh) complete(&mfd->refresher_comp); } }
gpl-2.0
TeamHackDroid/android_kernel_samsung_galaxys2plus-common
drivers/watchdog/stmp3xxx_wdt.c
4041
6650
/* * Watchdog driver for Freescale STMP37XX/STMP378X * * Author: Vitaly Wool <vital@embeddedalley.com> * * Copyright 2008 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/miscdevice.h> #include <linux/watchdog.h> #include <linux/platform_device.h> #include <linux/spinlock.h> #include <linux/uaccess.h> #include <mach/platform.h> #include <mach/regs-rtc.h> #define DEFAULT_HEARTBEAT 19 #define MAX_HEARTBEAT (0x10000000 >> 6) /* missing bitmask in headers */ #define BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER 0x80000000 #define WDT_IN_USE 0 #define WDT_OK_TO_CLOSE 1 #define WDOG_COUNTER_RATE 1000 /* 1 kHz clock */ static DEFINE_SPINLOCK(stmp3xxx_wdt_io_lock); static unsigned long wdt_status; static const int nowayout = WATCHDOG_NOWAYOUT; static int heartbeat = DEFAULT_HEARTBEAT; static unsigned long boot_status; static void wdt_enable(u32 value) { spin_lock(&stmp3xxx_wdt_io_lock); __raw_writel(value, REGS_RTC_BASE + HW_RTC_WATCHDOG); stmp3xxx_setl(BM_RTC_CTRL_WATCHDOGEN, REGS_RTC_BASE + HW_RTC_CTRL); stmp3xxx_setl(BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER, REGS_RTC_BASE + HW_RTC_PERSISTENT1); spin_unlock(&stmp3xxx_wdt_io_lock); } static void wdt_disable(void) { spin_lock(&stmp3xxx_wdt_io_lock); stmp3xxx_clearl(BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER, REGS_RTC_BASE + HW_RTC_PERSISTENT1); stmp3xxx_clearl(BM_RTC_CTRL_WATCHDOGEN, REGS_RTC_BASE + HW_RTC_CTRL); spin_unlock(&stmp3xxx_wdt_io_lock); } static void wdt_ping(void) { wdt_enable(heartbeat * WDOG_COUNTER_RATE); } static int stmp3xxx_wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(WDT_IN_USE, &wdt_status)) return -EBUSY; clear_bit(WDT_OK_TO_CLOSE, &wdt_status); wdt_ping(); return nonseekable_open(inode, file); } static ssize_t stmp3xxx_wdt_write(struct file *file, const char __user *data, size_t len, loff_t *ppos) { if (len) { if (!nowayout) { size_t i; clear_bit(WDT_OK_TO_CLOSE, &wdt_status); for (i = 0; i != len; i++) { char c; if (get_user(c, data + i)) return -EFAULT; if (c == 'V') set_bit(WDT_OK_TO_CLOSE, &wdt_status); } } wdt_ping(); } return len; } static const struct watchdog_info ident = { .options = WDIOF_CARDRESET | WDIOF_MAGICCLOSE | WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING, .identity = "STMP3XXX Watchdog", }; static long stmp3xxx_wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int __user *p = argp; int new_heartbeat, opts; int ret = -ENOTTY; switch (cmd) { case WDIOC_GETSUPPORT: ret = copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0; break; case WDIOC_GETSTATUS: ret = put_user(0, p); break; case WDIOC_GETBOOTSTATUS: ret = put_user(boot_status, p); break; case WDIOC_SETOPTIONS: if (get_user(opts, p)) { ret = -EFAULT; break; } if (opts & WDIOS_DISABLECARD) wdt_disable(); else if (opts & WDIOS_ENABLECARD) wdt_ping(); else { pr_debug("%s: unknown option 0x%x\n", __func__, opts); ret = -EINVAL; break; } ret = 0; break; case WDIOC_KEEPALIVE: wdt_ping(); ret = 0; break; case WDIOC_SETTIMEOUT: if (get_user(new_heartbeat, p)) { ret = -EFAULT; break; } if (new_heartbeat <= 0 || new_heartbeat > MAX_HEARTBEAT) { ret = -EINVAL; break; } heartbeat = new_heartbeat; wdt_ping(); /* Fall through */ case WDIOC_GETTIMEOUT: ret = put_user(heartbeat, p); break; } return ret; } static int stmp3xxx_wdt_release(struct inode *inode, struct file *file) { int ret = 0; if (!nowayout) { if (!test_bit(WDT_OK_TO_CLOSE, &wdt_status)) { wdt_ping(); pr_debug("%s: Device closed unexpectdly\n", __func__); ret = -EINVAL; } else { wdt_disable(); clear_bit(WDT_OK_TO_CLOSE, &wdt_status); } } clear_bit(WDT_IN_USE, &wdt_status); return ret; } static const struct file_operations stmp3xxx_wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = stmp3xxx_wdt_write, .unlocked_ioctl = stmp3xxx_wdt_ioctl, .open = stmp3xxx_wdt_open, .release = stmp3xxx_wdt_release, }; static struct miscdevice stmp3xxx_wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &stmp3xxx_wdt_fops, }; static int __devinit stmp3xxx_wdt_probe(struct platform_device *pdev) { int ret = 0; if (heartbeat < 1 || heartbeat > MAX_HEARTBEAT) heartbeat = DEFAULT_HEARTBEAT; boot_status = __raw_readl(REGS_RTC_BASE + HW_RTC_PERSISTENT1) & BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER; boot_status = !!boot_status; stmp3xxx_clearl(BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER, REGS_RTC_BASE + HW_RTC_PERSISTENT1); wdt_disable(); /* disable for now */ ret = misc_register(&stmp3xxx_wdt_miscdev); if (ret < 0) { dev_err(&pdev->dev, "cannot register misc device\n"); return ret; } printk(KERN_INFO "stmp3xxx watchdog: initialized, heartbeat %d sec\n", heartbeat); return ret; } static int __devexit stmp3xxx_wdt_remove(struct platform_device *pdev) { misc_deregister(&stmp3xxx_wdt_miscdev); return 0; } #ifdef CONFIG_PM static int wdt_suspended; static u32 wdt_saved_time; static int stmp3xxx_wdt_suspend(struct platform_device *pdev, pm_message_t state) { if (__raw_readl(REGS_RTC_BASE + HW_RTC_CTRL) & BM_RTC_CTRL_WATCHDOGEN) { wdt_suspended = 1; wdt_saved_time = __raw_readl(REGS_RTC_BASE + HW_RTC_WATCHDOG); wdt_disable(); } return 0; } static int stmp3xxx_wdt_resume(struct platform_device *pdev) { if (wdt_suspended) { wdt_enable(wdt_saved_time); wdt_suspended = 0; } return 0; } #else #define stmp3xxx_wdt_suspend NULL #define stmp3xxx_wdt_resume NULL #endif static struct platform_driver platform_wdt_driver = { .driver = { .name = "stmp3xxx_wdt", }, .probe = stmp3xxx_wdt_probe, .remove = __devexit_p(stmp3xxx_wdt_remove), .suspend = stmp3xxx_wdt_suspend, .resume = stmp3xxx_wdt_resume, }; static int __init stmp3xxx_wdt_init(void) { return platform_driver_register(&platform_wdt_driver); } static void __exit stmp3xxx_wdt_exit(void) { return platform_driver_unregister(&platform_wdt_driver); } module_init(stmp3xxx_wdt_init); module_exit(stmp3xxx_wdt_exit); MODULE_DESCRIPTION("STMP3XXX Watchdog Driver"); MODULE_LICENSE("GPL"); module_param(heartbeat, int, 0); MODULE_PARM_DESC(heartbeat, "Watchdog heartbeat period in seconds from 1 to " __MODULE_STRING(MAX_HEARTBEAT) ", default " __MODULE_STRING(DEFAULT_HEARTBEAT)); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
gpl-2.0
NaughtyMonkey75/kernel_htc_msm8974
arch/m68k/platform/coldfire/sltimers.c
4553
3935
/***************************************************************************/ /* * sltimers.c -- generic ColdFire slice timer support. * * Copyright (C) 2009-2010, Philippe De Muyter <phdm@macqel.be> * based on * timers.c -- generic ColdFire hardware timer support. * Copyright (C) 1999-2008, Greg Ungerer <gerg@snapgear.com> */ /***************************************************************************/ #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/profile.h> #include <linux/clocksource.h> #include <asm/io.h> #include <asm/traps.h> #include <asm/machdep.h> #include <asm/coldfire.h> #include <asm/mcfslt.h> #include <asm/mcfsim.h> /***************************************************************************/ #ifdef CONFIG_HIGHPROFILE /* * By default use Slice Timer 1 as the profiler clock timer. */ #define PA(a) (MCF_MBAR + MCFSLT_TIMER1 + (a)) /* * Choose a reasonably fast profile timer. Make it an odd value to * try and get good coverage of kernel operations. */ #define PROFILEHZ 1013 irqreturn_t mcfslt_profile_tick(int irq, void *dummy) { /* Reset Slice Timer 1 */ __raw_writel(MCFSLT_SSR_BE | MCFSLT_SSR_TE, PA(MCFSLT_SSR)); if (current->pid) profile_tick(CPU_PROFILING); return IRQ_HANDLED; } static struct irqaction mcfslt_profile_irq = { .name = "profile timer", .flags = IRQF_DISABLED | IRQF_TIMER, .handler = mcfslt_profile_tick, }; void mcfslt_profile_init(void) { printk(KERN_INFO "PROFILE: lodging TIMER 1 @ %dHz as profile timer\n", PROFILEHZ); setup_irq(MCF_IRQ_PROFILER, &mcfslt_profile_irq); /* Set up TIMER 2 as high speed profile clock */ __raw_writel(MCF_BUSCLK / PROFILEHZ - 1, PA(MCFSLT_STCNT)); __raw_writel(MCFSLT_SCR_RUN | MCFSLT_SCR_IEN | MCFSLT_SCR_TEN, PA(MCFSLT_SCR)); } #endif /* CONFIG_HIGHPROFILE */ /***************************************************************************/ /* * By default use Slice Timer 0 as the system clock timer. */ #define TA(a) (MCF_MBAR + MCFSLT_TIMER0 + (a)) static u32 mcfslt_cycles_per_jiffy; static u32 mcfslt_cnt; static irq_handler_t timer_interrupt; static irqreturn_t mcfslt_tick(int irq, void *dummy) { /* Reset Slice Timer 0 */ __raw_writel(MCFSLT_SSR_BE | MCFSLT_SSR_TE, TA(MCFSLT_SSR)); mcfslt_cnt += mcfslt_cycles_per_jiffy; return timer_interrupt(irq, dummy); } static struct irqaction mcfslt_timer_irq = { .name = "timer", .flags = IRQF_DISABLED | IRQF_TIMER, .handler = mcfslt_tick, }; static cycle_t mcfslt_read_clk(struct clocksource *cs) { unsigned long flags; u32 cycles, scnt; local_irq_save(flags); scnt = __raw_readl(TA(MCFSLT_SCNT)); cycles = mcfslt_cnt; if (__raw_readl(TA(MCFSLT_SSR)) & MCFSLT_SSR_TE) { cycles += mcfslt_cycles_per_jiffy; scnt = __raw_readl(TA(MCFSLT_SCNT)); } local_irq_restore(flags); /* subtract because slice timers count down */ return cycles + ((mcfslt_cycles_per_jiffy - 1) - scnt); } static struct clocksource mcfslt_clk = { .name = "slt", .rating = 250, .read = mcfslt_read_clk, .mask = CLOCKSOURCE_MASK(32), .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; void hw_timer_init(irq_handler_t handler) { mcfslt_cycles_per_jiffy = MCF_BUSCLK / HZ; /* * The coldfire slice timer (SLT) runs from STCNT to 0 included, * then STCNT again and so on. It counts thus actually * STCNT + 1 steps for 1 tick, not STCNT. So if you want * n cycles, initialize STCNT with n - 1. */ __raw_writel(mcfslt_cycles_per_jiffy - 1, TA(MCFSLT_STCNT)); __raw_writel(MCFSLT_SCR_RUN | MCFSLT_SCR_IEN | MCFSLT_SCR_TEN, TA(MCFSLT_SCR)); /* initialize mcfslt_cnt knowing that slice timers count down */ mcfslt_cnt = mcfslt_cycles_per_jiffy; timer_interrupt = handler; setup_irq(MCF_IRQ_TIMER, &mcfslt_timer_irq); clocksource_register_hz(&mcfslt_clk, MCF_BUSCLK); #ifdef CONFIG_HIGHPROFILE mcfslt_profile_init(); #endif }
gpl-2.0
MyAOSP/kernel_samsung_manta
arch/x86/kernel/tboot.c
4553
11623
/* * tboot.c: main implementation of helper functions used by kernel for * runtime support of Intel(R) Trusted Execution Technology * * Copyright (c) 2006-2009, Intel Corporation * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/dma_remapping.h> #include <linux/init_task.h> #include <linux/spinlock.h> #include <linux/export.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/init.h> #include <linux/dmar.h> #include <linux/cpu.h> #include <linux/pfn.h> #include <linux/mm.h> #include <linux/tboot.h> #include <asm/trampoline.h> #include <asm/processor.h> #include <asm/bootparam.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/swiotlb.h> #include <asm/fixmap.h> #include <asm/proto.h> #include <asm/setup.h> #include <asm/e820.h> #include <asm/io.h> #include "acpi/realmode/wakeup.h" /* Global pointer to shared data; NULL means no measured launch. */ struct tboot *tboot __read_mostly; EXPORT_SYMBOL(tboot); /* timeout for APs (in secs) to enter wait-for-SIPI state during shutdown */ #define AP_WAIT_TIMEOUT 1 #undef pr_fmt #define pr_fmt(fmt) "tboot: " fmt static u8 tboot_uuid[16] __initdata = TBOOT_UUID; void __init tboot_probe(void) { /* Look for valid page-aligned address for shared page. */ if (!boot_params.tboot_addr) return; /* * also verify that it is mapped as we expect it before calling * set_fixmap(), to reduce chance of garbage value causing crash */ if (!e820_any_mapped(boot_params.tboot_addr, boot_params.tboot_addr, E820_RESERVED)) { pr_warning("non-0 tboot_addr but it is not of type E820_RESERVED\n"); return; } /* only a natively booted kernel should be using TXT */ if (paravirt_enabled()) { pr_warning("non-0 tboot_addr but pv_ops is enabled\n"); return; } /* Map and check for tboot UUID. */ set_fixmap(FIX_TBOOT_BASE, boot_params.tboot_addr); tboot = (struct tboot *)fix_to_virt(FIX_TBOOT_BASE); if (memcmp(&tboot_uuid, &tboot->uuid, sizeof(tboot->uuid))) { pr_warning("tboot at 0x%llx is invalid\n", boot_params.tboot_addr); tboot = NULL; return; } if (tboot->version < 5) { pr_warning("tboot version is invalid: %u\n", tboot->version); tboot = NULL; return; } pr_info("found shared page at phys addr 0x%llx:\n", boot_params.tboot_addr); pr_debug("version: %d\n", tboot->version); pr_debug("log_addr: 0x%08x\n", tboot->log_addr); pr_debug("shutdown_entry: 0x%x\n", tboot->shutdown_entry); pr_debug("tboot_base: 0x%08x\n", tboot->tboot_base); pr_debug("tboot_size: 0x%x\n", tboot->tboot_size); } static pgd_t *tboot_pg_dir; static struct mm_struct tboot_mm = { .mm_rb = RB_ROOT, .pgd = swapper_pg_dir, .mm_users = ATOMIC_INIT(2), .mm_count = ATOMIC_INIT(1), .mmap_sem = __RWSEM_INITIALIZER(init_mm.mmap_sem), .page_table_lock = __SPIN_LOCK_UNLOCKED(init_mm.page_table_lock), .mmlist = LIST_HEAD_INIT(init_mm.mmlist), }; static inline void switch_to_tboot_pt(void) { write_cr3(virt_to_phys(tboot_pg_dir)); } static int map_tboot_page(unsigned long vaddr, unsigned long pfn, pgprot_t prot) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; pgd = pgd_offset(&tboot_mm, vaddr); pud = pud_alloc(&tboot_mm, pgd, vaddr); if (!pud) return -1; pmd = pmd_alloc(&tboot_mm, pud, vaddr); if (!pmd) return -1; pte = pte_alloc_map(&tboot_mm, NULL, pmd, vaddr); if (!pte) return -1; set_pte_at(&tboot_mm, vaddr, pte, pfn_pte(pfn, prot)); pte_unmap(pte); return 0; } static int map_tboot_pages(unsigned long vaddr, unsigned long start_pfn, unsigned long nr) { /* Reuse the original kernel mapping */ tboot_pg_dir = pgd_alloc(&tboot_mm); if (!tboot_pg_dir) return -1; for (; nr > 0; nr--, vaddr += PAGE_SIZE, start_pfn++) { if (map_tboot_page(vaddr, start_pfn, PAGE_KERNEL_EXEC)) return -1; } return 0; } static void tboot_create_trampoline(void) { u32 map_base, map_size; /* Create identity map for tboot shutdown code. */ map_base = PFN_DOWN(tboot->tboot_base); map_size = PFN_UP(tboot->tboot_size); if (map_tboot_pages(map_base << PAGE_SHIFT, map_base, map_size)) panic("tboot: Error mapping tboot pages (mfns) @ 0x%x, 0x%x\n", map_base, map_size); } #ifdef CONFIG_ACPI_SLEEP static void add_mac_region(phys_addr_t start, unsigned long size) { struct tboot_mac_region *mr; phys_addr_t end = start + size; if (tboot->num_mac_regions >= MAX_TB_MAC_REGIONS) panic("tboot: Too many MAC regions\n"); if (start && size) { mr = &tboot->mac_regions[tboot->num_mac_regions++]; mr->start = round_down(start, PAGE_SIZE); mr->size = round_up(end, PAGE_SIZE) - mr->start; } } static int tboot_setup_sleep(void) { int i; tboot->num_mac_regions = 0; for (i = 0; i < e820.nr_map; i++) { if ((e820.map[i].type != E820_RAM) && (e820.map[i].type != E820_RESERVED_KERN)) continue; add_mac_region(e820.map[i].addr, e820.map[i].size); } tboot->acpi_sinfo.kernel_s3_resume_vector = acpi_wakeup_address; return 0; } #else /* no CONFIG_ACPI_SLEEP */ static int tboot_setup_sleep(void) { /* S3 shutdown requested, but S3 not supported by the kernel... */ BUG(); return -1; } #endif void tboot_shutdown(u32 shutdown_type) { void (*shutdown)(void); if (!tboot_enabled()) return; /* * if we're being called before the 1:1 mapping is set up then just * return and let the normal shutdown happen; this should only be * due to very early panic() */ if (!tboot_pg_dir) return; /* if this is S3 then set regions to MAC */ if (shutdown_type == TB_SHUTDOWN_S3) if (tboot_setup_sleep()) return; tboot->shutdown_type = shutdown_type; switch_to_tboot_pt(); shutdown = (void(*)(void))(unsigned long)tboot->shutdown_entry; shutdown(); /* should not reach here */ while (1) halt(); } static void tboot_copy_fadt(const struct acpi_table_fadt *fadt) { #define TB_COPY_GAS(tbg, g) \ tbg.space_id = g.space_id; \ tbg.bit_width = g.bit_width; \ tbg.bit_offset = g.bit_offset; \ tbg.access_width = g.access_width; \ tbg.address = g.address; TB_COPY_GAS(tboot->acpi_sinfo.pm1a_cnt_blk, fadt->xpm1a_control_block); TB_COPY_GAS(tboot->acpi_sinfo.pm1b_cnt_blk, fadt->xpm1b_control_block); TB_COPY_GAS(tboot->acpi_sinfo.pm1a_evt_blk, fadt->xpm1a_event_block); TB_COPY_GAS(tboot->acpi_sinfo.pm1b_evt_blk, fadt->xpm1b_event_block); /* * We need phys addr of waking vector, but can't use virt_to_phys() on * &acpi_gbl_FACS because it is ioremap'ed, so calc from FACS phys * addr. */ tboot->acpi_sinfo.wakeup_vector = fadt->facs + offsetof(struct acpi_table_facs, firmware_waking_vector); } static int tboot_sleep(u8 sleep_state, u32 pm1a_control, u32 pm1b_control) { static u32 acpi_shutdown_map[ACPI_S_STATE_COUNT] = { /* S0,1,2: */ -1, -1, -1, /* S3: */ TB_SHUTDOWN_S3, /* S4: */ TB_SHUTDOWN_S4, /* S5: */ TB_SHUTDOWN_S5 }; if (!tboot_enabled()) return 0; tboot_copy_fadt(&acpi_gbl_FADT); tboot->acpi_sinfo.pm1a_cnt_val = pm1a_control; tboot->acpi_sinfo.pm1b_cnt_val = pm1b_control; /* we always use the 32b wakeup vector */ tboot->acpi_sinfo.vector_width = 32; if (sleep_state >= ACPI_S_STATE_COUNT || acpi_shutdown_map[sleep_state] == -1) { pr_warning("unsupported sleep state 0x%x\n", sleep_state); return -1; } tboot_shutdown(acpi_shutdown_map[sleep_state]); return 0; } static atomic_t ap_wfs_count; static int tboot_wait_for_aps(int num_aps) { unsigned long timeout; timeout = AP_WAIT_TIMEOUT*HZ; while (atomic_read((atomic_t *)&tboot->num_in_wfs) != num_aps && timeout) { mdelay(1); timeout--; } if (timeout) pr_warning("tboot wait for APs timeout\n"); return !(atomic_read((atomic_t *)&tboot->num_in_wfs) == num_aps); } static int __cpuinit tboot_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_DYING: atomic_inc(&ap_wfs_count); if (num_online_cpus() == 1) if (tboot_wait_for_aps(atomic_read(&ap_wfs_count))) return NOTIFY_BAD; break; } return NOTIFY_OK; } static struct notifier_block tboot_cpu_notifier __cpuinitdata = { .notifier_call = tboot_cpu_callback, }; static __init int tboot_late_init(void) { if (!tboot_enabled()) return 0; tboot_create_trampoline(); atomic_set(&ap_wfs_count, 0); register_hotcpu_notifier(&tboot_cpu_notifier); acpi_os_set_prepare_sleep(&tboot_sleep); return 0; } late_initcall(tboot_late_init); /* * TXT configuration registers (offsets from TXT_{PUB, PRIV}_CONFIG_REGS_BASE) */ #define TXT_PUB_CONFIG_REGS_BASE 0xfed30000 #define TXT_PRIV_CONFIG_REGS_BASE 0xfed20000 /* # pages for each config regs space - used by fixmap */ #define NR_TXT_CONFIG_PAGES ((TXT_PUB_CONFIG_REGS_BASE - \ TXT_PRIV_CONFIG_REGS_BASE) >> PAGE_SHIFT) /* offsets from pub/priv config space */ #define TXTCR_HEAP_BASE 0x0300 #define TXTCR_HEAP_SIZE 0x0308 #define SHA1_SIZE 20 struct sha1_hash { u8 hash[SHA1_SIZE]; }; struct sinit_mle_data { u32 version; /* currently 6 */ struct sha1_hash bios_acm_id; u32 edx_senter_flags; u64 mseg_valid; struct sha1_hash sinit_hash; struct sha1_hash mle_hash; struct sha1_hash stm_hash; struct sha1_hash lcp_policy_hash; u32 lcp_policy_control; u32 rlp_wakeup_addr; u32 reserved; u32 num_mdrs; u32 mdrs_off; u32 num_vtd_dmars; u32 vtd_dmars_off; } __packed; struct acpi_table_header *tboot_get_dmar_table(struct acpi_table_header *dmar_tbl) { void *heap_base, *heap_ptr, *config; if (!tboot_enabled()) return dmar_tbl; /* * ACPI tables may not be DMA protected by tboot, so use DMAR copy * SINIT saved in SinitMleData in TXT heap (which is DMA protected) */ /* map config space in order to get heap addr */ config = ioremap(TXT_PUB_CONFIG_REGS_BASE, NR_TXT_CONFIG_PAGES * PAGE_SIZE); if (!config) return NULL; /* now map TXT heap */ heap_base = ioremap(*(u64 *)(config + TXTCR_HEAP_BASE), *(u64 *)(config + TXTCR_HEAP_SIZE)); iounmap(config); if (!heap_base) return NULL; /* walk heap to SinitMleData */ /* skip BiosData */ heap_ptr = heap_base + *(u64 *)heap_base; /* skip OsMleData */ heap_ptr += *(u64 *)heap_ptr; /* skip OsSinitData */ heap_ptr += *(u64 *)heap_ptr; /* now points to SinitMleDataSize; set to SinitMleData */ heap_ptr += sizeof(u64); /* get addr of DMAR table */ dmar_tbl = (struct acpi_table_header *)(heap_ptr + ((struct sinit_mle_data *)heap_ptr)->vtd_dmars_off - sizeof(u64)); /* don't unmap heap because dmar.c needs access to this */ return dmar_tbl; } int tboot_force_iommu(void) { if (!tboot_enabled()) return 0; if (no_iommu || swiotlb || dmar_disabled) pr_warning("Forcing Intel-IOMMU to enabled\n"); dmar_disabled = 0; #ifdef CONFIG_SWIOTLB swiotlb = 0; #endif no_iommu = 0; return 1; }
gpl-2.0
FrozenCow/msm
drivers/input/keyboard/spear-keyboard.c
4809
7699
/* * SPEAr Keyboard Driver * Based on omap-keypad driver * * Copyright (C) 2010 ST Microelectronics * Rajeev Kumar<rajeev-dlh.kumar@st.com> * * 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/clk.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pm_wakeup.h> #include <linux/slab.h> #include <linux/types.h> #include <plat/keyboard.h> /* Keyboard Registers */ #define MODE_REG 0x00 /* 16 bit reg */ #define STATUS_REG 0x0C /* 2 bit reg */ #define DATA_REG 0x10 /* 8 bit reg */ #define INTR_MASK 0x54 /* Register Values */ /* * pclk freq mask = (APB FEQ -1)= 82 MHZ.Programme bit 15-9 in mode * control register as 1010010(82MHZ) */ #define PCLK_FREQ_MSK 0xA400 /* 82 MHz */ #define START_SCAN 0x0100 #define SCAN_RATE_10 0x0000 #define SCAN_RATE_20 0x0004 #define SCAN_RATE_40 0x0008 #define SCAN_RATE_80 0x000C #define MODE_KEYBOARD 0x0002 #define DATA_AVAIL 0x2 #define KEY_MASK 0xFF000000 #define KEY_VALUE 0x00FFFFFF #define ROW_MASK 0xF0 #define COLUMN_MASK 0x0F #define ROW_SHIFT 4 #define KEY_MATRIX_SHIFT 6 struct spear_kbd { struct input_dev *input; struct resource *res; void __iomem *io_base; struct clk *clk; unsigned int irq; unsigned int mode; unsigned short last_key; unsigned short keycodes[256]; }; static irqreturn_t spear_kbd_interrupt(int irq, void *dev_id) { struct spear_kbd *kbd = dev_id; struct input_dev *input = kbd->input; unsigned int key; u8 sts, val; sts = readb(kbd->io_base + STATUS_REG); if (!(sts & DATA_AVAIL)) return IRQ_NONE; if (kbd->last_key != KEY_RESERVED) { input_report_key(input, kbd->last_key, 0); kbd->last_key = KEY_RESERVED; } /* following reads active (row, col) pair */ val = readb(kbd->io_base + DATA_REG); key = kbd->keycodes[val]; input_event(input, EV_MSC, MSC_SCAN, val); input_report_key(input, key, 1); input_sync(input); kbd->last_key = key; /* clear interrupt */ writeb(0, kbd->io_base + STATUS_REG); return IRQ_HANDLED; } static int spear_kbd_open(struct input_dev *dev) { struct spear_kbd *kbd = input_get_drvdata(dev); int error; u16 val; kbd->last_key = KEY_RESERVED; error = clk_enable(kbd->clk); if (error) return error; /* program keyboard */ val = SCAN_RATE_80 | MODE_KEYBOARD | PCLK_FREQ_MSK | (kbd->mode << KEY_MATRIX_SHIFT); writew(val, kbd->io_base + MODE_REG); writeb(1, kbd->io_base + STATUS_REG); /* start key scan */ val = readw(kbd->io_base + MODE_REG); val |= START_SCAN; writew(val, kbd->io_base + MODE_REG); return 0; } static void spear_kbd_close(struct input_dev *dev) { struct spear_kbd *kbd = input_get_drvdata(dev); u16 val; /* stop key scan */ val = readw(kbd->io_base + MODE_REG); val &= ~START_SCAN; writew(val, kbd->io_base + MODE_REG); clk_disable(kbd->clk); kbd->last_key = KEY_RESERVED; } static int __devinit spear_kbd_probe(struct platform_device *pdev) { const struct kbd_platform_data *pdata = pdev->dev.platform_data; const struct matrix_keymap_data *keymap; struct spear_kbd *kbd; struct input_dev *input_dev; struct resource *res; int irq; int error; if (!pdata) { dev_err(&pdev->dev, "Invalid platform data\n"); return -EINVAL; } keymap = pdata->keymap; if (!keymap) { dev_err(&pdev->dev, "no keymap defined\n"); return -EINVAL; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "no keyboard resource defined\n"); return -EBUSY; } irq = platform_get_irq(pdev, 0); if (irq < 0) { dev_err(&pdev->dev, "not able to get irq for the device\n"); return irq; } kbd = kzalloc(sizeof(*kbd), GFP_KERNEL); input_dev = input_allocate_device(); if (!kbd || !input_dev) { dev_err(&pdev->dev, "out of memory\n"); error = -ENOMEM; goto err_free_mem; } kbd->input = input_dev; kbd->irq = irq; kbd->mode = pdata->mode; kbd->res = request_mem_region(res->start, resource_size(res), pdev->name); if (!kbd->res) { dev_err(&pdev->dev, "keyboard region already claimed\n"); error = -EBUSY; goto err_free_mem; } kbd->io_base = ioremap(res->start, resource_size(res)); if (!kbd->io_base) { dev_err(&pdev->dev, "ioremap failed for kbd_region\n"); error = -ENOMEM; goto err_release_mem_region; } kbd->clk = clk_get(&pdev->dev, NULL); if (IS_ERR(kbd->clk)) { error = PTR_ERR(kbd->clk); goto err_iounmap; } input_dev->name = "Spear Keyboard"; input_dev->phys = "keyboard/input0"; input_dev->dev.parent = &pdev->dev; input_dev->id.bustype = BUS_HOST; input_dev->id.vendor = 0x0001; input_dev->id.product = 0x0001; input_dev->id.version = 0x0100; input_dev->open = spear_kbd_open; input_dev->close = spear_kbd_close; __set_bit(EV_KEY, input_dev->evbit); if (pdata->rep) __set_bit(EV_REP, input_dev->evbit); input_set_capability(input_dev, EV_MSC, MSC_SCAN); input_dev->keycode = kbd->keycodes; input_dev->keycodesize = sizeof(kbd->keycodes[0]); input_dev->keycodemax = ARRAY_SIZE(kbd->keycodes); matrix_keypad_build_keymap(keymap, ROW_SHIFT, input_dev->keycode, input_dev->keybit); input_set_drvdata(input_dev, kbd); error = request_irq(irq, spear_kbd_interrupt, 0, "keyboard", kbd); if (error) { dev_err(&pdev->dev, "request_irq fail\n"); goto err_put_clk; } error = input_register_device(input_dev); if (error) { dev_err(&pdev->dev, "Unable to register keyboard device\n"); goto err_free_irq; } device_init_wakeup(&pdev->dev, 1); platform_set_drvdata(pdev, kbd); return 0; err_free_irq: free_irq(kbd->irq, kbd); err_put_clk: clk_put(kbd->clk); err_iounmap: iounmap(kbd->io_base); err_release_mem_region: release_mem_region(res->start, resource_size(res)); err_free_mem: input_free_device(input_dev); kfree(kbd); return error; } static int __devexit spear_kbd_remove(struct platform_device *pdev) { struct spear_kbd *kbd = platform_get_drvdata(pdev); free_irq(kbd->irq, kbd); input_unregister_device(kbd->input); clk_put(kbd->clk); iounmap(kbd->io_base); release_mem_region(kbd->res->start, resource_size(kbd->res)); kfree(kbd); device_init_wakeup(&pdev->dev, 1); platform_set_drvdata(pdev, NULL); return 0; } #ifdef CONFIG_PM static int spear_kbd_suspend(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct spear_kbd *kbd = platform_get_drvdata(pdev); struct input_dev *input_dev = kbd->input; mutex_lock(&input_dev->mutex); if (input_dev->users) clk_enable(kbd->clk); if (device_may_wakeup(&pdev->dev)) enable_irq_wake(kbd->irq); mutex_unlock(&input_dev->mutex); return 0; } static int spear_kbd_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct spear_kbd *kbd = platform_get_drvdata(pdev); struct input_dev *input_dev = kbd->input; mutex_lock(&input_dev->mutex); if (device_may_wakeup(&pdev->dev)) disable_irq_wake(kbd->irq); if (input_dev->users) clk_enable(kbd->clk); mutex_unlock(&input_dev->mutex); return 0; } #endif static SIMPLE_DEV_PM_OPS(spear_kbd_pm_ops, spear_kbd_suspend, spear_kbd_resume); static struct platform_driver spear_kbd_driver = { .probe = spear_kbd_probe, .remove = __devexit_p(spear_kbd_remove), .driver = { .name = "keyboard", .owner = THIS_MODULE, .pm = &spear_kbd_pm_ops, }, }; module_platform_driver(spear_kbd_driver); MODULE_AUTHOR("Rajeev Kumar"); MODULE_DESCRIPTION("SPEAr Keyboard Driver"); MODULE_LICENSE("GPL");
gpl-2.0
schqiushui/Kernel_MM_GPE_M8
drivers/infiniband/hw/mlx4/cq.c
4809
20989
/* * Copyright (c) 2007 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2007, 2008 Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/mlx4/cq.h> #include <linux/mlx4/qp.h> #include <linux/slab.h> #include "mlx4_ib.h" #include "user.h" static void mlx4_ib_cq_comp(struct mlx4_cq *cq) { struct ib_cq *ibcq = &to_mibcq(cq)->ibcq; ibcq->comp_handler(ibcq, ibcq->cq_context); } static void mlx4_ib_cq_event(struct mlx4_cq *cq, enum mlx4_event type) { struct ib_event event; struct ib_cq *ibcq; if (type != MLX4_EVENT_TYPE_CQ_ERROR) { printk(KERN_WARNING "mlx4_ib: Unexpected event type %d " "on CQ %06x\n", type, cq->cqn); return; } ibcq = &to_mibcq(cq)->ibcq; if (ibcq->event_handler) { event.device = ibcq->device; event.event = IB_EVENT_CQ_ERR; event.element.cq = ibcq; ibcq->event_handler(&event, ibcq->cq_context); } } static void *get_cqe_from_buf(struct mlx4_ib_cq_buf *buf, int n) { return mlx4_buf_offset(&buf->buf, n * sizeof (struct mlx4_cqe)); } static void *get_cqe(struct mlx4_ib_cq *cq, int n) { return get_cqe_from_buf(&cq->buf, n); } static void *get_sw_cqe(struct mlx4_ib_cq *cq, int n) { struct mlx4_cqe *cqe = get_cqe(cq, n & cq->ibcq.cqe); return (!!(cqe->owner_sr_opcode & MLX4_CQE_OWNER_MASK) ^ !!(n & (cq->ibcq.cqe + 1))) ? NULL : cqe; } static struct mlx4_cqe *next_cqe_sw(struct mlx4_ib_cq *cq) { return get_sw_cqe(cq, cq->mcq.cons_index); } int mlx4_ib_modify_cq(struct ib_cq *cq, u16 cq_count, u16 cq_period) { struct mlx4_ib_cq *mcq = to_mcq(cq); struct mlx4_ib_dev *dev = to_mdev(cq->device); return mlx4_cq_modify(dev->dev, &mcq->mcq, cq_count, cq_period); } static int mlx4_ib_alloc_cq_buf(struct mlx4_ib_dev *dev, struct mlx4_ib_cq_buf *buf, int nent) { int err; err = mlx4_buf_alloc(dev->dev, nent * sizeof(struct mlx4_cqe), PAGE_SIZE * 2, &buf->buf); if (err) goto out; err = mlx4_mtt_init(dev->dev, buf->buf.npages, buf->buf.page_shift, &buf->mtt); if (err) goto err_buf; err = mlx4_buf_write_mtt(dev->dev, &buf->mtt, &buf->buf); if (err) goto err_mtt; return 0; err_mtt: mlx4_mtt_cleanup(dev->dev, &buf->mtt); err_buf: mlx4_buf_free(dev->dev, nent * sizeof(struct mlx4_cqe), &buf->buf); out: return err; } static void mlx4_ib_free_cq_buf(struct mlx4_ib_dev *dev, struct mlx4_ib_cq_buf *buf, int cqe) { mlx4_buf_free(dev->dev, (cqe + 1) * sizeof(struct mlx4_cqe), &buf->buf); } static int mlx4_ib_get_cq_umem(struct mlx4_ib_dev *dev, struct ib_ucontext *context, struct mlx4_ib_cq_buf *buf, struct ib_umem **umem, u64 buf_addr, int cqe) { int err; *umem = ib_umem_get(context, buf_addr, cqe * sizeof (struct mlx4_cqe), IB_ACCESS_LOCAL_WRITE, 1); if (IS_ERR(*umem)) return PTR_ERR(*umem); err = mlx4_mtt_init(dev->dev, ib_umem_page_count(*umem), ilog2((*umem)->page_size), &buf->mtt); if (err) goto err_buf; err = mlx4_ib_umem_write_mtt(dev, &buf->mtt, *umem); if (err) goto err_mtt; return 0; err_mtt: mlx4_mtt_cleanup(dev->dev, &buf->mtt); err_buf: ib_umem_release(*umem); return err; } struct ib_cq *mlx4_ib_create_cq(struct ib_device *ibdev, int entries, int vector, struct ib_ucontext *context, struct ib_udata *udata) { struct mlx4_ib_dev *dev = to_mdev(ibdev); struct mlx4_ib_cq *cq; struct mlx4_uar *uar; int err; if (entries < 1 || entries > dev->dev->caps.max_cqes) return ERR_PTR(-EINVAL); cq = kmalloc(sizeof *cq, GFP_KERNEL); if (!cq) return ERR_PTR(-ENOMEM); entries = roundup_pow_of_two(entries + 1); cq->ibcq.cqe = entries - 1; mutex_init(&cq->resize_mutex); spin_lock_init(&cq->lock); cq->resize_buf = NULL; cq->resize_umem = NULL; if (context) { struct mlx4_ib_create_cq ucmd; if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd)) { err = -EFAULT; goto err_cq; } err = mlx4_ib_get_cq_umem(dev, context, &cq->buf, &cq->umem, ucmd.buf_addr, entries); if (err) goto err_cq; err = mlx4_ib_db_map_user(to_mucontext(context), ucmd.db_addr, &cq->db); if (err) goto err_mtt; uar = &to_mucontext(context)->uar; } else { err = mlx4_db_alloc(dev->dev, &cq->db, 1); if (err) goto err_cq; cq->mcq.set_ci_db = cq->db.db; cq->mcq.arm_db = cq->db.db + 1; *cq->mcq.set_ci_db = 0; *cq->mcq.arm_db = 0; err = mlx4_ib_alloc_cq_buf(dev, &cq->buf, entries); if (err) goto err_db; uar = &dev->priv_uar; } err = mlx4_cq_alloc(dev->dev, entries, &cq->buf.mtt, uar, cq->db.dma, &cq->mcq, vector, 0); if (err) goto err_dbmap; cq->mcq.comp = mlx4_ib_cq_comp; cq->mcq.event = mlx4_ib_cq_event; if (context) if (ib_copy_to_udata(udata, &cq->mcq.cqn, sizeof (__u32))) { err = -EFAULT; goto err_dbmap; } return &cq->ibcq; err_dbmap: if (context) mlx4_ib_db_unmap_user(to_mucontext(context), &cq->db); err_mtt: mlx4_mtt_cleanup(dev->dev, &cq->buf.mtt); if (context) ib_umem_release(cq->umem); else mlx4_ib_free_cq_buf(dev, &cq->buf, cq->ibcq.cqe); err_db: if (!context) mlx4_db_free(dev->dev, &cq->db); err_cq: kfree(cq); return ERR_PTR(err); } static int mlx4_alloc_resize_buf(struct mlx4_ib_dev *dev, struct mlx4_ib_cq *cq, int entries) { int err; if (cq->resize_buf) return -EBUSY; cq->resize_buf = kmalloc(sizeof *cq->resize_buf, GFP_ATOMIC); if (!cq->resize_buf) return -ENOMEM; err = mlx4_ib_alloc_cq_buf(dev, &cq->resize_buf->buf, entries); if (err) { kfree(cq->resize_buf); cq->resize_buf = NULL; return err; } cq->resize_buf->cqe = entries - 1; return 0; } static int mlx4_alloc_resize_umem(struct mlx4_ib_dev *dev, struct mlx4_ib_cq *cq, int entries, struct ib_udata *udata) { struct mlx4_ib_resize_cq ucmd; int err; if (cq->resize_umem) return -EBUSY; if (ib_copy_from_udata(&ucmd, udata, sizeof ucmd)) return -EFAULT; cq->resize_buf = kmalloc(sizeof *cq->resize_buf, GFP_ATOMIC); if (!cq->resize_buf) return -ENOMEM; err = mlx4_ib_get_cq_umem(dev, cq->umem->context, &cq->resize_buf->buf, &cq->resize_umem, ucmd.buf_addr, entries); if (err) { kfree(cq->resize_buf); cq->resize_buf = NULL; return err; } cq->resize_buf->cqe = entries - 1; return 0; } static int mlx4_ib_get_outstanding_cqes(struct mlx4_ib_cq *cq) { u32 i; i = cq->mcq.cons_index; while (get_sw_cqe(cq, i & cq->ibcq.cqe)) ++i; return i - cq->mcq.cons_index; } static void mlx4_ib_cq_resize_copy_cqes(struct mlx4_ib_cq *cq) { struct mlx4_cqe *cqe, *new_cqe; int i; i = cq->mcq.cons_index; cqe = get_cqe(cq, i & cq->ibcq.cqe); while ((cqe->owner_sr_opcode & MLX4_CQE_OPCODE_MASK) != MLX4_CQE_OPCODE_RESIZE) { new_cqe = get_cqe_from_buf(&cq->resize_buf->buf, (i + 1) & cq->resize_buf->cqe); memcpy(new_cqe, get_cqe(cq, i & cq->ibcq.cqe), sizeof(struct mlx4_cqe)); new_cqe->owner_sr_opcode = (cqe->owner_sr_opcode & ~MLX4_CQE_OWNER_MASK) | (((i + 1) & (cq->resize_buf->cqe + 1)) ? MLX4_CQE_OWNER_MASK : 0); cqe = get_cqe(cq, ++i & cq->ibcq.cqe); } ++cq->mcq.cons_index; } int mlx4_ib_resize_cq(struct ib_cq *ibcq, int entries, struct ib_udata *udata) { struct mlx4_ib_dev *dev = to_mdev(ibcq->device); struct mlx4_ib_cq *cq = to_mcq(ibcq); struct mlx4_mtt mtt; int outst_cqe; int err; mutex_lock(&cq->resize_mutex); if (entries < 1 || entries > dev->dev->caps.max_cqes) { err = -EINVAL; goto out; } entries = roundup_pow_of_two(entries + 1); if (entries == ibcq->cqe + 1) { err = 0; goto out; } if (ibcq->uobject) { err = mlx4_alloc_resize_umem(dev, cq, entries, udata); if (err) goto out; } else { /* Can't be smaller than the number of outstanding CQEs */ outst_cqe = mlx4_ib_get_outstanding_cqes(cq); if (entries < outst_cqe + 1) { err = 0; goto out; } err = mlx4_alloc_resize_buf(dev, cq, entries); if (err) goto out; } mtt = cq->buf.mtt; err = mlx4_cq_resize(dev->dev, &cq->mcq, entries, &cq->resize_buf->buf.mtt); if (err) goto err_buf; mlx4_mtt_cleanup(dev->dev, &mtt); if (ibcq->uobject) { cq->buf = cq->resize_buf->buf; cq->ibcq.cqe = cq->resize_buf->cqe; ib_umem_release(cq->umem); cq->umem = cq->resize_umem; kfree(cq->resize_buf); cq->resize_buf = NULL; cq->resize_umem = NULL; } else { struct mlx4_ib_cq_buf tmp_buf; int tmp_cqe = 0; spin_lock_irq(&cq->lock); if (cq->resize_buf) { mlx4_ib_cq_resize_copy_cqes(cq); tmp_buf = cq->buf; tmp_cqe = cq->ibcq.cqe; cq->buf = cq->resize_buf->buf; cq->ibcq.cqe = cq->resize_buf->cqe; kfree(cq->resize_buf); cq->resize_buf = NULL; } spin_unlock_irq(&cq->lock); if (tmp_cqe) mlx4_ib_free_cq_buf(dev, &tmp_buf, tmp_cqe); } goto out; err_buf: mlx4_mtt_cleanup(dev->dev, &cq->resize_buf->buf.mtt); if (!ibcq->uobject) mlx4_ib_free_cq_buf(dev, &cq->resize_buf->buf, cq->resize_buf->cqe); kfree(cq->resize_buf); cq->resize_buf = NULL; if (cq->resize_umem) { ib_umem_release(cq->resize_umem); cq->resize_umem = NULL; } out: mutex_unlock(&cq->resize_mutex); return err; } int mlx4_ib_destroy_cq(struct ib_cq *cq) { struct mlx4_ib_dev *dev = to_mdev(cq->device); struct mlx4_ib_cq *mcq = to_mcq(cq); mlx4_cq_free(dev->dev, &mcq->mcq); mlx4_mtt_cleanup(dev->dev, &mcq->buf.mtt); if (cq->uobject) { mlx4_ib_db_unmap_user(to_mucontext(cq->uobject->context), &mcq->db); ib_umem_release(mcq->umem); } else { mlx4_ib_free_cq_buf(dev, &mcq->buf, cq->cqe); mlx4_db_free(dev->dev, &mcq->db); } kfree(mcq); return 0; } static void dump_cqe(void *cqe) { __be32 *buf = cqe; printk(KERN_DEBUG "CQE contents %08x %08x %08x %08x %08x %08x %08x %08x\n", be32_to_cpu(buf[0]), be32_to_cpu(buf[1]), be32_to_cpu(buf[2]), be32_to_cpu(buf[3]), be32_to_cpu(buf[4]), be32_to_cpu(buf[5]), be32_to_cpu(buf[6]), be32_to_cpu(buf[7])); } static void mlx4_ib_handle_error_cqe(struct mlx4_err_cqe *cqe, struct ib_wc *wc) { if (cqe->syndrome == MLX4_CQE_SYNDROME_LOCAL_QP_OP_ERR) { printk(KERN_DEBUG "local QP operation err " "(QPN %06x, WQE index %x, vendor syndrome %02x, " "opcode = %02x)\n", be32_to_cpu(cqe->my_qpn), be16_to_cpu(cqe->wqe_index), cqe->vendor_err_syndrome, cqe->owner_sr_opcode & ~MLX4_CQE_OWNER_MASK); dump_cqe(cqe); } switch (cqe->syndrome) { case MLX4_CQE_SYNDROME_LOCAL_LENGTH_ERR: wc->status = IB_WC_LOC_LEN_ERR; break; case MLX4_CQE_SYNDROME_LOCAL_QP_OP_ERR: wc->status = IB_WC_LOC_QP_OP_ERR; break; case MLX4_CQE_SYNDROME_LOCAL_PROT_ERR: wc->status = IB_WC_LOC_PROT_ERR; break; case MLX4_CQE_SYNDROME_WR_FLUSH_ERR: wc->status = IB_WC_WR_FLUSH_ERR; break; case MLX4_CQE_SYNDROME_MW_BIND_ERR: wc->status = IB_WC_MW_BIND_ERR; break; case MLX4_CQE_SYNDROME_BAD_RESP_ERR: wc->status = IB_WC_BAD_RESP_ERR; break; case MLX4_CQE_SYNDROME_LOCAL_ACCESS_ERR: wc->status = IB_WC_LOC_ACCESS_ERR; break; case MLX4_CQE_SYNDROME_REMOTE_INVAL_REQ_ERR: wc->status = IB_WC_REM_INV_REQ_ERR; break; case MLX4_CQE_SYNDROME_REMOTE_ACCESS_ERR: wc->status = IB_WC_REM_ACCESS_ERR; break; case MLX4_CQE_SYNDROME_REMOTE_OP_ERR: wc->status = IB_WC_REM_OP_ERR; break; case MLX4_CQE_SYNDROME_TRANSPORT_RETRY_EXC_ERR: wc->status = IB_WC_RETRY_EXC_ERR; break; case MLX4_CQE_SYNDROME_RNR_RETRY_EXC_ERR: wc->status = IB_WC_RNR_RETRY_EXC_ERR; break; case MLX4_CQE_SYNDROME_REMOTE_ABORTED_ERR: wc->status = IB_WC_REM_ABORT_ERR; break; default: wc->status = IB_WC_GENERAL_ERR; break; } wc->vendor_err = cqe->vendor_err_syndrome; } static int mlx4_ib_ipoib_csum_ok(__be16 status, __be16 checksum) { return ((status & cpu_to_be16(MLX4_CQE_STATUS_IPV4 | MLX4_CQE_STATUS_IPV4F | MLX4_CQE_STATUS_IPV4OPT | MLX4_CQE_STATUS_IPV6 | MLX4_CQE_STATUS_IPOK)) == cpu_to_be16(MLX4_CQE_STATUS_IPV4 | MLX4_CQE_STATUS_IPOK)) && (status & cpu_to_be16(MLX4_CQE_STATUS_UDP | MLX4_CQE_STATUS_TCP)) && checksum == cpu_to_be16(0xffff); } static int mlx4_ib_poll_one(struct mlx4_ib_cq *cq, struct mlx4_ib_qp **cur_qp, struct ib_wc *wc) { struct mlx4_cqe *cqe; struct mlx4_qp *mqp; struct mlx4_ib_wq *wq; struct mlx4_ib_srq *srq; int is_send; int is_error; u32 g_mlpath_rqpn; u16 wqe_ctr; repoll: cqe = next_cqe_sw(cq); if (!cqe) return -EAGAIN; ++cq->mcq.cons_index; /* * Make sure we read CQ entry contents after we've checked the * ownership bit. */ rmb(); is_send = cqe->owner_sr_opcode & MLX4_CQE_IS_SEND_MASK; is_error = (cqe->owner_sr_opcode & MLX4_CQE_OPCODE_MASK) == MLX4_CQE_OPCODE_ERROR; if (unlikely((cqe->owner_sr_opcode & MLX4_CQE_OPCODE_MASK) == MLX4_OPCODE_NOP && is_send)) { printk(KERN_WARNING "Completion for NOP opcode detected!\n"); return -EINVAL; } /* Resize CQ in progress */ if (unlikely((cqe->owner_sr_opcode & MLX4_CQE_OPCODE_MASK) == MLX4_CQE_OPCODE_RESIZE)) { if (cq->resize_buf) { struct mlx4_ib_dev *dev = to_mdev(cq->ibcq.device); mlx4_ib_free_cq_buf(dev, &cq->buf, cq->ibcq.cqe); cq->buf = cq->resize_buf->buf; cq->ibcq.cqe = cq->resize_buf->cqe; kfree(cq->resize_buf); cq->resize_buf = NULL; } goto repoll; } if (!*cur_qp || (be32_to_cpu(cqe->vlan_my_qpn) & MLX4_CQE_QPN_MASK) != (*cur_qp)->mqp.qpn) { /* * We do not have to take the QP table lock here, * because CQs will be locked while QPs are removed * from the table. */ mqp = __mlx4_qp_lookup(to_mdev(cq->ibcq.device)->dev, be32_to_cpu(cqe->vlan_my_qpn)); if (unlikely(!mqp)) { printk(KERN_WARNING "CQ %06x with entry for unknown QPN %06x\n", cq->mcq.cqn, be32_to_cpu(cqe->vlan_my_qpn) & MLX4_CQE_QPN_MASK); return -EINVAL; } *cur_qp = to_mibqp(mqp); } wc->qp = &(*cur_qp)->ibqp; if (is_send) { wq = &(*cur_qp)->sq; if (!(*cur_qp)->sq_signal_bits) { wqe_ctr = be16_to_cpu(cqe->wqe_index); wq->tail += (u16) (wqe_ctr - (u16) wq->tail); } wc->wr_id = wq->wrid[wq->tail & (wq->wqe_cnt - 1)]; ++wq->tail; } else if ((*cur_qp)->ibqp.srq) { srq = to_msrq((*cur_qp)->ibqp.srq); wqe_ctr = be16_to_cpu(cqe->wqe_index); wc->wr_id = srq->wrid[wqe_ctr]; mlx4_ib_free_srq_wqe(srq, wqe_ctr); } else { wq = &(*cur_qp)->rq; wc->wr_id = wq->wrid[wq->tail & (wq->wqe_cnt - 1)]; ++wq->tail; } if (unlikely(is_error)) { mlx4_ib_handle_error_cqe((struct mlx4_err_cqe *) cqe, wc); return 0; } wc->status = IB_WC_SUCCESS; if (is_send) { wc->wc_flags = 0; switch (cqe->owner_sr_opcode & MLX4_CQE_OPCODE_MASK) { case MLX4_OPCODE_RDMA_WRITE_IMM: wc->wc_flags |= IB_WC_WITH_IMM; case MLX4_OPCODE_RDMA_WRITE: wc->opcode = IB_WC_RDMA_WRITE; break; case MLX4_OPCODE_SEND_IMM: wc->wc_flags |= IB_WC_WITH_IMM; case MLX4_OPCODE_SEND: case MLX4_OPCODE_SEND_INVAL: wc->opcode = IB_WC_SEND; break; case MLX4_OPCODE_RDMA_READ: wc->opcode = IB_WC_RDMA_READ; wc->byte_len = be32_to_cpu(cqe->byte_cnt); break; case MLX4_OPCODE_ATOMIC_CS: wc->opcode = IB_WC_COMP_SWAP; wc->byte_len = 8; break; case MLX4_OPCODE_ATOMIC_FA: wc->opcode = IB_WC_FETCH_ADD; wc->byte_len = 8; break; case MLX4_OPCODE_MASKED_ATOMIC_CS: wc->opcode = IB_WC_MASKED_COMP_SWAP; wc->byte_len = 8; break; case MLX4_OPCODE_MASKED_ATOMIC_FA: wc->opcode = IB_WC_MASKED_FETCH_ADD; wc->byte_len = 8; break; case MLX4_OPCODE_BIND_MW: wc->opcode = IB_WC_BIND_MW; break; case MLX4_OPCODE_LSO: wc->opcode = IB_WC_LSO; break; case MLX4_OPCODE_FMR: wc->opcode = IB_WC_FAST_REG_MR; break; case MLX4_OPCODE_LOCAL_INVAL: wc->opcode = IB_WC_LOCAL_INV; break; } } else { wc->byte_len = be32_to_cpu(cqe->byte_cnt); switch (cqe->owner_sr_opcode & MLX4_CQE_OPCODE_MASK) { case MLX4_RECV_OPCODE_RDMA_WRITE_IMM: wc->opcode = IB_WC_RECV_RDMA_WITH_IMM; wc->wc_flags = IB_WC_WITH_IMM; wc->ex.imm_data = cqe->immed_rss_invalid; break; case MLX4_RECV_OPCODE_SEND_INVAL: wc->opcode = IB_WC_RECV; wc->wc_flags = IB_WC_WITH_INVALIDATE; wc->ex.invalidate_rkey = be32_to_cpu(cqe->immed_rss_invalid); break; case MLX4_RECV_OPCODE_SEND: wc->opcode = IB_WC_RECV; wc->wc_flags = 0; break; case MLX4_RECV_OPCODE_SEND_IMM: wc->opcode = IB_WC_RECV; wc->wc_flags = IB_WC_WITH_IMM; wc->ex.imm_data = cqe->immed_rss_invalid; break; } wc->slid = be16_to_cpu(cqe->rlid); g_mlpath_rqpn = be32_to_cpu(cqe->g_mlpath_rqpn); wc->src_qp = g_mlpath_rqpn & 0xffffff; wc->dlid_path_bits = (g_mlpath_rqpn >> 24) & 0x7f; wc->wc_flags |= g_mlpath_rqpn & 0x80000000 ? IB_WC_GRH : 0; wc->pkey_index = be32_to_cpu(cqe->immed_rss_invalid) & 0x7f; wc->wc_flags |= mlx4_ib_ipoib_csum_ok(cqe->status, cqe->checksum) ? IB_WC_IP_CSUM_OK : 0; if (rdma_port_get_link_layer(wc->qp->device, (*cur_qp)->port) == IB_LINK_LAYER_ETHERNET) wc->sl = be16_to_cpu(cqe->sl_vid) >> 13; else wc->sl = be16_to_cpu(cqe->sl_vid) >> 12; } return 0; } int mlx4_ib_poll_cq(struct ib_cq *ibcq, int num_entries, struct ib_wc *wc) { struct mlx4_ib_cq *cq = to_mcq(ibcq); struct mlx4_ib_qp *cur_qp = NULL; unsigned long flags; int npolled; int err = 0; spin_lock_irqsave(&cq->lock, flags); for (npolled = 0; npolled < num_entries; ++npolled) { err = mlx4_ib_poll_one(cq, &cur_qp, wc + npolled); if (err) break; } mlx4_cq_set_ci(&cq->mcq); spin_unlock_irqrestore(&cq->lock, flags); if (err == 0 || err == -EAGAIN) return npolled; else return err; } int mlx4_ib_arm_cq(struct ib_cq *ibcq, enum ib_cq_notify_flags flags) { mlx4_cq_arm(&to_mcq(ibcq)->mcq, (flags & IB_CQ_SOLICITED_MASK) == IB_CQ_SOLICITED ? MLX4_CQ_DB_REQ_NOT_SOL : MLX4_CQ_DB_REQ_NOT, to_mdev(ibcq->device)->uar_map, MLX4_GET_DOORBELL_LOCK(&to_mdev(ibcq->device)->uar_lock)); return 0; } void __mlx4_ib_cq_clean(struct mlx4_ib_cq *cq, u32 qpn, struct mlx4_ib_srq *srq) { u32 prod_index; int nfreed = 0; struct mlx4_cqe *cqe, *dest; u8 owner_bit; /* * First we need to find the current producer index, so we * know where to start cleaning from. It doesn't matter if HW * adds new entries after this loop -- the QP we're worried * about is already in RESET, so the new entries won't come * from our QP and therefore don't need to be checked. */ for (prod_index = cq->mcq.cons_index; get_sw_cqe(cq, prod_index); ++prod_index) if (prod_index == cq->mcq.cons_index + cq->ibcq.cqe) break; /* * Now sweep backwards through the CQ, removing CQ entries * that match our QP by copying older entries on top of them. */ while ((int) --prod_index - (int) cq->mcq.cons_index >= 0) { cqe = get_cqe(cq, prod_index & cq->ibcq.cqe); if ((be32_to_cpu(cqe->vlan_my_qpn) & MLX4_CQE_QPN_MASK) == qpn) { if (srq && !(cqe->owner_sr_opcode & MLX4_CQE_IS_SEND_MASK)) mlx4_ib_free_srq_wqe(srq, be16_to_cpu(cqe->wqe_index)); ++nfreed; } else if (nfreed) { dest = get_cqe(cq, (prod_index + nfreed) & cq->ibcq.cqe); owner_bit = dest->owner_sr_opcode & MLX4_CQE_OWNER_MASK; memcpy(dest, cqe, sizeof *cqe); dest->owner_sr_opcode = owner_bit | (dest->owner_sr_opcode & ~MLX4_CQE_OWNER_MASK); } } if (nfreed) { cq->mcq.cons_index += nfreed; /* * Make sure update of buffer contents is done before * updating consumer index. */ wmb(); mlx4_cq_set_ci(&cq->mcq); } } void mlx4_ib_cq_clean(struct mlx4_ib_cq *cq, u32 qpn, struct mlx4_ib_srq *srq) { spin_lock_irq(&cq->lock); __mlx4_ib_cq_clean(cq, qpn, srq); spin_unlock_irq(&cq->lock); }
gpl-2.0
ztemt/Z5mini_H112_kernel
drivers/staging/line6/toneport.c
4809
11481
/* * Line6 Linux USB driver - 0.9.1beta * * Copyright (C) 2004-2010 Markus Grabner (grabner@icg.tugraz.at) * Emil Myhrman (emil.myhrman@gmail.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 2. * */ #include <linux/wait.h> #include <sound/control.h> #include "audio.h" #include "capture.h" #include "driver.h" #include "playback.h" #include "toneport.h" static int toneport_send_cmd(struct usb_device *usbdev, int cmd1, int cmd2); #define TONEPORT_PCM_DELAY 1 static struct snd_ratden toneport_ratden = { .num_min = 44100, .num_max = 44100, .num_step = 1, .den = 1 }; static struct line6_pcm_properties toneport_pcm_properties = { .snd_line6_playback_hw = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE | #ifdef CONFIG_PM SNDRV_PCM_INFO_RESUME | #endif SNDRV_PCM_INFO_SYNC_START), .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_KNOT, .rate_min = 44100, .rate_max = 44100, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = 60000, .period_bytes_min = 64, .period_bytes_max = 8192, .periods_min = 1, .periods_max = 1024}, .snd_line6_capture_hw = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID | #ifdef CONFIG_PM SNDRV_PCM_INFO_RESUME | #endif SNDRV_PCM_INFO_SYNC_START), .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_KNOT, .rate_min = 44100, .rate_max = 44100, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = 60000, .period_bytes_min = 64, .period_bytes_max = 8192, .periods_min = 1, .periods_max = 1024}, .snd_line6_rates = { .nrats = 1, .rats = &toneport_ratden}, .bytes_per_frame = 4 }; /* For the led on Guitarport. Brightness goes from 0x00 to 0x26. Set a value above this to have led blink. (void cmd_0x02(byte red, byte green) */ static int led_red = 0x00; static int led_green = 0x26; struct ToneportSourceInfo { const char *name; int code; }; static const struct ToneportSourceInfo toneport_source_info[] = { {"Microphone", 0x0a01}, {"Line", 0x0801}, {"Instrument", 0x0b01}, {"Inst & Mic", 0x0901} }; static bool toneport_has_led(short product) { return (product == LINE6_DEVID_GUITARPORT) || (product == LINE6_DEVID_TONEPORT_GX); /* add your device here if you are missing support for the LEDs */ } static void toneport_update_led(struct device *dev) { struct usb_interface *interface = to_usb_interface(dev); struct usb_line6_toneport *tp = usb_get_intfdata(interface); struct usb_line6 *line6; if (!tp) return; line6 = &tp->line6; if (line6) toneport_send_cmd(line6->usbdev, (led_red << 8) | 0x0002, led_green); } static ssize_t toneport_set_led_red(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int retval; long value; retval = strict_strtol(buf, 10, &value); if (retval) return retval; led_red = value; toneport_update_led(dev); return count; } static ssize_t toneport_set_led_green(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int retval; long value; retval = strict_strtol(buf, 10, &value); if (retval) return retval; led_green = value; toneport_update_led(dev); return count; } static DEVICE_ATTR(led_red, S_IWUSR | S_IRUGO, line6_nop_read, toneport_set_led_red); static DEVICE_ATTR(led_green, S_IWUSR | S_IRUGO, line6_nop_read, toneport_set_led_green); static int toneport_send_cmd(struct usb_device *usbdev, int cmd1, int cmd2) { int ret; ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0), 0x67, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT, cmd1, cmd2, NULL, 0, LINE6_TIMEOUT * HZ); if (ret < 0) { err("send failed (error %d)\n", ret); return ret; } return 0; } /* monitor info callback */ static int snd_toneport_monitor_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = 256; return 0; } /* monitor get callback */ static int snd_toneport_monitor_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = line6pcm->volume_monitor; return 0; } /* monitor put callback */ static int snd_toneport_monitor_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol); if (ucontrol->value.integer.value[0] == line6pcm->volume_monitor) return 0; line6pcm->volume_monitor = ucontrol->value.integer.value[0]; if (line6pcm->volume_monitor > 0) line6_pcm_acquire(line6pcm, LINE6_BITS_PCM_MONITOR); else line6_pcm_release(line6pcm, LINE6_BITS_PCM_MONITOR); return 1; } /* source info callback */ static int snd_toneport_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { const int size = ARRAY_SIZE(toneport_source_info); uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = size; if (uinfo->value.enumerated.item >= size) uinfo->value.enumerated.item = size - 1; strcpy(uinfo->value.enumerated.name, toneport_source_info[uinfo->value.enumerated.item].name); return 0; } /* source get callback */ static int snd_toneport_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol); struct usb_line6_toneport *toneport = (struct usb_line6_toneport *)line6pcm->line6; ucontrol->value.enumerated.item[0] = toneport->source; return 0; } /* source put callback */ static int snd_toneport_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol); struct usb_line6_toneport *toneport = (struct usb_line6_toneport *)line6pcm->line6; if (ucontrol->value.enumerated.item[0] == toneport->source) return 0; toneport->source = ucontrol->value.enumerated.item[0]; toneport_send_cmd(toneport->line6.usbdev, toneport_source_info[toneport->source].code, 0x0000); return 1; } static void toneport_start_pcm(unsigned long arg) { struct usb_line6_toneport *toneport = (struct usb_line6_toneport *)arg; struct usb_line6 *line6 = &toneport->line6; line6_pcm_acquire(line6->line6pcm, LINE6_BITS_PCM_MONITOR); } /* control definition */ static struct snd_kcontrol_new toneport_control_monitor = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Monitor Playback Volume", .index = 0, .access = SNDRV_CTL_ELEM_ACCESS_READWRITE, .info = snd_toneport_monitor_info, .get = snd_toneport_monitor_get, .put = snd_toneport_monitor_put }; /* source selector definition */ static struct snd_kcontrol_new toneport_control_source = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "PCM Capture Source", .index = 0, .access = SNDRV_CTL_ELEM_ACCESS_READWRITE, .info = snd_toneport_source_info, .get = snd_toneport_source_get, .put = snd_toneport_source_put }; /* Toneport destructor. */ static void toneport_destruct(struct usb_interface *interface) { struct usb_line6_toneport *toneport = usb_get_intfdata(interface); if (toneport == NULL) return; line6_cleanup_audio(&toneport->line6); } /* Setup Toneport device. */ static void toneport_setup(struct usb_line6_toneport *toneport) { int ticks; struct usb_line6 *line6 = &toneport->line6; struct usb_device *usbdev = line6->usbdev; /* sync time on device with host: */ ticks = (int)get_seconds(); line6_write_data(line6, 0x80c6, &ticks, 4); /* enable device: */ toneport_send_cmd(usbdev, 0x0301, 0x0000); /* initialize source select: */ switch (usbdev->descriptor.idProduct) { case LINE6_DEVID_TONEPORT_UX1: case LINE6_DEVID_TONEPORT_UX2: case LINE6_DEVID_PODSTUDIO_UX1: case LINE6_DEVID_PODSTUDIO_UX2: toneport_send_cmd(usbdev, toneport_source_info[toneport->source].code, 0x0000); } if (toneport_has_led(usbdev->descriptor.idProduct)) toneport_update_led(&usbdev->dev); } /* Try to init Toneport device. */ static int toneport_try_init(struct usb_interface *interface, struct usb_line6_toneport *toneport) { int err; struct usb_line6 *line6 = &toneport->line6; struct usb_device *usbdev = line6->usbdev; if ((interface == NULL) || (toneport == NULL)) return -ENODEV; /* initialize audio system: */ err = line6_init_audio(line6); if (err < 0) return err; /* initialize PCM subsystem: */ err = line6_init_pcm(line6, &toneport_pcm_properties); if (err < 0) return err; /* register monitor control: */ err = snd_ctl_add(line6->card, snd_ctl_new1(&toneport_control_monitor, line6->line6pcm)); if (err < 0) return err; /* register source select control: */ switch (usbdev->descriptor.idProduct) { case LINE6_DEVID_TONEPORT_UX1: case LINE6_DEVID_TONEPORT_UX2: case LINE6_DEVID_PODSTUDIO_UX1: case LINE6_DEVID_PODSTUDIO_UX2: err = snd_ctl_add(line6->card, snd_ctl_new1(&toneport_control_source, line6->line6pcm)); if (err < 0) return err; } /* register audio system: */ err = line6_register_audio(line6); if (err < 0) return err; line6_read_serial_number(line6, &toneport->serial_number); line6_read_data(line6, 0x80c2, &toneport->firmware_version, 1); if (toneport_has_led(usbdev->descriptor.idProduct)) { CHECK_RETURN(device_create_file (&interface->dev, &dev_attr_led_red)); CHECK_RETURN(device_create_file (&interface->dev, &dev_attr_led_green)); } toneport_setup(toneport); init_timer(&toneport->timer); toneport->timer.expires = jiffies + TONEPORT_PCM_DELAY * HZ; toneport->timer.function = toneport_start_pcm; toneport->timer.data = (unsigned long)toneport; add_timer(&toneport->timer); return 0; } /* Init Toneport device (and clean up in case of failure). */ int line6_toneport_init(struct usb_interface *interface, struct usb_line6_toneport *toneport) { int err = toneport_try_init(interface, toneport); if (err < 0) toneport_destruct(interface); return err; } /* Resume Toneport device after reset. */ void line6_toneport_reset_resume(struct usb_line6_toneport *toneport) { toneport_setup(toneport); } /* Toneport device disconnected. */ void line6_toneport_disconnect(struct usb_interface *interface) { struct usb_line6_toneport *toneport; if (interface == NULL) return; toneport = usb_get_intfdata(interface); del_timer_sync(&toneport->timer); if (toneport_has_led(toneport->line6.usbdev->descriptor.idProduct)) { device_remove_file(&interface->dev, &dev_attr_led_red); device_remove_file(&interface->dev, &dev_attr_led_green); } if (toneport != NULL) { struct snd_line6_pcm *line6pcm = toneport->line6.line6pcm; if (line6pcm != NULL) { line6_pcm_release(line6pcm, LINE6_BITS_PCM_MONITOR); line6_pcm_disconnect(line6pcm); } } toneport_destruct(interface); }
gpl-2.0
Fechinator/FechdaKernelReloaded6.0
net/batman-adv/vis.c
4809
25452
/* * Copyright (C) 2008-2012 B.A.T.M.A.N. contributors: * * Simon Wunderlich * * 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-1301, USA * */ #include "main.h" #include "send.h" #include "translation-table.h" #include "vis.h" #include "soft-interface.h" #include "hard-interface.h" #include "hash.h" #include "originator.h" #define MAX_VIS_PACKET_SIZE 1000 static void start_vis_timer(struct bat_priv *bat_priv); /* free the info */ static void free_info(struct kref *ref) { struct vis_info *info = container_of(ref, struct vis_info, refcount); struct bat_priv *bat_priv = info->bat_priv; struct recvlist_node *entry, *tmp; list_del_init(&info->send_list); spin_lock_bh(&bat_priv->vis_list_lock); list_for_each_entry_safe(entry, tmp, &info->recv_list, list) { list_del(&entry->list); kfree(entry); } spin_unlock_bh(&bat_priv->vis_list_lock); kfree_skb(info->skb_packet); kfree(info); } /* Compare two vis packets, used by the hashing algorithm */ static int vis_info_cmp(const struct hlist_node *node, const void *data2) { const struct vis_info *d1, *d2; const struct vis_packet *p1, *p2; d1 = container_of(node, struct vis_info, hash_entry); d2 = data2; p1 = (struct vis_packet *)d1->skb_packet->data; p2 = (struct vis_packet *)d2->skb_packet->data; return compare_eth(p1->vis_orig, p2->vis_orig); } /* hash function to choose an entry in a hash table of given size */ /* hash algorithm from http://en.wikipedia.org/wiki/Hash_table */ static uint32_t vis_info_choose(const void *data, uint32_t size) { const struct vis_info *vis_info = data; const struct vis_packet *packet; const unsigned char *key; uint32_t hash = 0; size_t i; packet = (struct vis_packet *)vis_info->skb_packet->data; key = packet->vis_orig; for (i = 0; i < ETH_ALEN; i++) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash % size; } static struct vis_info *vis_hash_find(struct bat_priv *bat_priv, const void *data) { struct hashtable_t *hash = bat_priv->vis_hash; struct hlist_head *head; struct hlist_node *node; struct vis_info *vis_info, *vis_info_tmp = NULL; uint32_t index; if (!hash) return NULL; index = vis_info_choose(data, hash->size); head = &hash->table[index]; rcu_read_lock(); hlist_for_each_entry_rcu(vis_info, node, head, hash_entry) { if (!vis_info_cmp(node, data)) continue; vis_info_tmp = vis_info; break; } rcu_read_unlock(); return vis_info_tmp; } /* insert interface to the list of interfaces of one originator, if it * does not already exist in the list */ static void vis_data_insert_interface(const uint8_t *interface, struct hlist_head *if_list, bool primary) { struct if_list_entry *entry; struct hlist_node *pos; hlist_for_each_entry(entry, pos, if_list, list) { if (compare_eth(entry->addr, interface)) return; } /* it's a new address, add it to the list */ entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->addr, interface, ETH_ALEN); entry->primary = primary; hlist_add_head(&entry->list, if_list); } static ssize_t vis_data_read_prim_sec(char *buff, const struct hlist_head *if_list) { struct if_list_entry *entry; struct hlist_node *pos; size_t len = 0; hlist_for_each_entry(entry, pos, if_list, list) { if (entry->primary) len += sprintf(buff + len, "PRIMARY, "); else len += sprintf(buff + len, "SEC %pM, ", entry->addr); } return len; } static size_t vis_data_count_prim_sec(struct hlist_head *if_list) { struct if_list_entry *entry; struct hlist_node *pos; size_t count = 0; hlist_for_each_entry(entry, pos, if_list, list) { if (entry->primary) count += 9; else count += 23; } return count; } /* read an entry */ static ssize_t vis_data_read_entry(char *buff, const struct vis_info_entry *entry, const uint8_t *src, bool primary) { /* maximal length: max(4+17+2, 3+17+1+3+2) == 26 */ if (primary && entry->quality == 0) return sprintf(buff, "TT %pM, ", entry->dest); else if (compare_eth(entry->src, src)) return sprintf(buff, "TQ %pM %d, ", entry->dest, entry->quality); return 0; } int vis_seq_print_text(struct seq_file *seq, void *offset) { struct hard_iface *primary_if; struct hlist_node *node; struct hlist_head *head; struct vis_info *info; struct vis_packet *packet; struct vis_info_entry *entries; struct net_device *net_dev = (struct net_device *)seq->private; struct bat_priv *bat_priv = netdev_priv(net_dev); struct hashtable_t *hash = bat_priv->vis_hash; HLIST_HEAD(vis_if_list); struct if_list_entry *entry; struct hlist_node *pos, *n; uint32_t i; int j, ret = 0; int vis_server = atomic_read(&bat_priv->vis_mode); size_t buff_pos, buf_size; char *buff; int compare; primary_if = primary_if_get_selected(bat_priv); if (!primary_if) goto out; if (vis_server == VIS_TYPE_CLIENT_UPDATE) goto out; buf_size = 1; /* Estimate length */ spin_lock_bh(&bat_priv->vis_hash_lock); for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(info, node, head, hash_entry) { packet = (struct vis_packet *)info->skb_packet->data; entries = (struct vis_info_entry *) ((char *)packet + sizeof(*packet)); for (j = 0; j < packet->entries; j++) { if (entries[j].quality == 0) continue; compare = compare_eth(entries[j].src, packet->vis_orig); vis_data_insert_interface(entries[j].src, &vis_if_list, compare); } hlist_for_each_entry(entry, pos, &vis_if_list, list) { buf_size += 18 + 26 * packet->entries; /* add primary/secondary records */ if (compare_eth(entry->addr, packet->vis_orig)) buf_size += vis_data_count_prim_sec(&vis_if_list); buf_size += 1; } hlist_for_each_entry_safe(entry, pos, n, &vis_if_list, list) { hlist_del(&entry->list); kfree(entry); } } rcu_read_unlock(); } buff = kmalloc(buf_size, GFP_ATOMIC); if (!buff) { spin_unlock_bh(&bat_priv->vis_hash_lock); ret = -ENOMEM; goto out; } buff[0] = '\0'; buff_pos = 0; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(info, node, head, hash_entry) { packet = (struct vis_packet *)info->skb_packet->data; entries = (struct vis_info_entry *) ((char *)packet + sizeof(*packet)); for (j = 0; j < packet->entries; j++) { if (entries[j].quality == 0) continue; compare = compare_eth(entries[j].src, packet->vis_orig); vis_data_insert_interface(entries[j].src, &vis_if_list, compare); } hlist_for_each_entry(entry, pos, &vis_if_list, list) { buff_pos += sprintf(buff + buff_pos, "%pM,", entry->addr); for (j = 0; j < packet->entries; j++) buff_pos += vis_data_read_entry( buff + buff_pos, &entries[j], entry->addr, entry->primary); /* add primary/secondary records */ if (compare_eth(entry->addr, packet->vis_orig)) buff_pos += vis_data_read_prim_sec(buff + buff_pos, &vis_if_list); buff_pos += sprintf(buff + buff_pos, "\n"); } hlist_for_each_entry_safe(entry, pos, n, &vis_if_list, list) { hlist_del(&entry->list); kfree(entry); } } rcu_read_unlock(); } spin_unlock_bh(&bat_priv->vis_hash_lock); seq_printf(seq, "%s", buff); kfree(buff); out: if (primary_if) hardif_free_ref(primary_if); return ret; } /* add the info packet to the send list, if it was not * already linked in. */ static void send_list_add(struct bat_priv *bat_priv, struct vis_info *info) { if (list_empty(&info->send_list)) { kref_get(&info->refcount); list_add_tail(&info->send_list, &bat_priv->vis_send_list); } } /* delete the info packet from the send list, if it was * linked in. */ static void send_list_del(struct vis_info *info) { if (!list_empty(&info->send_list)) { list_del_init(&info->send_list); kref_put(&info->refcount, free_info); } } /* tries to add one entry to the receive list. */ static void recv_list_add(struct bat_priv *bat_priv, struct list_head *recv_list, const char *mac) { struct recvlist_node *entry; entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->mac, mac, ETH_ALEN); spin_lock_bh(&bat_priv->vis_list_lock); list_add_tail(&entry->list, recv_list); spin_unlock_bh(&bat_priv->vis_list_lock); } /* returns 1 if this mac is in the recv_list */ static int recv_list_is_in(struct bat_priv *bat_priv, const struct list_head *recv_list, const char *mac) { const struct recvlist_node *entry; spin_lock_bh(&bat_priv->vis_list_lock); list_for_each_entry(entry, recv_list, list) { if (compare_eth(entry->mac, mac)) { spin_unlock_bh(&bat_priv->vis_list_lock); return 1; } } spin_unlock_bh(&bat_priv->vis_list_lock); return 0; } /* try to add the packet to the vis_hash. return NULL if invalid (e.g. too old, * broken.. ). vis hash must be locked outside. is_new is set when the packet * is newer than old entries in the hash. */ static struct vis_info *add_packet(struct bat_priv *bat_priv, struct vis_packet *vis_packet, int vis_info_len, int *is_new, int make_broadcast) { struct vis_info *info, *old_info; struct vis_packet *search_packet, *old_packet; struct vis_info search_elem; struct vis_packet *packet; int hash_added; *is_new = 0; /* sanity check */ if (!bat_priv->vis_hash) return NULL; /* see if the packet is already in vis_hash */ search_elem.skb_packet = dev_alloc_skb(sizeof(*search_packet)); if (!search_elem.skb_packet) return NULL; search_packet = (struct vis_packet *)skb_put(search_elem.skb_packet, sizeof(*search_packet)); memcpy(search_packet->vis_orig, vis_packet->vis_orig, ETH_ALEN); old_info = vis_hash_find(bat_priv, &search_elem); kfree_skb(search_elem.skb_packet); if (old_info) { old_packet = (struct vis_packet *)old_info->skb_packet->data; if (!seq_after(ntohl(vis_packet->seqno), ntohl(old_packet->seqno))) { if (old_packet->seqno == vis_packet->seqno) { recv_list_add(bat_priv, &old_info->recv_list, vis_packet->sender_orig); return old_info; } else { /* newer packet is already in hash. */ return NULL; } } /* remove old entry */ hash_remove(bat_priv->vis_hash, vis_info_cmp, vis_info_choose, old_info); send_list_del(old_info); kref_put(&old_info->refcount, free_info); } info = kmalloc(sizeof(*info), GFP_ATOMIC); if (!info) return NULL; info->skb_packet = dev_alloc_skb(sizeof(*packet) + vis_info_len + sizeof(struct ethhdr)); if (!info->skb_packet) { kfree(info); return NULL; } skb_reserve(info->skb_packet, sizeof(struct ethhdr)); packet = (struct vis_packet *)skb_put(info->skb_packet, sizeof(*packet) + vis_info_len); kref_init(&info->refcount); INIT_LIST_HEAD(&info->send_list); INIT_LIST_HEAD(&info->recv_list); info->first_seen = jiffies; info->bat_priv = bat_priv; memcpy(packet, vis_packet, sizeof(*packet) + vis_info_len); /* initialize and add new packet. */ *is_new = 1; /* Make it a broadcast packet, if required */ if (make_broadcast) memcpy(packet->target_orig, broadcast_addr, ETH_ALEN); /* repair if entries is longer than packet. */ if (packet->entries * sizeof(struct vis_info_entry) > vis_info_len) packet->entries = vis_info_len / sizeof(struct vis_info_entry); recv_list_add(bat_priv, &info->recv_list, packet->sender_orig); /* try to add it */ hash_added = hash_add(bat_priv->vis_hash, vis_info_cmp, vis_info_choose, info, &info->hash_entry); if (hash_added != 0) { /* did not work (for some reason) */ kref_put(&info->refcount, free_info); info = NULL; } return info; } /* handle the server sync packet, forward if needed. */ void receive_server_sync_packet(struct bat_priv *bat_priv, struct vis_packet *vis_packet, int vis_info_len) { struct vis_info *info; int is_new, make_broadcast; int vis_server = atomic_read(&bat_priv->vis_mode); make_broadcast = (vis_server == VIS_TYPE_SERVER_SYNC); spin_lock_bh(&bat_priv->vis_hash_lock); info = add_packet(bat_priv, vis_packet, vis_info_len, &is_new, make_broadcast); if (!info) goto end; /* only if we are server ourselves and packet is newer than the one in * hash.*/ if (vis_server == VIS_TYPE_SERVER_SYNC && is_new) send_list_add(bat_priv, info); end: spin_unlock_bh(&bat_priv->vis_hash_lock); } /* handle an incoming client update packet and schedule forward if needed. */ void receive_client_update_packet(struct bat_priv *bat_priv, struct vis_packet *vis_packet, int vis_info_len) { struct vis_info *info; struct vis_packet *packet; int is_new; int vis_server = atomic_read(&bat_priv->vis_mode); int are_target = 0; /* clients shall not broadcast. */ if (is_broadcast_ether_addr(vis_packet->target_orig)) return; /* Are we the target for this VIS packet? */ if (vis_server == VIS_TYPE_SERVER_SYNC && is_my_mac(vis_packet->target_orig)) are_target = 1; spin_lock_bh(&bat_priv->vis_hash_lock); info = add_packet(bat_priv, vis_packet, vis_info_len, &is_new, are_target); if (!info) goto end; /* note that outdated packets will be dropped at this point. */ packet = (struct vis_packet *)info->skb_packet->data; /* send only if we're the target server or ... */ if (are_target && is_new) { packet->vis_type = VIS_TYPE_SERVER_SYNC; /* upgrade! */ send_list_add(bat_priv, info); /* ... we're not the recipient (and thus need to forward). */ } else if (!is_my_mac(packet->target_orig)) { send_list_add(bat_priv, info); } end: spin_unlock_bh(&bat_priv->vis_hash_lock); } /* Walk the originators and find the VIS server with the best tq. Set the packet * address to its address and return the best_tq. * * Must be called with the originator hash locked */ static int find_best_vis_server(struct bat_priv *bat_priv, struct vis_info *info) { struct hashtable_t *hash = bat_priv->orig_hash; struct neigh_node *router; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; struct vis_packet *packet; int best_tq = -1; uint32_t i; packet = (struct vis_packet *)info->skb_packet->data; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { router = orig_node_get_router(orig_node); if (!router) continue; if ((orig_node->flags & VIS_SERVER) && (router->tq_avg > best_tq)) { best_tq = router->tq_avg; memcpy(packet->target_orig, orig_node->orig, ETH_ALEN); } neigh_node_free_ref(router); } rcu_read_unlock(); } return best_tq; } /* Return true if the vis packet is full. */ static bool vis_packet_full(const struct vis_info *info) { const struct vis_packet *packet; packet = (struct vis_packet *)info->skb_packet->data; if (MAX_VIS_PACKET_SIZE / sizeof(struct vis_info_entry) < packet->entries + 1) return true; return false; } /* generates a packet of own vis data, * returns 0 on success, -1 if no packet could be generated */ static int generate_vis_packet(struct bat_priv *bat_priv) { struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; struct neigh_node *router; struct vis_info *info = bat_priv->my_vis_info; struct vis_packet *packet = (struct vis_packet *)info->skb_packet->data; struct vis_info_entry *entry; struct tt_common_entry *tt_common_entry; int best_tq = -1; uint32_t i; info->first_seen = jiffies; packet->vis_type = atomic_read(&bat_priv->vis_mode); memcpy(packet->target_orig, broadcast_addr, ETH_ALEN); packet->header.ttl = TTL; packet->seqno = htonl(ntohl(packet->seqno) + 1); packet->entries = 0; skb_trim(info->skb_packet, sizeof(*packet)); if (packet->vis_type == VIS_TYPE_CLIENT_UPDATE) { best_tq = find_best_vis_server(bat_priv, info); if (best_tq < 0) return -1; } for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { router = orig_node_get_router(orig_node); if (!router) continue; if (!compare_eth(router->addr, orig_node->orig)) goto next; if (router->if_incoming->if_status != IF_ACTIVE) goto next; if (router->tq_avg < 1) goto next; /* fill one entry into buffer. */ entry = (struct vis_info_entry *) skb_put(info->skb_packet, sizeof(*entry)); memcpy(entry->src, router->if_incoming->net_dev->dev_addr, ETH_ALEN); memcpy(entry->dest, orig_node->orig, ETH_ALEN); entry->quality = router->tq_avg; packet->entries++; next: neigh_node_free_ref(router); if (vis_packet_full(info)) goto unlock; } rcu_read_unlock(); } hash = bat_priv->tt_local_hash; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(tt_common_entry, node, head, hash_entry) { entry = (struct vis_info_entry *) skb_put(info->skb_packet, sizeof(*entry)); memset(entry->src, 0, ETH_ALEN); memcpy(entry->dest, tt_common_entry->addr, ETH_ALEN); entry->quality = 0; /* 0 means TT */ packet->entries++; if (vis_packet_full(info)) goto unlock; } rcu_read_unlock(); } return 0; unlock: rcu_read_unlock(); return 0; } /* free old vis packets. Must be called with this vis_hash_lock * held */ static void purge_vis_packets(struct bat_priv *bat_priv) { uint32_t i; struct hashtable_t *hash = bat_priv->vis_hash; struct hlist_node *node, *node_tmp; struct hlist_head *head; struct vis_info *info; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; hlist_for_each_entry_safe(info, node, node_tmp, head, hash_entry) { /* never purge own data. */ if (info == bat_priv->my_vis_info) continue; if (has_timed_out(info->first_seen, VIS_TIMEOUT)) { hlist_del(node); send_list_del(info); kref_put(&info->refcount, free_info); } } } } static void broadcast_vis_packet(struct bat_priv *bat_priv, struct vis_info *info) { struct neigh_node *router; struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; struct vis_packet *packet; struct sk_buff *skb; struct hard_iface *hard_iface; uint8_t dstaddr[ETH_ALEN]; uint32_t i; packet = (struct vis_packet *)info->skb_packet->data; /* send to all routers in range. */ for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { /* if it's a vis server and reachable, send it. */ if (!(orig_node->flags & VIS_SERVER)) continue; router = orig_node_get_router(orig_node); if (!router) continue; /* don't send it if we already received the packet from * this node. */ if (recv_list_is_in(bat_priv, &info->recv_list, orig_node->orig)) { neigh_node_free_ref(router); continue; } memcpy(packet->target_orig, orig_node->orig, ETH_ALEN); hard_iface = router->if_incoming; memcpy(dstaddr, router->addr, ETH_ALEN); neigh_node_free_ref(router); skb = skb_clone(info->skb_packet, GFP_ATOMIC); if (skb) send_skb_packet(skb, hard_iface, dstaddr); } rcu_read_unlock(); } } static void unicast_vis_packet(struct bat_priv *bat_priv, struct vis_info *info) { struct orig_node *orig_node; struct neigh_node *router = NULL; struct sk_buff *skb; struct vis_packet *packet; packet = (struct vis_packet *)info->skb_packet->data; orig_node = orig_hash_find(bat_priv, packet->target_orig); if (!orig_node) goto out; router = orig_node_get_router(orig_node); if (!router) goto out; skb = skb_clone(info->skb_packet, GFP_ATOMIC); if (skb) send_skb_packet(skb, router->if_incoming, router->addr); out: if (router) neigh_node_free_ref(router); if (orig_node) orig_node_free_ref(orig_node); } /* only send one vis packet. called from send_vis_packets() */ static void send_vis_packet(struct bat_priv *bat_priv, struct vis_info *info) { struct hard_iface *primary_if; struct vis_packet *packet; primary_if = primary_if_get_selected(bat_priv); if (!primary_if) goto out; packet = (struct vis_packet *)info->skb_packet->data; if (packet->header.ttl < 2) { pr_debug("Error - can't send vis packet: ttl exceeded\n"); goto out; } memcpy(packet->sender_orig, primary_if->net_dev->dev_addr, ETH_ALEN); packet->header.ttl--; if (is_broadcast_ether_addr(packet->target_orig)) broadcast_vis_packet(bat_priv, info); else unicast_vis_packet(bat_priv, info); packet->header.ttl++; /* restore TTL */ out: if (primary_if) hardif_free_ref(primary_if); } /* called from timer; send (and maybe generate) vis packet. */ static void send_vis_packets(struct work_struct *work) { struct delayed_work *delayed_work = container_of(work, struct delayed_work, work); struct bat_priv *bat_priv = container_of(delayed_work, struct bat_priv, vis_work); struct vis_info *info; spin_lock_bh(&bat_priv->vis_hash_lock); purge_vis_packets(bat_priv); if (generate_vis_packet(bat_priv) == 0) { /* schedule if generation was successful */ send_list_add(bat_priv, bat_priv->my_vis_info); } while (!list_empty(&bat_priv->vis_send_list)) { info = list_first_entry(&bat_priv->vis_send_list, typeof(*info), send_list); kref_get(&info->refcount); spin_unlock_bh(&bat_priv->vis_hash_lock); send_vis_packet(bat_priv, info); spin_lock_bh(&bat_priv->vis_hash_lock); send_list_del(info); kref_put(&info->refcount, free_info); } spin_unlock_bh(&bat_priv->vis_hash_lock); start_vis_timer(bat_priv); } /* init the vis server. this may only be called when if_list is already * initialized (e.g. bat0 is initialized, interfaces have been added) */ int vis_init(struct bat_priv *bat_priv) { struct vis_packet *packet; int hash_added; if (bat_priv->vis_hash) return 1; spin_lock_bh(&bat_priv->vis_hash_lock); bat_priv->vis_hash = hash_new(256); if (!bat_priv->vis_hash) { pr_err("Can't initialize vis_hash\n"); goto err; } bat_priv->my_vis_info = kmalloc(MAX_VIS_PACKET_SIZE, GFP_ATOMIC); if (!bat_priv->my_vis_info) goto err; bat_priv->my_vis_info->skb_packet = dev_alloc_skb(sizeof(*packet) + MAX_VIS_PACKET_SIZE + sizeof(struct ethhdr)); if (!bat_priv->my_vis_info->skb_packet) goto free_info; skb_reserve(bat_priv->my_vis_info->skb_packet, sizeof(struct ethhdr)); packet = (struct vis_packet *)skb_put(bat_priv->my_vis_info->skb_packet, sizeof(*packet)); /* prefill the vis info */ bat_priv->my_vis_info->first_seen = jiffies - msecs_to_jiffies(VIS_INTERVAL); INIT_LIST_HEAD(&bat_priv->my_vis_info->recv_list); INIT_LIST_HEAD(&bat_priv->my_vis_info->send_list); kref_init(&bat_priv->my_vis_info->refcount); bat_priv->my_vis_info->bat_priv = bat_priv; packet->header.version = COMPAT_VERSION; packet->header.packet_type = BAT_VIS; packet->header.ttl = TTL; packet->seqno = 0; packet->entries = 0; INIT_LIST_HEAD(&bat_priv->vis_send_list); hash_added = hash_add(bat_priv->vis_hash, vis_info_cmp, vis_info_choose, bat_priv->my_vis_info, &bat_priv->my_vis_info->hash_entry); if (hash_added != 0) { pr_err("Can't add own vis packet into hash\n"); /* not in hash, need to remove it manually. */ kref_put(&bat_priv->my_vis_info->refcount, free_info); goto err; } spin_unlock_bh(&bat_priv->vis_hash_lock); start_vis_timer(bat_priv); return 1; free_info: kfree(bat_priv->my_vis_info); bat_priv->my_vis_info = NULL; err: spin_unlock_bh(&bat_priv->vis_hash_lock); vis_quit(bat_priv); return 0; } /* Decrease the reference count on a hash item info */ static void free_info_ref(struct hlist_node *node, void *arg) { struct vis_info *info; info = container_of(node, struct vis_info, hash_entry); send_list_del(info); kref_put(&info->refcount, free_info); } /* shutdown vis-server */ void vis_quit(struct bat_priv *bat_priv) { if (!bat_priv->vis_hash) return; cancel_delayed_work_sync(&bat_priv->vis_work); spin_lock_bh(&bat_priv->vis_hash_lock); /* properly remove, kill timers ... */ hash_delete(bat_priv->vis_hash, free_info_ref, NULL); bat_priv->vis_hash = NULL; bat_priv->my_vis_info = NULL; spin_unlock_bh(&bat_priv->vis_hash_lock); } /* schedule packets for (re)transmission */ static void start_vis_timer(struct bat_priv *bat_priv) { INIT_DELAYED_WORK(&bat_priv->vis_work, send_vis_packets); queue_delayed_work(bat_event_workqueue, &bat_priv->vis_work, msecs_to_jiffies(VIS_INTERVAL)); }
gpl-2.0
ElectryDev/android_kernel_kingdom_row
drivers/rtc/rtc-lpc32xx.c
4809
10192
/* * Copyright (C) 2010 NXP Semiconductors * * 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. * * 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/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/spinlock.h> #include <linux/rtc.h> #include <linux/slab.h> #include <linux/io.h> /* * Clock and Power control register offsets */ #define LPC32XX_RTC_UCOUNT 0x00 #define LPC32XX_RTC_DCOUNT 0x04 #define LPC32XX_RTC_MATCH0 0x08 #define LPC32XX_RTC_MATCH1 0x0C #define LPC32XX_RTC_CTRL 0x10 #define LPC32XX_RTC_INTSTAT 0x14 #define LPC32XX_RTC_KEY 0x18 #define LPC32XX_RTC_SRAM 0x80 #define LPC32XX_RTC_CTRL_MATCH0 (1 << 0) #define LPC32XX_RTC_CTRL_MATCH1 (1 << 1) #define LPC32XX_RTC_CTRL_ONSW_MATCH0 (1 << 2) #define LPC32XX_RTC_CTRL_ONSW_MATCH1 (1 << 3) #define LPC32XX_RTC_CTRL_SW_RESET (1 << 4) #define LPC32XX_RTC_CTRL_CNTR_DIS (1 << 6) #define LPC32XX_RTC_CTRL_ONSW_FORCE_HI (1 << 7) #define LPC32XX_RTC_INTSTAT_MATCH0 (1 << 0) #define LPC32XX_RTC_INTSTAT_MATCH1 (1 << 1) #define LPC32XX_RTC_INTSTAT_ONSW (1 << 2) #define LPC32XX_RTC_KEY_ONSW_LOADVAL 0xB5C13F27 #define RTC_NAME "rtc-lpc32xx" #define rtc_readl(dev, reg) \ __raw_readl((dev)->rtc_base + (reg)) #define rtc_writel(dev, reg, val) \ __raw_writel((val), (dev)->rtc_base + (reg)) struct lpc32xx_rtc { void __iomem *rtc_base; int irq; unsigned char alarm_enabled; struct rtc_device *rtc; spinlock_t lock; }; static int lpc32xx_rtc_read_time(struct device *dev, struct rtc_time *time) { unsigned long elapsed_sec; struct lpc32xx_rtc *rtc = dev_get_drvdata(dev); elapsed_sec = rtc_readl(rtc, LPC32XX_RTC_UCOUNT); rtc_time_to_tm(elapsed_sec, time); return rtc_valid_tm(time); } static int lpc32xx_rtc_set_mmss(struct device *dev, unsigned long secs) { struct lpc32xx_rtc *rtc = dev_get_drvdata(dev); u32 tmp; spin_lock_irq(&rtc->lock); /* RTC must be disabled during count update */ tmp = rtc_readl(rtc, LPC32XX_RTC_CTRL); rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp | LPC32XX_RTC_CTRL_CNTR_DIS); rtc_writel(rtc, LPC32XX_RTC_UCOUNT, secs); rtc_writel(rtc, LPC32XX_RTC_DCOUNT, 0xFFFFFFFF - secs); rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp &= ~LPC32XX_RTC_CTRL_CNTR_DIS); spin_unlock_irq(&rtc->lock); return 0; } static int lpc32xx_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *wkalrm) { struct lpc32xx_rtc *rtc = dev_get_drvdata(dev); rtc_time_to_tm(rtc_readl(rtc, LPC32XX_RTC_MATCH0), &wkalrm->time); wkalrm->enabled = rtc->alarm_enabled; wkalrm->pending = !!(rtc_readl(rtc, LPC32XX_RTC_INTSTAT) & LPC32XX_RTC_INTSTAT_MATCH0); return rtc_valid_tm(&wkalrm->time); } static int lpc32xx_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *wkalrm) { struct lpc32xx_rtc *rtc = dev_get_drvdata(dev); unsigned long alarmsecs; u32 tmp; int ret; ret = rtc_tm_to_time(&wkalrm->time, &alarmsecs); if (ret < 0) { dev_warn(dev, "Failed to convert time: %d\n", ret); return ret; } spin_lock_irq(&rtc->lock); /* Disable alarm during update */ tmp = rtc_readl(rtc, LPC32XX_RTC_CTRL); rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp & ~LPC32XX_RTC_CTRL_MATCH0); rtc_writel(rtc, LPC32XX_RTC_MATCH0, alarmsecs); rtc->alarm_enabled = wkalrm->enabled; if (wkalrm->enabled) { rtc_writel(rtc, LPC32XX_RTC_INTSTAT, LPC32XX_RTC_INTSTAT_MATCH0); rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp | LPC32XX_RTC_CTRL_MATCH0); } spin_unlock_irq(&rtc->lock); return 0; } static int lpc32xx_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct lpc32xx_rtc *rtc = dev_get_drvdata(dev); u32 tmp; spin_lock_irq(&rtc->lock); tmp = rtc_readl(rtc, LPC32XX_RTC_CTRL); if (enabled) { rtc->alarm_enabled = 1; tmp |= LPC32XX_RTC_CTRL_MATCH0; } else { rtc->alarm_enabled = 0; tmp &= ~LPC32XX_RTC_CTRL_MATCH0; } rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp); spin_unlock_irq(&rtc->lock); return 0; } static irqreturn_t lpc32xx_rtc_alarm_interrupt(int irq, void *dev) { struct lpc32xx_rtc *rtc = dev; spin_lock(&rtc->lock); /* Disable alarm interrupt */ rtc_writel(rtc, LPC32XX_RTC_CTRL, rtc_readl(rtc, LPC32XX_RTC_CTRL) & ~LPC32XX_RTC_CTRL_MATCH0); rtc->alarm_enabled = 0; /* * Write a large value to the match value so the RTC won't * keep firing the match status */ rtc_writel(rtc, LPC32XX_RTC_MATCH0, 0xFFFFFFFF); rtc_writel(rtc, LPC32XX_RTC_INTSTAT, LPC32XX_RTC_INTSTAT_MATCH0); spin_unlock(&rtc->lock); rtc_update_irq(rtc->rtc, 1, RTC_IRQF | RTC_AF); return IRQ_HANDLED; } static const struct rtc_class_ops lpc32xx_rtc_ops = { .read_time = lpc32xx_rtc_read_time, .set_mmss = lpc32xx_rtc_set_mmss, .read_alarm = lpc32xx_rtc_read_alarm, .set_alarm = lpc32xx_rtc_set_alarm, .alarm_irq_enable = lpc32xx_rtc_alarm_irq_enable, }; static int __devinit lpc32xx_rtc_probe(struct platform_device *pdev) { struct resource *res; struct lpc32xx_rtc *rtc; resource_size_t size; int rtcirq; u32 tmp; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Can't get memory resource\n"); return -ENOENT; } rtcirq = platform_get_irq(pdev, 0); if (rtcirq < 0 || rtcirq >= NR_IRQS) { dev_warn(&pdev->dev, "Can't get interrupt resource\n"); rtcirq = -1; } rtc = devm_kzalloc(&pdev->dev, sizeof(*rtc), GFP_KERNEL); if (unlikely(!rtc)) { dev_err(&pdev->dev, "Can't allocate memory\n"); return -ENOMEM; } rtc->irq = rtcirq; size = resource_size(res); if (!devm_request_mem_region(&pdev->dev, res->start, size, pdev->name)) { dev_err(&pdev->dev, "RTC registers are not free\n"); return -EBUSY; } rtc->rtc_base = devm_ioremap(&pdev->dev, res->start, size); if (!rtc->rtc_base) { dev_err(&pdev->dev, "Can't map memory\n"); return -ENOMEM; } spin_lock_init(&rtc->lock); /* * The RTC is on a separate power domain and can keep it's state * across a chip power cycle. If the RTC has never been previously * setup, then set it up now for the first time. */ tmp = rtc_readl(rtc, LPC32XX_RTC_CTRL); if (rtc_readl(rtc, LPC32XX_RTC_KEY) != LPC32XX_RTC_KEY_ONSW_LOADVAL) { tmp &= ~(LPC32XX_RTC_CTRL_SW_RESET | LPC32XX_RTC_CTRL_CNTR_DIS | LPC32XX_RTC_CTRL_MATCH0 | LPC32XX_RTC_CTRL_MATCH1 | LPC32XX_RTC_CTRL_ONSW_MATCH0 | LPC32XX_RTC_CTRL_ONSW_MATCH1 | LPC32XX_RTC_CTRL_ONSW_FORCE_HI); rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp); /* Clear latched interrupt states */ rtc_writel(rtc, LPC32XX_RTC_MATCH0, 0xFFFFFFFF); rtc_writel(rtc, LPC32XX_RTC_INTSTAT, LPC32XX_RTC_INTSTAT_MATCH0 | LPC32XX_RTC_INTSTAT_MATCH1 | LPC32XX_RTC_INTSTAT_ONSW); /* Write key value to RTC so it won't reload on reset */ rtc_writel(rtc, LPC32XX_RTC_KEY, LPC32XX_RTC_KEY_ONSW_LOADVAL); } else { rtc_writel(rtc, LPC32XX_RTC_CTRL, tmp & ~LPC32XX_RTC_CTRL_MATCH0); } platform_set_drvdata(pdev, rtc); rtc->rtc = rtc_device_register(RTC_NAME, &pdev->dev, &lpc32xx_rtc_ops, THIS_MODULE); if (IS_ERR(rtc->rtc)) { dev_err(&pdev->dev, "Can't get RTC\n"); platform_set_drvdata(pdev, NULL); return PTR_ERR(rtc->rtc); } /* * IRQ is enabled after device registration in case alarm IRQ * is pending upon suspend exit. */ if (rtc->irq >= 0) { if (devm_request_irq(&pdev->dev, rtc->irq, lpc32xx_rtc_alarm_interrupt, 0, pdev->name, rtc) < 0) { dev_warn(&pdev->dev, "Can't request interrupt.\n"); rtc->irq = -1; } else { device_init_wakeup(&pdev->dev, 1); } } return 0; } static int __devexit lpc32xx_rtc_remove(struct platform_device *pdev) { struct lpc32xx_rtc *rtc = platform_get_drvdata(pdev); if (rtc->irq >= 0) device_init_wakeup(&pdev->dev, 0); platform_set_drvdata(pdev, NULL); rtc_device_unregister(rtc->rtc); return 0; } #ifdef CONFIG_PM static int lpc32xx_rtc_suspend(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct lpc32xx_rtc *rtc = platform_get_drvdata(pdev); if (rtc->irq >= 0) { if (device_may_wakeup(&pdev->dev)) enable_irq_wake(rtc->irq); else disable_irq_wake(rtc->irq); } return 0; } static int lpc32xx_rtc_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct lpc32xx_rtc *rtc = platform_get_drvdata(pdev); if (rtc->irq >= 0 && device_may_wakeup(&pdev->dev)) disable_irq_wake(rtc->irq); return 0; } /* Unconditionally disable the alarm */ static int lpc32xx_rtc_freeze(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct lpc32xx_rtc *rtc = platform_get_drvdata(pdev); spin_lock_irq(&rtc->lock); rtc_writel(rtc, LPC32XX_RTC_CTRL, rtc_readl(rtc, LPC32XX_RTC_CTRL) & ~LPC32XX_RTC_CTRL_MATCH0); spin_unlock_irq(&rtc->lock); return 0; } static int lpc32xx_rtc_thaw(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct lpc32xx_rtc *rtc = platform_get_drvdata(pdev); if (rtc->alarm_enabled) { spin_lock_irq(&rtc->lock); rtc_writel(rtc, LPC32XX_RTC_CTRL, rtc_readl(rtc, LPC32XX_RTC_CTRL) | LPC32XX_RTC_CTRL_MATCH0); spin_unlock_irq(&rtc->lock); } return 0; } static const struct dev_pm_ops lpc32xx_rtc_pm_ops = { .suspend = lpc32xx_rtc_suspend, .resume = lpc32xx_rtc_resume, .freeze = lpc32xx_rtc_freeze, .thaw = lpc32xx_rtc_thaw, .restore = lpc32xx_rtc_resume }; #define LPC32XX_RTC_PM_OPS (&lpc32xx_rtc_pm_ops) #else #define LPC32XX_RTC_PM_OPS NULL #endif static struct platform_driver lpc32xx_rtc_driver = { .probe = lpc32xx_rtc_probe, .remove = __devexit_p(lpc32xx_rtc_remove), .driver = { .name = RTC_NAME, .owner = THIS_MODULE, .pm = LPC32XX_RTC_PM_OPS }, }; module_platform_driver(lpc32xx_rtc_driver); MODULE_AUTHOR("Kevin Wells <wellsk40@gmail.com"); MODULE_DESCRIPTION("RTC driver for the LPC32xx SoC"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:rtc-lpc32xx");
gpl-2.0
Jackeagle/CAF-Kernel
net/batman-adv/vis.c
4809
25452
/* * Copyright (C) 2008-2012 B.A.T.M.A.N. contributors: * * Simon Wunderlich * * 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-1301, USA * */ #include "main.h" #include "send.h" #include "translation-table.h" #include "vis.h" #include "soft-interface.h" #include "hard-interface.h" #include "hash.h" #include "originator.h" #define MAX_VIS_PACKET_SIZE 1000 static void start_vis_timer(struct bat_priv *bat_priv); /* free the info */ static void free_info(struct kref *ref) { struct vis_info *info = container_of(ref, struct vis_info, refcount); struct bat_priv *bat_priv = info->bat_priv; struct recvlist_node *entry, *tmp; list_del_init(&info->send_list); spin_lock_bh(&bat_priv->vis_list_lock); list_for_each_entry_safe(entry, tmp, &info->recv_list, list) { list_del(&entry->list); kfree(entry); } spin_unlock_bh(&bat_priv->vis_list_lock); kfree_skb(info->skb_packet); kfree(info); } /* Compare two vis packets, used by the hashing algorithm */ static int vis_info_cmp(const struct hlist_node *node, const void *data2) { const struct vis_info *d1, *d2; const struct vis_packet *p1, *p2; d1 = container_of(node, struct vis_info, hash_entry); d2 = data2; p1 = (struct vis_packet *)d1->skb_packet->data; p2 = (struct vis_packet *)d2->skb_packet->data; return compare_eth(p1->vis_orig, p2->vis_orig); } /* hash function to choose an entry in a hash table of given size */ /* hash algorithm from http://en.wikipedia.org/wiki/Hash_table */ static uint32_t vis_info_choose(const void *data, uint32_t size) { const struct vis_info *vis_info = data; const struct vis_packet *packet; const unsigned char *key; uint32_t hash = 0; size_t i; packet = (struct vis_packet *)vis_info->skb_packet->data; key = packet->vis_orig; for (i = 0; i < ETH_ALEN; i++) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash % size; } static struct vis_info *vis_hash_find(struct bat_priv *bat_priv, const void *data) { struct hashtable_t *hash = bat_priv->vis_hash; struct hlist_head *head; struct hlist_node *node; struct vis_info *vis_info, *vis_info_tmp = NULL; uint32_t index; if (!hash) return NULL; index = vis_info_choose(data, hash->size); head = &hash->table[index]; rcu_read_lock(); hlist_for_each_entry_rcu(vis_info, node, head, hash_entry) { if (!vis_info_cmp(node, data)) continue; vis_info_tmp = vis_info; break; } rcu_read_unlock(); return vis_info_tmp; } /* insert interface to the list of interfaces of one originator, if it * does not already exist in the list */ static void vis_data_insert_interface(const uint8_t *interface, struct hlist_head *if_list, bool primary) { struct if_list_entry *entry; struct hlist_node *pos; hlist_for_each_entry(entry, pos, if_list, list) { if (compare_eth(entry->addr, interface)) return; } /* it's a new address, add it to the list */ entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->addr, interface, ETH_ALEN); entry->primary = primary; hlist_add_head(&entry->list, if_list); } static ssize_t vis_data_read_prim_sec(char *buff, const struct hlist_head *if_list) { struct if_list_entry *entry; struct hlist_node *pos; size_t len = 0; hlist_for_each_entry(entry, pos, if_list, list) { if (entry->primary) len += sprintf(buff + len, "PRIMARY, "); else len += sprintf(buff + len, "SEC %pM, ", entry->addr); } return len; } static size_t vis_data_count_prim_sec(struct hlist_head *if_list) { struct if_list_entry *entry; struct hlist_node *pos; size_t count = 0; hlist_for_each_entry(entry, pos, if_list, list) { if (entry->primary) count += 9; else count += 23; } return count; } /* read an entry */ static ssize_t vis_data_read_entry(char *buff, const struct vis_info_entry *entry, const uint8_t *src, bool primary) { /* maximal length: max(4+17+2, 3+17+1+3+2) == 26 */ if (primary && entry->quality == 0) return sprintf(buff, "TT %pM, ", entry->dest); else if (compare_eth(entry->src, src)) return sprintf(buff, "TQ %pM %d, ", entry->dest, entry->quality); return 0; } int vis_seq_print_text(struct seq_file *seq, void *offset) { struct hard_iface *primary_if; struct hlist_node *node; struct hlist_head *head; struct vis_info *info; struct vis_packet *packet; struct vis_info_entry *entries; struct net_device *net_dev = (struct net_device *)seq->private; struct bat_priv *bat_priv = netdev_priv(net_dev); struct hashtable_t *hash = bat_priv->vis_hash; HLIST_HEAD(vis_if_list); struct if_list_entry *entry; struct hlist_node *pos, *n; uint32_t i; int j, ret = 0; int vis_server = atomic_read(&bat_priv->vis_mode); size_t buff_pos, buf_size; char *buff; int compare; primary_if = primary_if_get_selected(bat_priv); if (!primary_if) goto out; if (vis_server == VIS_TYPE_CLIENT_UPDATE) goto out; buf_size = 1; /* Estimate length */ spin_lock_bh(&bat_priv->vis_hash_lock); for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(info, node, head, hash_entry) { packet = (struct vis_packet *)info->skb_packet->data; entries = (struct vis_info_entry *) ((char *)packet + sizeof(*packet)); for (j = 0; j < packet->entries; j++) { if (entries[j].quality == 0) continue; compare = compare_eth(entries[j].src, packet->vis_orig); vis_data_insert_interface(entries[j].src, &vis_if_list, compare); } hlist_for_each_entry(entry, pos, &vis_if_list, list) { buf_size += 18 + 26 * packet->entries; /* add primary/secondary records */ if (compare_eth(entry->addr, packet->vis_orig)) buf_size += vis_data_count_prim_sec(&vis_if_list); buf_size += 1; } hlist_for_each_entry_safe(entry, pos, n, &vis_if_list, list) { hlist_del(&entry->list); kfree(entry); } } rcu_read_unlock(); } buff = kmalloc(buf_size, GFP_ATOMIC); if (!buff) { spin_unlock_bh(&bat_priv->vis_hash_lock); ret = -ENOMEM; goto out; } buff[0] = '\0'; buff_pos = 0; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(info, node, head, hash_entry) { packet = (struct vis_packet *)info->skb_packet->data; entries = (struct vis_info_entry *) ((char *)packet + sizeof(*packet)); for (j = 0; j < packet->entries; j++) { if (entries[j].quality == 0) continue; compare = compare_eth(entries[j].src, packet->vis_orig); vis_data_insert_interface(entries[j].src, &vis_if_list, compare); } hlist_for_each_entry(entry, pos, &vis_if_list, list) { buff_pos += sprintf(buff + buff_pos, "%pM,", entry->addr); for (j = 0; j < packet->entries; j++) buff_pos += vis_data_read_entry( buff + buff_pos, &entries[j], entry->addr, entry->primary); /* add primary/secondary records */ if (compare_eth(entry->addr, packet->vis_orig)) buff_pos += vis_data_read_prim_sec(buff + buff_pos, &vis_if_list); buff_pos += sprintf(buff + buff_pos, "\n"); } hlist_for_each_entry_safe(entry, pos, n, &vis_if_list, list) { hlist_del(&entry->list); kfree(entry); } } rcu_read_unlock(); } spin_unlock_bh(&bat_priv->vis_hash_lock); seq_printf(seq, "%s", buff); kfree(buff); out: if (primary_if) hardif_free_ref(primary_if); return ret; } /* add the info packet to the send list, if it was not * already linked in. */ static void send_list_add(struct bat_priv *bat_priv, struct vis_info *info) { if (list_empty(&info->send_list)) { kref_get(&info->refcount); list_add_tail(&info->send_list, &bat_priv->vis_send_list); } } /* delete the info packet from the send list, if it was * linked in. */ static void send_list_del(struct vis_info *info) { if (!list_empty(&info->send_list)) { list_del_init(&info->send_list); kref_put(&info->refcount, free_info); } } /* tries to add one entry to the receive list. */ static void recv_list_add(struct bat_priv *bat_priv, struct list_head *recv_list, const char *mac) { struct recvlist_node *entry; entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->mac, mac, ETH_ALEN); spin_lock_bh(&bat_priv->vis_list_lock); list_add_tail(&entry->list, recv_list); spin_unlock_bh(&bat_priv->vis_list_lock); } /* returns 1 if this mac is in the recv_list */ static int recv_list_is_in(struct bat_priv *bat_priv, const struct list_head *recv_list, const char *mac) { const struct recvlist_node *entry; spin_lock_bh(&bat_priv->vis_list_lock); list_for_each_entry(entry, recv_list, list) { if (compare_eth(entry->mac, mac)) { spin_unlock_bh(&bat_priv->vis_list_lock); return 1; } } spin_unlock_bh(&bat_priv->vis_list_lock); return 0; } /* try to add the packet to the vis_hash. return NULL if invalid (e.g. too old, * broken.. ). vis hash must be locked outside. is_new is set when the packet * is newer than old entries in the hash. */ static struct vis_info *add_packet(struct bat_priv *bat_priv, struct vis_packet *vis_packet, int vis_info_len, int *is_new, int make_broadcast) { struct vis_info *info, *old_info; struct vis_packet *search_packet, *old_packet; struct vis_info search_elem; struct vis_packet *packet; int hash_added; *is_new = 0; /* sanity check */ if (!bat_priv->vis_hash) return NULL; /* see if the packet is already in vis_hash */ search_elem.skb_packet = dev_alloc_skb(sizeof(*search_packet)); if (!search_elem.skb_packet) return NULL; search_packet = (struct vis_packet *)skb_put(search_elem.skb_packet, sizeof(*search_packet)); memcpy(search_packet->vis_orig, vis_packet->vis_orig, ETH_ALEN); old_info = vis_hash_find(bat_priv, &search_elem); kfree_skb(search_elem.skb_packet); if (old_info) { old_packet = (struct vis_packet *)old_info->skb_packet->data; if (!seq_after(ntohl(vis_packet->seqno), ntohl(old_packet->seqno))) { if (old_packet->seqno == vis_packet->seqno) { recv_list_add(bat_priv, &old_info->recv_list, vis_packet->sender_orig); return old_info; } else { /* newer packet is already in hash. */ return NULL; } } /* remove old entry */ hash_remove(bat_priv->vis_hash, vis_info_cmp, vis_info_choose, old_info); send_list_del(old_info); kref_put(&old_info->refcount, free_info); } info = kmalloc(sizeof(*info), GFP_ATOMIC); if (!info) return NULL; info->skb_packet = dev_alloc_skb(sizeof(*packet) + vis_info_len + sizeof(struct ethhdr)); if (!info->skb_packet) { kfree(info); return NULL; } skb_reserve(info->skb_packet, sizeof(struct ethhdr)); packet = (struct vis_packet *)skb_put(info->skb_packet, sizeof(*packet) + vis_info_len); kref_init(&info->refcount); INIT_LIST_HEAD(&info->send_list); INIT_LIST_HEAD(&info->recv_list); info->first_seen = jiffies; info->bat_priv = bat_priv; memcpy(packet, vis_packet, sizeof(*packet) + vis_info_len); /* initialize and add new packet. */ *is_new = 1; /* Make it a broadcast packet, if required */ if (make_broadcast) memcpy(packet->target_orig, broadcast_addr, ETH_ALEN); /* repair if entries is longer than packet. */ if (packet->entries * sizeof(struct vis_info_entry) > vis_info_len) packet->entries = vis_info_len / sizeof(struct vis_info_entry); recv_list_add(bat_priv, &info->recv_list, packet->sender_orig); /* try to add it */ hash_added = hash_add(bat_priv->vis_hash, vis_info_cmp, vis_info_choose, info, &info->hash_entry); if (hash_added != 0) { /* did not work (for some reason) */ kref_put(&info->refcount, free_info); info = NULL; } return info; } /* handle the server sync packet, forward if needed. */ void receive_server_sync_packet(struct bat_priv *bat_priv, struct vis_packet *vis_packet, int vis_info_len) { struct vis_info *info; int is_new, make_broadcast; int vis_server = atomic_read(&bat_priv->vis_mode); make_broadcast = (vis_server == VIS_TYPE_SERVER_SYNC); spin_lock_bh(&bat_priv->vis_hash_lock); info = add_packet(bat_priv, vis_packet, vis_info_len, &is_new, make_broadcast); if (!info) goto end; /* only if we are server ourselves and packet is newer than the one in * hash.*/ if (vis_server == VIS_TYPE_SERVER_SYNC && is_new) send_list_add(bat_priv, info); end: spin_unlock_bh(&bat_priv->vis_hash_lock); } /* handle an incoming client update packet and schedule forward if needed. */ void receive_client_update_packet(struct bat_priv *bat_priv, struct vis_packet *vis_packet, int vis_info_len) { struct vis_info *info; struct vis_packet *packet; int is_new; int vis_server = atomic_read(&bat_priv->vis_mode); int are_target = 0; /* clients shall not broadcast. */ if (is_broadcast_ether_addr(vis_packet->target_orig)) return; /* Are we the target for this VIS packet? */ if (vis_server == VIS_TYPE_SERVER_SYNC && is_my_mac(vis_packet->target_orig)) are_target = 1; spin_lock_bh(&bat_priv->vis_hash_lock); info = add_packet(bat_priv, vis_packet, vis_info_len, &is_new, are_target); if (!info) goto end; /* note that outdated packets will be dropped at this point. */ packet = (struct vis_packet *)info->skb_packet->data; /* send only if we're the target server or ... */ if (are_target && is_new) { packet->vis_type = VIS_TYPE_SERVER_SYNC; /* upgrade! */ send_list_add(bat_priv, info); /* ... we're not the recipient (and thus need to forward). */ } else if (!is_my_mac(packet->target_orig)) { send_list_add(bat_priv, info); } end: spin_unlock_bh(&bat_priv->vis_hash_lock); } /* Walk the originators and find the VIS server with the best tq. Set the packet * address to its address and return the best_tq. * * Must be called with the originator hash locked */ static int find_best_vis_server(struct bat_priv *bat_priv, struct vis_info *info) { struct hashtable_t *hash = bat_priv->orig_hash; struct neigh_node *router; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; struct vis_packet *packet; int best_tq = -1; uint32_t i; packet = (struct vis_packet *)info->skb_packet->data; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { router = orig_node_get_router(orig_node); if (!router) continue; if ((orig_node->flags & VIS_SERVER) && (router->tq_avg > best_tq)) { best_tq = router->tq_avg; memcpy(packet->target_orig, orig_node->orig, ETH_ALEN); } neigh_node_free_ref(router); } rcu_read_unlock(); } return best_tq; } /* Return true if the vis packet is full. */ static bool vis_packet_full(const struct vis_info *info) { const struct vis_packet *packet; packet = (struct vis_packet *)info->skb_packet->data; if (MAX_VIS_PACKET_SIZE / sizeof(struct vis_info_entry) < packet->entries + 1) return true; return false; } /* generates a packet of own vis data, * returns 0 on success, -1 if no packet could be generated */ static int generate_vis_packet(struct bat_priv *bat_priv) { struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; struct neigh_node *router; struct vis_info *info = bat_priv->my_vis_info; struct vis_packet *packet = (struct vis_packet *)info->skb_packet->data; struct vis_info_entry *entry; struct tt_common_entry *tt_common_entry; int best_tq = -1; uint32_t i; info->first_seen = jiffies; packet->vis_type = atomic_read(&bat_priv->vis_mode); memcpy(packet->target_orig, broadcast_addr, ETH_ALEN); packet->header.ttl = TTL; packet->seqno = htonl(ntohl(packet->seqno) + 1); packet->entries = 0; skb_trim(info->skb_packet, sizeof(*packet)); if (packet->vis_type == VIS_TYPE_CLIENT_UPDATE) { best_tq = find_best_vis_server(bat_priv, info); if (best_tq < 0) return -1; } for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { router = orig_node_get_router(orig_node); if (!router) continue; if (!compare_eth(router->addr, orig_node->orig)) goto next; if (router->if_incoming->if_status != IF_ACTIVE) goto next; if (router->tq_avg < 1) goto next; /* fill one entry into buffer. */ entry = (struct vis_info_entry *) skb_put(info->skb_packet, sizeof(*entry)); memcpy(entry->src, router->if_incoming->net_dev->dev_addr, ETH_ALEN); memcpy(entry->dest, orig_node->orig, ETH_ALEN); entry->quality = router->tq_avg; packet->entries++; next: neigh_node_free_ref(router); if (vis_packet_full(info)) goto unlock; } rcu_read_unlock(); } hash = bat_priv->tt_local_hash; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(tt_common_entry, node, head, hash_entry) { entry = (struct vis_info_entry *) skb_put(info->skb_packet, sizeof(*entry)); memset(entry->src, 0, ETH_ALEN); memcpy(entry->dest, tt_common_entry->addr, ETH_ALEN); entry->quality = 0; /* 0 means TT */ packet->entries++; if (vis_packet_full(info)) goto unlock; } rcu_read_unlock(); } return 0; unlock: rcu_read_unlock(); return 0; } /* free old vis packets. Must be called with this vis_hash_lock * held */ static void purge_vis_packets(struct bat_priv *bat_priv) { uint32_t i; struct hashtable_t *hash = bat_priv->vis_hash; struct hlist_node *node, *node_tmp; struct hlist_head *head; struct vis_info *info; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; hlist_for_each_entry_safe(info, node, node_tmp, head, hash_entry) { /* never purge own data. */ if (info == bat_priv->my_vis_info) continue; if (has_timed_out(info->first_seen, VIS_TIMEOUT)) { hlist_del(node); send_list_del(info); kref_put(&info->refcount, free_info); } } } } static void broadcast_vis_packet(struct bat_priv *bat_priv, struct vis_info *info) { struct neigh_node *router; struct hashtable_t *hash = bat_priv->orig_hash; struct hlist_node *node; struct hlist_head *head; struct orig_node *orig_node; struct vis_packet *packet; struct sk_buff *skb; struct hard_iface *hard_iface; uint8_t dstaddr[ETH_ALEN]; uint32_t i; packet = (struct vis_packet *)info->skb_packet->data; /* send to all routers in range. */ for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) { /* if it's a vis server and reachable, send it. */ if (!(orig_node->flags & VIS_SERVER)) continue; router = orig_node_get_router(orig_node); if (!router) continue; /* don't send it if we already received the packet from * this node. */ if (recv_list_is_in(bat_priv, &info->recv_list, orig_node->orig)) { neigh_node_free_ref(router); continue; } memcpy(packet->target_orig, orig_node->orig, ETH_ALEN); hard_iface = router->if_incoming; memcpy(dstaddr, router->addr, ETH_ALEN); neigh_node_free_ref(router); skb = skb_clone(info->skb_packet, GFP_ATOMIC); if (skb) send_skb_packet(skb, hard_iface, dstaddr); } rcu_read_unlock(); } } static void unicast_vis_packet(struct bat_priv *bat_priv, struct vis_info *info) { struct orig_node *orig_node; struct neigh_node *router = NULL; struct sk_buff *skb; struct vis_packet *packet; packet = (struct vis_packet *)info->skb_packet->data; orig_node = orig_hash_find(bat_priv, packet->target_orig); if (!orig_node) goto out; router = orig_node_get_router(orig_node); if (!router) goto out; skb = skb_clone(info->skb_packet, GFP_ATOMIC); if (skb) send_skb_packet(skb, router->if_incoming, router->addr); out: if (router) neigh_node_free_ref(router); if (orig_node) orig_node_free_ref(orig_node); } /* only send one vis packet. called from send_vis_packets() */ static void send_vis_packet(struct bat_priv *bat_priv, struct vis_info *info) { struct hard_iface *primary_if; struct vis_packet *packet; primary_if = primary_if_get_selected(bat_priv); if (!primary_if) goto out; packet = (struct vis_packet *)info->skb_packet->data; if (packet->header.ttl < 2) { pr_debug("Error - can't send vis packet: ttl exceeded\n"); goto out; } memcpy(packet->sender_orig, primary_if->net_dev->dev_addr, ETH_ALEN); packet->header.ttl--; if (is_broadcast_ether_addr(packet->target_orig)) broadcast_vis_packet(bat_priv, info); else unicast_vis_packet(bat_priv, info); packet->header.ttl++; /* restore TTL */ out: if (primary_if) hardif_free_ref(primary_if); } /* called from timer; send (and maybe generate) vis packet. */ static void send_vis_packets(struct work_struct *work) { struct delayed_work *delayed_work = container_of(work, struct delayed_work, work); struct bat_priv *bat_priv = container_of(delayed_work, struct bat_priv, vis_work); struct vis_info *info; spin_lock_bh(&bat_priv->vis_hash_lock); purge_vis_packets(bat_priv); if (generate_vis_packet(bat_priv) == 0) { /* schedule if generation was successful */ send_list_add(bat_priv, bat_priv->my_vis_info); } while (!list_empty(&bat_priv->vis_send_list)) { info = list_first_entry(&bat_priv->vis_send_list, typeof(*info), send_list); kref_get(&info->refcount); spin_unlock_bh(&bat_priv->vis_hash_lock); send_vis_packet(bat_priv, info); spin_lock_bh(&bat_priv->vis_hash_lock); send_list_del(info); kref_put(&info->refcount, free_info); } spin_unlock_bh(&bat_priv->vis_hash_lock); start_vis_timer(bat_priv); } /* init the vis server. this may only be called when if_list is already * initialized (e.g. bat0 is initialized, interfaces have been added) */ int vis_init(struct bat_priv *bat_priv) { struct vis_packet *packet; int hash_added; if (bat_priv->vis_hash) return 1; spin_lock_bh(&bat_priv->vis_hash_lock); bat_priv->vis_hash = hash_new(256); if (!bat_priv->vis_hash) { pr_err("Can't initialize vis_hash\n"); goto err; } bat_priv->my_vis_info = kmalloc(MAX_VIS_PACKET_SIZE, GFP_ATOMIC); if (!bat_priv->my_vis_info) goto err; bat_priv->my_vis_info->skb_packet = dev_alloc_skb(sizeof(*packet) + MAX_VIS_PACKET_SIZE + sizeof(struct ethhdr)); if (!bat_priv->my_vis_info->skb_packet) goto free_info; skb_reserve(bat_priv->my_vis_info->skb_packet, sizeof(struct ethhdr)); packet = (struct vis_packet *)skb_put(bat_priv->my_vis_info->skb_packet, sizeof(*packet)); /* prefill the vis info */ bat_priv->my_vis_info->first_seen = jiffies - msecs_to_jiffies(VIS_INTERVAL); INIT_LIST_HEAD(&bat_priv->my_vis_info->recv_list); INIT_LIST_HEAD(&bat_priv->my_vis_info->send_list); kref_init(&bat_priv->my_vis_info->refcount); bat_priv->my_vis_info->bat_priv = bat_priv; packet->header.version = COMPAT_VERSION; packet->header.packet_type = BAT_VIS; packet->header.ttl = TTL; packet->seqno = 0; packet->entries = 0; INIT_LIST_HEAD(&bat_priv->vis_send_list); hash_added = hash_add(bat_priv->vis_hash, vis_info_cmp, vis_info_choose, bat_priv->my_vis_info, &bat_priv->my_vis_info->hash_entry); if (hash_added != 0) { pr_err("Can't add own vis packet into hash\n"); /* not in hash, need to remove it manually. */ kref_put(&bat_priv->my_vis_info->refcount, free_info); goto err; } spin_unlock_bh(&bat_priv->vis_hash_lock); start_vis_timer(bat_priv); return 1; free_info: kfree(bat_priv->my_vis_info); bat_priv->my_vis_info = NULL; err: spin_unlock_bh(&bat_priv->vis_hash_lock); vis_quit(bat_priv); return 0; } /* Decrease the reference count on a hash item info */ static void free_info_ref(struct hlist_node *node, void *arg) { struct vis_info *info; info = container_of(node, struct vis_info, hash_entry); send_list_del(info); kref_put(&info->refcount, free_info); } /* shutdown vis-server */ void vis_quit(struct bat_priv *bat_priv) { if (!bat_priv->vis_hash) return; cancel_delayed_work_sync(&bat_priv->vis_work); spin_lock_bh(&bat_priv->vis_hash_lock); /* properly remove, kill timers ... */ hash_delete(bat_priv->vis_hash, free_info_ref, NULL); bat_priv->vis_hash = NULL; bat_priv->my_vis_info = NULL; spin_unlock_bh(&bat_priv->vis_hash_lock); } /* schedule packets for (re)transmission */ static void start_vis_timer(struct bat_priv *bat_priv) { INIT_DELAYED_WORK(&bat_priv->vis_work, send_vis_packets); queue_delayed_work(bat_event_workqueue, &bat_priv->vis_work, msecs_to_jiffies(VIS_INTERVAL)); }
gpl-2.0
StelixROM/android_kernel_google_msm
drivers/rtc/rtc-m41t93.c
4809
5700
/* * * Driver for ST M41T93 SPI RTC * * (c) 2010 Nikolaus Voss, Weinmann Medical GmbH * * 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/bcd.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/rtc.h> #include <linux/spi/spi.h> #define M41T93_REG_SSEC 0 #define M41T93_REG_ST_SEC 1 #define M41T93_REG_MIN 2 #define M41T93_REG_CENT_HOUR 3 #define M41T93_REG_WDAY 4 #define M41T93_REG_DAY 5 #define M41T93_REG_MON 6 #define M41T93_REG_YEAR 7 #define M41T93_REG_ALM_HOUR_HT 0xc #define M41T93_REG_FLAGS 0xf #define M41T93_FLAG_ST (1 << 7) #define M41T93_FLAG_OF (1 << 2) #define M41T93_FLAG_BL (1 << 4) #define M41T93_FLAG_HT (1 << 6) static inline int m41t93_set_reg(struct spi_device *spi, u8 addr, u8 data) { u8 buf[2]; /* MSB must be '1' to write */ buf[0] = addr | 0x80; buf[1] = data; return spi_write(spi, buf, sizeof(buf)); } static int m41t93_set_time(struct device *dev, struct rtc_time *tm) { struct spi_device *spi = to_spi_device(dev); u8 buf[9] = {0x80}; /* write cmd + 8 data bytes */ u8 * const data = &buf[1]; /* ptr to first data byte */ dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n", "write", tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); if (tm->tm_year < 100) { dev_warn(&spi->dev, "unsupported date (before 2000-01-01).\n"); return -EINVAL; } data[M41T93_REG_SSEC] = 0; data[M41T93_REG_ST_SEC] = bin2bcd(tm->tm_sec); data[M41T93_REG_MIN] = bin2bcd(tm->tm_min); data[M41T93_REG_CENT_HOUR] = bin2bcd(tm->tm_hour) | ((tm->tm_year/100-1) << 6); data[M41T93_REG_DAY] = bin2bcd(tm->tm_mday); data[M41T93_REG_WDAY] = bin2bcd(tm->tm_wday + 1); data[M41T93_REG_MON] = bin2bcd(tm->tm_mon + 1); data[M41T93_REG_YEAR] = bin2bcd(tm->tm_year % 100); return spi_write(spi, buf, sizeof(buf)); } static int m41t93_get_time(struct device *dev, struct rtc_time *tm) { struct spi_device *spi = to_spi_device(dev); const u8 start_addr = 0; u8 buf[8]; int century_after_1900; int tmp; int ret = 0; /* Check status of clock. Two states must be considered: 1. halt bit (HT) is set: the clock is running but update of readout registers has been disabled due to power failure. This is normal case after poweron. Time is valid after resetting HT bit. 2. oscillator fail bit (OF) is set. Oscillator has be stopped and time is invalid: a) OF can be immeditely reset. b) OF cannot be immediately reset: oscillator has to be restarted. */ tmp = spi_w8r8(spi, M41T93_REG_ALM_HOUR_HT); if (tmp < 0) return tmp; if (tmp & M41T93_FLAG_HT) { dev_dbg(&spi->dev, "HT bit is set, reenable clock update.\n"); m41t93_set_reg(spi, M41T93_REG_ALM_HOUR_HT, tmp & ~M41T93_FLAG_HT); } tmp = spi_w8r8(spi, M41T93_REG_FLAGS); if (tmp < 0) return tmp; if (tmp & M41T93_FLAG_OF) { ret = -EINVAL; dev_warn(&spi->dev, "OF bit is set, resetting.\n"); m41t93_set_reg(spi, M41T93_REG_FLAGS, tmp & ~M41T93_FLAG_OF); tmp = spi_w8r8(spi, M41T93_REG_FLAGS); if (tmp < 0) return tmp; else if (tmp & M41T93_FLAG_OF) { u8 reset_osc = buf[M41T93_REG_ST_SEC] | M41T93_FLAG_ST; dev_warn(&spi->dev, "OF bit is still set, kickstarting clock.\n"); m41t93_set_reg(spi, M41T93_REG_ST_SEC, reset_osc); reset_osc &= ~M41T93_FLAG_ST; m41t93_set_reg(spi, M41T93_REG_ST_SEC, reset_osc); } } if (tmp & M41T93_FLAG_BL) dev_warn(&spi->dev, "BL bit is set, replace battery.\n"); /* read actual time/date */ tmp = spi_write_then_read(spi, &start_addr, 1, buf, sizeof(buf)); if (tmp < 0) return tmp; tm->tm_sec = bcd2bin(buf[M41T93_REG_ST_SEC]); tm->tm_min = bcd2bin(buf[M41T93_REG_MIN]); tm->tm_hour = bcd2bin(buf[M41T93_REG_CENT_HOUR] & 0x3f); tm->tm_mday = bcd2bin(buf[M41T93_REG_DAY]); tm->tm_mon = bcd2bin(buf[M41T93_REG_MON]) - 1; tm->tm_wday = bcd2bin(buf[M41T93_REG_WDAY] & 0x0f) - 1; century_after_1900 = (buf[M41T93_REG_CENT_HOUR] >> 6) + 1; tm->tm_year = bcd2bin(buf[M41T93_REG_YEAR]) + century_after_1900 * 100; dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n", "read", tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); return ret < 0 ? ret : rtc_valid_tm(tm); } static const struct rtc_class_ops m41t93_rtc_ops = { .read_time = m41t93_get_time, .set_time = m41t93_set_time, }; static struct spi_driver m41t93_driver; static int __devinit m41t93_probe(struct spi_device *spi) { struct rtc_device *rtc; int res; spi->bits_per_word = 8; spi_setup(spi); res = spi_w8r8(spi, M41T93_REG_WDAY); if (res < 0 || (res & 0xf8) != 0) { dev_err(&spi->dev, "not found 0x%x.\n", res); return -ENODEV; } rtc = rtc_device_register(m41t93_driver.driver.name, &spi->dev, &m41t93_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) return PTR_ERR(rtc); dev_set_drvdata(&spi->dev, rtc); return 0; } static int __devexit m41t93_remove(struct spi_device *spi) { struct rtc_device *rtc = spi_get_drvdata(spi); if (rtc) rtc_device_unregister(rtc); return 0; } static struct spi_driver m41t93_driver = { .driver = { .name = "rtc-m41t93", .owner = THIS_MODULE, }, .probe = m41t93_probe, .remove = __devexit_p(m41t93_remove), }; module_spi_driver(m41t93_driver); MODULE_AUTHOR("Nikolaus Voss <n.voss@weinmann.de>"); MODULE_DESCRIPTION("Driver for ST M41T93 SPI RTC"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:rtc-m41t93");
gpl-2.0
Dm47021/LGE_Kernel_F6mt
drivers/staging/tidspbridge/core/io_sm.c
4809
62256
/* * io_sm.c * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * IO dispatcher for a shared memory channel driver. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* * Channel Invariant: * There is an important invariant condition which must be maintained per * channel outside of bridge_chnl_get_ioc() and IO_Dispatch(), violation of * which may cause timeouts and/or failure of the sync_wait_on_event * function. */ #include <linux/types.h> #include <linux/list.h> /* Host OS */ #include <dspbridge/host_os.h> #include <linux/workqueue.h> /* ----------------------------------- DSP/BIOS Bridge */ #include <dspbridge/dbdefs.h> /* Services Layer */ #include <dspbridge/ntfy.h> #include <dspbridge/sync.h> /* Hardware Abstraction Layer */ #include <hw_defs.h> #include <hw_mmu.h> /* Bridge Driver */ #include <dspbridge/dspdeh.h> #include <dspbridge/dspio.h> #include <dspbridge/dspioctl.h> #include <dspbridge/wdt.h> #include <_tiomap.h> #include <tiomap_io.h> #include <_tiomap_pwr.h> /* Platform Manager */ #include <dspbridge/cod.h> #include <dspbridge/node.h> #include <dspbridge/dev.h> /* Others */ #include <dspbridge/rms_sh.h> #include <dspbridge/mgr.h> #include <dspbridge/drv.h> #include "_cmm.h" #include "module_list.h" /* This */ #include <dspbridge/io_sm.h> #include "_msg_sm.h" /* Defines, Data Structures, Typedefs */ #define OUTPUTNOTREADY 0xffff #define NOTENABLED 0xffff /* Channel(s) not enabled */ #define EXTEND "_EXT_END" #define SWAP_WORD(x) (x) #define UL_PAGE_ALIGN_SIZE 0x10000 /* Page Align Size */ #define MAX_PM_REQS 32 #define MMU_FAULT_HEAD1 0xa5a5a5a5 #define MMU_FAULT_HEAD2 0x96969696 #define POLL_MAX 1000 #define MAX_MMU_DBGBUFF 10240 /* IO Manager: only one created per board */ struct io_mgr { /* These four fields must be the first fields in a io_mgr_ struct */ /* Bridge device context */ struct bridge_dev_context *bridge_context; /* Function interface to Bridge driver */ struct bridge_drv_interface *intf_fxns; struct dev_object *dev_obj; /* Device this board represents */ /* These fields initialized in bridge_io_create() */ struct chnl_mgr *chnl_mgr; struct shm *shared_mem; /* Shared Memory control */ u8 *input; /* Address of input channel */ u8 *output; /* Address of output channel */ struct msg_mgr *msg_mgr; /* Message manager */ /* Msg control for from DSP messages */ struct msg_ctrl *msg_input_ctrl; /* Msg control for to DSP messages */ struct msg_ctrl *msg_output_ctrl; u8 *msg_input; /* Address of input messages */ u8 *msg_output; /* Address of output messages */ u32 sm_buf_size; /* Size of a shared memory I/O channel */ bool shared_irq; /* Is this IRQ shared? */ u32 word_size; /* Size in bytes of DSP word */ u16 intr_val; /* Interrupt value */ /* Private extnd proc info; mmu setup */ struct mgr_processorextinfo ext_proc_info; struct cmm_object *cmm_mgr; /* Shared Mem Mngr */ struct work_struct io_workq; /* workqueue */ #if defined(CONFIG_TIDSPBRIDGE_BACKTRACE) u32 trace_buffer_begin; /* Trace message start address */ u32 trace_buffer_end; /* Trace message end address */ u32 trace_buffer_current; /* Trace message current address */ u32 gpp_read_pointer; /* GPP Read pointer to Trace buffer */ u8 *msg; u32 gpp_va; u32 dsp_va; #endif /* IO Dpc */ u32 dpc_req; /* Number of requested DPC's. */ u32 dpc_sched; /* Number of executed DPC's. */ struct tasklet_struct dpc_tasklet; spinlock_t dpc_lock; }; /* Function Prototypes */ static void io_dispatch_pm(struct io_mgr *pio_mgr); static void notify_chnl_complete(struct chnl_object *pchnl, struct chnl_irp *chnl_packet_obj); static void input_chnl(struct io_mgr *pio_mgr, struct chnl_object *pchnl, u8 io_mode); static void output_chnl(struct io_mgr *pio_mgr, struct chnl_object *pchnl, u8 io_mode); static void input_msg(struct io_mgr *pio_mgr, struct msg_mgr *hmsg_mgr); static void output_msg(struct io_mgr *pio_mgr, struct msg_mgr *hmsg_mgr); static u32 find_ready_output(struct chnl_mgr *chnl_mgr_obj, struct chnl_object *pchnl, u32 mask); /* Bus Addr (cached kernel) */ static int register_shm_segs(struct io_mgr *hio_mgr, struct cod_manager *cod_man, u32 dw_gpp_base_pa); static inline void set_chnl_free(struct shm *sm, u32 chnl) { sm->host_free_mask &= ~(1 << chnl); } static inline void set_chnl_busy(struct shm *sm, u32 chnl) { sm->host_free_mask |= 1 << chnl; } /* * ======== bridge_io_create ======== * Create an IO manager object. */ int bridge_io_create(struct io_mgr **io_man, struct dev_object *hdev_obj, const struct io_attrs *mgr_attrts) { struct io_mgr *pio_mgr = NULL; struct bridge_dev_context *hbridge_context = NULL; struct cfg_devnode *dev_node_obj; struct chnl_mgr *hchnl_mgr; u8 dev_type; /* Check requirements */ if (!io_man || !mgr_attrts || mgr_attrts->word_size == 0) return -EFAULT; *io_man = NULL; dev_get_chnl_mgr(hdev_obj, &hchnl_mgr); if (!hchnl_mgr || hchnl_mgr->iomgr) return -EFAULT; /* * Message manager will be created when a file is loaded, since * size of message buffer in shared memory is configurable in * the base image. */ dev_get_bridge_context(hdev_obj, &hbridge_context); if (!hbridge_context) return -EFAULT; dev_get_dev_type(hdev_obj, &dev_type); /* Allocate IO manager object */ pio_mgr = kzalloc(sizeof(struct io_mgr), GFP_KERNEL); if (!pio_mgr) return -ENOMEM; /* Initialize chnl_mgr object */ pio_mgr->chnl_mgr = hchnl_mgr; pio_mgr->word_size = mgr_attrts->word_size; if (dev_type == DSP_UNIT) { /* Create an IO DPC */ tasklet_init(&pio_mgr->dpc_tasklet, io_dpc, (u32) pio_mgr); /* Initialize DPC counters */ pio_mgr->dpc_req = 0; pio_mgr->dpc_sched = 0; spin_lock_init(&pio_mgr->dpc_lock); if (dev_get_dev_node(hdev_obj, &dev_node_obj)) { bridge_io_destroy(pio_mgr); return -EIO; } } pio_mgr->bridge_context = hbridge_context; pio_mgr->shared_irq = mgr_attrts->irq_shared; if (dsp_wdt_init()) { bridge_io_destroy(pio_mgr); return -EPERM; } /* Return IO manager object to caller... */ hchnl_mgr->iomgr = pio_mgr; *io_man = pio_mgr; return 0; } /* * ======== bridge_io_destroy ======== * Purpose: * Disable interrupts, destroy the IO manager. */ int bridge_io_destroy(struct io_mgr *hio_mgr) { int status = 0; if (hio_mgr) { /* Free IO DPC object */ tasklet_kill(&hio_mgr->dpc_tasklet); #if defined(CONFIG_TIDSPBRIDGE_BACKTRACE) kfree(hio_mgr->msg); #endif dsp_wdt_exit(); /* Free this IO manager object */ kfree(hio_mgr); } else { status = -EFAULT; } return status; } /* * ======== bridge_io_on_loaded ======== * Purpose: * Called when a new program is loaded to get shared memory buffer * parameters from COFF file. ulSharedBufferBase and ulSharedBufferLimit * are in DSP address units. */ int bridge_io_on_loaded(struct io_mgr *hio_mgr) { struct cod_manager *cod_man; struct chnl_mgr *hchnl_mgr; struct msg_mgr *hmsg_mgr; u32 ul_shm_base; u32 ul_shm_base_offset; u32 ul_shm_limit; u32 ul_shm_length = -1; u32 ul_mem_length = -1; u32 ul_msg_base; u32 ul_msg_limit; u32 ul_msg_length = -1; u32 ul_ext_end; u32 ul_gpp_pa = 0; u32 ul_gpp_va = 0; u32 ul_dsp_va = 0; u32 ul_seg_size = 0; u32 ul_pad_size = 0; u32 i; int status = 0; u8 num_procs = 0; s32 ndx = 0; /* DSP MMU setup table */ struct bridge_ioctl_extproc ae_proc[BRDIOCTL_NUMOFMMUTLB]; struct cfg_hostres *host_res; struct bridge_dev_context *pbridge_context; u32 map_attrs; u32 shm0_end; u32 ul_dyn_ext_base; u32 ul_seg1_size = 0; u32 pa_curr = 0; u32 va_curr = 0; u32 gpp_va_curr = 0; u32 num_bytes = 0; u32 all_bits = 0; u32 page_size[] = { HW_PAGE_SIZE16MB, HW_PAGE_SIZE1MB, HW_PAGE_SIZE64KB, HW_PAGE_SIZE4KB }; status = dev_get_bridge_context(hio_mgr->dev_obj, &pbridge_context); if (!pbridge_context) { status = -EFAULT; goto func_end; } host_res = pbridge_context->resources; if (!host_res) { status = -EFAULT; goto func_end; } status = dev_get_cod_mgr(hio_mgr->dev_obj, &cod_man); if (!cod_man) { status = -EFAULT; goto func_end; } hchnl_mgr = hio_mgr->chnl_mgr; /* The message manager is destroyed when the board is stopped. */ dev_get_msg_mgr(hio_mgr->dev_obj, &hio_mgr->msg_mgr); hmsg_mgr = hio_mgr->msg_mgr; if (!hchnl_mgr || !hmsg_mgr) { status = -EFAULT; goto func_end; } if (hio_mgr->shared_mem) hio_mgr->shared_mem = NULL; /* Get start and length of channel part of shared memory */ status = cod_get_sym_value(cod_man, CHNL_SHARED_BUFFER_BASE_SYM, &ul_shm_base); if (status) { status = -EFAULT; goto func_end; } status = cod_get_sym_value(cod_man, CHNL_SHARED_BUFFER_LIMIT_SYM, &ul_shm_limit); if (status) { status = -EFAULT; goto func_end; } if (ul_shm_limit <= ul_shm_base) { status = -EINVAL; goto func_end; } /* Get total length in bytes */ ul_shm_length = (ul_shm_limit - ul_shm_base + 1) * hio_mgr->word_size; /* Calculate size of a PROCCOPY shared memory region */ dev_dbg(bridge, "%s: (proc)proccopy shmmem size: 0x%x bytes\n", __func__, (ul_shm_length - sizeof(struct shm))); /* Get start and length of message part of shared memory */ status = cod_get_sym_value(cod_man, MSG_SHARED_BUFFER_BASE_SYM, &ul_msg_base); if (!status) { status = cod_get_sym_value(cod_man, MSG_SHARED_BUFFER_LIMIT_SYM, &ul_msg_limit); if (!status) { if (ul_msg_limit <= ul_msg_base) { status = -EINVAL; } else { /* * Length (bytes) of messaging part of shared * memory. */ ul_msg_length = (ul_msg_limit - ul_msg_base + 1) * hio_mgr->word_size; /* * Total length (bytes) of shared memory: * chnl + msg. */ ul_mem_length = ul_shm_length + ul_msg_length; } } else { status = -EFAULT; } } else { status = -EFAULT; } if (!status) { #if defined(CONFIG_TIDSPBRIDGE_BACKTRACE) status = cod_get_sym_value(cod_man, DSP_TRACESEC_END, &shm0_end); #else status = cod_get_sym_value(cod_man, SHM0_SHARED_END_SYM, &shm0_end); #endif if (status) status = -EFAULT; } if (!status) { status = cod_get_sym_value(cod_man, DYNEXTBASE, &ul_dyn_ext_base); if (status) status = -EFAULT; } if (!status) { status = cod_get_sym_value(cod_man, EXTEND, &ul_ext_end); if (status) status = -EFAULT; } if (!status) { /* Get memory reserved in host resources */ (void)mgr_enum_processor_info(0, (struct dsp_processorinfo *) &hio_mgr->ext_proc_info, sizeof(struct mgr_processorextinfo), &num_procs); /* The first MMU TLB entry(TLB_0) in DCD is ShmBase. */ ndx = 0; ul_gpp_pa = host_res->mem_phys[1]; ul_gpp_va = host_res->mem_base[1]; /* This is the virtual uncached ioremapped address!!! */ /* Why can't we directly take the DSPVA from the symbols? */ ul_dsp_va = hio_mgr->ext_proc_info.ty_tlb[0].dsp_virt; ul_seg_size = (shm0_end - ul_dsp_va) * hio_mgr->word_size; ul_seg1_size = (ul_ext_end - ul_dyn_ext_base) * hio_mgr->word_size; /* 4K align */ ul_seg1_size = (ul_seg1_size + 0xFFF) & (~0xFFFUL); /* 64K align */ ul_seg_size = (ul_seg_size + 0xFFFF) & (~0xFFFFUL); ul_pad_size = UL_PAGE_ALIGN_SIZE - ((ul_gpp_pa + ul_seg1_size) % UL_PAGE_ALIGN_SIZE); if (ul_pad_size == UL_PAGE_ALIGN_SIZE) ul_pad_size = 0x0; dev_dbg(bridge, "%s: ul_gpp_pa %x, ul_gpp_va %x, ul_dsp_va %x, " "shm0_end %x, ul_dyn_ext_base %x, ul_ext_end %x, " "ul_seg_size %x ul_seg1_size %x \n", __func__, ul_gpp_pa, ul_gpp_va, ul_dsp_va, shm0_end, ul_dyn_ext_base, ul_ext_end, ul_seg_size, ul_seg1_size); if ((ul_seg_size + ul_seg1_size + ul_pad_size) > host_res->mem_length[1]) { pr_err("%s: shm Error, reserved 0x%x required 0x%x\n", __func__, host_res->mem_length[1], ul_seg_size + ul_seg1_size + ul_pad_size); status = -ENOMEM; } } if (status) goto func_end; pa_curr = ul_gpp_pa; va_curr = ul_dyn_ext_base * hio_mgr->word_size; gpp_va_curr = ul_gpp_va; num_bytes = ul_seg1_size; /* * Try to fit into TLB entries. If not possible, push them to page * tables. It is quite possible that if sections are not on * bigger page boundary, we may end up making several small pages. * So, push them onto page tables, if that is the case. */ map_attrs = 0x00000000; map_attrs = DSP_MAPLITTLEENDIAN; map_attrs |= DSP_MAPPHYSICALADDR; map_attrs |= DSP_MAPELEMSIZE32; map_attrs |= DSP_MAPDONOTLOCK; while (num_bytes) { /* * To find the max. page size with which both PA & VA are * aligned. */ all_bits = pa_curr | va_curr; dev_dbg(bridge, "all_bits %x, pa_curr %x, va_curr %x, " "num_bytes %x\n", all_bits, pa_curr, va_curr, num_bytes); for (i = 0; i < 4; i++) { if ((num_bytes >= page_size[i]) && ((all_bits & (page_size[i] - 1)) == 0)) { status = hio_mgr->intf_fxns-> brd_mem_map(hio_mgr->bridge_context, pa_curr, va_curr, page_size[i], map_attrs, NULL); if (status) goto func_end; pa_curr += page_size[i]; va_curr += page_size[i]; gpp_va_curr += page_size[i]; num_bytes -= page_size[i]; /* * Don't try smaller sizes. Hopefully we have * reached an address aligned to a bigger page * size. */ break; } } } pa_curr += ul_pad_size; va_curr += ul_pad_size; gpp_va_curr += ul_pad_size; /* Configure the TLB entries for the next cacheable segment */ num_bytes = ul_seg_size; va_curr = ul_dsp_va * hio_mgr->word_size; while (num_bytes) { /* * To find the max. page size with which both PA & VA are * aligned. */ all_bits = pa_curr | va_curr; dev_dbg(bridge, "all_bits for Seg1 %x, pa_curr %x, " "va_curr %x, num_bytes %x\n", all_bits, pa_curr, va_curr, num_bytes); for (i = 0; i < 4; i++) { if (!(num_bytes >= page_size[i]) || !((all_bits & (page_size[i] - 1)) == 0)) continue; if (ndx < MAX_LOCK_TLB_ENTRIES) { /* * This is the physical address written to * DSP MMU. */ ae_proc[ndx].gpp_pa = pa_curr; /* * This is the virtual uncached ioremapped * address!!! */ ae_proc[ndx].gpp_va = gpp_va_curr; ae_proc[ndx].dsp_va = va_curr / hio_mgr->word_size; ae_proc[ndx].size = page_size[i]; ae_proc[ndx].endianism = HW_LITTLE_ENDIAN; ae_proc[ndx].elem_size = HW_ELEM_SIZE16BIT; ae_proc[ndx].mixed_mode = HW_MMU_CPUES; dev_dbg(bridge, "shm MMU TLB entry PA %x" " VA %x DSP_VA %x Size %x\n", ae_proc[ndx].gpp_pa, ae_proc[ndx].gpp_va, ae_proc[ndx].dsp_va * hio_mgr->word_size, page_size[i]); ndx++; } else { status = hio_mgr->intf_fxns-> brd_mem_map(hio_mgr->bridge_context, pa_curr, va_curr, page_size[i], map_attrs, NULL); dev_dbg(bridge, "shm MMU PTE entry PA %x" " VA %x DSP_VA %x Size %x\n", ae_proc[ndx].gpp_pa, ae_proc[ndx].gpp_va, ae_proc[ndx].dsp_va * hio_mgr->word_size, page_size[i]); if (status) goto func_end; } pa_curr += page_size[i]; va_curr += page_size[i]; gpp_va_curr += page_size[i]; num_bytes -= page_size[i]; /* * Don't try smaller sizes. Hopefully we have reached * an address aligned to a bigger page size. */ break; } } /* * Copy remaining entries from CDB. All entries are 1 MB and * should not conflict with shm entries on MPU or DSP side. */ for (i = 3; i < 7 && ndx < BRDIOCTL_NUMOFMMUTLB; i++) { if (hio_mgr->ext_proc_info.ty_tlb[i].gpp_phys == 0) continue; if ((hio_mgr->ext_proc_info.ty_tlb[i].gpp_phys > ul_gpp_pa - 0x100000 && hio_mgr->ext_proc_info.ty_tlb[i].gpp_phys <= ul_gpp_pa + ul_seg_size) || (hio_mgr->ext_proc_info.ty_tlb[i].dsp_virt > ul_dsp_va - 0x100000 / hio_mgr->word_size && hio_mgr->ext_proc_info.ty_tlb[i].dsp_virt <= ul_dsp_va + ul_seg_size / hio_mgr->word_size)) { dev_dbg(bridge, "CDB MMU entry %d conflicts with " "shm.\n\tCDB: GppPa %x, DspVa %x.\n\tSHM: " "GppPa %x, DspVa %x, Bytes %x.\n", i, hio_mgr->ext_proc_info.ty_tlb[i].gpp_phys, hio_mgr->ext_proc_info.ty_tlb[i].dsp_virt, ul_gpp_pa, ul_dsp_va, ul_seg_size); status = -EPERM; } else { if (ndx < MAX_LOCK_TLB_ENTRIES) { ae_proc[ndx].dsp_va = hio_mgr->ext_proc_info.ty_tlb[i]. dsp_virt; ae_proc[ndx].gpp_pa = hio_mgr->ext_proc_info.ty_tlb[i]. gpp_phys; ae_proc[ndx].gpp_va = 0; /* 1 MB */ ae_proc[ndx].size = 0x100000; dev_dbg(bridge, "shm MMU entry PA %x " "DSP_VA 0x%x\n", ae_proc[ndx].gpp_pa, ae_proc[ndx].dsp_va); ndx++; } else { status = hio_mgr->intf_fxns->brd_mem_map (hio_mgr->bridge_context, hio_mgr->ext_proc_info.ty_tlb[i]. gpp_phys, hio_mgr->ext_proc_info.ty_tlb[i]. dsp_virt, 0x100000, map_attrs, NULL); } } if (status) goto func_end; } map_attrs = 0x00000000; map_attrs = DSP_MAPLITTLEENDIAN; map_attrs |= DSP_MAPPHYSICALADDR; map_attrs |= DSP_MAPELEMSIZE32; map_attrs |= DSP_MAPDONOTLOCK; /* Map the L4 peripherals */ i = 0; while (l4_peripheral_table[i].phys_addr) { status = hio_mgr->intf_fxns->brd_mem_map (hio_mgr->bridge_context, l4_peripheral_table[i].phys_addr, l4_peripheral_table[i].dsp_virt_addr, HW_PAGE_SIZE4KB, map_attrs, NULL); if (status) goto func_end; i++; } for (i = ndx; i < BRDIOCTL_NUMOFMMUTLB; i++) { ae_proc[i].dsp_va = 0; ae_proc[i].gpp_pa = 0; ae_proc[i].gpp_va = 0; ae_proc[i].size = 0; } /* * Set the shm physical address entry (grayed out in CDB file) * to the virtual uncached ioremapped address of shm reserved * on MPU. */ hio_mgr->ext_proc_info.ty_tlb[0].gpp_phys = (ul_gpp_va + ul_seg1_size + ul_pad_size); /* * Need shm Phys addr. IO supports only one DSP for now: * num_procs = 1. */ if (!hio_mgr->ext_proc_info.ty_tlb[0].gpp_phys || num_procs != 1) { status = -EFAULT; goto func_end; } else { if (ae_proc[0].dsp_va > ul_shm_base) { status = -EPERM; goto func_end; } /* ul_shm_base may not be at ul_dsp_va address */ ul_shm_base_offset = (ul_shm_base - ae_proc[0].dsp_va) * hio_mgr->word_size; /* * bridge_dev_ctrl() will set dev context dsp-mmu info. In * bridge_brd_start() the MMU will be re-programed with MMU * DSPVa-GPPPa pair info while DSP is in a known * (reset) state. */ status = hio_mgr->intf_fxns->dev_cntrl(hio_mgr->bridge_context, BRDIOCTL_SETMMUCONFIG, ae_proc); if (status) goto func_end; ul_shm_base = hio_mgr->ext_proc_info.ty_tlb[0].gpp_phys; ul_shm_base += ul_shm_base_offset; ul_shm_base = (u32) MEM_LINEAR_ADDRESS((void *)ul_shm_base, ul_mem_length); if (ul_shm_base == 0) { status = -EFAULT; goto func_end; } /* Register SM */ status = register_shm_segs(hio_mgr, cod_man, ae_proc[0].gpp_pa); } hio_mgr->shared_mem = (struct shm *)ul_shm_base; hio_mgr->input = (u8 *) hio_mgr->shared_mem + sizeof(struct shm); hio_mgr->output = hio_mgr->input + (ul_shm_length - sizeof(struct shm)) / 2; hio_mgr->sm_buf_size = hio_mgr->output - hio_mgr->input; /* Set up Shared memory addresses for messaging. */ hio_mgr->msg_input_ctrl = (struct msg_ctrl *)((u8 *) hio_mgr->shared_mem + ul_shm_length); hio_mgr->msg_input = (u8 *) hio_mgr->msg_input_ctrl + sizeof(struct msg_ctrl); hio_mgr->msg_output_ctrl = (struct msg_ctrl *)((u8 *) hio_mgr->msg_input_ctrl + ul_msg_length / 2); hio_mgr->msg_output = (u8 *) hio_mgr->msg_output_ctrl + sizeof(struct msg_ctrl); hmsg_mgr->max_msgs = ((u8 *) hio_mgr->msg_output_ctrl - hio_mgr->msg_input) / sizeof(struct msg_dspmsg); dev_dbg(bridge, "IO MGR shm details: shared_mem %p, input %p, " "output %p, msg_input_ctrl %p, msg_input %p, " "msg_output_ctrl %p, msg_output %p\n", (u8 *) hio_mgr->shared_mem, hio_mgr->input, hio_mgr->output, (u8 *) hio_mgr->msg_input_ctrl, hio_mgr->msg_input, (u8 *) hio_mgr->msg_output_ctrl, hio_mgr->msg_output); dev_dbg(bridge, "(proc) Mas msgs in shared memory: 0x%x\n", hmsg_mgr->max_msgs); memset((void *)hio_mgr->shared_mem, 0, sizeof(struct shm)); #if defined(CONFIG_TIDSPBRIDGE_BACKTRACE) /* Get the start address of trace buffer */ status = cod_get_sym_value(cod_man, SYS_PUTCBEG, &hio_mgr->trace_buffer_begin); if (status) { status = -EFAULT; goto func_end; } hio_mgr->gpp_read_pointer = hio_mgr->trace_buffer_begin = (ul_gpp_va + ul_seg1_size + ul_pad_size) + (hio_mgr->trace_buffer_begin - ul_dsp_va); /* Get the end address of trace buffer */ status = cod_get_sym_value(cod_man, SYS_PUTCEND, &hio_mgr->trace_buffer_end); if (status) { status = -EFAULT; goto func_end; } hio_mgr->trace_buffer_end = (ul_gpp_va + ul_seg1_size + ul_pad_size) + (hio_mgr->trace_buffer_end - ul_dsp_va); /* Get the current address of DSP write pointer */ status = cod_get_sym_value(cod_man, BRIDGE_SYS_PUTC_CURRENT, &hio_mgr->trace_buffer_current); if (status) { status = -EFAULT; goto func_end; } hio_mgr->trace_buffer_current = (ul_gpp_va + ul_seg1_size + ul_pad_size) + (hio_mgr->trace_buffer_current - ul_dsp_va); /* Calculate the size of trace buffer */ kfree(hio_mgr->msg); hio_mgr->msg = kmalloc(((hio_mgr->trace_buffer_end - hio_mgr->trace_buffer_begin) * hio_mgr->word_size) + 2, GFP_KERNEL); if (!hio_mgr->msg) status = -ENOMEM; hio_mgr->dsp_va = ul_dsp_va; hio_mgr->gpp_va = (ul_gpp_va + ul_seg1_size + ul_pad_size); #endif func_end: return status; } /* * ======== io_buf_size ======== * Size of shared memory I/O channel. */ u32 io_buf_size(struct io_mgr *hio_mgr) { if (hio_mgr) return hio_mgr->sm_buf_size; else return 0; } /* * ======== io_cancel_chnl ======== * Cancel IO on a given PCPY channel. */ void io_cancel_chnl(struct io_mgr *hio_mgr, u32 chnl) { struct io_mgr *pio_mgr = (struct io_mgr *)hio_mgr; struct shm *sm; if (!hio_mgr) goto func_end; sm = hio_mgr->shared_mem; /* Inform DSP that we have no more buffers on this channel */ set_chnl_free(sm, chnl); sm_interrupt_dsp(pio_mgr->bridge_context, MBX_PCPY_CLASS); func_end: return; } /* * ======== io_dispatch_pm ======== * Performs I/O dispatch on PM related messages from DSP */ static void io_dispatch_pm(struct io_mgr *pio_mgr) { int status; u32 parg[2]; /* Perform Power message processing here */ parg[0] = pio_mgr->intr_val; /* Send the command to the Bridge clk/pwr manager to handle */ if (parg[0] == MBX_PM_HIBERNATE_EN) { dev_dbg(bridge, "PM: Hibernate command\n"); status = pio_mgr->intf_fxns-> dev_cntrl(pio_mgr->bridge_context, BRDIOCTL_PWR_HIBERNATE, parg); if (status) pr_err("%s: hibernate cmd failed 0x%x\n", __func__, status); } else if (parg[0] == MBX_PM_OPP_REQ) { parg[1] = pio_mgr->shared_mem->opp_request.rqst_opp_pt; dev_dbg(bridge, "PM: Requested OPP = 0x%x\n", parg[1]); status = pio_mgr->intf_fxns-> dev_cntrl(pio_mgr->bridge_context, BRDIOCTL_CONSTRAINT_REQUEST, parg); if (status) dev_dbg(bridge, "PM: Failed to set constraint " "= 0x%x\n", parg[1]); } else { dev_dbg(bridge, "PM: clk control value of msg = 0x%x\n", parg[0]); status = pio_mgr->intf_fxns-> dev_cntrl(pio_mgr->bridge_context, BRDIOCTL_CLK_CTRL, parg); if (status) dev_dbg(bridge, "PM: Failed to ctrl the DSP clk" "= 0x%x\n", *parg); } } /* * ======== io_dpc ======== * Deferred procedure call for shared memory channel driver ISR. Carries * out the dispatch of I/O as a non-preemptible event.It can only be * pre-empted by an ISR. */ void io_dpc(unsigned long ref_data) { struct io_mgr *pio_mgr = (struct io_mgr *)ref_data; struct chnl_mgr *chnl_mgr_obj; struct msg_mgr *msg_mgr_obj; struct deh_mgr *hdeh_mgr; u32 requested; u32 serviced; if (!pio_mgr) goto func_end; chnl_mgr_obj = pio_mgr->chnl_mgr; dev_get_msg_mgr(pio_mgr->dev_obj, &msg_mgr_obj); dev_get_deh_mgr(pio_mgr->dev_obj, &hdeh_mgr); if (!chnl_mgr_obj) goto func_end; requested = pio_mgr->dpc_req; serviced = pio_mgr->dpc_sched; if (serviced == requested) goto func_end; /* Process pending DPC's */ do { /* Check value of interrupt reg to ensure it's a valid error */ if ((pio_mgr->intr_val > DEH_BASE) && (pio_mgr->intr_val < DEH_LIMIT)) { /* Notify DSP/BIOS exception */ if (hdeh_mgr) { #ifdef CONFIG_TIDSPBRIDGE_BACKTRACE print_dsp_debug_trace(pio_mgr); #endif bridge_deh_notify(hdeh_mgr, DSP_SYSERROR, pio_mgr->intr_val); } } /* Proc-copy chanel dispatch */ input_chnl(pio_mgr, NULL, IO_SERVICE); output_chnl(pio_mgr, NULL, IO_SERVICE); #ifdef CHNL_MESSAGES if (msg_mgr_obj) { /* Perform I/O dispatch on message queues */ input_msg(pio_mgr, msg_mgr_obj); output_msg(pio_mgr, msg_mgr_obj); } #endif #ifdef CONFIG_TIDSPBRIDGE_BACKTRACE if (pio_mgr->intr_val & MBX_DBG_SYSPRINTF) { /* Notify DSP Trace message */ print_dsp_debug_trace(pio_mgr); } #endif serviced++; } while (serviced != requested); pio_mgr->dpc_sched = requested; func_end: return; } /* * ======== io_mbox_msg ======== * Main interrupt handler for the shared memory IO manager. * Calls the Bridge's CHNL_ISR to determine if this interrupt is ours, then * schedules a DPC to dispatch I/O. */ int io_mbox_msg(struct notifier_block *self, unsigned long len, void *msg) { struct io_mgr *pio_mgr; struct dev_object *dev_obj; unsigned long flags; dev_obj = dev_get_first(); dev_get_io_mgr(dev_obj, &pio_mgr); if (!pio_mgr) return NOTIFY_BAD; pio_mgr->intr_val = (u16)((u32)msg); if (pio_mgr->intr_val & MBX_PM_CLASS) io_dispatch_pm(pio_mgr); if (pio_mgr->intr_val == MBX_DEH_RESET) { pio_mgr->intr_val = 0; } else { spin_lock_irqsave(&pio_mgr->dpc_lock, flags); pio_mgr->dpc_req++; spin_unlock_irqrestore(&pio_mgr->dpc_lock, flags); tasklet_schedule(&pio_mgr->dpc_tasklet); } return NOTIFY_OK; } /* * ======== io_request_chnl ======== * Purpose: * Request chanenel I/O from the DSP. Sets flags in shared memory, then * interrupts the DSP. */ void io_request_chnl(struct io_mgr *io_manager, struct chnl_object *pchnl, u8 io_mode, u16 *mbx_val) { struct chnl_mgr *chnl_mgr_obj; struct shm *sm; if (!pchnl || !mbx_val) goto func_end; chnl_mgr_obj = io_manager->chnl_mgr; sm = io_manager->shared_mem; if (io_mode == IO_INPUT) { /* Indicate to the DSP we have a buffer available for input */ set_chnl_busy(sm, pchnl->chnl_id); *mbx_val = MBX_PCPY_CLASS; } else if (io_mode == IO_OUTPUT) { /* * Record the fact that we have a buffer available for * output. */ chnl_mgr_obj->output_mask |= (1 << pchnl->chnl_id); } else { } func_end: return; } /* * ======== iosm_schedule ======== * Schedule DPC for IO. */ void iosm_schedule(struct io_mgr *io_manager) { unsigned long flags; if (!io_manager) return; /* Increment count of DPC's pending. */ spin_lock_irqsave(&io_manager->dpc_lock, flags); io_manager->dpc_req++; spin_unlock_irqrestore(&io_manager->dpc_lock, flags); /* Schedule DPC */ tasklet_schedule(&io_manager->dpc_tasklet); } /* * ======== find_ready_output ======== * Search for a host output channel which is ready to send. If this is * called as a result of servicing the DPC, then implement a round * robin search; otherwise, this was called by a client thread (via * IO_Dispatch()), so just start searching from the current channel id. */ static u32 find_ready_output(struct chnl_mgr *chnl_mgr_obj, struct chnl_object *pchnl, u32 mask) { u32 ret = OUTPUTNOTREADY; u32 id, start_id; u32 shift; id = (pchnl != NULL ? pchnl->chnl_id : (chnl_mgr_obj->last_output + 1)); id = ((id == CHNL_MAXCHANNELS) ? 0 : id); if (id >= CHNL_MAXCHANNELS) goto func_end; if (mask) { shift = (1 << id); start_id = id; do { if (mask & shift) { ret = id; if (pchnl == NULL) chnl_mgr_obj->last_output = id; break; } id = id + 1; id = ((id == CHNL_MAXCHANNELS) ? 0 : id); shift = (1 << id); } while (id != start_id); } func_end: return ret; } /* * ======== input_chnl ======== * Dispatch a buffer on an input channel. */ static void input_chnl(struct io_mgr *pio_mgr, struct chnl_object *pchnl, u8 io_mode) { struct chnl_mgr *chnl_mgr_obj; struct shm *sm; u32 chnl_id; u32 bytes; struct chnl_irp *chnl_packet_obj = NULL; u32 dw_arg; bool clear_chnl = false; bool notify_client = false; sm = pio_mgr->shared_mem; chnl_mgr_obj = pio_mgr->chnl_mgr; /* Attempt to perform input */ if (!sm->input_full) goto func_end; bytes = sm->input_size * chnl_mgr_obj->word_size; chnl_id = sm->input_id; dw_arg = sm->arg; if (chnl_id >= CHNL_MAXCHANNELS) { /* Shouldn't be here: would indicate corrupted shm. */ goto func_end; } pchnl = chnl_mgr_obj->channels[chnl_id]; if ((pchnl != NULL) && CHNL_IS_INPUT(pchnl->chnl_mode)) { if ((pchnl->state & ~CHNL_STATEEOS) == CHNL_STATEREADY) { /* Get the I/O request, and attempt a transfer */ if (!list_empty(&pchnl->io_requests)) { if (!pchnl->cio_reqs) goto func_end; chnl_packet_obj = list_first_entry( &pchnl->io_requests, struct chnl_irp, link); list_del(&chnl_packet_obj->link); pchnl->cio_reqs--; /* * Ensure we don't overflow the client's * buffer. */ bytes = min(bytes, chnl_packet_obj->byte_size); memcpy(chnl_packet_obj->host_sys_buf, pio_mgr->input, bytes); pchnl->bytes_moved += bytes; chnl_packet_obj->byte_size = bytes; chnl_packet_obj->arg = dw_arg; chnl_packet_obj->status = CHNL_IOCSTATCOMPLETE; if (bytes == 0) { /* * This assertion fails if the DSP * sends EOS more than once on this * channel. */ if (pchnl->state & CHNL_STATEEOS) goto func_end; /* * Zero bytes indicates EOS. Update * IOC status for this chirp, and also * the channel state. */ chnl_packet_obj->status |= CHNL_IOCSTATEOS; pchnl->state |= CHNL_STATEEOS; /* * Notify that end of stream has * occurred. */ ntfy_notify(pchnl->ntfy_obj, DSP_STREAMDONE); } /* Tell DSP if no more I/O buffers available */ if (list_empty(&pchnl->io_requests)) set_chnl_free(sm, pchnl->chnl_id); clear_chnl = true; notify_client = true; } else { /* * Input full for this channel, but we have no * buffers available. The channel must be * "idling". Clear out the physical input * channel. */ clear_chnl = true; } } else { /* Input channel cancelled: clear input channel */ clear_chnl = true; } } else { /* DPC fired after host closed channel: clear input channel */ clear_chnl = true; } if (clear_chnl) { /* Indicate to the DSP we have read the input */ sm->input_full = 0; sm_interrupt_dsp(pio_mgr->bridge_context, MBX_PCPY_CLASS); } if (notify_client) { /* Notify client with IO completion record */ notify_chnl_complete(pchnl, chnl_packet_obj); } func_end: return; } /* * ======== input_msg ======== * Copies messages from shared memory to the message queues. */ static void input_msg(struct io_mgr *pio_mgr, struct msg_mgr *hmsg_mgr) { u32 num_msgs; u32 i; u8 *msg_input; struct msg_queue *msg_queue_obj; struct msg_frame *pmsg; struct msg_dspmsg msg; struct msg_ctrl *msg_ctr_obj; u32 input_empty; u32 addr; msg_ctr_obj = pio_mgr->msg_input_ctrl; /* Get the number of input messages to be read */ input_empty = msg_ctr_obj->buf_empty; num_msgs = msg_ctr_obj->size; if (input_empty) return; msg_input = pio_mgr->msg_input; for (i = 0; i < num_msgs; i++) { /* Read the next message */ addr = (u32) &(((struct msg_dspmsg *)msg_input)->msg.cmd); msg.msg.cmd = read_ext32_bit_dsp_data(pio_mgr->bridge_context, addr); addr = (u32) &(((struct msg_dspmsg *)msg_input)->msg.arg1); msg.msg.arg1 = read_ext32_bit_dsp_data(pio_mgr->bridge_context, addr); addr = (u32) &(((struct msg_dspmsg *)msg_input)->msg.arg2); msg.msg.arg2 = read_ext32_bit_dsp_data(pio_mgr->bridge_context, addr); addr = (u32) &(((struct msg_dspmsg *)msg_input)->msgq_id); msg.msgq_id = read_ext32_bit_dsp_data(pio_mgr->bridge_context, addr); msg_input += sizeof(struct msg_dspmsg); /* Determine which queue to put the message in */ dev_dbg(bridge, "input msg: cmd=0x%x arg1=0x%x " "arg2=0x%x msgq_id=0x%x\n", msg.msg.cmd, msg.msg.arg1, msg.msg.arg2, msg.msgq_id); /* * Interrupt may occur before shared memory and message * input locations have been set up. If all nodes were * cleaned up, hmsg_mgr->max_msgs should be 0. */ list_for_each_entry(msg_queue_obj, &hmsg_mgr->queue_list, list_elem) { if (msg.msgq_id != msg_queue_obj->msgq_id) continue; /* Found it */ if (msg.msg.cmd == RMS_EXITACK) { /* * Call the node exit notification. * The exit message does not get * queued. */ (*hmsg_mgr->on_exit)(msg_queue_obj->arg, msg.msg.arg1); break; } /* * Not an exit acknowledgement, queue * the message. */ if (list_empty(&msg_queue_obj->msg_free_list)) { /* * No free frame to copy the * message into. */ pr_err("%s: no free msg frames," " discarding msg\n", __func__); break; } pmsg = list_first_entry(&msg_queue_obj->msg_free_list, struct msg_frame, list_elem); list_del(&pmsg->list_elem); pmsg->msg_data = msg; list_add_tail(&pmsg->list_elem, &msg_queue_obj->msg_used_list); ntfy_notify(msg_queue_obj->ntfy_obj, DSP_NODEMESSAGEREADY); sync_set_event(msg_queue_obj->sync_event); } } /* Set the post SWI flag */ if (num_msgs > 0) { /* Tell the DSP we've read the messages */ msg_ctr_obj->buf_empty = true; msg_ctr_obj->post_swi = true; sm_interrupt_dsp(pio_mgr->bridge_context, MBX_PCPY_CLASS); } } /* * ======== notify_chnl_complete ======== * Purpose: * Signal the channel event, notifying the client that I/O has completed. */ static void notify_chnl_complete(struct chnl_object *pchnl, struct chnl_irp *chnl_packet_obj) { bool signal_event; if (!pchnl || !pchnl->sync_event || !chnl_packet_obj) goto func_end; /* * Note: we signal the channel event only if the queue of IO * completions is empty. If it is not empty, the event is sure to be * signalled by the only IO completion list consumer: * bridge_chnl_get_ioc(). */ signal_event = list_empty(&pchnl->io_completions); /* Enqueue the IO completion info for the client */ list_add_tail(&chnl_packet_obj->link, &pchnl->io_completions); pchnl->cio_cs++; if (pchnl->cio_cs > pchnl->chnl_packets) goto func_end; /* Signal the channel event (if not already set) that IO is complete */ if (signal_event) sync_set_event(pchnl->sync_event); /* Notify that IO is complete */ ntfy_notify(pchnl->ntfy_obj, DSP_STREAMIOCOMPLETION); func_end: return; } /* * ======== output_chnl ======== * Purpose: * Dispatch a buffer on an output channel. */ static void output_chnl(struct io_mgr *pio_mgr, struct chnl_object *pchnl, u8 io_mode) { struct chnl_mgr *chnl_mgr_obj; struct shm *sm; u32 chnl_id; struct chnl_irp *chnl_packet_obj; u32 dw_dsp_f_mask; chnl_mgr_obj = pio_mgr->chnl_mgr; sm = pio_mgr->shared_mem; /* Attempt to perform output */ if (sm->output_full) goto func_end; if (pchnl && !((pchnl->state & ~CHNL_STATEEOS) == CHNL_STATEREADY)) goto func_end; /* Look to see if both a PC and DSP output channel are ready */ dw_dsp_f_mask = sm->dsp_free_mask; chnl_id = find_ready_output(chnl_mgr_obj, pchnl, (chnl_mgr_obj->output_mask & dw_dsp_f_mask)); if (chnl_id == OUTPUTNOTREADY) goto func_end; pchnl = chnl_mgr_obj->channels[chnl_id]; if (!pchnl || list_empty(&pchnl->io_requests)) { /* Shouldn't get here */ goto func_end; } if (!pchnl->cio_reqs) goto func_end; /* Get the I/O request, and attempt a transfer */ chnl_packet_obj = list_first_entry(&pchnl->io_requests, struct chnl_irp, link); list_del(&chnl_packet_obj->link); pchnl->cio_reqs--; /* Record fact that no more I/O buffers available */ if (list_empty(&pchnl->io_requests)) chnl_mgr_obj->output_mask &= ~(1 << chnl_id); /* Transfer buffer to DSP side */ chnl_packet_obj->byte_size = min(pio_mgr->sm_buf_size, chnl_packet_obj->byte_size); memcpy(pio_mgr->output, chnl_packet_obj->host_sys_buf, chnl_packet_obj->byte_size); pchnl->bytes_moved += chnl_packet_obj->byte_size; /* Write all 32 bits of arg */ sm->arg = chnl_packet_obj->arg; #if _CHNL_WORDSIZE == 2 /* Access can be different SM access word size (e.g. 16/32 bit words) */ sm->output_id = (u16) chnl_id; sm->output_size = (u16) (chnl_packet_obj->byte_size + chnl_mgr_obj->word_size - 1) / (u16) chnl_mgr_obj->word_size; #else sm->output_id = chnl_id; sm->output_size = (chnl_packet_obj->byte_size + chnl_mgr_obj->word_size - 1) / chnl_mgr_obj->word_size; #endif sm->output_full = 1; /* Indicate to the DSP we have written the output */ sm_interrupt_dsp(pio_mgr->bridge_context, MBX_PCPY_CLASS); /* Notify client with IO completion record (keep EOS) */ chnl_packet_obj->status &= CHNL_IOCSTATEOS; notify_chnl_complete(pchnl, chnl_packet_obj); /* Notify if stream is done. */ if (chnl_packet_obj->status & CHNL_IOCSTATEOS) ntfy_notify(pchnl->ntfy_obj, DSP_STREAMDONE); func_end: return; } /* * ======== output_msg ======== * Copies messages from the message queues to the shared memory. */ static void output_msg(struct io_mgr *pio_mgr, struct msg_mgr *hmsg_mgr) { u32 num_msgs = 0; u32 i; struct msg_dspmsg *msg_output; struct msg_frame *pmsg; struct msg_ctrl *msg_ctr_obj; u32 val; u32 addr; msg_ctr_obj = pio_mgr->msg_output_ctrl; /* Check if output has been cleared */ if (!msg_ctr_obj->buf_empty) return; num_msgs = (hmsg_mgr->msgs_pending > hmsg_mgr->max_msgs) ? hmsg_mgr->max_msgs : hmsg_mgr->msgs_pending; msg_output = (struct msg_dspmsg *) pio_mgr->msg_output; /* Copy num_msgs messages into shared memory */ for (i = 0; i < num_msgs; i++) { if (list_empty(&hmsg_mgr->msg_used_list)) continue; pmsg = list_first_entry(&hmsg_mgr->msg_used_list, struct msg_frame, list_elem); list_del(&pmsg->list_elem); val = (pmsg->msg_data).msgq_id; addr = (u32) &msg_output->msgq_id; write_ext32_bit_dsp_data(pio_mgr->bridge_context, addr, val); val = (pmsg->msg_data).msg.cmd; addr = (u32) &msg_output->msg.cmd; write_ext32_bit_dsp_data(pio_mgr->bridge_context, addr, val); val = (pmsg->msg_data).msg.arg1; addr = (u32) &msg_output->msg.arg1; write_ext32_bit_dsp_data(pio_mgr->bridge_context, addr, val); val = (pmsg->msg_data).msg.arg2; addr = (u32) &msg_output->msg.arg2; write_ext32_bit_dsp_data(pio_mgr->bridge_context, addr, val); msg_output++; list_add_tail(&pmsg->list_elem, &hmsg_mgr->msg_free_list); sync_set_event(hmsg_mgr->sync_event); } if (num_msgs > 0) { hmsg_mgr->msgs_pending -= num_msgs; #if _CHNL_WORDSIZE == 2 /* * Access can be different SM access word size * (e.g. 16/32 bit words) */ msg_ctr_obj->size = (u16) num_msgs; #else msg_ctr_obj->size = num_msgs; #endif msg_ctr_obj->buf_empty = false; /* Set the post SWI flag */ msg_ctr_obj->post_swi = true; /* Tell the DSP we have written the output. */ sm_interrupt_dsp(pio_mgr->bridge_context, MBX_PCPY_CLASS); } } /* * ======== register_shm_segs ======== * purpose: * Registers GPP SM segment with CMM. */ static int register_shm_segs(struct io_mgr *hio_mgr, struct cod_manager *cod_man, u32 dw_gpp_base_pa) { int status = 0; u32 ul_shm0_base = 0; u32 shm0_end = 0; u32 ul_shm0_rsrvd_start = 0; u32 ul_rsrvd_size = 0; u32 ul_gpp_phys; u32 ul_dsp_virt; u32 ul_shm_seg_id0 = 0; u32 dw_offset, dw_gpp_base_va, ul_dsp_size; /* * Read address and size info for first SM region. * Get start of 1st SM Heap region. */ status = cod_get_sym_value(cod_man, SHM0_SHARED_BASE_SYM, &ul_shm0_base); if (ul_shm0_base == 0) { status = -EPERM; goto func_end; } /* Get end of 1st SM Heap region */ if (!status) { /* Get start and length of message part of shared memory */ status = cod_get_sym_value(cod_man, SHM0_SHARED_END_SYM, &shm0_end); if (shm0_end == 0) { status = -EPERM; goto func_end; } } /* Start of Gpp reserved region */ if (!status) { /* Get start and length of message part of shared memory */ status = cod_get_sym_value(cod_man, SHM0_SHARED_RESERVED_BASE_SYM, &ul_shm0_rsrvd_start); if (ul_shm0_rsrvd_start == 0) { status = -EPERM; goto func_end; } } /* Register with CMM */ if (!status) { status = dev_get_cmm_mgr(hio_mgr->dev_obj, &hio_mgr->cmm_mgr); if (!status) { status = cmm_un_register_gppsm_seg(hio_mgr->cmm_mgr, CMM_ALLSEGMENTS); } } /* Register new SM region(s) */ if (!status && (shm0_end - ul_shm0_base) > 0) { /* Calc size (bytes) of SM the GPP can alloc from */ ul_rsrvd_size = (shm0_end - ul_shm0_rsrvd_start + 1) * hio_mgr->word_size; if (ul_rsrvd_size <= 0) { status = -EPERM; goto func_end; } /* Calc size of SM DSP can alloc from */ ul_dsp_size = (ul_shm0_rsrvd_start - ul_shm0_base) * hio_mgr->word_size; if (ul_dsp_size <= 0) { status = -EPERM; goto func_end; } /* First TLB entry reserved for Bridge SM use. */ ul_gpp_phys = hio_mgr->ext_proc_info.ty_tlb[0].gpp_phys; /* Get size in bytes */ ul_dsp_virt = hio_mgr->ext_proc_info.ty_tlb[0].dsp_virt * hio_mgr->word_size; /* * Calc byte offset used to convert GPP phys <-> DSP byte * address. */ if (dw_gpp_base_pa > ul_dsp_virt) dw_offset = dw_gpp_base_pa - ul_dsp_virt; else dw_offset = ul_dsp_virt - dw_gpp_base_pa; if (ul_shm0_rsrvd_start * hio_mgr->word_size < ul_dsp_virt) { status = -EPERM; goto func_end; } /* * Calc Gpp phys base of SM region. * This is actually uncached kernel virtual address. */ dw_gpp_base_va = ul_gpp_phys + ul_shm0_rsrvd_start * hio_mgr->word_size - ul_dsp_virt; /* * Calc Gpp phys base of SM region. * This is the physical address. */ dw_gpp_base_pa = dw_gpp_base_pa + ul_shm0_rsrvd_start * hio_mgr->word_size - ul_dsp_virt; /* Register SM Segment 0. */ status = cmm_register_gppsm_seg(hio_mgr->cmm_mgr, dw_gpp_base_pa, ul_rsrvd_size, dw_offset, (dw_gpp_base_pa > ul_dsp_virt) ? CMM_ADDTODSPPA : CMM_SUBFROMDSPPA, (u32) (ul_shm0_base * hio_mgr->word_size), ul_dsp_size, &ul_shm_seg_id0, dw_gpp_base_va); /* First SM region is seg_id = 1 */ if (ul_shm_seg_id0 != 1) status = -EPERM; } func_end: return status; } /* ZCPY IO routines. */ /* * ======== IO_SHMcontrol ======== * Sets the requested shm setting. */ int io_sh_msetting(struct io_mgr *hio_mgr, u8 desc, void *pargs) { #ifdef CONFIG_TIDSPBRIDGE_DVFS u32 i; struct dspbridge_platform_data *pdata = omap_dspbridge_dev->dev.platform_data; switch (desc) { case SHM_CURROPP: /* Update the shared memory with requested OPP information */ if (pargs != NULL) hio_mgr->shared_mem->opp_table_struct.curr_opp_pt = *(u32 *) pargs; else return -EPERM; break; case SHM_OPPINFO: /* * Update the shared memory with the voltage, frequency, * min and max frequency values for an OPP. */ for (i = 0; i <= dsp_max_opps; i++) { hio_mgr->shared_mem->opp_table_struct.opp_point[i]. voltage = vdd1_dsp_freq[i][0]; dev_dbg(bridge, "OPP-shm: voltage: %d\n", vdd1_dsp_freq[i][0]); hio_mgr->shared_mem->opp_table_struct. opp_point[i].frequency = vdd1_dsp_freq[i][1]; dev_dbg(bridge, "OPP-shm: frequency: %d\n", vdd1_dsp_freq[i][1]); hio_mgr->shared_mem->opp_table_struct.opp_point[i]. min_freq = vdd1_dsp_freq[i][2]; dev_dbg(bridge, "OPP-shm: min freq: %d\n", vdd1_dsp_freq[i][2]); hio_mgr->shared_mem->opp_table_struct.opp_point[i]. max_freq = vdd1_dsp_freq[i][3]; dev_dbg(bridge, "OPP-shm: max freq: %d\n", vdd1_dsp_freq[i][3]); } hio_mgr->shared_mem->opp_table_struct.num_opp_pts = dsp_max_opps; dev_dbg(bridge, "OPP-shm: max OPP number: %d\n", dsp_max_opps); /* Update the current OPP number */ if (pdata->dsp_get_opp) i = (*pdata->dsp_get_opp) (); hio_mgr->shared_mem->opp_table_struct.curr_opp_pt = i; dev_dbg(bridge, "OPP-shm: value programmed = %d\n", i); break; case SHM_GETOPP: /* Get the OPP that DSP has requested */ *(u32 *) pargs = hio_mgr->shared_mem->opp_request.rqst_opp_pt; break; default: break; } #endif return 0; } /* * ======== bridge_io_get_proc_load ======== * Gets the Processor's Load information */ int bridge_io_get_proc_load(struct io_mgr *hio_mgr, struct dsp_procloadstat *proc_lstat) { if (!hio_mgr->shared_mem) return -EFAULT; proc_lstat->curr_load = hio_mgr->shared_mem->load_mon_info.curr_dsp_load; proc_lstat->predicted_load = hio_mgr->shared_mem->load_mon_info.pred_dsp_load; proc_lstat->curr_dsp_freq = hio_mgr->shared_mem->load_mon_info.curr_dsp_freq; proc_lstat->predicted_freq = hio_mgr->shared_mem->load_mon_info.pred_dsp_freq; dev_dbg(bridge, "Curr Load = %d, Pred Load = %d, Curr Freq = %d, " "Pred Freq = %d\n", proc_lstat->curr_load, proc_lstat->predicted_load, proc_lstat->curr_dsp_freq, proc_lstat->predicted_freq); return 0; } #if defined(CONFIG_TIDSPBRIDGE_BACKTRACE) void print_dsp_debug_trace(struct io_mgr *hio_mgr) { u32 ul_new_message_length = 0, ul_gpp_cur_pointer; while (true) { /* Get the DSP current pointer */ ul_gpp_cur_pointer = *(u32 *) (hio_mgr->trace_buffer_current); ul_gpp_cur_pointer = hio_mgr->gpp_va + (ul_gpp_cur_pointer - hio_mgr->dsp_va); /* No new debug messages available yet */ if (ul_gpp_cur_pointer == hio_mgr->gpp_read_pointer) { break; } else if (ul_gpp_cur_pointer > hio_mgr->gpp_read_pointer) { /* Continuous data */ ul_new_message_length = ul_gpp_cur_pointer - hio_mgr->gpp_read_pointer; memcpy(hio_mgr->msg, (char *)hio_mgr->gpp_read_pointer, ul_new_message_length); hio_mgr->msg[ul_new_message_length] = '\0'; /* * Advance the GPP trace pointer to DSP current * pointer. */ hio_mgr->gpp_read_pointer += ul_new_message_length; /* Print the trace messages */ pr_info("DSPTrace: %s\n", hio_mgr->msg); } else if (ul_gpp_cur_pointer < hio_mgr->gpp_read_pointer) { /* Handle trace buffer wraparound */ memcpy(hio_mgr->msg, (char *)hio_mgr->gpp_read_pointer, hio_mgr->trace_buffer_end - hio_mgr->gpp_read_pointer); ul_new_message_length = ul_gpp_cur_pointer - hio_mgr->trace_buffer_begin; memcpy(&hio_mgr->msg[hio_mgr->trace_buffer_end - hio_mgr->gpp_read_pointer], (char *)hio_mgr->trace_buffer_begin, ul_new_message_length); hio_mgr->msg[hio_mgr->trace_buffer_end - hio_mgr->gpp_read_pointer + ul_new_message_length] = '\0'; /* * Advance the GPP trace pointer to DSP current * pointer. */ hio_mgr->gpp_read_pointer = hio_mgr->trace_buffer_begin + ul_new_message_length; /* Print the trace messages */ pr_info("DSPTrace: %s\n", hio_mgr->msg); } } } #endif #ifdef CONFIG_TIDSPBRIDGE_BACKTRACE /* * ======== print_dsp_trace_buffer ======== * Prints the trace buffer returned from the DSP (if DBG_Trace is enabled). * Parameters: * hdeh_mgr: Handle to DEH manager object * number of extra carriage returns to generate. * Returns: * 0: Success. * -ENOMEM: Unable to allocate memory. * Requires: * hdeh_mgr muse be valid. Checked in bridge_deh_notify. */ int print_dsp_trace_buffer(struct bridge_dev_context *hbridge_context) { int status = 0; struct cod_manager *cod_mgr; u32 ul_trace_end; u32 ul_trace_begin; u32 trace_cur_pos; u32 ul_num_bytes = 0; u32 ul_num_words = 0; u32 ul_word_size = 2; char *psz_buf; char *str_beg; char *trace_end; char *buf_end; char *new_line; struct bridge_dev_context *pbridge_context = hbridge_context; struct bridge_drv_interface *intf_fxns; struct dev_object *dev_obj = (struct dev_object *) pbridge_context->dev_obj; status = dev_get_cod_mgr(dev_obj, &cod_mgr); if (cod_mgr) { /* Look for SYS_PUTCBEG/SYS_PUTCEND */ status = cod_get_sym_value(cod_mgr, COD_TRACEBEG, &ul_trace_begin); } else { status = -EFAULT; } if (!status) status = cod_get_sym_value(cod_mgr, COD_TRACEEND, &ul_trace_end); if (!status) /* trace_cur_pos will hold the address of a DSP pointer */ status = cod_get_sym_value(cod_mgr, COD_TRACECURPOS, &trace_cur_pos); if (status) goto func_end; ul_num_bytes = (ul_trace_end - ul_trace_begin); ul_num_words = ul_num_bytes * ul_word_size; status = dev_get_intf_fxns(dev_obj, &intf_fxns); if (status) goto func_end; psz_buf = kzalloc(ul_num_bytes + 2, GFP_ATOMIC); if (psz_buf != NULL) { /* Read trace buffer data */ status = (*intf_fxns->brd_read)(pbridge_context, (u8 *)psz_buf, (u32)ul_trace_begin, ul_num_bytes, 0); if (status) goto func_end; /* Pack and do newline conversion */ pr_debug("PrintDspTraceBuffer: " "before pack and unpack.\n"); pr_debug("%s: DSP Trace Buffer Begin:\n" "=======================\n%s\n", __func__, psz_buf); /* Read the value at the DSP address in trace_cur_pos. */ status = (*intf_fxns->brd_read)(pbridge_context, (u8 *)&trace_cur_pos, (u32)trace_cur_pos, 4, 0); if (status) goto func_end; /* Pack and do newline conversion */ pr_info("DSP Trace Buffer Begin:\n" "=======================\n%s\n", psz_buf); /* convert to offset */ trace_cur_pos = trace_cur_pos - ul_trace_begin; if (ul_num_bytes) { /* * The buffer is not full, find the end of the * data -- buf_end will be >= pszBuf after * while. */ buf_end = &psz_buf[ul_num_bytes+1]; /* DSP print position */ trace_end = &psz_buf[trace_cur_pos]; /* * Search buffer for a new_line and replace it * with '\0', then print as string. * Continue until end of buffer is reached. */ str_beg = trace_end; ul_num_bytes = buf_end - str_beg; while (str_beg < buf_end) { new_line = strnchr(str_beg, ul_num_bytes, '\n'); if (new_line && new_line < buf_end) { *new_line = 0; pr_debug("%s\n", str_beg); str_beg = ++new_line; ul_num_bytes = buf_end - str_beg; } else { /* * Assume buffer empty if it contains * a zero */ if (*str_beg != '\0') { str_beg[ul_num_bytes] = 0; pr_debug("%s\n", str_beg); } str_beg = buf_end; ul_num_bytes = 0; } } /* * Search buffer for a nNewLine and replace it * with '\0', then print as string. * Continue until buffer is exhausted. */ str_beg = psz_buf; ul_num_bytes = trace_end - str_beg; while (str_beg < trace_end) { new_line = strnchr(str_beg, ul_num_bytes, '\n'); if (new_line != NULL && new_line < trace_end) { *new_line = 0; pr_debug("%s\n", str_beg); str_beg = ++new_line; ul_num_bytes = trace_end - str_beg; } else { /* * Assume buffer empty if it contains * a zero */ if (*str_beg != '\0') { str_beg[ul_num_bytes] = 0; pr_debug("%s\n", str_beg); } str_beg = trace_end; ul_num_bytes = 0; } } } pr_info("\n=======================\n" "DSP Trace Buffer End:\n"); kfree(psz_buf); } else { status = -ENOMEM; } func_end: if (status) dev_dbg(bridge, "%s Failed, status 0x%x\n", __func__, status); return status; } /** * dump_dsp_stack() - This function dumps the data on the DSP stack. * @bridge_context: Bridge driver's device context pointer. * */ int dump_dsp_stack(struct bridge_dev_context *bridge_context) { int status = 0; struct cod_manager *code_mgr; struct node_mgr *node_mgr; u32 trace_begin; char name[256]; struct { u32 head[2]; u32 size; } mmu_fault_dbg_info; u32 *buffer; u32 *buffer_beg; u32 *buffer_end; u32 exc_type; u32 dyn_ext_base; u32 i; u32 offset_output; u32 total_size; u32 poll_cnt; const char *dsp_regs[] = {"EFR", "IERR", "ITSR", "NTSR", "IRP", "NRP", "AMR", "SSR", "ILC", "RILC", "IER", "CSR"}; const char *exec_ctxt[] = {"Task", "SWI", "HWI", "Unknown"}; struct bridge_drv_interface *intf_fxns; struct dev_object *dev_object = bridge_context->dev_obj; status = dev_get_cod_mgr(dev_object, &code_mgr); if (!code_mgr) { pr_debug("%s: Failed on dev_get_cod_mgr.\n", __func__); status = -EFAULT; } if (!status) { status = dev_get_node_manager(dev_object, &node_mgr); if (!node_mgr) { pr_debug("%s: Failed on dev_get_node_manager.\n", __func__); status = -EFAULT; } } if (!status) { /* Look for SYS_PUTCBEG/SYS_PUTCEND: */ status = cod_get_sym_value(code_mgr, COD_TRACEBEG, &trace_begin); pr_debug("%s: trace_begin Value 0x%x\n", __func__, trace_begin); if (status) pr_debug("%s: Failed on cod_get_sym_value.\n", __func__); } if (!status) status = dev_get_intf_fxns(dev_object, &intf_fxns); /* * Check for the "magic number" in the trace buffer. If it has * yet to appear then poll the trace buffer to wait for it. Its * appearance signals that the DSP has finished dumping its state. */ mmu_fault_dbg_info.head[0] = 0; mmu_fault_dbg_info.head[1] = 0; if (!status) { poll_cnt = 0; while ((mmu_fault_dbg_info.head[0] != MMU_FAULT_HEAD1 || mmu_fault_dbg_info.head[1] != MMU_FAULT_HEAD2) && poll_cnt < POLL_MAX) { /* Read DSP dump size from the DSP trace buffer... */ status = (*intf_fxns->brd_read)(bridge_context, (u8 *)&mmu_fault_dbg_info, (u32)trace_begin, sizeof(mmu_fault_dbg_info), 0); if (status) break; poll_cnt++; } if (mmu_fault_dbg_info.head[0] != MMU_FAULT_HEAD1 && mmu_fault_dbg_info.head[1] != MMU_FAULT_HEAD2) { status = -ETIME; pr_err("%s:No DSP MMU-Fault information available.\n", __func__); } } if (!status) { total_size = mmu_fault_dbg_info.size; /* Limit the size in case DSP went crazy */ if (total_size > MAX_MMU_DBGBUFF) total_size = MAX_MMU_DBGBUFF; buffer = kzalloc(total_size, GFP_ATOMIC); if (!buffer) { status = -ENOMEM; pr_debug("%s: Failed to " "allocate stack dump buffer.\n", __func__); goto func_end; } buffer_beg = buffer; buffer_end = buffer + total_size / 4; /* Read bytes from the DSP trace buffer... */ status = (*intf_fxns->brd_read)(bridge_context, (u8 *)buffer, (u32)trace_begin, total_size, 0); if (status) { pr_debug("%s: Failed to Read Trace Buffer.\n", __func__); goto func_end; } pr_err("\nAproximate Crash Position:\n" "--------------------------\n"); exc_type = buffer[3]; if (!exc_type) i = buffer[79]; /* IRP */ else i = buffer[80]; /* NRP */ status = cod_get_sym_value(code_mgr, DYNEXTBASE, &dyn_ext_base); if (status) { status = -EFAULT; goto func_end; } if ((i > dyn_ext_base) && (node_find_addr(node_mgr, i, 0x1000, &offset_output, name) == 0)) pr_err("0x%-8x [\"%s\" + 0x%x]\n", i, name, i - offset_output); else pr_err("0x%-8x [Unable to match to a symbol.]\n", i); buffer += 4; pr_err("\nExecution Info:\n" "---------------\n"); if (*buffer < ARRAY_SIZE(exec_ctxt)) { pr_err("Execution context \t%s\n", exec_ctxt[*buffer++]); } else { pr_err("Execution context corrupt\n"); kfree(buffer_beg); return -EFAULT; } pr_err("Task Handle\t\t0x%x\n", *buffer++); pr_err("Stack Pointer\t\t0x%x\n", *buffer++); pr_err("Stack Top\t\t0x%x\n", *buffer++); pr_err("Stack Bottom\t\t0x%x\n", *buffer++); pr_err("Stack Size\t\t0x%x\n", *buffer++); pr_err("Stack Size In Use\t0x%x\n", *buffer++); pr_err("\nCPU Registers\n" "---------------\n"); for (i = 0; i < 32; i++) { if (i == 4 || i == 6 || i == 8) pr_err("A%d 0x%-8x [Function Argument %d]\n", i, *buffer++, i-3); else if (i == 15) pr_err("A15 0x%-8x [Frame Pointer]\n", *buffer++); else pr_err("A%d 0x%x\n", i, *buffer++); } pr_err("\nB0 0x%x\n", *buffer++); pr_err("B1 0x%x\n", *buffer++); pr_err("B2 0x%x\n", *buffer++); if ((*buffer > dyn_ext_base) && (node_find_addr(node_mgr, *buffer, 0x1000, &offset_output, name) == 0)) pr_err("B3 0x%-8x [Function Return Pointer:" " \"%s\" + 0x%x]\n", *buffer, name, *buffer - offset_output); else pr_err("B3 0x%-8x [Function Return Pointer:" "Unable to match to a symbol.]\n", *buffer); buffer++; for (i = 4; i < 32; i++) { if (i == 4 || i == 6 || i == 8) pr_err("B%d 0x%-8x [Function Argument %d]\n", i, *buffer++, i-2); else if (i == 14) pr_err("B14 0x%-8x [Data Page Pointer]\n", *buffer++); else pr_err("B%d 0x%x\n", i, *buffer++); } pr_err("\n"); for (i = 0; i < ARRAY_SIZE(dsp_regs); i++) pr_err("%s 0x%x\n", dsp_regs[i], *buffer++); pr_err("\nStack:\n" "------\n"); for (i = 0; buffer < buffer_end; i++, buffer++) { if ((*buffer > dyn_ext_base) && ( node_find_addr(node_mgr, *buffer , 0x600, &offset_output, name) == 0)) pr_err("[%d] 0x%-8x [\"%s\" + 0x%x]\n", i, *buffer, name, *buffer - offset_output); else pr_err("[%d] 0x%x\n", i, *buffer); } kfree(buffer_beg); } func_end: return status; } /** * dump_dl_modules() - This functions dumps the _DLModules loaded in DSP side * @bridge_context: Bridge driver's device context pointer. * */ void dump_dl_modules(struct bridge_dev_context *bridge_context) { struct cod_manager *code_mgr; struct bridge_drv_interface *intf_fxns; struct bridge_dev_context *bridge_ctxt = bridge_context; struct dev_object *dev_object = bridge_ctxt->dev_obj; struct modules_header modules_hdr; struct dll_module *module_struct = NULL; u32 module_dsp_addr; u32 module_size; u32 module_struct_size = 0; u32 sect_ndx; char *sect_str ; int status = 0; status = dev_get_intf_fxns(dev_object, &intf_fxns); if (status) { pr_debug("%s: Failed on dev_get_intf_fxns.\n", __func__); goto func_end; } status = dev_get_cod_mgr(dev_object, &code_mgr); if (!code_mgr) { pr_debug("%s: Failed on dev_get_cod_mgr.\n", __func__); status = -EFAULT; goto func_end; } /* Lookup the address of the modules_header structure */ status = cod_get_sym_value(code_mgr, "_DLModules", &module_dsp_addr); if (status) { pr_debug("%s: Failed on cod_get_sym_value for _DLModules.\n", __func__); goto func_end; } pr_debug("%s: _DLModules at 0x%x\n", __func__, module_dsp_addr); /* Copy the modules_header structure from DSP memory. */ status = (*intf_fxns->brd_read)(bridge_context, (u8 *) &modules_hdr, (u32) module_dsp_addr, sizeof(modules_hdr), 0); if (status) { pr_debug("%s: Failed failed to read modules header.\n", __func__); goto func_end; } module_dsp_addr = modules_hdr.first_module; module_size = modules_hdr.first_module_size; pr_debug("%s: dll_module_header 0x%x %d\n", __func__, module_dsp_addr, module_size); pr_err("\nDynamically Loaded Modules:\n" "---------------------------\n"); /* For each dll_module structure in the list... */ while (module_size) { /* * Allocate/re-allocate memory to hold the dll_module * structure. The memory is re-allocated only if the existing * allocation is too small. */ if (module_size > module_struct_size) { kfree(module_struct); module_struct = kzalloc(module_size+128, GFP_ATOMIC); module_struct_size = module_size+128; pr_debug("%s: allocated module struct %p %d\n", __func__, module_struct, module_struct_size); if (!module_struct) goto func_end; } /* Copy the dll_module structure from DSP memory */ status = (*intf_fxns->brd_read)(bridge_context, (u8 *)module_struct, module_dsp_addr, module_size, 0); if (status) { pr_debug( "%s: Failed to read dll_module stuct for 0x%x.\n", __func__, module_dsp_addr); break; } /* Update info regarding the _next_ module in the list. */ module_dsp_addr = module_struct->next_module; module_size = module_struct->next_module_size; pr_debug("%s: next module 0x%x %d, this module num sects %d\n", __func__, module_dsp_addr, module_size, module_struct->num_sects); /* * The section name strings start immedialty following * the array of dll_sect structures. */ sect_str = (char *) &module_struct-> sects[module_struct->num_sects]; pr_err("%s\n", sect_str); /* * Advance to the first section name string. * Each string follows the one before. */ sect_str += strlen(sect_str) + 1; /* Access each dll_sect structure and its name string. */ for (sect_ndx = 0; sect_ndx < module_struct->num_sects; sect_ndx++) { pr_err(" Section: 0x%x ", module_struct->sects[sect_ndx].sect_load_adr); if (((u32) sect_str - (u32) module_struct) < module_struct_size) { pr_err("%s\n", sect_str); /* Each string follows the one before. */ sect_str += strlen(sect_str)+1; } else { pr_err("<string error>\n"); pr_debug("%s: section name sting address " "is invalid %p\n", __func__, sect_str); } } } func_end: kfree(module_struct); } #endif
gpl-2.0
davidmueller13/android_kernel_samsung_lt03lte
drivers/media/radio/radio-rtrack2.c
4809
3371
/* * RadioTrack II driver * Copyright 1998 Ben Pfaff * * Based on RadioTrack I/RadioReveal (C) 1997 M. Kirkwood * Converted to new API by Alan Cox <alan@lxorguk.ukuu.org.uk> * Various bugfixes and enhancements by Russell Kroll <rkroll@exploits.org> * * Converted to the radio-isa framework by Hans Verkuil <hans.verkuil@cisco.com> * Converted to V4L2 API by Mauro Carvalho Chehab <mchehab@infradead.org> */ #include <linux/module.h> /* Modules */ #include <linux/init.h> /* Initdata */ #include <linux/ioport.h> /* request_region */ #include <linux/delay.h> /* udelay */ #include <linux/videodev2.h> /* kernel radio structs */ #include <linux/mutex.h> #include <linux/io.h> /* outb, outb_p */ #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include "radio-isa.h" MODULE_AUTHOR("Ben Pfaff"); MODULE_DESCRIPTION("A driver for the RadioTrack II radio card."); MODULE_LICENSE("GPL"); MODULE_VERSION("0.1.99"); #ifndef CONFIG_RADIO_RTRACK2_PORT #define CONFIG_RADIO_RTRACK2_PORT -1 #endif #define RTRACK2_MAX 2 static int io[RTRACK2_MAX] = { [0] = CONFIG_RADIO_RTRACK2_PORT, [1 ... (RTRACK2_MAX - 1)] = -1 }; static int radio_nr[RTRACK2_MAX] = { [0 ... (RTRACK2_MAX - 1)] = -1 }; module_param_array(io, int, NULL, 0444); MODULE_PARM_DESC(io, "I/O addresses of the RadioTrack card (0x20f or 0x30f)"); module_param_array(radio_nr, int, NULL, 0444); MODULE_PARM_DESC(radio_nr, "Radio device numbers"); static struct radio_isa_card *rtrack2_alloc(void) { return kzalloc(sizeof(struct radio_isa_card), GFP_KERNEL); } static void zero(struct radio_isa_card *isa) { outb_p(1, isa->io); outb_p(3, isa->io); outb_p(1, isa->io); } static void one(struct radio_isa_card *isa) { outb_p(5, isa->io); outb_p(7, isa->io); outb_p(5, isa->io); } static int rtrack2_s_frequency(struct radio_isa_card *isa, u32 freq) { int i; freq = freq / 200 + 856; outb_p(0xc8, isa->io); outb_p(0xc9, isa->io); outb_p(0xc9, isa->io); for (i = 0; i < 10; i++) zero(isa); for (i = 14; i >= 0; i--) if (freq & (1 << i)) one(isa); else zero(isa); outb_p(0xc8, isa->io); if (!v4l2_ctrl_g_ctrl(isa->mute)) outb_p(0, isa->io); return 0; } static u32 rtrack2_g_signal(struct radio_isa_card *isa) { /* bit set = no signal present */ return (inb(isa->io) & 2) ? 0 : 0xffff; } static int rtrack2_s_mute_volume(struct radio_isa_card *isa, bool mute, int vol) { outb(mute, isa->io); return 0; } static const struct radio_isa_ops rtrack2_ops = { .alloc = rtrack2_alloc, .s_mute_volume = rtrack2_s_mute_volume, .s_frequency = rtrack2_s_frequency, .g_signal = rtrack2_g_signal, }; static const int rtrack2_ioports[] = { 0x20f, 0x30f }; static struct radio_isa_driver rtrack2_driver = { .driver = { .match = radio_isa_match, .probe = radio_isa_probe, .remove = radio_isa_remove, .driver = { .name = "radio-rtrack2", }, }, .io_params = io, .radio_nr_params = radio_nr, .io_ports = rtrack2_ioports, .num_of_io_ports = ARRAY_SIZE(rtrack2_ioports), .region_size = 4, .card = "AIMSlab RadioTrack II", .ops = &rtrack2_ops, .has_stereo = true, }; static int __init rtrack2_init(void) { return isa_register_driver(&rtrack2_driver.driver, RTRACK2_MAX); } static void __exit rtrack2_exit(void) { isa_unregister_driver(&rtrack2_driver.driver); } module_init(rtrack2_init); module_exit(rtrack2_exit);
gpl-2.0
xXminiWHOOPERxX/MSM8974-Mini-Reloaded-Sense-Kernel
arch/hexagon/mm/ioremap.c
6089
1677
/* * I/O remap functions for Hexagon * * Copyright (c) 2010-2011, 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. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <linux/io.h> #include <linux/vmalloc.h> void __iomem *ioremap_nocache(unsigned long phys_addr, unsigned long size) { unsigned long last_addr, addr; unsigned long offset = phys_addr & ~PAGE_MASK; struct vm_struct *area; pgprot_t prot = __pgprot(_PAGE_PRESENT|_PAGE_READ|_PAGE_WRITE |(__HEXAGON_C_DEV << 6)); last_addr = phys_addr + size - 1; /* Wrapping not allowed */ if (!size || (last_addr < phys_addr)) return NULL; /* Rounds up to next page size, including whole-page offset */ size = PAGE_ALIGN(offset + size); area = get_vm_area(size, VM_IOREMAP); addr = (unsigned long)area->addr; if (ioremap_page_range(addr, addr+size, phys_addr, prot)) { vunmap((void *)addr); return NULL; } return (void __iomem *) (offset + addr); } void __iounmap(const volatile void __iomem *addr) { vunmap((void *) ((unsigned long) addr & PAGE_MASK)); }
gpl-2.0
helicopter88/android_kernel_lge_hammerhead
drivers/staging/vt6655/wcmd.c
7881
41408
/* * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * File: wcmd.c * * Purpose: Handles the management command interface functions * * Author: Lyndon Chen * * Date: May 8, 2003 * * Functions: * s_vProbeChannel - Active scan channel * s_MgrMakeProbeRequest - Make ProbeRequest packet * CommandTimer - Timer function to handle command * s_bCommandComplete - Command Complete function * bScheduleCommand - Push Command and wait Command Scheduler to do * vCommandTimer- Command call back functions * vCommandTimerWait- Call back timer * bClearBSSID_SCAN- Clear BSSID_SCAN cmd in CMD Queue * * Revision History: * */ #include "ttype.h" #include "tmacro.h" #include "device.h" #include "mac.h" #include "card.h" #include "80211hdr.h" #include "wcmd.h" #include "wmgr.h" #include "power.h" #include "wctl.h" #include "baseband.h" #include "rxtx.h" #include "rf.h" #include "iowpa.h" #include "channel.h" /*--------------------- Static Definitions -------------------------*/ /*--------------------- Static Classes ----------------------------*/ /*--------------------- Static Variables --------------------------*/ static int msglevel =MSG_LEVEL_INFO; //static int msglevel =MSG_LEVEL_DEBUG; /*--------------------- Static Functions --------------------------*/ static void s_vProbeChannel( PSDevice pDevice ); static PSTxMgmtPacket s_MgrMakeProbeRequest( PSDevice pDevice, PSMgmtObject pMgmt, unsigned char *pScanBSSID, PWLAN_IE_SSID pSSID, PWLAN_IE_SUPP_RATES pCurrRates, PWLAN_IE_SUPP_RATES pCurrExtSuppRates ); static bool s_bCommandComplete ( PSDevice pDevice ); /*--------------------- Export Variables --------------------------*/ /*--------------------- Export Functions --------------------------*/ /* * Description: * Stop AdHoc beacon during scan process * * Parameters: * In: * pDevice - Pointer to the adapter * Out: * none * * Return Value: none * */ static void vAdHocBeaconStop(PSDevice pDevice) { PSMgmtObject pMgmt = &(pDevice->sMgmtObj); bool bStop; /* * temporarily stop Beacon packet for AdHoc Server * if all of the following coditions are met: * (1) STA is in AdHoc mode * (2) VT3253 is programmed as automatic Beacon Transmitting * (3) One of the following conditions is met * (3.1) AdHoc channel is in B/G band and the * current scan channel is in A band * or * (3.2) AdHoc channel is in A mode */ bStop = false; if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && (pMgmt->eCurrState >= WMAC_STATE_STARTED)) { if ((pMgmt->uIBSSChannel <= CB_MAX_CHANNEL_24G) && (pMgmt->uScanChannel > CB_MAX_CHANNEL_24G)) { bStop = true; } if (pMgmt->uIBSSChannel > CB_MAX_CHANNEL_24G) { bStop = true; } } if (bStop) { MACvRegBitsOff(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX); } } /* vAdHocBeaconStop */ /* * Description: * Restart AdHoc beacon after scan process complete * * Parameters: * In: * pDevice - Pointer to the adapter * Out: * none * * Return Value: none * */ static void vAdHocBeaconRestart(PSDevice pDevice) { PSMgmtObject pMgmt = &(pDevice->sMgmtObj); /* * Restart Beacon packet for AdHoc Server * if all of the following coditions are met: * (1) STA is in AdHoc mode * (2) VT3253 is programmed as automatic Beacon Transmitting */ if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && (pMgmt->eCurrState >= WMAC_STATE_STARTED)) { MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX); } } /*+ * * Routine Description: * Prepare and send probe request management frames. * * * Return Value: * none. * -*/ static void s_vProbeChannel( PSDevice pDevice ) { //1M, 2M, 5M, 11M, 18M, 24M, 36M, 54M unsigned char abyCurrSuppRatesG[] = {WLAN_EID_SUPP_RATES, 8, 0x02, 0x04, 0x0B, 0x16, 0x24, 0x30, 0x48, 0x6C}; unsigned char abyCurrExtSuppRatesG[] = {WLAN_EID_EXTSUPP_RATES, 4, 0x0C, 0x12, 0x18, 0x60}; //6M, 9M, 12M, 48M unsigned char abyCurrSuppRatesA[] = {WLAN_EID_SUPP_RATES, 8, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C}; unsigned char abyCurrSuppRatesB[] = {WLAN_EID_SUPP_RATES, 4, 0x02, 0x04, 0x0B, 0x16}; unsigned char *pbyRate; PSTxMgmtPacket pTxPacket; PSMgmtObject pMgmt = pDevice->pMgmt; unsigned int ii; if (pDevice->eCurrentPHYType == PHY_TYPE_11A) { pbyRate = &abyCurrSuppRatesA[0]; } else if (pDevice->eCurrentPHYType == PHY_TYPE_11B) { pbyRate = &abyCurrSuppRatesB[0]; } else { pbyRate = &abyCurrSuppRatesG[0]; } // build an assocreq frame and send it pTxPacket = s_MgrMakeProbeRequest ( pDevice, pMgmt, pMgmt->abyScanBSSID, (PWLAN_IE_SSID)pMgmt->abyScanSSID, (PWLAN_IE_SUPP_RATES)pbyRate, (PWLAN_IE_SUPP_RATES)abyCurrExtSuppRatesG ); if (pTxPacket != NULL ){ for (ii = 0; ii < 2 ; ii++) { if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Probe request sending fail.. \n"); } else { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Probe request is sending.. \n"); } } } } /*+ * * Routine Description: * Constructs an probe request frame * * * Return Value: * A ptr to Tx frame or NULL on allocation failue * -*/ PSTxMgmtPacket s_MgrMakeProbeRequest( PSDevice pDevice, PSMgmtObject pMgmt, unsigned char *pScanBSSID, PWLAN_IE_SSID pSSID, PWLAN_IE_SUPP_RATES pCurrRates, PWLAN_IE_SUPP_RATES pCurrExtSuppRates ) { PSTxMgmtPacket pTxPacket = NULL; WLAN_FR_PROBEREQ sFrame; pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool; memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_PROBEREQ_FR_MAXLEN); pTxPacket->p80211Header = (PUWLAN_80211HDR)((unsigned char *)pTxPacket + sizeof(STxMgmtPacket)); sFrame.pBuf = (unsigned char *)pTxPacket->p80211Header; sFrame.len = WLAN_PROBEREQ_FR_MAXLEN; vMgrEncodeProbeRequest(&sFrame); sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16( ( WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) | WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_PROBEREQ) )); memcpy( sFrame.pHdr->sA3.abyAddr1, pScanBSSID, WLAN_ADDR_LEN); memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN); memcpy( sFrame.pHdr->sA3.abyAddr3, pScanBSSID, WLAN_BSSID_LEN); // Copy the SSID, pSSID->len=0 indicate broadcast SSID sFrame.pSSID = (PWLAN_IE_SSID)(sFrame.pBuf + sFrame.len); sFrame.len += pSSID->len + WLAN_IEHDR_LEN; memcpy(sFrame.pSSID, pSSID, pSSID->len + WLAN_IEHDR_LEN); sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len); sFrame.len += pCurrRates->len + WLAN_IEHDR_LEN; memcpy(sFrame.pSuppRates, pCurrRates, pCurrRates->len + WLAN_IEHDR_LEN); // Copy the extension rate set if (pDevice->eCurrentPHYType == PHY_TYPE_11G) { sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len); sFrame.len += pCurrExtSuppRates->len + WLAN_IEHDR_LEN; memcpy(sFrame.pExtSuppRates, pCurrExtSuppRates, pCurrExtSuppRates->len + WLAN_IEHDR_LEN); } pTxPacket->cbMPDULen = sFrame.len; pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN; return pTxPacket; } void vCommandTimerWait( void *hDeviceContext, unsigned int MSecond ) { PSDevice pDevice = (PSDevice)hDeviceContext; init_timer(&pDevice->sTimerCommand); pDevice->sTimerCommand.data = (unsigned long) pDevice; pDevice->sTimerCommand.function = (TimerFunction)vCommandTimer; // RUN_AT :1 msec ~= (HZ/1024) pDevice->sTimerCommand.expires = (unsigned int)RUN_AT((MSecond * HZ) >> 10); add_timer(&pDevice->sTimerCommand); return; } void vCommandTimer ( void *hDeviceContext ) { PSDevice pDevice = (PSDevice)hDeviceContext; PSMgmtObject pMgmt = pDevice->pMgmt; PWLAN_IE_SSID pItemSSID; PWLAN_IE_SSID pItemSSIDCurr; CMD_STATUS Status; unsigned int ii; unsigned char byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80}; struct sk_buff *skb; if (pDevice->dwDiagRefCount != 0) return; if (pDevice->bCmdRunning != true) return; spin_lock_irq(&pDevice->lock); switch ( pDevice->eCommandState ) { case WLAN_CMD_SCAN_START: pDevice->byReAssocCount = 0; if (pDevice->bRadioOff == true) { s_bCommandComplete(pDevice); spin_unlock_irq(&pDevice->lock); return; } if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) { s_bCommandComplete(pDevice); CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_AP); spin_unlock_irq(&pDevice->lock); return; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState= WLAN_CMD_SCAN_START\n"); pItemSSID = (PWLAN_IE_SSID)pMgmt->abyScanSSID; // wait all Data TD complete if (pDevice->iTDUsed[TYPE_AC0DMA] != 0){ spin_unlock_irq(&pDevice->lock); vCommandTimerWait((void *)pDevice, 10); return; } if (pMgmt->uScanChannel == 0 ) { pMgmt->uScanChannel = pDevice->byMinChannel; // Set Baseband to be more sensitive. } if (pMgmt->uScanChannel > pDevice->byMaxChannel) { pMgmt->eScanState = WMAC_NO_SCANNING; // Set Baseband's sensitivity back. // Set channel back set_channel(pMgmt->pAdapter, pMgmt->uCurrChannel); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Scanning, set back to channel: [%d]\n", pMgmt->uCurrChannel); if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) { CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_ADHOC); } else { CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_INFRASTRUCTURE); } vAdHocBeaconRestart(pDevice); s_bCommandComplete(pDevice); } else { //2008-8-4 <add> by chester if (!is_channel_valid(pMgmt->uScanChannel)) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Invalid channel pMgmt->uScanChannel = %d \n",pMgmt->uScanChannel); s_bCommandComplete(pDevice); return; } //printk("chester-pMgmt->uScanChannel=%d,pDevice->byMaxChannel=%d\n",pMgmt->uScanChannel,pDevice->byMaxChannel); if (pMgmt->uScanChannel == pDevice->byMinChannel) { //pMgmt->eScanType = WMAC_SCAN_ACTIVE; pMgmt->abyScanBSSID[0] = 0xFF; pMgmt->abyScanBSSID[1] = 0xFF; pMgmt->abyScanBSSID[2] = 0xFF; pMgmt->abyScanBSSID[3] = 0xFF; pMgmt->abyScanBSSID[4] = 0xFF; pMgmt->abyScanBSSID[5] = 0xFF; pItemSSID->byElementID = WLAN_EID_SSID; // clear bssid list // BSSvClearBSSList((void *)pDevice, pDevice->bLinkPass); pMgmt->eScanState = WMAC_IS_SCANNING; } vAdHocBeaconStop(pDevice); if (set_channel(pMgmt->pAdapter, pMgmt->uScanChannel) == true) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SCAN Channel: %d\n", pMgmt->uScanChannel); } else { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SET SCAN Channel Fail: %d\n", pMgmt->uScanChannel); } CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_UNKNOWN); // printk("chester-mxch=%d\n",pDevice->byMaxChannel); // printk("chester-ch=%d\n",pMgmt->uScanChannel); pMgmt->uScanChannel++; //2008-8-4 <modify> by chester if (!is_channel_valid(pMgmt->uScanChannel) && pMgmt->uScanChannel <= pDevice->byMaxChannel ){ pMgmt->uScanChannel=pDevice->byMaxChannel+1; pMgmt->eCommandState = WLAN_CMD_SCAN_END; } if ((pMgmt->b11hEnable == false) || (pMgmt->uScanChannel < CB_MAX_CHANNEL_24G)) { s_vProbeChannel(pDevice); spin_unlock_irq(&pDevice->lock); vCommandTimerWait((void *)pDevice, WCMD_ACTIVE_SCAN_TIME); return; } else { spin_unlock_irq(&pDevice->lock); vCommandTimerWait((void *)pDevice, WCMD_PASSIVE_SCAN_TIME); return; } } break; case WLAN_CMD_SCAN_END: // Set Baseband's sensitivity back. // Set channel back set_channel(pMgmt->pAdapter, pMgmt->uCurrChannel); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Scanning, set back to channel: [%d]\n", pMgmt->uCurrChannel); if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) { CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_ADHOC); } else { CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_INFRASTRUCTURE); } pMgmt->eScanState = WMAC_NO_SCANNING; vAdHocBeaconRestart(pDevice); //2008-0409-07, <Add> by Einsn Liu #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT if(pMgmt->eScanType == WMAC_SCAN_PASSIVE) {//send scan event to wpa_Supplicant union iwreq_data wrqu; memset(&wrqu, 0, sizeof(wrqu)); wireless_send_event(pDevice->dev, SIOCGIWSCAN, &wrqu, NULL); } #endif s_bCommandComplete(pDevice); break; case WLAN_CMD_DISASSOCIATE_START : pDevice->byReAssocCount = 0; if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (pMgmt->eCurrState != WMAC_STATE_ASSOC)) { s_bCommandComplete(pDevice); spin_unlock_irq(&pDevice->lock); return; } else { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Send Disassociation Packet..\n"); // reason = 8 : disassoc because sta has left vMgrDisassocBeginSta((void *)pDevice, pMgmt, pMgmt->abyCurrBSSID, (8), &Status); pDevice->bLinkPass = false; // unlock command busy pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID; pItemSSID->len = 0; memset(pItemSSID->abySSID, 0, WLAN_SSID_MAXLEN); pMgmt->eCurrState = WMAC_STATE_IDLE; pMgmt->sNodeDBTable[0].bActive = false; // pDevice->bBeaconBufReady = false; } netif_stop_queue(pDevice->dev); pDevice->eCommandState = WLAN_DISASSOCIATE_WAIT; // wait all Control TD complete if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){ vCommandTimerWait((void *)pDevice, 10); spin_unlock_irq(&pDevice->lock); return; } DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" CARDbRadioPowerOff\n"); //2008-09-02 <mark> by chester // CARDbRadioPowerOff(pDevice); s_bCommandComplete(pDevice); break; case WLAN_DISASSOCIATE_WAIT : // wait all Control TD complete if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){ vCommandTimerWait((void *)pDevice, 10); spin_unlock_irq(&pDevice->lock); return; } //2008-09-02 <mark> by chester // CARDbRadioPowerOff(pDevice); s_bCommandComplete(pDevice); break; case WLAN_CMD_SSID_START: pDevice->byReAssocCount = 0; if (pDevice->bRadioOff == true) { s_bCommandComplete(pDevice); spin_unlock_irq(&pDevice->lock); return; } //printk("chester-currmode=%d\n",pMgmt->eCurrMode); printk("chester-abyDesireSSID=%s\n",((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->abySSID); //memcpy(pMgmt->abyAdHocSSID,pMgmt->abyDesireSSID, //((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->len + WLAN_IEHDR_LEN); pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID; pItemSSIDCurr = (PWLAN_IE_SSID)pMgmt->abyCurrSSID; DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" cmd: desire ssid = %s\n", pItemSSID->abySSID); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" cmd: curr ssid = %s\n", pItemSSIDCurr->abySSID); if (pMgmt->eCurrState == WMAC_STATE_ASSOC) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Cmd pMgmt->eCurrState == WMAC_STATE_ASSOC\n"); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pItemSSID->len =%d\n",pItemSSID->len); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pItemSSIDCurr->len = %d\n",pItemSSIDCurr->len); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" desire ssid = %s\n", pItemSSID->abySSID); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" curr ssid = %s\n", pItemSSIDCurr->abySSID); } if ((pMgmt->eCurrState == WMAC_STATE_ASSOC) || ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA)&& (pMgmt->eCurrState == WMAC_STATE_JOINTED))) { if (pItemSSID->len == pItemSSIDCurr->len) { if (memcmp(pItemSSID->abySSID, pItemSSIDCurr->abySSID, pItemSSID->len) == 0) { s_bCommandComplete(pDevice); spin_unlock_irq(&pDevice->lock); return; } } netif_stop_queue(pDevice->dev); pDevice->bLinkPass = false; } // set initial state pMgmt->eCurrState = WMAC_STATE_IDLE; pMgmt->eCurrMode = WMAC_MODE_STANDBY; PSvDisablePowerSaving((void *)pDevice); BSSvClearNodeDBTable(pDevice, 0); vMgrJoinBSSBegin((void *)pDevice, &Status); // if Infra mode if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (pMgmt->eCurrState == WMAC_STATE_JOINTED)) { // Call mgr to begin the deauthentication // reason = (3) because sta has left ESS if (pMgmt->eCurrState>= WMAC_STATE_AUTH) { vMgrDeAuthenBeginSta((void *)pDevice, pMgmt, pMgmt->abyCurrBSSID, (3), &Status); } // Call mgr to begin the authentication vMgrAuthenBeginSta((void *)pDevice, pMgmt, &Status); if (Status == CMD_STATUS_SUCCESS) { pDevice->byLinkWaitCount = 0; pDevice->eCommandState = WLAN_AUTHENTICATE_WAIT; vCommandTimerWait((void *)pDevice, AUTHENTICATE_TIMEOUT); spin_unlock_irq(&pDevice->lock); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Set eCommandState = WLAN_AUTHENTICATE_WAIT\n"); return; } } // if Adhoc mode else if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) { if (pMgmt->eCurrState == WMAC_STATE_JOINTED) { if (netif_queue_stopped(pDevice->dev)){ netif_wake_queue(pDevice->dev); } pDevice->bLinkPass = true; pMgmt->sNodeDBTable[0].bActive = true; pMgmt->sNodeDBTable[0].uInActiveCount = 0; bClearBSSID_SCAN(pDevice); } else { // start own IBSS vMgrCreateOwnIBSS((void *)pDevice, &Status); if (Status != CMD_STATUS_SUCCESS){ DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " WLAN_CMD_IBSS_CREATE fail ! \n"); } BSSvAddMulticastNode(pDevice); } } // if SSID not found else if (pMgmt->eCurrMode == WMAC_MODE_STANDBY) { if (pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA || pMgmt->eConfigMode == WMAC_CONFIG_AUTO) { // start own IBSS vMgrCreateOwnIBSS((void *)pDevice, &Status); if (Status != CMD_STATUS_SUCCESS){ DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" WLAN_CMD_IBSS_CREATE fail ! \n"); } BSSvAddMulticastNode(pDevice); if (netif_queue_stopped(pDevice->dev)){ netif_wake_queue(pDevice->dev); } pDevice->bLinkPass = true; } else { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disconnect SSID none\n"); #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT // if(pDevice->bWPASuppWextEnabled == true) { union iwreq_data wrqu; memset(&wrqu, 0, sizeof (wrqu)); wrqu.ap_addr.sa_family = ARPHRD_ETHER; printk("wireless_send_event--->SIOCGIWAP(disassociated:vMgrJoinBSSBegin Fail !!)\n"); wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL); } #endif } } s_bCommandComplete(pDevice); break; case WLAN_AUTHENTICATE_WAIT : DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_AUTHENTICATE_WAIT\n"); if (pMgmt->eCurrState == WMAC_STATE_AUTH) { // Call mgr to begin the association pDevice->byLinkWaitCount = 0; DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCurrState == WMAC_STATE_AUTH\n"); vMgrAssocBeginSta((void *)pDevice, pMgmt, &Status); if (Status == CMD_STATUS_SUCCESS) { pDevice->byLinkWaitCount = 0; DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState = WLAN_ASSOCIATE_WAIT\n"); pDevice->eCommandState = WLAN_ASSOCIATE_WAIT; vCommandTimerWait((void *)pDevice, ASSOCIATE_TIMEOUT); spin_unlock_irq(&pDevice->lock); return; } } else if(pMgmt->eCurrState < WMAC_STATE_AUTHPENDING) { printk("WLAN_AUTHENTICATE_WAIT:Authen Fail???\n"); } else if(pDevice->byLinkWaitCount <= 4){ //mike add:wait another 2 sec if authenticated_frame delay! pDevice->byLinkWaitCount ++; printk("WLAN_AUTHENTICATE_WAIT:wait %d times!!\n",pDevice->byLinkWaitCount); spin_unlock_irq(&pDevice->lock); vCommandTimerWait((void *)pDevice, AUTHENTICATE_TIMEOUT/2); return; } pDevice->byLinkWaitCount = 0; #if 0 #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT // if(pDevice->bWPASuppWextEnabled == true) { union iwreq_data wrqu; memset(&wrqu, 0, sizeof (wrqu)); wrqu.ap_addr.sa_family = ARPHRD_ETHER; printk("wireless_send_event--->SIOCGIWAP(disassociated:AUTHENTICATE_WAIT_timeout)\n"); wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL); } #endif #endif s_bCommandComplete(pDevice); break; case WLAN_ASSOCIATE_WAIT : if (pMgmt->eCurrState == WMAC_STATE_ASSOC) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCurrState == WMAC_STATE_ASSOC\n"); if (pDevice->ePSMode != WMAC_POWER_CAM) { PSvEnablePowerSaving((void *)pDevice, pMgmt->wListenInterval); } if (pMgmt->eAuthenMode >= WMAC_AUTH_WPA) { KeybRemoveAllKey(&(pDevice->sKey), pDevice->abyBSSID, pDevice->PortOffset); } pDevice->bLinkPass = true; pDevice->byLinkWaitCount = 0; pDevice->byReAssocCount = 0; bClearBSSID_SCAN(pDevice); if (pDevice->byFOETuning) { BBvSetFOE(pDevice->PortOffset); PSbSendNullPacket(pDevice); } if (netif_queue_stopped(pDevice->dev)){ netif_wake_queue(pDevice->dev); } #ifdef TxInSleep if(pDevice->IsTxDataTrigger != false) { //TxDataTimer is not triggered at the first time // printk("Re-initial TxDataTimer****\n"); del_timer(&pDevice->sTimerTxData); init_timer(&pDevice->sTimerTxData); pDevice->sTimerTxData.data = (unsigned long) pDevice; pDevice->sTimerTxData.function = (TimerFunction)BSSvSecondTxData; pDevice->sTimerTxData.expires = RUN_AT(10*HZ); //10s callback pDevice->fTxDataInSleep = false; pDevice->nTxDataTimeCout = 0; } else { // printk("mike:-->First time triger TimerTxData InSleep\n"); } pDevice->IsTxDataTrigger = true; add_timer(&pDevice->sTimerTxData); #endif } else if(pMgmt->eCurrState < WMAC_STATE_ASSOCPENDING) { printk("WLAN_ASSOCIATE_WAIT:Association Fail???\n"); } else if(pDevice->byLinkWaitCount <= 4){ //mike add:wait another 2 sec if associated_frame delay! pDevice->byLinkWaitCount ++; printk("WLAN_ASSOCIATE_WAIT:wait %d times!!\n",pDevice->byLinkWaitCount); spin_unlock_irq(&pDevice->lock); vCommandTimerWait((void *)pDevice, ASSOCIATE_TIMEOUT/2); return; } pDevice->byLinkWaitCount = 0; #if 0 #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT // if(pDevice->bWPASuppWextEnabled == true) { union iwreq_data wrqu; memset(&wrqu, 0, sizeof (wrqu)); wrqu.ap_addr.sa_family = ARPHRD_ETHER; printk("wireless_send_event--->SIOCGIWAP(disassociated:ASSOCIATE_WAIT_timeout)\n"); wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL); } #endif #endif s_bCommandComplete(pDevice); break; case WLAN_CMD_AP_MODE_START : DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_CMD_AP_MODE_START\n"); if (pMgmt->eConfigMode == WMAC_CONFIG_AP) { del_timer(&pMgmt->sTimerSecondCallback); pMgmt->eCurrState = WMAC_STATE_IDLE; pMgmt->eCurrMode = WMAC_MODE_STANDBY; pDevice->bLinkPass = false; if (pDevice->bEnableHostWEP == true) BSSvClearNodeDBTable(pDevice, 1); else BSSvClearNodeDBTable(pDevice, 0); pDevice->uAssocCount = 0; pMgmt->eCurrState = WMAC_STATE_IDLE; pDevice->bFixRate = false; vMgrCreateOwnIBSS((void *)pDevice, &Status); if (Status != CMD_STATUS_SUCCESS){ DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " vMgrCreateOwnIBSS fail ! \n"); } // alway turn off unicast bit MACvRegBitsOff(pDevice->PortOffset, MAC_REG_RCR, RCR_UNICAST); pDevice->byRxMode &= ~RCR_UNICAST; DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wcmd: rx_mode = %x\n", pDevice->byRxMode ); BSSvAddMulticastNode(pDevice); if (netif_queue_stopped(pDevice->dev)){ netif_wake_queue(pDevice->dev); } pDevice->bLinkPass = true; add_timer(&pMgmt->sTimerSecondCallback); } s_bCommandComplete(pDevice); break; case WLAN_CMD_TX_PSPACKET_START : // DTIM Multicast tx if (pMgmt->sNodeDBTable[0].bRxPSPoll) { while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[0].sTxPSQueue)) != NULL) { if (skb_queue_empty(&pMgmt->sNodeDBTable[0].sTxPSQueue)) { pMgmt->abyPSTxMap[0] &= ~byMask[0]; pDevice->bMoreData = false; } else { pDevice->bMoreData = true; } if (!device_dma0_xmit(pDevice, skb, 0)) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Multicast ps tx fail \n"); } pMgmt->sNodeDBTable[0].wEnQueueCnt--; } } // PS nodes tx for (ii = 1; ii < (MAX_NODE_NUM + 1); ii++) { if (pMgmt->sNodeDBTable[ii].bActive && pMgmt->sNodeDBTable[ii].bRxPSPoll) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Index=%d Enqueu Cnt= %d\n", ii, pMgmt->sNodeDBTable[ii].wEnQueueCnt); while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) != NULL) { if (skb_queue_empty(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) { // clear tx map pMgmt->abyPSTxMap[pMgmt->sNodeDBTable[ii].wAID >> 3] &= ~byMask[pMgmt->sNodeDBTable[ii].wAID & 7]; pDevice->bMoreData = false; } else { pDevice->bMoreData = true; } if (!device_dma0_xmit(pDevice, skb, ii)) { DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "sta ps tx fail \n"); } pMgmt->sNodeDBTable[ii].wEnQueueCnt--; // check if sta ps enable, wait next pspoll // if sta ps disable, send all pending buffers. if (pMgmt->sNodeDBTable[ii].bPSEnable) break; } if (skb_queue_empty(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) { // clear tx map pMgmt->abyPSTxMap[pMgmt->sNodeDBTable[ii].wAID >> 3] &= ~byMask[pMgmt->sNodeDBTable[ii].wAID & 7]; DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Index=%d PS queue clear \n", ii); } pMgmt->sNodeDBTable[ii].bRxPSPoll = false; } } s_bCommandComplete(pDevice); break; case WLAN_CMD_RADIO_START : DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_CMD_RADIO_START\n"); if (pDevice->bRadioCmd == true) CARDbRadioPowerOn(pDevice); else CARDbRadioPowerOff(pDevice); s_bCommandComplete(pDevice); break; case WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE : //DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_CMD_CHECK_BBSENSITIVITY_START\n"); // wait all TD complete if (pDevice->iTDUsed[TYPE_AC0DMA] != 0){ vCommandTimerWait((void *)pDevice, 10); spin_unlock_irq(&pDevice->lock); return; } if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){ vCommandTimerWait((void *)pDevice, 10); spin_unlock_irq(&pDevice->lock); return; } pDevice->byBBVGACurrent = pDevice->byBBVGANew; BBvSetVGAGainOffset(pDevice, pDevice->byBBVGACurrent); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SetVGAGainOffset %02X\n", pDevice->byBBVGACurrent); s_bCommandComplete(pDevice); break; default : s_bCommandComplete(pDevice); break; } //switch spin_unlock_irq(&pDevice->lock); return; } static bool s_bCommandComplete ( PSDevice pDevice ) { PWLAN_IE_SSID pSSID; bool bRadioCmd = false; //unsigned short wDeAuthenReason = 0; bool bForceSCAN = true; PSMgmtObject pMgmt = pDevice->pMgmt; pDevice->eCommandState = WLAN_CMD_IDLE; if (pDevice->cbFreeCmdQueue == CMD_Q_SIZE) { //Command Queue Empty pDevice->bCmdRunning = false; return true; } else { pDevice->eCommand = pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].eCmd; pSSID = (PWLAN_IE_SSID)pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].abyCmdDesireSSID; bRadioCmd = pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].bRadioCmd; bForceSCAN = pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].bForceSCAN; ADD_ONE_WITH_WRAP_AROUND(pDevice->uCmdDequeueIdx, CMD_Q_SIZE); pDevice->cbFreeCmdQueue++; pDevice->bCmdRunning = true; switch ( pDevice->eCommand ) { case WLAN_CMD_BSSID_SCAN: DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState= WLAN_CMD_BSSID_SCAN\n"); pDevice->eCommandState = WLAN_CMD_SCAN_START; pMgmt->uScanChannel = 0; if (pSSID->len != 0) { memcpy(pMgmt->abyScanSSID, pSSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1); } else { memset(pMgmt->abyScanSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1); } /* if ((bForceSCAN == false) && (pDevice->bLinkPass == true)) { if ((pSSID->len == ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len) && ( !memcmp(pSSID->abySSID, ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->abySSID, pSSID->len))) { pDevice->eCommandState = WLAN_CMD_IDLE; } } */ break; case WLAN_CMD_SSID: pDevice->eCommandState = WLAN_CMD_SSID_START; if (pSSID->len > WLAN_SSID_MAXLEN) pSSID->len = WLAN_SSID_MAXLEN; if (pSSID->len != 0) memcpy(pDevice->pMgmt->abyDesireSSID, pSSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1); DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState= WLAN_CMD_SSID_START\n"); break; case WLAN_CMD_DISASSOCIATE: pDevice->eCommandState = WLAN_CMD_DISASSOCIATE_START; break; case WLAN_CMD_RX_PSPOLL: pDevice->eCommandState = WLAN_CMD_TX_PSPACKET_START; break; case WLAN_CMD_RUN_AP: pDevice->eCommandState = WLAN_CMD_AP_MODE_START; break; case WLAN_CMD_RADIO: pDevice->eCommandState = WLAN_CMD_RADIO_START; pDevice->bRadioCmd = bRadioCmd; break; case WLAN_CMD_CHANGE_BBSENSITIVITY: pDevice->eCommandState = WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE; break; default: break; } vCommandTimerWait((void *)pDevice, 0); } return true; } bool bScheduleCommand ( void *hDeviceContext, CMD_CODE eCommand, unsigned char *pbyItem0 ) { PSDevice pDevice = (PSDevice)hDeviceContext; if (pDevice->cbFreeCmdQueue == 0) { return (false); } pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].eCmd = eCommand; pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bForceSCAN = true; memset(pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].abyCmdDesireSSID, 0 , WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1); if (pbyItem0 != NULL) { switch (eCommand) { case WLAN_CMD_BSSID_SCAN: memcpy(pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].abyCmdDesireSSID, pbyItem0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1); pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bForceSCAN = false; break; case WLAN_CMD_SSID: memcpy(pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].abyCmdDesireSSID, pbyItem0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1); break; case WLAN_CMD_DISASSOCIATE: pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bNeedRadioOFF = *((int *)pbyItem0); break; /* case WLAN_CMD_DEAUTH: pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].wDeAuthenReason = *((unsigned short *)pbyItem0); break; */ case WLAN_CMD_RX_PSPOLL: break; case WLAN_CMD_RADIO: pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bRadioCmd = *((int *)pbyItem0); break; case WLAN_CMD_CHANGE_BBSENSITIVITY: pDevice->eCommandState = WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE; break; default: break; } } ADD_ONE_WITH_WRAP_AROUND(pDevice->uCmdEnqueueIdx, CMD_Q_SIZE); pDevice->cbFreeCmdQueue--; if (pDevice->bCmdRunning == false) { s_bCommandComplete(pDevice); } else { } return (true); } /* * Description: * Clear BSSID_SCAN cmd in CMD Queue * * Parameters: * In: * hDeviceContext - Pointer to the adapter * eCommand - Command * Out: * none * * Return Value: true if success; otherwise false * */ bool bClearBSSID_SCAN ( void *hDeviceContext ) { PSDevice pDevice = (PSDevice)hDeviceContext; unsigned int uCmdDequeueIdx = pDevice->uCmdDequeueIdx; unsigned int ii; if ((pDevice->cbFreeCmdQueue < CMD_Q_SIZE) && (uCmdDequeueIdx != pDevice->uCmdEnqueueIdx)) { for (ii = 0; ii < (CMD_Q_SIZE - pDevice->cbFreeCmdQueue); ii ++) { if (pDevice->eCmdQueue[uCmdDequeueIdx].eCmd == WLAN_CMD_BSSID_SCAN) pDevice->eCmdQueue[uCmdDequeueIdx].eCmd = WLAN_CMD_IDLE; ADD_ONE_WITH_WRAP_AROUND(uCmdDequeueIdx, CMD_Q_SIZE); if (uCmdDequeueIdx == pDevice->uCmdEnqueueIdx) break; } } return true; } //mike add:reset command timer void vResetCommandTimer( void *hDeviceContext ) { PSDevice pDevice = (PSDevice)hDeviceContext; //delete timer del_timer(&pDevice->sTimerCommand); //init timer init_timer(&pDevice->sTimerCommand); pDevice->sTimerCommand.data = (unsigned long) pDevice; pDevice->sTimerCommand.function = (TimerFunction)vCommandTimer; pDevice->sTimerCommand.expires = RUN_AT(HZ); pDevice->cbFreeCmdQueue = CMD_Q_SIZE; pDevice->uCmdDequeueIdx = 0; pDevice->uCmdEnqueueIdx = 0; pDevice->eCommandState = WLAN_CMD_IDLE; pDevice->bCmdRunning = false; pDevice->bCmdClear = false; } #ifdef TxInSleep void BSSvSecondTxData( void *hDeviceContext ) { PSDevice pDevice = (PSDevice)hDeviceContext; PSMgmtObject pMgmt = &(pDevice->sMgmtObj); pDevice->nTxDataTimeCout++; if(pDevice->nTxDataTimeCout<4) //don't tx data if timer less than 40s { // printk("mike:%s-->no data Tx not exceed the desired Time as %d\n",__FUNCTION__, // (int)pDevice->nTxDataTimeCout); pDevice->sTimerTxData.expires = RUN_AT(10*HZ); //10s callback add_timer(&pDevice->sTimerTxData); return; } spin_lock_irq(&pDevice->lock); #if 1 if(((pDevice->bLinkPass ==true)&&(pMgmt->eAuthenMode < WMAC_AUTH_WPA)) || //open && sharekey linking (pDevice->fWPA_Authened == true)) { //wpa linking #else if(pDevice->bLinkPass ==true) { #endif // printk("mike:%s-->InSleep Tx Data Procedure\n",__FUNCTION__); pDevice->fTxDataInSleep = true; PSbSendNullPacket(pDevice); //send null packet pDevice->fTxDataInSleep = false; } spin_unlock_irq(&pDevice->lock); pDevice->sTimerTxData.expires = RUN_AT(10*HZ); //10s callback add_timer(&pDevice->sTimerTxData); return; } #endif
gpl-2.0
aatjitra/7105u1
drivers/parisc/led.c
8393
20416
/* * Chassis LCD/LED driver for HP-PARISC workstations * * (c) Copyright 2000 Red Hat Software * (c) Copyright 2000 Helge Deller <hdeller@redhat.com> * (c) Copyright 2001-2009 Helge Deller <deller@gmx.de> * (c) Copyright 2001 Randolph Chung <tausq@debian.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. * * TODO: * - speed-up calculations with inlined assembler * - interface to write to second row of LCD from /proc (if technically possible) * * Changes: * - Audit copy_from_user in led_proc_write. * Daniele Bellucci <bellucda@tiscali.it> * - Switch from using a tasklet to a work queue, so the led_LCD_driver * can sleep. * David Pye <dmp@davidmpye.dyndns.org> */ #include <linux/module.h> #include <linux/stddef.h> /* for offsetof() */ #include <linux/init.h> #include <linux/types.h> #include <linux/ioport.h> #include <linux/utsname.h> #include <linux/capability.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/inetdevice.h> #include <linux/in.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <linux/reboot.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/ctype.h> #include <linux/blkdev.h> #include <linux/workqueue.h> #include <linux/rcupdate.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/hardware.h> #include <asm/param.h> /* HZ */ #include <asm/led.h> #include <asm/pdc.h> #include <asm/uaccess.h> /* The control of the LEDs and LCDs on PARISC-machines have to be done completely in software. The necessary calculations are done in a work queue task which is scheduled regularly, and since the calculations may consume a relatively large amount of CPU time, some of the calculations can be turned off with the following variables (controlled via procfs) */ static int led_type __read_mostly = -1; static unsigned char lastleds; /* LED state from most recent update */ static unsigned int led_heartbeat __read_mostly = 1; static unsigned int led_diskio __read_mostly = 1; static unsigned int led_lanrxtx __read_mostly = 1; static char lcd_text[32] __read_mostly; static char lcd_text_default[32] __read_mostly; static int lcd_no_led_support __read_mostly = 0; /* KittyHawk doesn't support LED on its LCD */ static struct workqueue_struct *led_wq; static void led_work_func(struct work_struct *); static DECLARE_DELAYED_WORK(led_task, led_work_func); #if 0 #define DPRINTK(x) printk x #else #define DPRINTK(x) #endif struct lcd_block { unsigned char command; /* stores the command byte */ unsigned char on; /* value for turning LED on */ unsigned char off; /* value for turning LED off */ }; /* Structure returned by PDC_RETURN_CHASSIS_INFO */ /* NOTE: we use unsigned long:16 two times, since the following member lcd_cmd_reg_addr needs to be 64bit aligned on 64bit PA2.0-machines */ struct pdc_chassis_lcd_info_ret_block { unsigned long model:16; /* DISPLAY_MODEL_XXXX */ unsigned long lcd_width:16; /* width of the LCD in chars (DISPLAY_MODEL_LCD only) */ unsigned long lcd_cmd_reg_addr; /* ptr to LCD cmd-register & data ptr for LED */ unsigned long lcd_data_reg_addr; /* ptr to LCD data-register (LCD only) */ unsigned int min_cmd_delay; /* delay in uS after cmd-write (LCD only) */ unsigned char reset_cmd1; /* command #1 for writing LCD string (LCD only) */ unsigned char reset_cmd2; /* command #2 for writing LCD string (LCD only) */ unsigned char act_enable; /* 0 = no activity (LCD only) */ struct lcd_block heartbeat; struct lcd_block disk_io; struct lcd_block lan_rcv; struct lcd_block lan_tx; char _pad; }; /* LCD_CMD and LCD_DATA for KittyHawk machines */ #define KITTYHAWK_LCD_CMD F_EXTEND(0xf0190000UL) /* 64bit-ready */ #define KITTYHAWK_LCD_DATA (KITTYHAWK_LCD_CMD+1) /* lcd_info is pre-initialized to the values needed to program KittyHawk LCD's * HP seems to have used Sharp/Hitachi HD44780 LCDs most of the time. */ static struct pdc_chassis_lcd_info_ret_block lcd_info __attribute__((aligned(8))) __read_mostly = { .model = DISPLAY_MODEL_LCD, .lcd_width = 16, .lcd_cmd_reg_addr = KITTYHAWK_LCD_CMD, .lcd_data_reg_addr = KITTYHAWK_LCD_DATA, .min_cmd_delay = 80, .reset_cmd1 = 0x80, .reset_cmd2 = 0xc0, }; /* direct access to some of the lcd_info variables */ #define LCD_CMD_REG lcd_info.lcd_cmd_reg_addr #define LCD_DATA_REG lcd_info.lcd_data_reg_addr #define LED_DATA_REG lcd_info.lcd_cmd_reg_addr /* LASI & ASP only */ #define LED_HASLCD 1 #define LED_NOLCD 0 /* The workqueue must be created at init-time */ static int start_task(void) { /* Display the default text now */ if (led_type == LED_HASLCD) lcd_print( lcd_text_default ); /* KittyHawk has no LED support on its LCD */ if (lcd_no_led_support) return 0; /* Create the work queue and queue the LED task */ led_wq = create_singlethread_workqueue("led_wq"); queue_delayed_work(led_wq, &led_task, 0); return 0; } device_initcall(start_task); /* ptr to LCD/LED-specific function */ static void (*led_func_ptr) (unsigned char) __read_mostly; #ifdef CONFIG_PROC_FS static int led_proc_show(struct seq_file *m, void *v) { switch ((long)m->private) { case LED_NOLCD: seq_printf(m, "Heartbeat: %d\n", led_heartbeat); seq_printf(m, "Disk IO: %d\n", led_diskio); seq_printf(m, "LAN Rx/Tx: %d\n", led_lanrxtx); break; case LED_HASLCD: seq_printf(m, "%s\n", lcd_text); break; default: return 0; } return 0; } static int led_proc_open(struct inode *inode, struct file *file) { return single_open(file, led_proc_show, PDE(inode)->data); } static ssize_t led_proc_write(struct file *file, const char *buf, size_t count, loff_t *pos) { void *data = PDE(file->f_path.dentry->d_inode)->data; char *cur, lbuf[32]; int d; if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (count >= sizeof(lbuf)) count = sizeof(lbuf)-1; if (copy_from_user(lbuf, buf, count)) return -EFAULT; lbuf[count] = 0; cur = lbuf; switch ((long)data) { case LED_NOLCD: d = *cur++ - '0'; if (d != 0 && d != 1) goto parse_error; led_heartbeat = d; if (*cur++ != ' ') goto parse_error; d = *cur++ - '0'; if (d != 0 && d != 1) goto parse_error; led_diskio = d; if (*cur++ != ' ') goto parse_error; d = *cur++ - '0'; if (d != 0 && d != 1) goto parse_error; led_lanrxtx = d; break; case LED_HASLCD: if (*cur && cur[strlen(cur)-1] == '\n') cur[strlen(cur)-1] = 0; if (*cur == 0) cur = lcd_text_default; lcd_print(cur); break; default: return 0; } return count; parse_error: if ((long)data == LED_NOLCD) printk(KERN_CRIT "Parse error: expect \"n n n\" (n == 0 or 1) for heartbeat,\ndisk io and lan tx/rx indicators\n"); return -EINVAL; } static const struct file_operations led_proc_fops = { .owner = THIS_MODULE, .open = led_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = led_proc_write, }; static int __init led_create_procfs(void) { struct proc_dir_entry *proc_pdc_root = NULL; struct proc_dir_entry *ent; if (led_type == -1) return -1; proc_pdc_root = proc_mkdir("pdc", 0); if (!proc_pdc_root) return -1; if (!lcd_no_led_support) { ent = proc_create_data("led", S_IRUGO|S_IWUSR, proc_pdc_root, &led_proc_fops, (void *)LED_NOLCD); /* LED */ if (!ent) return -1; } if (led_type == LED_HASLCD) { ent = proc_create_data("lcd", S_IRUGO|S_IWUSR, proc_pdc_root, &led_proc_fops, (void *)LED_HASLCD); /* LCD */ if (!ent) return -1; } return 0; } #endif /* ** ** led_ASP_driver() ** */ #define LED_DATA 0x01 /* data to shift (0:on 1:off) */ #define LED_STROBE 0x02 /* strobe to clock data */ static void led_ASP_driver(unsigned char leds) { int i; leds = ~leds; for (i = 0; i < 8; i++) { unsigned char value; value = (leds & 0x80) >> 7; gsc_writeb( value, LED_DATA_REG ); gsc_writeb( value | LED_STROBE, LED_DATA_REG ); leds <<= 1; } } /* ** ** led_LASI_driver() ** */ static void led_LASI_driver(unsigned char leds) { leds = ~leds; gsc_writeb( leds, LED_DATA_REG ); } /* ** ** led_LCD_driver() ** */ static void led_LCD_driver(unsigned char leds) { static int i; static unsigned char mask[4] = { LED_HEARTBEAT, LED_DISK_IO, LED_LAN_RCV, LED_LAN_TX }; static struct lcd_block * blockp[4] = { &lcd_info.heartbeat, &lcd_info.disk_io, &lcd_info.lan_rcv, &lcd_info.lan_tx }; /* Convert min_cmd_delay to milliseconds */ unsigned int msec_cmd_delay = 1 + (lcd_info.min_cmd_delay / 1000); for (i=0; i<4; ++i) { if ((leds & mask[i]) != (lastleds & mask[i])) { gsc_writeb( blockp[i]->command, LCD_CMD_REG ); msleep(msec_cmd_delay); gsc_writeb( leds & mask[i] ? blockp[i]->on : blockp[i]->off, LCD_DATA_REG ); msleep(msec_cmd_delay); } } } /* ** ** led_get_net_activity() ** ** calculate if there was TX- or RX-throughput on the network interfaces ** (analog to dev_get_info() from net/core/dev.c) ** */ static __inline__ int led_get_net_activity(void) { #ifndef CONFIG_NET return 0; #else static u64 rx_total_last, tx_total_last; u64 rx_total, tx_total; struct net_device *dev; int retval; rx_total = tx_total = 0; /* we are running as a workqueue task, so we can use an RCU lookup */ rcu_read_lock(); for_each_netdev_rcu(&init_net, dev) { const struct rtnl_link_stats64 *stats; struct rtnl_link_stats64 temp; struct in_device *in_dev = __in_dev_get_rcu(dev); if (!in_dev || !in_dev->ifa_list) continue; if (ipv4_is_loopback(in_dev->ifa_list->ifa_local)) continue; stats = dev_get_stats(dev, &temp); rx_total += stats->rx_packets; tx_total += stats->tx_packets; } rcu_read_unlock(); retval = 0; if (rx_total != rx_total_last) { rx_total_last = rx_total; retval |= LED_LAN_RCV; } if (tx_total != tx_total_last) { tx_total_last = tx_total; retval |= LED_LAN_TX; } return retval; #endif } /* ** ** led_get_diskio_activity() ** ** calculate if there was disk-io in the system ** */ static __inline__ int led_get_diskio_activity(void) { static unsigned long last_pgpgin, last_pgpgout; unsigned long events[NR_VM_EVENT_ITEMS]; int changed; all_vm_events(events); /* Just use a very simple calculation here. Do not care about overflow, since we only want to know if there was activity or not. */ changed = (events[PGPGIN] != last_pgpgin) || (events[PGPGOUT] != last_pgpgout); last_pgpgin = events[PGPGIN]; last_pgpgout = events[PGPGOUT]; return (changed ? LED_DISK_IO : 0); } /* ** led_work_func() ** ** manages when and which chassis LCD/LED gets updated TODO: - display load average (older machines like 715/64 have 4 "free" LED's for that) - optimizations */ #define HEARTBEAT_LEN (HZ*10/100) #define HEARTBEAT_2ND_RANGE_START (HZ*28/100) #define HEARTBEAT_2ND_RANGE_END (HEARTBEAT_2ND_RANGE_START + HEARTBEAT_LEN) #define LED_UPDATE_INTERVAL (1 + (HZ*19/1000)) static void led_work_func (struct work_struct *unused) { static unsigned long last_jiffies; static unsigned long count_HZ; /* counter in range 0..HZ */ unsigned char currentleds = 0; /* stores current value of the LEDs */ /* exit if not initialized */ if (!led_func_ptr) return; /* increment the heartbeat timekeeper */ count_HZ += jiffies - last_jiffies; last_jiffies = jiffies; if (count_HZ >= HZ) count_HZ = 0; if (likely(led_heartbeat)) { /* flash heartbeat-LED like a real heart * (2 x short then a long delay) */ if (count_HZ < HEARTBEAT_LEN || (count_HZ >= HEARTBEAT_2ND_RANGE_START && count_HZ < HEARTBEAT_2ND_RANGE_END)) currentleds |= LED_HEARTBEAT; } if (likely(led_lanrxtx)) currentleds |= led_get_net_activity(); if (likely(led_diskio)) currentleds |= led_get_diskio_activity(); /* blink LEDs if we got an Oops (HPMC) */ if (unlikely(oops_in_progress)) { if (boot_cpu_data.cpu_type >= pcxl2) { /* newer machines don't have loadavg. LEDs, so we * let all LEDs blink twice per second instead */ currentleds = (count_HZ <= (HZ/2)) ? 0 : 0xff; } else { /* old machines: blink loadavg. LEDs twice per second */ if (count_HZ <= (HZ/2)) currentleds &= ~(LED4|LED5|LED6|LED7); else currentleds |= (LED4|LED5|LED6|LED7); } } if (currentleds != lastleds) { led_func_ptr(currentleds); /* Update the LCD/LEDs */ lastleds = currentleds; } queue_delayed_work(led_wq, &led_task, LED_UPDATE_INTERVAL); } /* ** led_halt() ** ** called by the reboot notifier chain at shutdown and stops all ** LED/LCD activities. ** */ static int led_halt(struct notifier_block *, unsigned long, void *); static struct notifier_block led_notifier = { .notifier_call = led_halt, }; static int notifier_disabled = 0; static int led_halt(struct notifier_block *nb, unsigned long event, void *buf) { char *txt; if (notifier_disabled) return NOTIFY_OK; notifier_disabled = 1; switch (event) { case SYS_RESTART: txt = "SYSTEM RESTART"; break; case SYS_HALT: txt = "SYSTEM HALT"; break; case SYS_POWER_OFF: txt = "SYSTEM POWER OFF"; break; default: return NOTIFY_DONE; } /* Cancel the work item and delete the queue */ if (led_wq) { cancel_delayed_work_sync(&led_task); destroy_workqueue(led_wq); led_wq = NULL; } if (lcd_info.model == DISPLAY_MODEL_LCD) lcd_print(txt); else if (led_func_ptr) led_func_ptr(0xff); /* turn all LEDs ON */ return NOTIFY_OK; } /* ** register_led_driver() ** ** registers an external LED or LCD for usage by this driver. ** currently only LCD-, LASI- and ASP-style LCD/LED's are supported. ** */ int __init register_led_driver(int model, unsigned long cmd_reg, unsigned long data_reg) { static int initialized; if (initialized || !data_reg) return 1; lcd_info.model = model; /* store the values */ LCD_CMD_REG = (cmd_reg == LED_CMD_REG_NONE) ? 0 : cmd_reg; switch (lcd_info.model) { case DISPLAY_MODEL_LCD: LCD_DATA_REG = data_reg; printk(KERN_INFO "LCD display at %lx,%lx registered\n", LCD_CMD_REG , LCD_DATA_REG); led_func_ptr = led_LCD_driver; led_type = LED_HASLCD; break; case DISPLAY_MODEL_LASI: LED_DATA_REG = data_reg; led_func_ptr = led_LASI_driver; printk(KERN_INFO "LED display at %lx registered\n", LED_DATA_REG); led_type = LED_NOLCD; break; case DISPLAY_MODEL_OLD_ASP: LED_DATA_REG = data_reg; led_func_ptr = led_ASP_driver; printk(KERN_INFO "LED (ASP-style) display at %lx registered\n", LED_DATA_REG); led_type = LED_NOLCD; break; default: printk(KERN_ERR "%s: Wrong LCD/LED model %d !\n", __func__, lcd_info.model); return 1; } /* mark the LCD/LED driver now as initialized and * register to the reboot notifier chain */ initialized++; register_reboot_notifier(&led_notifier); /* Ensure the work is queued */ if (led_wq) { queue_delayed_work(led_wq, &led_task, 0); } return 0; } /* ** register_led_regions() ** ** register_led_regions() registers the LCD/LED regions for /procfs. ** At bootup - where the initialisation of the LCD/LED normally happens - ** not all internal structures of request_region() are properly set up, ** so that we delay the led-registration until after busdevices_init() ** has been executed. ** */ void __init register_led_regions(void) { switch (lcd_info.model) { case DISPLAY_MODEL_LCD: request_mem_region((unsigned long)LCD_CMD_REG, 1, "lcd_cmd"); request_mem_region((unsigned long)LCD_DATA_REG, 1, "lcd_data"); break; case DISPLAY_MODEL_LASI: case DISPLAY_MODEL_OLD_ASP: request_mem_region((unsigned long)LED_DATA_REG, 1, "led_data"); break; } } /* ** ** lcd_print() ** ** Displays the given string on the LCD-Display of newer machines. ** lcd_print() disables/enables the timer-based led work queue to ** avoid a race condition while writing the CMD/DATA register pair. ** */ int lcd_print( const char *str ) { int i; if (!led_func_ptr || lcd_info.model != DISPLAY_MODEL_LCD) return 0; /* temporarily disable the led work task */ if (led_wq) cancel_delayed_work_sync(&led_task); /* copy display string to buffer for procfs */ strlcpy(lcd_text, str, sizeof(lcd_text)); /* Set LCD Cursor to 1st character */ gsc_writeb(lcd_info.reset_cmd1, LCD_CMD_REG); udelay(lcd_info.min_cmd_delay); /* Print the string */ for (i=0; i < lcd_info.lcd_width; i++) { if (str && *str) gsc_writeb(*str++, LCD_DATA_REG); else gsc_writeb(' ', LCD_DATA_REG); udelay(lcd_info.min_cmd_delay); } /* re-queue the work */ if (led_wq) { queue_delayed_work(led_wq, &led_task, 0); } return lcd_info.lcd_width; } /* ** led_init() ** ** led_init() is called very early in the bootup-process from setup.c ** and asks the PDC for an usable chassis LCD or LED. ** If the PDC doesn't return any info, then the LED ** is detected by lasi.c or asp.c and registered with the ** above functions lasi_led_init() or asp_led_init(). ** KittyHawk machines have often a buggy PDC, so that ** we explicitly check for those machines here. */ int __init led_init(void) { struct pdc_chassis_info chassis_info; int ret; snprintf(lcd_text_default, sizeof(lcd_text_default), "Linux %s", init_utsname()->release); /* Work around the buggy PDC of KittyHawk-machines */ switch (CPU_HVERSION) { case 0x580: /* KittyHawk DC2-100 (K100) */ case 0x581: /* KittyHawk DC3-120 (K210) */ case 0x582: /* KittyHawk DC3 100 (K400) */ case 0x583: /* KittyHawk DC3 120 (K410) */ case 0x58B: /* KittyHawk DC2 100 (K200) */ printk(KERN_INFO "%s: KittyHawk-Machine (hversion 0x%x) found, " "LED detection skipped.\n", __FILE__, CPU_HVERSION); lcd_no_led_support = 1; goto found; /* use the preinitialized values of lcd_info */ } /* initialize the struct, so that we can check for valid return values */ lcd_info.model = DISPLAY_MODEL_NONE; chassis_info.actcnt = chassis_info.maxcnt = 0; ret = pdc_chassis_info(&chassis_info, &lcd_info, sizeof(lcd_info)); if (ret == PDC_OK) { DPRINTK((KERN_INFO "%s: chassis info: model=%d (%s), " "lcd_width=%d, cmd_delay=%u,\n" "%s: sizecnt=%d, actcnt=%ld, maxcnt=%ld\n", __FILE__, lcd_info.model, (lcd_info.model==DISPLAY_MODEL_LCD) ? "LCD" : (lcd_info.model==DISPLAY_MODEL_LASI) ? "LED" : "unknown", lcd_info.lcd_width, lcd_info.min_cmd_delay, __FILE__, sizeof(lcd_info), chassis_info.actcnt, chassis_info.maxcnt)); DPRINTK((KERN_INFO "%s: cmd=%p, data=%p, reset1=%x, reset2=%x, act_enable=%d\n", __FILE__, lcd_info.lcd_cmd_reg_addr, lcd_info.lcd_data_reg_addr, lcd_info.reset_cmd1, lcd_info.reset_cmd2, lcd_info.act_enable )); /* check the results. Some machines have a buggy PDC */ if (chassis_info.actcnt <= 0 || chassis_info.actcnt != chassis_info.maxcnt) goto not_found; switch (lcd_info.model) { case DISPLAY_MODEL_LCD: /* LCD display */ if (chassis_info.actcnt < offsetof(struct pdc_chassis_lcd_info_ret_block, _pad)-1) goto not_found; if (!lcd_info.act_enable) { DPRINTK((KERN_INFO "PDC prohibited usage of the LCD.\n")); goto not_found; } break; case DISPLAY_MODEL_NONE: /* no LED or LCD available */ printk(KERN_INFO "PDC reported no LCD or LED.\n"); goto not_found; case DISPLAY_MODEL_LASI: /* Lasi style 8 bit LED display */ if (chassis_info.actcnt != 8 && chassis_info.actcnt != 32) goto not_found; break; default: printk(KERN_WARNING "PDC reported unknown LCD/LED model %d\n", lcd_info.model); goto not_found; } /* switch() */ found: /* register the LCD/LED driver */ register_led_driver(lcd_info.model, LCD_CMD_REG, LCD_DATA_REG); return 0; } else { /* if() */ DPRINTK((KERN_INFO "pdc_chassis_info call failed with retval = %d\n", ret)); } not_found: lcd_info.model = DISPLAY_MODEL_NONE; return 1; } static void __exit led_exit(void) { unregister_reboot_notifier(&led_notifier); return; } #ifdef CONFIG_PROC_FS module_init(led_create_procfs) #endif
gpl-2.0
Fevax/exynos8890_stock
security/keys/key.c
202
30054
/* Basic authentication token and access key management * * Copyright (C) 2004-2008 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/poison.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/security.h> #include <linux/workqueue.h> #include <linux/random.h> #include <linux/err.h> #include "internal.h" struct kmem_cache *key_jar; struct rb_root key_serial_tree; /* tree of keys indexed by serial */ DEFINE_SPINLOCK(key_serial_lock); struct rb_root key_user_tree; /* tree of quota records indexed by UID */ DEFINE_SPINLOCK(key_user_lock); unsigned int key_quota_root_maxkeys = 1000000; /* root's key count quota */ unsigned int key_quota_root_maxbytes = 25000000; /* root's key space quota */ unsigned int key_quota_maxkeys = 200; /* general key count quota */ unsigned int key_quota_maxbytes = 20000; /* general key space quota */ static LIST_HEAD(key_types_list); static DECLARE_RWSEM(key_types_sem); /* We serialise key instantiation and link */ DEFINE_MUTEX(key_construction_mutex); #ifdef KEY_DEBUGGING void __key_check(const struct key *key) { printk("__key_check: key %p {%08x} should be {%08x}\n", key, key->magic, KEY_DEBUG_MAGIC); BUG(); } #endif /* * Get the key quota record for a user, allocating a new record if one doesn't * already exist. */ struct key_user *key_user_lookup(kuid_t uid) { struct key_user *candidate = NULL, *user; struct rb_node *parent = NULL; struct rb_node **p; try_again: p = &key_user_tree.rb_node; spin_lock(&key_user_lock); /* search the tree for a user record with a matching UID */ while (*p) { parent = *p; user = rb_entry(parent, struct key_user, node); if (uid_lt(uid, user->uid)) p = &(*p)->rb_left; else if (uid_gt(uid, user->uid)) p = &(*p)->rb_right; else goto found; } /* if we get here, we failed to find a match in the tree */ if (!candidate) { /* allocate a candidate user record if we don't already have * one */ spin_unlock(&key_user_lock); user = NULL; candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL); if (unlikely(!candidate)) goto out; /* the allocation may have scheduled, so we need to repeat the * search lest someone else added the record whilst we were * asleep */ goto try_again; } /* if we get here, then the user record still hadn't appeared on the * second pass - so we use the candidate record */ atomic_set(&candidate->usage, 1); atomic_set(&candidate->nkeys, 0); atomic_set(&candidate->nikeys, 0); candidate->uid = uid; candidate->qnkeys = 0; candidate->qnbytes = 0; spin_lock_init(&candidate->lock); mutex_init(&candidate->cons_lock); rb_link_node(&candidate->node, parent, p); rb_insert_color(&candidate->node, &key_user_tree); spin_unlock(&key_user_lock); user = candidate; goto out; /* okay - we found a user record for this UID */ found: atomic_inc(&user->usage); spin_unlock(&key_user_lock); kfree(candidate); out: return user; } /* * Dispose of a user structure */ void key_user_put(struct key_user *user) { if (atomic_dec_and_lock(&user->usage, &key_user_lock)) { rb_erase(&user->node, &key_user_tree); spin_unlock(&key_user_lock); kfree(user); } } /* * Allocate a serial number for a key. These are assigned randomly to avoid * security issues through covert channel problems. */ static inline void key_alloc_serial(struct key *key) { struct rb_node *parent, **p; struct key *xkey; /* propose a random serial number and look for a hole for it in the * serial number tree */ do { get_random_bytes(&key->serial, sizeof(key->serial)); key->serial >>= 1; /* negative numbers are not permitted */ } while (key->serial < 3); spin_lock(&key_serial_lock); attempt_insertion: parent = NULL; p = &key_serial_tree.rb_node; while (*p) { parent = *p; xkey = rb_entry(parent, struct key, serial_node); if (key->serial < xkey->serial) p = &(*p)->rb_left; else if (key->serial > xkey->serial) p = &(*p)->rb_right; else goto serial_exists; } /* we've found a suitable hole - arrange for this key to occupy it */ rb_link_node(&key->serial_node, parent, p); rb_insert_color(&key->serial_node, &key_serial_tree); spin_unlock(&key_serial_lock); return; /* we found a key with the proposed serial number - walk the tree from * that point looking for the next unused serial number */ serial_exists: for (;;) { key->serial++; if (key->serial < 3) { key->serial = 3; goto attempt_insertion; } parent = rb_next(parent); if (!parent) goto attempt_insertion; xkey = rb_entry(parent, struct key, serial_node); if (key->serial < xkey->serial) goto attempt_insertion; } } /** * key_alloc - Allocate a key of the specified type. * @type: The type of key to allocate. * @desc: The key description to allow the key to be searched out. * @uid: The owner of the new key. * @gid: The group ID for the new key's group permissions. * @cred: The credentials specifying UID namespace. * @perm: The permissions mask of the new key. * @flags: Flags specifying quota properties. * * Allocate a key of the specified type with the attributes given. The key is * returned in an uninstantiated state and the caller needs to instantiate the * key before returning. * * The user's key count quota is updated to reflect the creation of the key and * the user's key data quota has the default for the key type reserved. The * instantiation function should amend this as necessary. If insufficient * quota is available, -EDQUOT will be returned. * * The LSM security modules can prevent a key being created, in which case * -EACCES will be returned. * * Returns a pointer to the new key if successful and an error code otherwise. * * Note that the caller needs to ensure the key type isn't uninstantiated. * Internally this can be done by locking key_types_sem. Externally, this can * be done by either never unregistering the key type, or making sure * key_alloc() calls don't race with module unloading. */ struct key *key_alloc(struct key_type *type, const char *desc, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags) { struct key_user *user = NULL; struct key *key; size_t desclen, quotalen; int ret; key = ERR_PTR(-EINVAL); if (!desc || !*desc) goto error; if (type->vet_description) { ret = type->vet_description(desc); if (ret < 0) { key = ERR_PTR(ret); goto error; } } desclen = strlen(desc); quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ user = key_user_lookup(uid); if (!user) goto no_memory_1; /* check that the user's quota permits allocation of another key and * its description */ if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&user->lock); if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) { if (user->qnkeys + 1 >= maxkeys || user->qnbytes + quotalen >= maxbytes || user->qnbytes + quotalen < user->qnbytes) goto no_quota; } user->qnkeys++; user->qnbytes += quotalen; spin_unlock(&user->lock); } /* allocate and initialise the key and its description */ key = kmem_cache_zalloc(key_jar, GFP_KERNEL); if (!key) goto no_memory_2; if (desc) { key->index_key.desc_len = desclen; key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); if (!key->description) goto no_memory_3; } atomic_set(&key->usage, 1); init_rwsem(&key->sem); lockdep_set_class(&key->sem, &type->lock_class); key->index_key.type = type; key->user = user; key->quotalen = quotalen; key->datalen = type->def_datalen; key->uid = uid; key->gid = gid; key->perm = perm; if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) key->flags |= 1 << KEY_FLAG_IN_QUOTA; if (flags & KEY_ALLOC_TRUSTED) key->flags |= 1 << KEY_FLAG_TRUSTED; #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC; #endif /* let the security module know about the key */ ret = security_key_alloc(key, cred, flags); if (ret < 0) goto security_error; /* publish the key by giving it a serial number */ atomic_inc(&user->nkeys); key_alloc_serial(key); error: return key; security_error: kfree(key->description); kmem_cache_free(key_jar, key); if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); key = ERR_PTR(ret); goto error; no_memory_3: kmem_cache_free(key_jar, key); no_memory_2: if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); no_memory_1: key = ERR_PTR(-ENOMEM); goto error; no_quota: spin_unlock(&user->lock); key_user_put(user); key = ERR_PTR(-EDQUOT); goto error; } EXPORT_SYMBOL(key_alloc); /** * key_payload_reserve - Adjust data quota reservation for the key's payload * @key: The key to make the reservation for. * @datalen: The amount of data payload the caller now wants. * * Adjust the amount of the owning user's key data quota that a key reserves. * If the amount is increased, then -EDQUOT may be returned if there isn't * enough free quota available. * * If successful, 0 is returned. */ int key_payload_reserve(struct key *key, size_t datalen) { int delta = (int)datalen - key->datalen; int ret = 0; key_check(key); /* contemplate the quota adjustment */ if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&key->user->lock); if (delta > 0 && (key->user->qnbytes + delta >= maxbytes || key->user->qnbytes + delta < key->user->qnbytes)) { ret = -EDQUOT; } else { key->user->qnbytes += delta; key->quotalen += delta; } spin_unlock(&key->user->lock); } /* change the recorded data length if that didn't generate an error */ if (ret == 0) key->datalen = datalen; return ret; } EXPORT_SYMBOL(key_payload_reserve); /* * Instantiate a key and link it into the target keyring atomically. Must be * called with the target keyring's semaphore writelocked. The target key's * semaphore need not be locked as instantiation is serialised by * key_construction_mutex. */ static int __key_instantiate_and_link(struct key *key, struct key_preparsed_payload *prep, struct key *keyring, struct key *authkey, struct assoc_array_edit **_edit) { int ret, awaken; key_check(key); key_check(keyring); awaken = 0; ret = -EBUSY; mutex_lock(&key_construction_mutex); /* can't instantiate twice */ if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { /* instantiate the key */ ret = key->type->instantiate(key, prep); if (ret == 0) { /* mark the key as being instantiated */ atomic_inc(&key->user->nikeys); set_bit(KEY_FLAG_INSTANTIATED, &key->flags); if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) awaken = 1; /* and link it into the destination keyring */ if (keyring) __key_link(key, _edit); /* disable the authorisation key */ if (authkey) key_revoke(authkey); if (prep->expiry != TIME_T_MAX) { key->expiry = prep->expiry; key_schedule_gc(prep->expiry + key_gc_delay); } } } mutex_unlock(&key_construction_mutex); /* wake up anyone waiting for a key to be constructed */ if (awaken) wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); return ret; } /** * key_instantiate_and_link - Instantiate a key and link it into the keyring. * @key: The key to instantiate. * @data: The data to use to instantiate the keyring. * @datalen: The length of @data. * @keyring: Keyring to create a link in on success (or NULL). * @authkey: The authorisation token permitting instantiation. * * Instantiate a key that's in the uninstantiated state using the provided data * and, if successful, link it in to the destination keyring if one is * supplied. * * If successful, 0 is returned, the authorisation token is revoked and anyone * waiting for the key is woken up. If the key was already instantiated, * -EBUSY will be returned. */ int key_instantiate_and_link(struct key *key, const void *data, size_t datalen, struct key *keyring, struct key *authkey) { struct key_preparsed_payload prep; struct assoc_array_edit *edit; int ret; memset(&prep, 0, sizeof(prep)); prep.data = data; prep.datalen = datalen; prep.quotalen = key->type->def_datalen; prep.expiry = TIME_T_MAX; if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) goto error; } if (keyring) { ret = __key_link_begin(keyring, &key->index_key, &edit); if (ret < 0) goto error; } ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit); if (keyring) __key_link_end(keyring, &key->index_key, edit); error: if (key->type->preparse) key->type->free_preparse(&prep); return ret; } EXPORT_SYMBOL(key_instantiate_and_link); /** * key_reject_and_link - Negatively instantiate a key and link it into the keyring. * @key: The key to instantiate. * @timeout: The timeout on the negative key. * @error: The error to return when the key is hit. * @keyring: Keyring to create a link in on success (or NULL). * @authkey: The authorisation token permitting instantiation. * * Negatively instantiate a key that's in the uninstantiated state and, if * successful, set its timeout and stored error and link it in to the * destination keyring if one is supplied. The key and any links to the key * will be automatically garbage collected after the timeout expires. * * Negative keys are used to rate limit repeated request_key() calls by causing * them to return the stored error code (typically ENOKEY) until the negative * key expires. * * If successful, 0 is returned, the authorisation token is revoked and anyone * waiting for the key is woken up. If the key was already instantiated, * -EBUSY will be returned. */ int key_reject_and_link(struct key *key, unsigned timeout, unsigned error, struct key *keyring, struct key *authkey) { struct assoc_array_edit *edit; struct timespec now; int ret, awaken, link_ret = 0; key_check(key); key_check(keyring); awaken = 0; ret = -EBUSY; if (keyring) link_ret = __key_link_begin(keyring, &key->index_key, &edit); mutex_lock(&key_construction_mutex); /* can't instantiate twice */ if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { /* mark the key as being negatively instantiated */ atomic_inc(&key->user->nikeys); key->type_data.reject_error = -error; smp_wmb(); set_bit(KEY_FLAG_NEGATIVE, &key->flags); set_bit(KEY_FLAG_INSTANTIATED, &key->flags); now = current_kernel_time(); key->expiry = now.tv_sec + timeout; key_schedule_gc(key->expiry + key_gc_delay); if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) awaken = 1; ret = 0; /* and link it into the destination keyring */ if (keyring && link_ret == 0) __key_link(key, &edit); /* disable the authorisation key */ if (authkey) key_revoke(authkey); } mutex_unlock(&key_construction_mutex); if (keyring) __key_link_end(keyring, &key->index_key, edit); /* wake up anyone waiting for a key to be constructed */ if (awaken) wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); return ret == 0 ? link_ret : ret; } EXPORT_SYMBOL(key_reject_and_link); /** * key_put - Discard a reference to a key. * @key: The key to discard a reference from. * * Discard a reference to a key, and when all the references are gone, we * schedule the cleanup task to come and pull it out of the tree in process * context at some later time. */ void key_put(struct key *key) { if (key) { key_check(key); if (atomic_dec_and_test(&key->usage)) schedule_work(&key_gc_work); } } EXPORT_SYMBOL(key_put); /* * Find a key by its serial number. */ struct key *key_lookup(key_serial_t id) { struct rb_node *n; struct key *key; spin_lock(&key_serial_lock); /* search the tree for the specified key */ n = key_serial_tree.rb_node; while (n) { key = rb_entry(n, struct key, serial_node); if (id < key->serial) n = n->rb_left; else if (id > key->serial) n = n->rb_right; else goto found; } not_found: key = ERR_PTR(-ENOKEY); goto error; found: /* pretend it doesn't exist if it is awaiting deletion */ if (atomic_read(&key->usage) == 0) goto not_found; /* this races with key_put(), but that doesn't matter since key_put() * doesn't actually change the key */ __key_get(key); error: spin_unlock(&key_serial_lock); return key; } /* * Find and lock the specified key type against removal. * * We return with the sem read-locked if successful. If the type wasn't * available -ENOKEY is returned instead. */ struct key_type *key_type_lookup(const char *type) { struct key_type *ktype; down_read(&key_types_sem); /* look up the key type to see if it's one of the registered kernel * types */ list_for_each_entry(ktype, &key_types_list, link) { if (strcmp(ktype->name, type) == 0) goto found_kernel_type; } up_read(&key_types_sem); ktype = ERR_PTR(-ENOKEY); found_kernel_type: return ktype; } void key_set_timeout(struct key *key, unsigned timeout) { struct timespec now; time_t expiry = 0; /* make the changes with the locks held to prevent races */ down_write(&key->sem); if (timeout > 0) { now = current_kernel_time(); expiry = now.tv_sec + timeout; } key->expiry = expiry; key_schedule_gc(key->expiry + key_gc_delay); up_write(&key->sem); } EXPORT_SYMBOL_GPL(key_set_timeout); /* * Unlock a key type locked by key_type_lookup(). */ void key_type_put(struct key_type *ktype) { up_read(&key_types_sem); } /* * Attempt to update an existing key. * * The key is given to us with an incremented refcount that we need to discard * if we get an error. */ static inline key_ref_t __key_update(key_ref_t key_ref, struct key_preparsed_payload *prep) { struct key *key = key_ref_to_ptr(key_ref); int ret; /* need write permission on the key to update it */ ret = key_permission(key_ref, KEY_NEED_WRITE); if (ret < 0) goto error; ret = -EEXIST; if (!key->type->update) goto error; down_write(&key->sem); ret = key->type->update(key, prep); if (ret == 0) /* updating a negative key instantiates it */ clear_bit(KEY_FLAG_NEGATIVE, &key->flags); up_write(&key->sem); if (ret < 0) goto error; out: return key_ref; error: key_put(key); key_ref = ERR_PTR(ret); goto out; } /** * key_create_or_update - Update or create and instantiate a key. * @keyring_ref: A pointer to the destination keyring with possession flag. * @type: The type of key. * @description: The searchable description for the key. * @payload: The data to use to instantiate or update the key. * @plen: The length of @payload. * @perm: The permissions mask for a new key. * @flags: The quota flags for a new key. * * Search the destination keyring for a key of the same description and if one * is found, update it, otherwise create and instantiate a new one and create a * link to it from that keyring. * * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be * concocted. * * Returns a pointer to the new key if successful, -ENODEV if the key type * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the * caller isn't permitted to modify the keyring or the LSM did not permit * creation of the key. * * On success, the possession flag from the keyring ref will be tacked on to * the key ref before it is returned. */ key_ref_t key_create_or_update(key_ref_t keyring_ref, const char *type, const char *description, const void *payload, size_t plen, key_perm_t perm, unsigned long flags) { struct keyring_index_key index_key = { .description = description, }; struct key_preparsed_payload prep; struct assoc_array_edit *edit; const struct cred *cred = current_cred(); struct key *keyring, *key = NULL; key_ref_t key_ref; int ret; /* look up the key type to see if it's one of the registered kernel * types */ index_key.type = key_type_lookup(type); if (IS_ERR(index_key.type)) { key_ref = ERR_PTR(-ENODEV); goto error; } key_ref = ERR_PTR(-EINVAL); if (!index_key.type->instantiate || (!index_key.description && !index_key.type->preparse)) goto error_put_type; keyring = key_ref_to_ptr(keyring_ref); key_check(keyring); key_ref = ERR_PTR(-ENOTDIR); if (keyring->type != &key_type_keyring) goto error_put_type; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = index_key.type->def_datalen; prep.trusted = flags & KEY_ALLOC_TRUSTED; prep.expiry = TIME_T_MAX; if (index_key.type->preparse) { ret = index_key.type->preparse(&prep); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } if (!index_key.description) index_key.description = prep.description; key_ref = ERR_PTR(-EINVAL); if (!index_key.description) goto error_free_prep; } index_key.desc_len = strlen(index_key.description); key_ref = ERR_PTR(-EPERM); if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags)) goto error_free_prep; flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0; ret = __key_link_begin(keyring, &index_key, &edit); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } /* if we're going to allocate a new key, we're going to have * to modify the keyring */ ret = key_permission(keyring_ref, KEY_NEED_WRITE); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_link_end; } /* if it's possible to update this type of key, search for an existing * key of the same type and description in the destination keyring and * update that instead if possible */ if (index_key.type->update) { key_ref = find_key_to_update(keyring_ref, &index_key); if (key_ref) goto found_matching_key; } /* if the client doesn't provide, decide on the permissions we want */ if (perm == KEY_PERM_UNDEF) { perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (index_key.type->read) perm |= KEY_POS_READ; if (index_key.type == &key_type_keyring || index_key.type->update) perm |= KEY_POS_WRITE; } /* allocate a new key */ key = key_alloc(index_key.type, index_key.description, cred->fsuid, cred->fsgid, cred, perm, flags); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error_link_end; } /* instantiate it and link it into the target keyring */ ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit); if (ret < 0) { key_put(key); key_ref = ERR_PTR(ret); goto error_link_end; } key_ref = make_key_ref(key, is_key_possessed(keyring_ref)); error_link_end: __key_link_end(keyring, &index_key, edit); error_free_prep: if (index_key.type->preparse) index_key.type->free_preparse(&prep); error_put_type: key_type_put(index_key.type); error: return key_ref; found_matching_key: /* we found a matching key, so we're going to try to update it * - we can drop the locks first as we have the key pinned */ __key_link_end(keyring, &index_key, edit); key_ref = __key_update(key_ref, &prep); goto error_free_prep; } EXPORT_SYMBOL(key_create_or_update); /** * key_update - Update a key's contents. * @key_ref: The pointer (plus possession flag) to the key. * @payload: The data to be used to update the key. * @plen: The length of @payload. * * Attempt to update the contents of a key with the given payload data. The * caller must be granted Write permission on the key. Negative keys can be * instantiated by this method. * * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key * type does not support updating. The key type may return other errors. */ int key_update(key_ref_t key_ref, const void *payload, size_t plen) { struct key_preparsed_payload prep; struct key *key = key_ref_to_ptr(key_ref); int ret; key_check(key); /* the key must be writable */ ret = key_permission(key_ref, KEY_NEED_WRITE); if (ret < 0) goto error; /* attempt to update it if supported */ ret = -EOPNOTSUPP; if (!key->type->update) goto error; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = key->type->def_datalen; prep.expiry = TIME_T_MAX; if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) goto error; } down_write(&key->sem); ret = key->type->update(key, &prep); if (ret == 0) /* updating a negative key instantiates it */ clear_bit(KEY_FLAG_NEGATIVE, &key->flags); up_write(&key->sem); error: if (key->type->preparse) key->type->free_preparse(&prep); return ret; } EXPORT_SYMBOL(key_update); /** * key_revoke - Revoke a key. * @key: The key to be revoked. * * Mark a key as being revoked and ask the type to free up its resources. The * revocation timeout is set and the key and all its links will be * automatically garbage collected after key_gc_delay amount of time if they * are not manually dealt with first. */ void key_revoke(struct key *key) { struct timespec now; time_t time; key_check(key); /* make sure no one's trying to change or use the key when we mark it * - we tell lockdep that we might nest because we might be revoking an * authorisation key whilst holding the sem on a key we've just * instantiated */ down_write_nested(&key->sem, 1); if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) && key->type->revoke) key->type->revoke(key); /* set the death time to no more than the expiry time */ now = current_kernel_time(); time = now.tv_sec; if (key->revoked_at == 0 || key->revoked_at > time) { key->revoked_at = time; key_schedule_gc(key->revoked_at + key_gc_delay); } up_write(&key->sem); } EXPORT_SYMBOL(key_revoke); /** * key_invalidate - Invalidate a key. * @key: The key to be invalidated. * * Mark a key as being invalidated and have it cleaned up immediately. The key * is ignored by all searches and other operations from this point. */ void key_invalidate(struct key *key) { kenter("%d", key_serial(key)); key_check(key); if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) { down_write_nested(&key->sem, 1); if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) key_schedule_gc_links(); up_write(&key->sem); } } EXPORT_SYMBOL(key_invalidate); /** * generic_key_instantiate - Simple instantiation of a key from preparsed data * @key: The key to be instantiated * @prep: The preparsed data to load. * * Instantiate a key from preparsed data. We assume we can just copy the data * in directly and clear the old pointers. * * This can be pointed to directly by the key type instantiate op pointer. */ int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep) { int ret; pr_devel("==>%s()\n", __func__); ret = key_payload_reserve(key, prep->quotalen); if (ret == 0) { key->type_data.p[0] = prep->type_data[0]; key->type_data.p[1] = prep->type_data[1]; rcu_assign_keypointer(key, prep->payload[0]); key->payload.data2[1] = prep->payload[1]; prep->type_data[0] = NULL; prep->type_data[1] = NULL; prep->payload[0] = NULL; prep->payload[1] = NULL; } pr_devel("<==%s() = %d\n", __func__, ret); return ret; } EXPORT_SYMBOL(generic_key_instantiate); /** * register_key_type - Register a type of key. * @ktype: The new key type. * * Register a new key type. * * Returns 0 on success or -EEXIST if a type of this name already exists. */ int register_key_type(struct key_type *ktype) { struct key_type *p; int ret; memset(&ktype->lock_class, 0, sizeof(ktype->lock_class)); ret = -EEXIST; down_write(&key_types_sem); /* disallow key types with the same name */ list_for_each_entry(p, &key_types_list, link) { if (strcmp(p->name, ktype->name) == 0) goto out; } /* store the type */ list_add(&ktype->link, &key_types_list); pr_notice("Key type %s registered\n", ktype->name); ret = 0; out: up_write(&key_types_sem); return ret; } EXPORT_SYMBOL(register_key_type); /** * unregister_key_type - Unregister a type of key. * @ktype: The key type. * * Unregister a key type and mark all the extant keys of this type as dead. * Those keys of this type are then destroyed to get rid of their payloads and * they and their links will be garbage collected as soon as possible. */ void unregister_key_type(struct key_type *ktype) { down_write(&key_types_sem); list_del_init(&ktype->link); downgrade_write(&key_types_sem); key_gc_keytype(ktype); pr_notice("Key type %s unregistered\n", ktype->name); up_read(&key_types_sem); } EXPORT_SYMBOL(unregister_key_type); /* * Initialise the key management state. */ void __init key_init(void) { /* allocate a slab in which we can store keys */ key_jar = kmem_cache_create("key_jar", sizeof(struct key), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); /* add the special key types */ list_add_tail(&key_type_keyring.link, &key_types_list); list_add_tail(&key_type_dead.link, &key_types_list); list_add_tail(&key_type_user.link, &key_types_list); list_add_tail(&key_type_logon.link, &key_types_list); /* record the root user tracking */ rb_link_node(&root_key_user.node, NULL, &key_user_tree.rb_node); rb_insert_color(&root_key_user.node, &key_user_tree); }
gpl-2.0
The-Sickness/DOL1-S6
drivers/net/ethernet/marvell/mvneta.c
202
77541
/* * Driver for Marvell NETA network card for Armada XP and Armada 370 SoCs. * * Copyright (C) 2012 Marvell * * Rami Rosen <rosenr@marvell.com> * Thomas Petazzoni <thomas.petazzoni@free-electrons.com> * * 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/kernel.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/platform_device.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/mbus.h> #include <linux/module.h> #include <linux/interrupt.h> #include <net/ip.h> #include <net/ipv6.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_mdio.h> #include <linux/of_net.h> #include <linux/of_address.h> #include <linux/phy.h> #include <linux/clk.h> /* Registers */ #define MVNETA_RXQ_CONFIG_REG(q) (0x1400 + ((q) << 2)) #define MVNETA_RXQ_HW_BUF_ALLOC BIT(1) #define MVNETA_RXQ_PKT_OFFSET_ALL_MASK (0xf << 8) #define MVNETA_RXQ_PKT_OFFSET_MASK(offs) ((offs) << 8) #define MVNETA_RXQ_THRESHOLD_REG(q) (0x14c0 + ((q) << 2)) #define MVNETA_RXQ_NON_OCCUPIED(v) ((v) << 16) #define MVNETA_RXQ_BASE_ADDR_REG(q) (0x1480 + ((q) << 2)) #define MVNETA_RXQ_SIZE_REG(q) (0x14a0 + ((q) << 2)) #define MVNETA_RXQ_BUF_SIZE_SHIFT 19 #define MVNETA_RXQ_BUF_SIZE_MASK (0x1fff << 19) #define MVNETA_RXQ_STATUS_REG(q) (0x14e0 + ((q) << 2)) #define MVNETA_RXQ_OCCUPIED_ALL_MASK 0x3fff #define MVNETA_RXQ_STATUS_UPDATE_REG(q) (0x1500 + ((q) << 2)) #define MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT 16 #define MVNETA_RXQ_ADD_NON_OCCUPIED_MAX 255 #define MVNETA_PORT_RX_RESET 0x1cc0 #define MVNETA_PORT_RX_DMA_RESET BIT(0) #define MVNETA_PHY_ADDR 0x2000 #define MVNETA_PHY_ADDR_MASK 0x1f #define MVNETA_MBUS_RETRY 0x2010 #define MVNETA_UNIT_INTR_CAUSE 0x2080 #define MVNETA_UNIT_CONTROL 0x20B0 #define MVNETA_PHY_POLLING_ENABLE BIT(1) #define MVNETA_WIN_BASE(w) (0x2200 + ((w) << 3)) #define MVNETA_WIN_SIZE(w) (0x2204 + ((w) << 3)) #define MVNETA_WIN_REMAP(w) (0x2280 + ((w) << 2)) #define MVNETA_BASE_ADDR_ENABLE 0x2290 #define MVNETA_PORT_CONFIG 0x2400 #define MVNETA_UNI_PROMISC_MODE BIT(0) #define MVNETA_DEF_RXQ(q) ((q) << 1) #define MVNETA_DEF_RXQ_ARP(q) ((q) << 4) #define MVNETA_TX_UNSET_ERR_SUM BIT(12) #define MVNETA_DEF_RXQ_TCP(q) ((q) << 16) #define MVNETA_DEF_RXQ_UDP(q) ((q) << 19) #define MVNETA_DEF_RXQ_BPDU(q) ((q) << 22) #define MVNETA_RX_CSUM_WITH_PSEUDO_HDR BIT(25) #define MVNETA_PORT_CONFIG_DEFL_VALUE(q) (MVNETA_DEF_RXQ(q) | \ MVNETA_DEF_RXQ_ARP(q) | \ MVNETA_DEF_RXQ_TCP(q) | \ MVNETA_DEF_RXQ_UDP(q) | \ MVNETA_DEF_RXQ_BPDU(q) | \ MVNETA_TX_UNSET_ERR_SUM | \ MVNETA_RX_CSUM_WITH_PSEUDO_HDR) #define MVNETA_PORT_CONFIG_EXTEND 0x2404 #define MVNETA_MAC_ADDR_LOW 0x2414 #define MVNETA_MAC_ADDR_HIGH 0x2418 #define MVNETA_SDMA_CONFIG 0x241c #define MVNETA_SDMA_BRST_SIZE_16 4 #define MVNETA_NO_DESC_SWAP 0x0 #define MVNETA_RX_BRST_SZ_MASK(burst) ((burst) << 1) #define MVNETA_RX_NO_DATA_SWAP BIT(4) #define MVNETA_TX_NO_DATA_SWAP BIT(5) #define MVNETA_TX_BRST_SZ_MASK(burst) ((burst) << 22) #define MVNETA_PORT_STATUS 0x2444 #define MVNETA_TX_IN_PRGRS BIT(1) #define MVNETA_TX_FIFO_EMPTY BIT(8) #define MVNETA_RX_MIN_FRAME_SIZE 0x247c #define MVNETA_TYPE_PRIO 0x24bc #define MVNETA_FORCE_UNI BIT(21) #define MVNETA_TXQ_CMD_1 0x24e4 #define MVNETA_TXQ_CMD 0x2448 #define MVNETA_TXQ_DISABLE_SHIFT 8 #define MVNETA_TXQ_ENABLE_MASK 0x000000ff #define MVNETA_ACC_MODE 0x2500 #define MVNETA_CPU_MAP(cpu) (0x2540 + ((cpu) << 2)) #define MVNETA_CPU_RXQ_ACCESS_ALL_MASK 0x000000ff #define MVNETA_CPU_TXQ_ACCESS_ALL_MASK 0x0000ff00 #define MVNETA_RXQ_TIME_COAL_REG(q) (0x2580 + ((q) << 2)) /* Exception Interrupt Port/Queue Cause register */ #define MVNETA_INTR_NEW_CAUSE 0x25a0 #define MVNETA_INTR_NEW_MASK 0x25a4 /* bits 0..7 = TXQ SENT, one bit per queue. * bits 8..15 = RXQ OCCUP, one bit per queue. * bits 16..23 = RXQ FREE, one bit per queue. * bit 29 = OLD_REG_SUM, see old reg ? * bit 30 = TX_ERR_SUM, one bit for 4 ports * bit 31 = MISC_SUM, one bit for 4 ports */ #define MVNETA_TX_INTR_MASK(nr_txqs) (((1 << nr_txqs) - 1) << 0) #define MVNETA_TX_INTR_MASK_ALL (0xff << 0) #define MVNETA_RX_INTR_MASK(nr_rxqs) (((1 << nr_rxqs) - 1) << 8) #define MVNETA_RX_INTR_MASK_ALL (0xff << 8) #define MVNETA_INTR_OLD_CAUSE 0x25a8 #define MVNETA_INTR_OLD_MASK 0x25ac /* Data Path Port/Queue Cause Register */ #define MVNETA_INTR_MISC_CAUSE 0x25b0 #define MVNETA_INTR_MISC_MASK 0x25b4 #define MVNETA_CAUSE_PHY_STATUS_CHANGE BIT(0) #define MVNETA_CAUSE_LINK_CHANGE BIT(1) #define MVNETA_CAUSE_PTP BIT(4) #define MVNETA_CAUSE_INTERNAL_ADDR_ERR BIT(7) #define MVNETA_CAUSE_RX_OVERRUN BIT(8) #define MVNETA_CAUSE_RX_CRC_ERROR BIT(9) #define MVNETA_CAUSE_RX_LARGE_PKT BIT(10) #define MVNETA_CAUSE_TX_UNDERUN BIT(11) #define MVNETA_CAUSE_PRBS_ERR BIT(12) #define MVNETA_CAUSE_PSC_SYNC_CHANGE BIT(13) #define MVNETA_CAUSE_SERDES_SYNC_ERR BIT(14) #define MVNETA_CAUSE_BMU_ALLOC_ERR_SHIFT 16 #define MVNETA_CAUSE_BMU_ALLOC_ERR_ALL_MASK (0xF << MVNETA_CAUSE_BMU_ALLOC_ERR_SHIFT) #define MVNETA_CAUSE_BMU_ALLOC_ERR_MASK(pool) (1 << (MVNETA_CAUSE_BMU_ALLOC_ERR_SHIFT + (pool))) #define MVNETA_CAUSE_TXQ_ERROR_SHIFT 24 #define MVNETA_CAUSE_TXQ_ERROR_ALL_MASK (0xFF << MVNETA_CAUSE_TXQ_ERROR_SHIFT) #define MVNETA_CAUSE_TXQ_ERROR_MASK(q) (1 << (MVNETA_CAUSE_TXQ_ERROR_SHIFT + (q))) #define MVNETA_INTR_ENABLE 0x25b8 #define MVNETA_TXQ_INTR_ENABLE_ALL_MASK 0x0000ff00 #define MVNETA_RXQ_INTR_ENABLE_ALL_MASK 0xff000000 // note: neta says it's 0x000000FF #define MVNETA_RXQ_CMD 0x2680 #define MVNETA_RXQ_DISABLE_SHIFT 8 #define MVNETA_RXQ_ENABLE_MASK 0x000000ff #define MVETH_TXQ_TOKEN_COUNT_REG(q) (0x2700 + ((q) << 4)) #define MVETH_TXQ_TOKEN_CFG_REG(q) (0x2704 + ((q) << 4)) #define MVNETA_GMAC_CTRL_0 0x2c00 #define MVNETA_GMAC_MAX_RX_SIZE_SHIFT 2 #define MVNETA_GMAC_MAX_RX_SIZE_MASK 0x7ffc #define MVNETA_GMAC0_PORT_ENABLE BIT(0) #define MVNETA_GMAC_CTRL_2 0x2c08 #define MVNETA_GMAC2_PCS_ENABLE BIT(3) #define MVNETA_GMAC2_PORT_RGMII BIT(4) #define MVNETA_GMAC2_PORT_RESET BIT(6) #define MVNETA_GMAC_STATUS 0x2c10 #define MVNETA_GMAC_LINK_UP BIT(0) #define MVNETA_GMAC_SPEED_1000 BIT(1) #define MVNETA_GMAC_SPEED_100 BIT(2) #define MVNETA_GMAC_FULL_DUPLEX BIT(3) #define MVNETA_GMAC_RX_FLOW_CTRL_ENABLE BIT(4) #define MVNETA_GMAC_TX_FLOW_CTRL_ENABLE BIT(5) #define MVNETA_GMAC_RX_FLOW_CTRL_ACTIVE BIT(6) #define MVNETA_GMAC_TX_FLOW_CTRL_ACTIVE BIT(7) #define MVNETA_GMAC_AUTONEG_CONFIG 0x2c0c #define MVNETA_GMAC_FORCE_LINK_DOWN BIT(0) #define MVNETA_GMAC_FORCE_LINK_PASS BIT(1) #define MVNETA_GMAC_CONFIG_MII_SPEED BIT(5) #define MVNETA_GMAC_CONFIG_GMII_SPEED BIT(6) #define MVNETA_GMAC_AN_SPEED_EN BIT(7) #define MVNETA_GMAC_CONFIG_FULL_DUPLEX BIT(12) #define MVNETA_GMAC_AN_DUPLEX_EN BIT(13) #define MVNETA_MIB_COUNTERS_BASE 0x3080 #define MVNETA_MIB_LATE_COLLISION 0x7c #define MVNETA_DA_FILT_SPEC_MCAST 0x3400 #define MVNETA_DA_FILT_OTH_MCAST 0x3500 #define MVNETA_DA_FILT_UCAST_BASE 0x3600 #define MVNETA_TXQ_BASE_ADDR_REG(q) (0x3c00 + ((q) << 2)) #define MVNETA_TXQ_SIZE_REG(q) (0x3c20 + ((q) << 2)) #define MVNETA_TXQ_SENT_THRESH_ALL_MASK 0x3fff0000 #define MVNETA_TXQ_SENT_THRESH_MASK(coal) ((coal) << 16) #define MVNETA_TXQ_UPDATE_REG(q) (0x3c60 + ((q) << 2)) #define MVNETA_TXQ_DEC_SENT_SHIFT 16 #define MVNETA_TXQ_STATUS_REG(q) (0x3c40 + ((q) << 2)) #define MVNETA_TXQ_SENT_DESC_SHIFT 16 #define MVNETA_TXQ_SENT_DESC_MASK 0x3fff0000 #define MVNETA_PORT_TX_RESET 0x3cf0 #define MVNETA_PORT_TX_DMA_RESET BIT(0) #define MVNETA_TX_MTU 0x3e0c #define MVNETA_TX_TOKEN_SIZE 0x3e14 #define MVNETA_TX_TOKEN_SIZE_MAX 0xffffffff #define MVNETA_TXQ_TOKEN_SIZE_REG(q) (0x3e40 + ((q) << 2)) #define MVNETA_TXQ_TOKEN_SIZE_MAX 0x7fffffff #define MVNETA_CAUSE_TXQ_SENT_DESC_ALL_MASK 0xff /* Descriptor ring Macros */ #define MVNETA_QUEUE_NEXT_DESC(q, index) \ (((index) < (q)->last_desc) ? ((index) + 1) : 0) /* Various constants */ /* Coalescing */ #define MVNETA_TXDONE_COAL_PKTS 16 #define MVNETA_RX_COAL_PKTS 32 #define MVNETA_RX_COAL_USEC 100 /* Napi polling weight */ #define MVNETA_RX_POLL_WEIGHT 64 /* The two bytes Marvell header. Either contains a special value used * by Marvell switches when a specific hardware mode is enabled (not * supported by this driver) or is filled automatically by zeroes on * the RX side. Those two bytes being at the front of the Ethernet * header, they allow to have the IP header aligned on a 4 bytes * boundary automatically: the hardware skips those two bytes on its * own. */ #define MVNETA_MH_SIZE 2 #define MVNETA_VLAN_TAG_LEN 4 #define MVNETA_CPU_D_CACHE_LINE_SIZE 32 #define MVNETA_TX_CSUM_MAX_SIZE 9800 #define MVNETA_ACC_MODE_EXT 1 /* Timeout constants */ #define MVNETA_TX_DISABLE_TIMEOUT_MSEC 1000 #define MVNETA_RX_DISABLE_TIMEOUT_MSEC 1000 #define MVNETA_TX_FIFO_EMPTY_TIMEOUT 10000 #define MVNETA_TX_MTU_MAX 0x3ffff /* Max number of Rx descriptors */ #define MVNETA_MAX_RXD 128 /* Max number of Tx descriptors */ #define MVNETA_MAX_TXD 532 /* descriptor aligned size */ #define MVNETA_DESC_ALIGNED_SIZE 32 #define MVNETA_RX_PKT_SIZE(mtu) \ ALIGN((mtu) + MVNETA_MH_SIZE + MVNETA_VLAN_TAG_LEN + \ ETH_HLEN + ETH_FCS_LEN, \ MVNETA_CPU_D_CACHE_LINE_SIZE) #define MVNETA_RX_BUF_SIZE(pkt_size) ((pkt_size) + NET_SKB_PAD) struct mvneta_pcpu_stats { struct u64_stats_sync syncp; u64 rx_packets; u64 rx_bytes; u64 tx_packets; u64 tx_bytes; }; struct mvneta_port { int pkt_size; void __iomem *base; struct mvneta_rx_queue *rxqs; struct mvneta_tx_queue *txqs; struct net_device *dev; u32 cause_rx_tx; struct napi_struct napi; /* Napi weight */ int weight; /* Core clock */ struct clk *clk; u8 mcast_count[256]; u16 tx_ring_size; u16 rx_ring_size; struct mvneta_pcpu_stats *stats; struct mii_bus *mii_bus; struct phy_device *phy_dev; phy_interface_t phy_interface; struct device_node *phy_node; unsigned int link; unsigned int duplex; unsigned int speed; }; /* The mvneta_tx_desc and mvneta_rx_desc structures describe the * layout of the transmit and reception DMA descriptors, and their * layout is therefore defined by the hardware design */ struct mvneta_tx_desc { u32 command; /* Options used by HW for packet transmitting.*/ #define MVNETA_TX_L3_OFF_SHIFT 0 #define MVNETA_TX_IP_HLEN_SHIFT 8 #define MVNETA_TX_L4_UDP BIT(16) #define MVNETA_TX_L3_IP6 BIT(17) #define MVNETA_TXD_IP_CSUM BIT(18) #define MVNETA_TXD_Z_PAD BIT(19) #define MVNETA_TXD_L_DESC BIT(20) #define MVNETA_TXD_F_DESC BIT(21) #define MVNETA_TXD_FLZ_DESC (MVNETA_TXD_Z_PAD | \ MVNETA_TXD_L_DESC | \ MVNETA_TXD_F_DESC) #define MVNETA_TX_L4_CSUM_FULL BIT(30) #define MVNETA_TX_L4_CSUM_NOT BIT(31) u16 reserverd1; /* csum_l4 (for future use) */ u16 data_size; /* Data size of transmitted packet in bytes */ u32 buf_phys_addr; /* Physical addr of transmitted buffer */ u32 reserved2; /* hw_cmd - (for future use, PMT) */ u32 reserved3[4]; /* Reserved - (for future use) */ }; struct mvneta_rx_desc { u32 status; /* Info about received packet */ #define MVNETA_RXD_ERR_CRC 0x0 #define MVNETA_RXD_ERR_SUMMARY BIT(16) #define MVNETA_RXD_ERR_OVERRUN BIT(17) #define MVNETA_RXD_ERR_LEN BIT(18) #define MVNETA_RXD_ERR_RESOURCE (BIT(17) | BIT(18)) #define MVNETA_RXD_ERR_CODE_MASK (BIT(17) | BIT(18)) #define MVNETA_RXD_L3_IP4 BIT(25) #define MVNETA_RXD_FIRST_LAST_DESC (BIT(26) | BIT(27)) #define MVNETA_RXD_L4_CSUM_OK BIT(30) u16 reserved1; /* pnc_info - (for future use, PnC) */ u16 data_size; /* Size of received packet in bytes */ u32 buf_phys_addr; /* Physical address of the buffer */ u32 reserved2; /* pnc_flow_id (for future use, PnC) */ u32 buf_cookie; /* cookie for access to RX buffer in rx path */ u16 reserved3; /* prefetch_cmd, for future use */ u16 reserved4; /* csum_l4 - (for future use, PnC) */ u32 reserved5; /* pnc_extra PnC (for future use, PnC) */ u32 reserved6; /* hw_cmd (for future use, PnC and HWF) */ }; struct mvneta_tx_queue { /* Number of this TX queue, in the range 0-7 */ u8 id; /* Number of TX DMA descriptors in the descriptor ring */ int size; /* Number of currently used TX DMA descriptor in the * descriptor ring */ int count; /* Array of transmitted skb */ struct sk_buff **tx_skb; /* Index of last TX DMA descriptor that was inserted */ int txq_put_index; /* Index of the TX DMA descriptor to be cleaned up */ int txq_get_index; u32 done_pkts_coal; /* Virtual address of the TX DMA descriptors array */ struct mvneta_tx_desc *descs; /* DMA address of the TX DMA descriptors array */ dma_addr_t descs_phys; /* Index of the last TX DMA descriptor */ int last_desc; /* Index of the next TX DMA descriptor to process */ int next_desc_to_proc; }; struct mvneta_rx_queue { /* rx queue number, in the range 0-7 */ u8 id; /* num of rx descriptors in the rx descriptor ring */ int size; /* counter of times when mvneta_refill() failed */ int missed; u32 pkts_coal; u32 time_coal; /* Virtual address of the RX DMA descriptors array */ struct mvneta_rx_desc *descs; /* DMA address of the RX DMA descriptors array */ dma_addr_t descs_phys; /* Index of the last RX DMA descriptor */ int last_desc; /* Index of the next RX DMA descriptor to process */ int next_desc_to_proc; }; static int rxq_number = 8; static int txq_number = 8; static int rxq_def; #define MVNETA_DRIVER_NAME "mvneta" #define MVNETA_DRIVER_VERSION "1.0" /* Utility/helper methods */ /* Write helper method */ static void mvreg_write(struct mvneta_port *pp, u32 offset, u32 data) { writel(data, pp->base + offset); } /* Read helper method */ static u32 mvreg_read(struct mvneta_port *pp, u32 offset) { return readl(pp->base + offset); } /* Increment txq get counter */ static void mvneta_txq_inc_get(struct mvneta_tx_queue *txq) { txq->txq_get_index++; if (txq->txq_get_index == txq->size) txq->txq_get_index = 0; } /* Increment txq put counter */ static void mvneta_txq_inc_put(struct mvneta_tx_queue *txq) { txq->txq_put_index++; if (txq->txq_put_index == txq->size) txq->txq_put_index = 0; } /* Clear all MIB counters */ static void mvneta_mib_counters_clear(struct mvneta_port *pp) { int i; u32 dummy; /* Perform dummy reads from MIB counters */ for (i = 0; i < MVNETA_MIB_LATE_COLLISION; i += 4) dummy = mvreg_read(pp, (MVNETA_MIB_COUNTERS_BASE + i)); } /* Get System Network Statistics */ struct rtnl_link_stats64 *mvneta_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct mvneta_port *pp = netdev_priv(dev); unsigned int start; int cpu; for_each_possible_cpu(cpu) { struct mvneta_pcpu_stats *cpu_stats; u64 rx_packets; u64 rx_bytes; u64 tx_packets; u64 tx_bytes; cpu_stats = per_cpu_ptr(pp->stats, cpu); do { start = u64_stats_fetch_begin_bh(&cpu_stats->syncp); rx_packets = cpu_stats->rx_packets; rx_bytes = cpu_stats->rx_bytes; tx_packets = cpu_stats->tx_packets; tx_bytes = cpu_stats->tx_bytes; } while (u64_stats_fetch_retry_bh(&cpu_stats->syncp, start)); stats->rx_packets += rx_packets; stats->rx_bytes += rx_bytes; stats->tx_packets += tx_packets; stats->tx_bytes += tx_bytes; } stats->rx_errors = dev->stats.rx_errors; stats->rx_dropped = dev->stats.rx_dropped; stats->tx_dropped = dev->stats.tx_dropped; return stats; } /* Rx descriptors helper methods */ /* Checks whether the given RX descriptor is both the first and the * last descriptor for the RX packet. Each RX packet is currently * received through a single RX descriptor, so not having each RX * descriptor with its first and last bits set is an error */ static int mvneta_rxq_desc_is_first_last(struct mvneta_rx_desc *desc) { return (desc->status & MVNETA_RXD_FIRST_LAST_DESC) == MVNETA_RXD_FIRST_LAST_DESC; } /* Add number of descriptors ready to receive new packets */ static void mvneta_rxq_non_occup_desc_add(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int ndescs) { /* Only MVNETA_RXQ_ADD_NON_OCCUPIED_MAX (255) descriptors can * be added at once */ while (ndescs > MVNETA_RXQ_ADD_NON_OCCUPIED_MAX) { mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), (MVNETA_RXQ_ADD_NON_OCCUPIED_MAX << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT)); ndescs -= MVNETA_RXQ_ADD_NON_OCCUPIED_MAX; } mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), (ndescs << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT)); } /* Get number of RX descriptors occupied by received packets */ static int mvneta_rxq_busy_desc_num_get(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { u32 val; val = mvreg_read(pp, MVNETA_RXQ_STATUS_REG(rxq->id)); return val & MVNETA_RXQ_OCCUPIED_ALL_MASK; } /* Update num of rx desc called upon return from rx path or * from mvneta_rxq_drop_pkts(). */ static void mvneta_rxq_desc_num_update(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int rx_done, int rx_filled) { u32 val; if ((rx_done <= 0xff) && (rx_filled <= 0xff)) { val = rx_done | (rx_filled << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT); mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), val); return; } /* Only 255 descriptors can be added at once */ while ((rx_done > 0) || (rx_filled > 0)) { if (rx_done <= 0xff) { val = rx_done; rx_done = 0; } else { val = 0xff; rx_done -= 0xff; } if (rx_filled <= 0xff) { val |= rx_filled << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT; rx_filled = 0; } else { val |= 0xff << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT; rx_filled -= 0xff; } mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), val); } } /* Get pointer to next RX descriptor to be processed by SW */ static struct mvneta_rx_desc * mvneta_rxq_next_desc_get(struct mvneta_rx_queue *rxq) { int rx_desc = rxq->next_desc_to_proc; rxq->next_desc_to_proc = MVNETA_QUEUE_NEXT_DESC(rxq, rx_desc); return rxq->descs + rx_desc; } /* Change maximum receive size of the port. */ static void mvneta_max_rx_size_set(struct mvneta_port *pp, int max_rx_size) { u32 val; val = mvreg_read(pp, MVNETA_GMAC_CTRL_0); val &= ~MVNETA_GMAC_MAX_RX_SIZE_MASK; val |= ((max_rx_size - MVNETA_MH_SIZE) / 2) << MVNETA_GMAC_MAX_RX_SIZE_SHIFT; mvreg_write(pp, MVNETA_GMAC_CTRL_0, val); } /* Set rx queue offset */ static void mvneta_rxq_offset_set(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int offset) { u32 val; val = mvreg_read(pp, MVNETA_RXQ_CONFIG_REG(rxq->id)); val &= ~MVNETA_RXQ_PKT_OFFSET_ALL_MASK; /* Offset is in */ val |= MVNETA_RXQ_PKT_OFFSET_MASK(offset >> 3); mvreg_write(pp, MVNETA_RXQ_CONFIG_REG(rxq->id), val); } /* Tx descriptors helper methods */ /* Update HW with number of TX descriptors to be sent */ static void mvneta_txq_pend_desc_add(struct mvneta_port *pp, struct mvneta_tx_queue *txq, int pend_desc) { u32 val; /* Only 255 descriptors can be added at once ; Assume caller * process TX desriptors in quanta less than 256 */ val = pend_desc; mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val); } /* Get pointer to next TX descriptor to be processed (send) by HW */ static struct mvneta_tx_desc * mvneta_txq_next_desc_get(struct mvneta_tx_queue *txq) { int tx_desc = txq->next_desc_to_proc; txq->next_desc_to_proc = MVNETA_QUEUE_NEXT_DESC(txq, tx_desc); return txq->descs + tx_desc; } /* Release the last allocated TX descriptor. Useful to handle DMA * mapping failures in the TX path. */ static void mvneta_txq_desc_put(struct mvneta_tx_queue *txq) { if (txq->next_desc_to_proc == 0) txq->next_desc_to_proc = txq->last_desc - 1; else txq->next_desc_to_proc--; } /* Set rxq buf size */ static void mvneta_rxq_buf_size_set(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int buf_size) { u32 val; val = mvreg_read(pp, MVNETA_RXQ_SIZE_REG(rxq->id)); val &= ~MVNETA_RXQ_BUF_SIZE_MASK; val |= ((buf_size >> 3) << MVNETA_RXQ_BUF_SIZE_SHIFT); mvreg_write(pp, MVNETA_RXQ_SIZE_REG(rxq->id), val); } /* Disable buffer management (BM) */ static void mvneta_rxq_bm_disable(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { u32 val; val = mvreg_read(pp, MVNETA_RXQ_CONFIG_REG(rxq->id)); val &= ~MVNETA_RXQ_HW_BUF_ALLOC; mvreg_write(pp, MVNETA_RXQ_CONFIG_REG(rxq->id), val); } /* Sets the RGMII Enable bit (RGMIIEn) in port MAC control register */ static void mvneta_gmac_rgmii_set(struct mvneta_port *pp, int enable) { u32 val; val = mvreg_read(pp, MVNETA_GMAC_CTRL_2); if (enable) val |= MVNETA_GMAC2_PORT_RGMII; else val &= ~MVNETA_GMAC2_PORT_RGMII; mvreg_write(pp, MVNETA_GMAC_CTRL_2, val); } /* Config SGMII port */ static void mvneta_port_sgmii_config(struct mvneta_port *pp) { u32 val; val = mvreg_read(pp, MVNETA_GMAC_CTRL_2); val |= MVNETA_GMAC2_PCS_ENABLE; mvreg_write(pp, MVNETA_GMAC_CTRL_2, val); } /* Start the Ethernet port RX and TX activity */ static void mvneta_port_up(struct mvneta_port *pp) { int queue; u32 q_map; /* Enable all initialized TXs. */ mvneta_mib_counters_clear(pp); q_map = 0; for (queue = 0; queue < txq_number; queue++) { struct mvneta_tx_queue *txq = &pp->txqs[queue]; if (txq->descs != NULL) q_map |= (1 << queue); } mvreg_write(pp, MVNETA_TXQ_CMD, q_map); /* Enable all initialized RXQs. */ q_map = 0; for (queue = 0; queue < rxq_number; queue++) { struct mvneta_rx_queue *rxq = &pp->rxqs[queue]; if (rxq->descs != NULL) q_map |= (1 << queue); } mvreg_write(pp, MVNETA_RXQ_CMD, q_map); } /* Stop the Ethernet port activity */ static void mvneta_port_down(struct mvneta_port *pp) { u32 val; int count; /* Stop Rx port activity. Check port Rx activity. */ val = mvreg_read(pp, MVNETA_RXQ_CMD) & MVNETA_RXQ_ENABLE_MASK; /* Issue stop command for active channels only */ if (val != 0) mvreg_write(pp, MVNETA_RXQ_CMD, val << MVNETA_RXQ_DISABLE_SHIFT); /* Wait for all Rx activity to terminate. */ count = 0; do { if (count++ >= MVNETA_RX_DISABLE_TIMEOUT_MSEC) { netdev_warn(pp->dev, "TIMEOUT for RX stopped ! rx_queue_cmd: 0x08%x\n", val); break; } mdelay(1); val = mvreg_read(pp, MVNETA_RXQ_CMD); } while (val & 0xff); /* Stop Tx port activity. Check port Tx activity. Issue stop * command for active channels only */ val = (mvreg_read(pp, MVNETA_TXQ_CMD)) & MVNETA_TXQ_ENABLE_MASK; if (val != 0) mvreg_write(pp, MVNETA_TXQ_CMD, (val << MVNETA_TXQ_DISABLE_SHIFT)); /* Wait for all Tx activity to terminate. */ count = 0; do { if (count++ >= MVNETA_TX_DISABLE_TIMEOUT_MSEC) { netdev_warn(pp->dev, "TIMEOUT for TX stopped status=0x%08x\n", val); break; } mdelay(1); /* Check TX Command reg that all Txqs are stopped */ val = mvreg_read(pp, MVNETA_TXQ_CMD); } while (val & 0xff); /* Double check to verify that TX FIFO is empty */ count = 0; do { if (count++ >= MVNETA_TX_FIFO_EMPTY_TIMEOUT) { netdev_warn(pp->dev, "TX FIFO empty timeout status=0x08%x\n", val); break; } mdelay(1); val = mvreg_read(pp, MVNETA_PORT_STATUS); } while (!(val & MVNETA_TX_FIFO_EMPTY) && (val & MVNETA_TX_IN_PRGRS)); udelay(200); } /* Enable the port by setting the port enable bit of the MAC control register */ static void mvneta_port_enable(struct mvneta_port *pp) { u32 val; /* Enable port */ val = mvreg_read(pp, MVNETA_GMAC_CTRL_0); val |= MVNETA_GMAC0_PORT_ENABLE; mvreg_write(pp, MVNETA_GMAC_CTRL_0, val); } /* Disable the port and wait for about 200 usec before retuning */ static void mvneta_port_disable(struct mvneta_port *pp) { u32 val; /* Reset the Enable bit in the Serial Control Register */ val = mvreg_read(pp, MVNETA_GMAC_CTRL_0); val &= ~MVNETA_GMAC0_PORT_ENABLE; mvreg_write(pp, MVNETA_GMAC_CTRL_0, val); udelay(200); } /* Multicast tables methods */ /* Set all entries in Unicast MAC Table; queue==-1 means reject all */ static void mvneta_set_ucast_table(struct mvneta_port *pp, int queue) { int offset; u32 val; if (queue == -1) { val = 0; } else { val = 0x1 | (queue << 1); val |= (val << 24) | (val << 16) | (val << 8); } for (offset = 0; offset <= 0xc; offset += 4) mvreg_write(pp, MVNETA_DA_FILT_UCAST_BASE + offset, val); } /* Set all entries in Special Multicast MAC Table; queue==-1 means reject all */ static void mvneta_set_special_mcast_table(struct mvneta_port *pp, int queue) { int offset; u32 val; if (queue == -1) { val = 0; } else { val = 0x1 | (queue << 1); val |= (val << 24) | (val << 16) | (val << 8); } for (offset = 0; offset <= 0xfc; offset += 4) mvreg_write(pp, MVNETA_DA_FILT_SPEC_MCAST + offset, val); } /* Set all entries in Other Multicast MAC Table. queue==-1 means reject all */ static void mvneta_set_other_mcast_table(struct mvneta_port *pp, int queue) { int offset; u32 val; if (queue == -1) { memset(pp->mcast_count, 0, sizeof(pp->mcast_count)); val = 0; } else { memset(pp->mcast_count, 1, sizeof(pp->mcast_count)); val = 0x1 | (queue << 1); val |= (val << 24) | (val << 16) | (val << 8); } for (offset = 0; offset <= 0xfc; offset += 4) mvreg_write(pp, MVNETA_DA_FILT_OTH_MCAST + offset, val); } /* This method sets defaults to the NETA port: * Clears interrupt Cause and Mask registers. * Clears all MAC tables. * Sets defaults to all registers. * Resets RX and TX descriptor rings. * Resets PHY. * This method can be called after mvneta_port_down() to return the port * settings to defaults. */ static void mvneta_defaults_set(struct mvneta_port *pp) { int cpu; int queue; u32 val; /* Clear all Cause registers */ mvreg_write(pp, MVNETA_INTR_NEW_CAUSE, 0); mvreg_write(pp, MVNETA_INTR_OLD_CAUSE, 0); mvreg_write(pp, MVNETA_INTR_MISC_CAUSE, 0); /* Mask all interrupts */ mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0); mvreg_write(pp, MVNETA_INTR_OLD_MASK, 0); mvreg_write(pp, MVNETA_INTR_MISC_MASK, 0); mvreg_write(pp, MVNETA_INTR_ENABLE, 0); /* Enable MBUS Retry bit16 */ mvreg_write(pp, MVNETA_MBUS_RETRY, 0x20); /* Set CPU queue access map - all CPUs have access to all RX * queues and to all TX queues */ for (cpu = 0; cpu < CONFIG_NR_CPUS; cpu++) mvreg_write(pp, MVNETA_CPU_MAP(cpu), (MVNETA_CPU_RXQ_ACCESS_ALL_MASK | MVNETA_CPU_TXQ_ACCESS_ALL_MASK)); /* Reset RX and TX DMAs */ mvreg_write(pp, MVNETA_PORT_RX_RESET, MVNETA_PORT_RX_DMA_RESET); mvreg_write(pp, MVNETA_PORT_TX_RESET, MVNETA_PORT_TX_DMA_RESET); /* Disable Legacy WRR, Disable EJP, Release from reset */ mvreg_write(pp, MVNETA_TXQ_CMD_1, 0); for (queue = 0; queue < txq_number; queue++) { mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(queue), 0); mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(queue), 0); } mvreg_write(pp, MVNETA_PORT_TX_RESET, 0); mvreg_write(pp, MVNETA_PORT_RX_RESET, 0); /* Set Port Acceleration Mode */ val = MVNETA_ACC_MODE_EXT; mvreg_write(pp, MVNETA_ACC_MODE, val); /* Update val of portCfg register accordingly with all RxQueue types */ val = MVNETA_PORT_CONFIG_DEFL_VALUE(rxq_def); mvreg_write(pp, MVNETA_PORT_CONFIG, val); val = 0; mvreg_write(pp, MVNETA_PORT_CONFIG_EXTEND, val); mvreg_write(pp, MVNETA_RX_MIN_FRAME_SIZE, 64); /* Build PORT_SDMA_CONFIG_REG */ val = 0; /* Default burst size */ val |= MVNETA_TX_BRST_SZ_MASK(MVNETA_SDMA_BRST_SIZE_16); val |= MVNETA_RX_BRST_SZ_MASK(MVNETA_SDMA_BRST_SIZE_16); val |= (MVNETA_RX_NO_DATA_SWAP | MVNETA_TX_NO_DATA_SWAP | MVNETA_NO_DESC_SWAP); /* Assign port SDMA configuration */ mvreg_write(pp, MVNETA_SDMA_CONFIG, val); /* Disable PHY polling in hardware, since we're using the * kernel phylib to do this. */ val = mvreg_read(pp, MVNETA_UNIT_CONTROL); val &= ~MVNETA_PHY_POLLING_ENABLE; mvreg_write(pp, MVNETA_UNIT_CONTROL, val); mvneta_set_ucast_table(pp, -1); mvneta_set_special_mcast_table(pp, -1); mvneta_set_other_mcast_table(pp, -1); /* Set port interrupt enable register - default enable all */ mvreg_write(pp, MVNETA_INTR_ENABLE, (MVNETA_RXQ_INTR_ENABLE_ALL_MASK | MVNETA_TXQ_INTR_ENABLE_ALL_MASK)); } /* Set max sizes for tx queues */ static void mvneta_txq_max_tx_size_set(struct mvneta_port *pp, int max_tx_size) { u32 val, size, mtu; int queue; mtu = max_tx_size * 8; if (mtu > MVNETA_TX_MTU_MAX) mtu = MVNETA_TX_MTU_MAX; /* Set MTU */ val = mvreg_read(pp, MVNETA_TX_MTU); val &= ~MVNETA_TX_MTU_MAX; val |= mtu; mvreg_write(pp, MVNETA_TX_MTU, val); /* TX token size and all TXQs token size must be larger that MTU */ val = mvreg_read(pp, MVNETA_TX_TOKEN_SIZE); size = val & MVNETA_TX_TOKEN_SIZE_MAX; if (size < mtu) { size = mtu; val &= ~MVNETA_TX_TOKEN_SIZE_MAX; val |= size; mvreg_write(pp, MVNETA_TX_TOKEN_SIZE, val); } for (queue = 0; queue < txq_number; queue++) { val = mvreg_read(pp, MVNETA_TXQ_TOKEN_SIZE_REG(queue)); size = val & MVNETA_TXQ_TOKEN_SIZE_MAX; if (size < mtu) { size = mtu; val &= ~MVNETA_TXQ_TOKEN_SIZE_MAX; val |= size; mvreg_write(pp, MVNETA_TXQ_TOKEN_SIZE_REG(queue), val); } } } /* Set unicast address */ static void mvneta_set_ucast_addr(struct mvneta_port *pp, u8 last_nibble, int queue) { unsigned int unicast_reg; unsigned int tbl_offset; unsigned int reg_offset; /* Locate the Unicast table entry */ last_nibble = (0xf & last_nibble); /* offset from unicast tbl base */ tbl_offset = (last_nibble / 4) * 4; /* offset within the above reg */ reg_offset = last_nibble % 4; unicast_reg = mvreg_read(pp, (MVNETA_DA_FILT_UCAST_BASE + tbl_offset)); if (queue == -1) { /* Clear accepts frame bit at specified unicast DA tbl entry */ unicast_reg &= ~(0xff << (8 * reg_offset)); } else { unicast_reg &= ~(0xff << (8 * reg_offset)); unicast_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset)); } mvreg_write(pp, (MVNETA_DA_FILT_UCAST_BASE + tbl_offset), unicast_reg); } /* Set mac address */ static void mvneta_mac_addr_set(struct mvneta_port *pp, unsigned char *addr, int queue) { unsigned int mac_h; unsigned int mac_l; if (queue != -1) { mac_l = (addr[4] << 8) | (addr[5]); mac_h = (addr[0] << 24) | (addr[1] << 16) | (addr[2] << 8) | (addr[3] << 0); mvreg_write(pp, MVNETA_MAC_ADDR_LOW, mac_l); mvreg_write(pp, MVNETA_MAC_ADDR_HIGH, mac_h); } /* Accept frames of this address */ mvneta_set_ucast_addr(pp, addr[5], queue); } /* Set the number of packets that will be received before RX interrupt * will be generated by HW. */ static void mvneta_rx_pkts_coal_set(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, u32 value) { mvreg_write(pp, MVNETA_RXQ_THRESHOLD_REG(rxq->id), value | MVNETA_RXQ_NON_OCCUPIED(0)); rxq->pkts_coal = value; } /* Set the time delay in usec before RX interrupt will be generated by * HW. */ static void mvneta_rx_time_coal_set(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, u32 value) { u32 val; unsigned long clk_rate; clk_rate = clk_get_rate(pp->clk); val = (clk_rate / 1000000) * value; mvreg_write(pp, MVNETA_RXQ_TIME_COAL_REG(rxq->id), val); rxq->time_coal = value; } /* Set threshold for TX_DONE pkts coalescing */ static void mvneta_tx_done_pkts_coal_set(struct mvneta_port *pp, struct mvneta_tx_queue *txq, u32 value) { u32 val; val = mvreg_read(pp, MVNETA_TXQ_SIZE_REG(txq->id)); val &= ~MVNETA_TXQ_SENT_THRESH_ALL_MASK; val |= MVNETA_TXQ_SENT_THRESH_MASK(value); mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), val); txq->done_pkts_coal = value; } /* Handle rx descriptor fill by setting buf_cookie and buf_phys_addr */ static void mvneta_rx_desc_fill(struct mvneta_rx_desc *rx_desc, u32 phys_addr, u32 cookie) { rx_desc->buf_cookie = cookie; rx_desc->buf_phys_addr = phys_addr; } /* Decrement sent descriptors counter */ static void mvneta_txq_sent_desc_dec(struct mvneta_port *pp, struct mvneta_tx_queue *txq, int sent_desc) { u32 val; /* Only 255 TX descriptors can be updated at once */ while (sent_desc > 0xff) { val = 0xff << MVNETA_TXQ_DEC_SENT_SHIFT; mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val); sent_desc = sent_desc - 0xff; } val = sent_desc << MVNETA_TXQ_DEC_SENT_SHIFT; mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val); } /* Get number of TX descriptors already sent by HW */ static int mvneta_txq_sent_desc_num_get(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { u32 val; int sent_desc; val = mvreg_read(pp, MVNETA_TXQ_STATUS_REG(txq->id)); sent_desc = (val & MVNETA_TXQ_SENT_DESC_MASK) >> MVNETA_TXQ_SENT_DESC_SHIFT; return sent_desc; } /* Get number of sent descriptors and decrement counter. * The number of sent descriptors is returned. */ static int mvneta_txq_sent_desc_proc(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { int sent_desc; /* Get number of sent descriptors */ sent_desc = mvneta_txq_sent_desc_num_get(pp, txq); /* Decrement sent descriptors counter */ if (sent_desc) mvneta_txq_sent_desc_dec(pp, txq, sent_desc); return sent_desc; } /* Set TXQ descriptors fields relevant for CSUM calculation */ static u32 mvneta_txq_desc_csum(int l3_offs, int l3_proto, int ip_hdr_len, int l4_proto) { u32 command; /* Fields: L3_offset, IP_hdrlen, L3_type, G_IPv4_chk, * G_L4_chk, L4_type; required only for checksum * calculation */ command = l3_offs << MVNETA_TX_L3_OFF_SHIFT; command |= ip_hdr_len << MVNETA_TX_IP_HLEN_SHIFT; if (l3_proto == htons(ETH_P_IP)) command |= MVNETA_TXD_IP_CSUM; else command |= MVNETA_TX_L3_IP6; if (l4_proto == IPPROTO_TCP) command |= MVNETA_TX_L4_CSUM_FULL; else if (l4_proto == IPPROTO_UDP) command |= MVNETA_TX_L4_UDP | MVNETA_TX_L4_CSUM_FULL; else command |= MVNETA_TX_L4_CSUM_NOT; return command; } /* Display more error info */ static void mvneta_rx_error(struct mvneta_port *pp, struct mvneta_rx_desc *rx_desc) { u32 status = rx_desc->status; if (!mvneta_rxq_desc_is_first_last(rx_desc)) { netdev_err(pp->dev, "bad rx status %08x (buffer oversize), size=%d\n", rx_desc->status, rx_desc->data_size); return; } switch (status & MVNETA_RXD_ERR_CODE_MASK) { case MVNETA_RXD_ERR_CRC: netdev_err(pp->dev, "bad rx status %08x (crc error), size=%d\n", status, rx_desc->data_size); break; case MVNETA_RXD_ERR_OVERRUN: netdev_err(pp->dev, "bad rx status %08x (overrun error), size=%d\n", status, rx_desc->data_size); break; case MVNETA_RXD_ERR_LEN: netdev_err(pp->dev, "bad rx status %08x (max frame length error), size=%d\n", status, rx_desc->data_size); break; case MVNETA_RXD_ERR_RESOURCE: netdev_err(pp->dev, "bad rx status %08x (resource error), size=%d\n", status, rx_desc->data_size); break; } } /* Handle RX checksum offload */ static void mvneta_rx_csum(struct mvneta_port *pp, struct mvneta_rx_desc *rx_desc, struct sk_buff *skb) { if ((rx_desc->status & MVNETA_RXD_L3_IP4) && (rx_desc->status & MVNETA_RXD_L4_CSUM_OK)) { skb->csum = 0; skb->ip_summed = CHECKSUM_UNNECESSARY; return; } skb->ip_summed = CHECKSUM_NONE; } /* Return tx queue pointer (find last set bit) according to causeTxDone reg */ static struct mvneta_tx_queue *mvneta_tx_done_policy(struct mvneta_port *pp, u32 cause) { int queue = fls(cause) - 1; return (queue < 0 || queue >= txq_number) ? NULL : &pp->txqs[queue]; } /* Free tx queue skbuffs */ static void mvneta_txq_bufs_free(struct mvneta_port *pp, struct mvneta_tx_queue *txq, int num) { int i; for (i = 0; i < num; i++) { struct mvneta_tx_desc *tx_desc = txq->descs + txq->txq_get_index; struct sk_buff *skb = txq->tx_skb[txq->txq_get_index]; mvneta_txq_inc_get(txq); if (!skb) continue; dma_unmap_single(pp->dev->dev.parent, tx_desc->buf_phys_addr, tx_desc->data_size, DMA_TO_DEVICE); dev_kfree_skb_any(skb); } } /* Handle end of transmission */ static int mvneta_txq_done(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { struct netdev_queue *nq = netdev_get_tx_queue(pp->dev, txq->id); int tx_done; tx_done = mvneta_txq_sent_desc_proc(pp, txq); if (tx_done == 0) return tx_done; mvneta_txq_bufs_free(pp, txq, tx_done); txq->count -= tx_done; if (netif_tx_queue_stopped(nq)) { if (txq->size - txq->count >= MAX_SKB_FRAGS + 1) netif_tx_wake_queue(nq); } return tx_done; } /* Refill processing */ static int mvneta_rx_refill(struct mvneta_port *pp, struct mvneta_rx_desc *rx_desc) { dma_addr_t phys_addr; struct sk_buff *skb; skb = netdev_alloc_skb(pp->dev, pp->pkt_size); if (!skb) return -ENOMEM; phys_addr = dma_map_single(pp->dev->dev.parent, skb->head, MVNETA_RX_BUF_SIZE(pp->pkt_size), DMA_FROM_DEVICE); if (unlikely(dma_mapping_error(pp->dev->dev.parent, phys_addr))) { dev_kfree_skb(skb); return -ENOMEM; } mvneta_rx_desc_fill(rx_desc, phys_addr, (u32)skb); return 0; } /* Handle tx checksum */ static u32 mvneta_skb_tx_csum(struct mvneta_port *pp, struct sk_buff *skb) { if (skb->ip_summed == CHECKSUM_PARTIAL) { int ip_hdr_len = 0; u8 l4_proto; if (skb->protocol == htons(ETH_P_IP)) { struct iphdr *ip4h = ip_hdr(skb); /* Calculate IPv4 checksum and L4 checksum */ ip_hdr_len = ip4h->ihl; l4_proto = ip4h->protocol; } else if (skb->protocol == htons(ETH_P_IPV6)) { struct ipv6hdr *ip6h = ipv6_hdr(skb); /* Read l4_protocol from one of IPv6 extra headers */ if (skb_network_header_len(skb) > 0) ip_hdr_len = (skb_network_header_len(skb) >> 2); l4_proto = ip6h->nexthdr; } else return MVNETA_TX_L4_CSUM_NOT; return mvneta_txq_desc_csum(skb_network_offset(skb), skb->protocol, ip_hdr_len, l4_proto); } return MVNETA_TX_L4_CSUM_NOT; } /* Returns rx queue pointer (find last set bit) according to causeRxTx * value */ static struct mvneta_rx_queue *mvneta_rx_policy(struct mvneta_port *pp, u32 cause) { int queue = fls(cause >> 8) - 1; return (queue < 0 || queue >= rxq_number) ? NULL : &pp->rxqs[queue]; } /* Drop packets received by the RXQ and free buffers */ static void mvneta_rxq_drop_pkts(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { int rx_done, i; rx_done = mvneta_rxq_busy_desc_num_get(pp, rxq); for (i = 0; i < rxq->size; i++) { struct mvneta_rx_desc *rx_desc = rxq->descs + i; struct sk_buff *skb = (struct sk_buff *)rx_desc->buf_cookie; dev_kfree_skb_any(skb); dma_unmap_single(pp->dev->dev.parent, rx_desc->buf_phys_addr, rx_desc->data_size, DMA_FROM_DEVICE); } if (rx_done) mvneta_rxq_desc_num_update(pp, rxq, rx_done, rx_done); } /* Main rx processing */ static int mvneta_rx(struct mvneta_port *pp, int rx_todo, struct mvneta_rx_queue *rxq) { struct net_device *dev = pp->dev; int rx_done, rx_filled; u32 rcvd_pkts = 0; u32 rcvd_bytes = 0; /* Get number of received packets */ rx_done = mvneta_rxq_busy_desc_num_get(pp, rxq); if (rx_todo > rx_done) rx_todo = rx_done; rx_done = 0; rx_filled = 0; /* Fairness NAPI loop */ while (rx_done < rx_todo) { struct mvneta_rx_desc *rx_desc = mvneta_rxq_next_desc_get(rxq); struct sk_buff *skb; u32 rx_status; int rx_bytes, err; prefetch(rx_desc); rx_done++; rx_filled++; rx_status = rx_desc->status; skb = (struct sk_buff *)rx_desc->buf_cookie; if (!mvneta_rxq_desc_is_first_last(rx_desc) || (rx_status & MVNETA_RXD_ERR_SUMMARY)) { dev->stats.rx_errors++; mvneta_rx_error(pp, rx_desc); mvneta_rx_desc_fill(rx_desc, rx_desc->buf_phys_addr, (u32)skb); continue; } dma_unmap_single(pp->dev->dev.parent, rx_desc->buf_phys_addr, rx_desc->data_size, DMA_FROM_DEVICE); rx_bytes = rx_desc->data_size - (ETH_FCS_LEN + MVNETA_MH_SIZE); rcvd_pkts++; rcvd_bytes += rx_bytes; /* Linux processing */ skb_reserve(skb, MVNETA_MH_SIZE); skb_put(skb, rx_bytes); skb->protocol = eth_type_trans(skb, dev); mvneta_rx_csum(pp, rx_desc, skb); napi_gro_receive(&pp->napi, skb); /* Refill processing */ err = mvneta_rx_refill(pp, rx_desc); if (err) { netdev_err(pp->dev, "Linux processing - Can't refill\n"); rxq->missed++; rx_filled--; } } if (rcvd_pkts) { struct mvneta_pcpu_stats *stats = this_cpu_ptr(pp->stats); u64_stats_update_begin(&stats->syncp); stats->rx_packets += rcvd_pkts; stats->rx_bytes += rcvd_bytes; u64_stats_update_end(&stats->syncp); } /* Update rxq management counters */ mvneta_rxq_desc_num_update(pp, rxq, rx_done, rx_filled); return rx_done; } /* Handle tx fragmentation processing */ static int mvneta_tx_frag_process(struct mvneta_port *pp, struct sk_buff *skb, struct mvneta_tx_queue *txq) { struct mvneta_tx_desc *tx_desc; int i; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; void *addr = page_address(frag->page.p) + frag->page_offset; tx_desc = mvneta_txq_next_desc_get(txq); tx_desc->data_size = frag->size; tx_desc->buf_phys_addr = dma_map_single(pp->dev->dev.parent, addr, tx_desc->data_size, DMA_TO_DEVICE); if (dma_mapping_error(pp->dev->dev.parent, tx_desc->buf_phys_addr)) { mvneta_txq_desc_put(txq); goto error; } if (i == (skb_shinfo(skb)->nr_frags - 1)) { /* Last descriptor */ tx_desc->command = MVNETA_TXD_L_DESC | MVNETA_TXD_Z_PAD; txq->tx_skb[txq->txq_put_index] = skb; mvneta_txq_inc_put(txq); } else { /* Descriptor in the middle: Not First, Not Last */ tx_desc->command = 0; txq->tx_skb[txq->txq_put_index] = NULL; mvneta_txq_inc_put(txq); } } return 0; error: /* Release all descriptors that were used to map fragments of * this packet, as well as the corresponding DMA mappings */ for (i = i - 1; i >= 0; i--) { tx_desc = txq->descs + i; dma_unmap_single(pp->dev->dev.parent, tx_desc->buf_phys_addr, tx_desc->data_size, DMA_TO_DEVICE); mvneta_txq_desc_put(txq); } return -ENOMEM; } /* Main tx processing */ static int mvneta_tx(struct sk_buff *skb, struct net_device *dev) { struct mvneta_port *pp = netdev_priv(dev); u16 txq_id = skb_get_queue_mapping(skb); struct mvneta_tx_queue *txq = &pp->txqs[txq_id]; struct mvneta_tx_desc *tx_desc; struct netdev_queue *nq; int frags = 0; u32 tx_cmd; if (!netif_running(dev)) goto out; frags = skb_shinfo(skb)->nr_frags + 1; nq = netdev_get_tx_queue(dev, txq_id); /* Get a descriptor for the first part of the packet */ tx_desc = mvneta_txq_next_desc_get(txq); tx_cmd = mvneta_skb_tx_csum(pp, skb); tx_desc->data_size = skb_headlen(skb); tx_desc->buf_phys_addr = dma_map_single(dev->dev.parent, skb->data, tx_desc->data_size, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(dev->dev.parent, tx_desc->buf_phys_addr))) { mvneta_txq_desc_put(txq); frags = 0; goto out; } if (frags == 1) { /* First and Last descriptor */ tx_cmd |= MVNETA_TXD_FLZ_DESC; tx_desc->command = tx_cmd; txq->tx_skb[txq->txq_put_index] = skb; mvneta_txq_inc_put(txq); } else { /* First but not Last */ tx_cmd |= MVNETA_TXD_F_DESC; txq->tx_skb[txq->txq_put_index] = NULL; mvneta_txq_inc_put(txq); tx_desc->command = tx_cmd; /* Continue with other skb fragments */ if (mvneta_tx_frag_process(pp, skb, txq)) { dma_unmap_single(dev->dev.parent, tx_desc->buf_phys_addr, tx_desc->data_size, DMA_TO_DEVICE); mvneta_txq_desc_put(txq); frags = 0; goto out; } } txq->count += frags; mvneta_txq_pend_desc_add(pp, txq, frags); if (txq->size - txq->count < MAX_SKB_FRAGS + 1) netif_tx_stop_queue(nq); out: if (frags > 0) { struct mvneta_pcpu_stats *stats = this_cpu_ptr(pp->stats); u64_stats_update_begin(&stats->syncp); stats->tx_packets++; stats->tx_bytes += skb->len; u64_stats_update_end(&stats->syncp); } else { dev->stats.tx_dropped++; dev_kfree_skb_any(skb); } return NETDEV_TX_OK; } /* Free tx resources, when resetting a port */ static void mvneta_txq_done_force(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { int tx_done = txq->count; mvneta_txq_bufs_free(pp, txq, tx_done); /* reset txq */ txq->count = 0; txq->txq_put_index = 0; txq->txq_get_index = 0; } /* handle tx done - called from tx done timer callback */ static u32 mvneta_tx_done_gbe(struct mvneta_port *pp, u32 cause_tx_done, int *tx_todo) { struct mvneta_tx_queue *txq; u32 tx_done = 0; struct netdev_queue *nq; *tx_todo = 0; while (cause_tx_done != 0) { txq = mvneta_tx_done_policy(pp, cause_tx_done); if (!txq) break; nq = netdev_get_tx_queue(pp->dev, txq->id); __netif_tx_lock(nq, smp_processor_id()); if (txq->count) { tx_done += mvneta_txq_done(pp, txq); *tx_todo += txq->count; } __netif_tx_unlock(nq); cause_tx_done &= ~((1 << txq->id)); } return tx_done; } /* Compute crc8 of the specified address, using a unique algorithm , * according to hw spec, different than generic crc8 algorithm */ static int mvneta_addr_crc(unsigned char *addr) { int crc = 0; int i; for (i = 0; i < ETH_ALEN; i++) { int j; crc = (crc ^ addr[i]) << 8; for (j = 7; j >= 0; j--) { if (crc & (0x100 << j)) crc ^= 0x107 << j; } } return crc; } /* This method controls the net device special MAC multicast support. * The Special Multicast Table for MAC addresses supports MAC of the form * 0x01-00-5E-00-00-XX (where XX is between 0x00 and 0xFF). * The MAC DA[7:0] bits are used as a pointer to the Special Multicast * Table entries in the DA-Filter table. This method set the Special * Multicast Table appropriate entry. */ static void mvneta_set_special_mcast_addr(struct mvneta_port *pp, unsigned char last_byte, int queue) { unsigned int smc_table_reg; unsigned int tbl_offset; unsigned int reg_offset; /* Register offset from SMC table base */ tbl_offset = (last_byte / 4); /* Entry offset within the above reg */ reg_offset = last_byte % 4; smc_table_reg = mvreg_read(pp, (MVNETA_DA_FILT_SPEC_MCAST + tbl_offset * 4)); if (queue == -1) smc_table_reg &= ~(0xff << (8 * reg_offset)); else { smc_table_reg &= ~(0xff << (8 * reg_offset)); smc_table_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset)); } mvreg_write(pp, MVNETA_DA_FILT_SPEC_MCAST + tbl_offset * 4, smc_table_reg); } /* This method controls the network device Other MAC multicast support. * The Other Multicast Table is used for multicast of another type. * A CRC-8 is used as an index to the Other Multicast Table entries * in the DA-Filter table. * The method gets the CRC-8 value from the calling routine and * sets the Other Multicast Table appropriate entry according to the * specified CRC-8 . */ static void mvneta_set_other_mcast_addr(struct mvneta_port *pp, unsigned char crc8, int queue) { unsigned int omc_table_reg; unsigned int tbl_offset; unsigned int reg_offset; tbl_offset = (crc8 / 4) * 4; /* Register offset from OMC table base */ reg_offset = crc8 % 4; /* Entry offset within the above reg */ omc_table_reg = mvreg_read(pp, MVNETA_DA_FILT_OTH_MCAST + tbl_offset); if (queue == -1) { /* Clear accepts frame bit at specified Other DA table entry */ omc_table_reg &= ~(0xff << (8 * reg_offset)); } else { omc_table_reg &= ~(0xff << (8 * reg_offset)); omc_table_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset)); } mvreg_write(pp, MVNETA_DA_FILT_OTH_MCAST + tbl_offset, omc_table_reg); } /* The network device supports multicast using two tables: * 1) Special Multicast Table for MAC addresses of the form * 0x01-00-5E-00-00-XX (where XX is between 0x00 and 0xFF). * The MAC DA[7:0] bits are used as a pointer to the Special Multicast * Table entries in the DA-Filter table. * 2) Other Multicast Table for multicast of another type. A CRC-8 value * is used as an index to the Other Multicast Table entries in the * DA-Filter table. */ static int mvneta_mcast_addr_set(struct mvneta_port *pp, unsigned char *p_addr, int queue) { unsigned char crc_result = 0; if (memcmp(p_addr, "\x01\x00\x5e\x00\x00", 5) == 0) { mvneta_set_special_mcast_addr(pp, p_addr[5], queue); return 0; } crc_result = mvneta_addr_crc(p_addr); if (queue == -1) { if (pp->mcast_count[crc_result] == 0) { netdev_info(pp->dev, "No valid Mcast for crc8=0x%02x\n", crc_result); return -EINVAL; } pp->mcast_count[crc_result]--; if (pp->mcast_count[crc_result] != 0) { netdev_info(pp->dev, "After delete there are %d valid Mcast for crc8=0x%02x\n", pp->mcast_count[crc_result], crc_result); return -EINVAL; } } else pp->mcast_count[crc_result]++; mvneta_set_other_mcast_addr(pp, crc_result, queue); return 0; } /* Configure Fitering mode of Ethernet port */ static void mvneta_rx_unicast_promisc_set(struct mvneta_port *pp, int is_promisc) { u32 port_cfg_reg, val; port_cfg_reg = mvreg_read(pp, MVNETA_PORT_CONFIG); val = mvreg_read(pp, MVNETA_TYPE_PRIO); /* Set / Clear UPM bit in port configuration register */ if (is_promisc) { /* Accept all Unicast addresses */ port_cfg_reg |= MVNETA_UNI_PROMISC_MODE; val |= MVNETA_FORCE_UNI; mvreg_write(pp, MVNETA_MAC_ADDR_LOW, 0xffff); mvreg_write(pp, MVNETA_MAC_ADDR_HIGH, 0xffffffff); } else { /* Reject all Unicast addresses */ port_cfg_reg &= ~MVNETA_UNI_PROMISC_MODE; val &= ~MVNETA_FORCE_UNI; } mvreg_write(pp, MVNETA_PORT_CONFIG, port_cfg_reg); mvreg_write(pp, MVNETA_TYPE_PRIO, val); } /* register unicast and multicast addresses */ static void mvneta_set_rx_mode(struct net_device *dev) { struct mvneta_port *pp = netdev_priv(dev); struct netdev_hw_addr *ha; if (dev->flags & IFF_PROMISC) { /* Accept all: Multicast + Unicast */ mvneta_rx_unicast_promisc_set(pp, 1); mvneta_set_ucast_table(pp, rxq_def); mvneta_set_special_mcast_table(pp, rxq_def); mvneta_set_other_mcast_table(pp, rxq_def); } else { /* Accept single Unicast */ mvneta_rx_unicast_promisc_set(pp, 0); mvneta_set_ucast_table(pp, -1); mvneta_mac_addr_set(pp, dev->dev_addr, rxq_def); if (dev->flags & IFF_ALLMULTI) { /* Accept all multicast */ mvneta_set_special_mcast_table(pp, rxq_def); mvneta_set_other_mcast_table(pp, rxq_def); } else { /* Accept only initialized multicast */ mvneta_set_special_mcast_table(pp, -1); mvneta_set_other_mcast_table(pp, -1); if (!netdev_mc_empty(dev)) { netdev_for_each_mc_addr(ha, dev) { mvneta_mcast_addr_set(pp, ha->addr, rxq_def); } } } } } /* Interrupt handling - the callback for request_irq() */ static irqreturn_t mvneta_isr(int irq, void *dev_id) { struct mvneta_port *pp = (struct mvneta_port *)dev_id; /* Mask all interrupts */ mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0); napi_schedule(&pp->napi); return IRQ_HANDLED; } /* NAPI handler * Bits 0 - 7 of the causeRxTx register indicate that are transmitted * packets on the corresponding TXQ (Bit 0 is for TX queue 1). * Bits 8 -15 of the cause Rx Tx register indicate that are received * packets on the corresponding RXQ (Bit 8 is for RX queue 0). * Each CPU has its own causeRxTx register */ static int mvneta_poll(struct napi_struct *napi, int budget) { int rx_done = 0; u32 cause_rx_tx; unsigned long flags; struct mvneta_port *pp = netdev_priv(napi->dev); if (!netif_running(pp->dev)) { napi_complete(napi); return rx_done; } /* Read cause register */ cause_rx_tx = mvreg_read(pp, MVNETA_INTR_NEW_CAUSE) & (MVNETA_RX_INTR_MASK(rxq_number) | MVNETA_TX_INTR_MASK(txq_number)); /* Release Tx descriptors */ if (cause_rx_tx & MVNETA_TX_INTR_MASK_ALL) { int tx_todo = 0; mvneta_tx_done_gbe(pp, (cause_rx_tx & MVNETA_TX_INTR_MASK_ALL), &tx_todo); cause_rx_tx &= ~MVNETA_TX_INTR_MASK_ALL; } /* For the case where the last mvneta_poll did not process all * RX packets */ cause_rx_tx |= pp->cause_rx_tx; if (rxq_number > 1) { while ((cause_rx_tx & MVNETA_RX_INTR_MASK_ALL) && (budget > 0)) { int count; struct mvneta_rx_queue *rxq; /* get rx queue number from cause_rx_tx */ rxq = mvneta_rx_policy(pp, cause_rx_tx); if (!rxq) break; /* process the packet in that rx queue */ count = mvneta_rx(pp, budget, rxq); rx_done += count; budget -= count; if (budget > 0) { /* set off the rx bit of the * corresponding bit in the cause rx * tx register, so that next iteration * will find the next rx queue where * packets are received on */ cause_rx_tx &= ~((1 << rxq->id) << 8); } } } else { rx_done = mvneta_rx(pp, budget, &pp->rxqs[rxq_def]); budget -= rx_done; } if (budget > 0) { cause_rx_tx = 0; napi_complete(napi); local_irq_save(flags); mvreg_write(pp, MVNETA_INTR_NEW_MASK, MVNETA_RX_INTR_MASK(rxq_number) | MVNETA_TX_INTR_MASK(txq_number)); local_irq_restore(flags); } pp->cause_rx_tx = cause_rx_tx; return rx_done; } /* Handle rxq fill: allocates rxq skbs; called when initializing a port */ static int mvneta_rxq_fill(struct mvneta_port *pp, struct mvneta_rx_queue *rxq, int num) { struct net_device *dev = pp->dev; int i; for (i = 0; i < num; i++) { struct sk_buff *skb; struct mvneta_rx_desc *rx_desc; unsigned long phys_addr; skb = dev_alloc_skb(pp->pkt_size); if (!skb) { netdev_err(dev, "%s:rxq %d, %d of %d buffs filled\n", __func__, rxq->id, i, num); break; } rx_desc = rxq->descs + i; memset(rx_desc, 0, sizeof(struct mvneta_rx_desc)); phys_addr = dma_map_single(dev->dev.parent, skb->head, MVNETA_RX_BUF_SIZE(pp->pkt_size), DMA_FROM_DEVICE); if (unlikely(dma_mapping_error(dev->dev.parent, phys_addr))) { dev_kfree_skb(skb); break; } mvneta_rx_desc_fill(rx_desc, phys_addr, (u32)skb); } /* Add this number of RX descriptors as non occupied (ready to * get packets) */ mvneta_rxq_non_occup_desc_add(pp, rxq, i); return i; } /* Free all packets pending transmit from all TXQs and reset TX port */ static void mvneta_tx_reset(struct mvneta_port *pp) { int queue; /* free the skb's in the hal tx ring */ for (queue = 0; queue < txq_number; queue++) mvneta_txq_done_force(pp, &pp->txqs[queue]); mvreg_write(pp, MVNETA_PORT_TX_RESET, MVNETA_PORT_TX_DMA_RESET); mvreg_write(pp, MVNETA_PORT_TX_RESET, 0); } static void mvneta_rx_reset(struct mvneta_port *pp) { mvreg_write(pp, MVNETA_PORT_RX_RESET, MVNETA_PORT_RX_DMA_RESET); mvreg_write(pp, MVNETA_PORT_RX_RESET, 0); } /* Rx/Tx queue initialization/cleanup methods */ /* Create a specified RX queue */ static int mvneta_rxq_init(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { rxq->size = pp->rx_ring_size; /* Allocate memory for RX descriptors */ rxq->descs = dma_alloc_coherent(pp->dev->dev.parent, rxq->size * MVNETA_DESC_ALIGNED_SIZE, &rxq->descs_phys, GFP_KERNEL); if (rxq->descs == NULL) return -ENOMEM; BUG_ON(rxq->descs != PTR_ALIGN(rxq->descs, MVNETA_CPU_D_CACHE_LINE_SIZE)); rxq->last_desc = rxq->size - 1; /* Set Rx descriptors queue starting address */ mvreg_write(pp, MVNETA_RXQ_BASE_ADDR_REG(rxq->id), rxq->descs_phys); mvreg_write(pp, MVNETA_RXQ_SIZE_REG(rxq->id), rxq->size); /* Set Offset */ mvneta_rxq_offset_set(pp, rxq, NET_SKB_PAD); /* Set coalescing pkts and time */ mvneta_rx_pkts_coal_set(pp, rxq, rxq->pkts_coal); mvneta_rx_time_coal_set(pp, rxq, rxq->time_coal); /* Fill RXQ with buffers from RX pool */ mvneta_rxq_buf_size_set(pp, rxq, MVNETA_RX_BUF_SIZE(pp->pkt_size)); mvneta_rxq_bm_disable(pp, rxq); mvneta_rxq_fill(pp, rxq, rxq->size); return 0; } /* Cleanup Rx queue */ static void mvneta_rxq_deinit(struct mvneta_port *pp, struct mvneta_rx_queue *rxq) { mvneta_rxq_drop_pkts(pp, rxq); if (rxq->descs) dma_free_coherent(pp->dev->dev.parent, rxq->size * MVNETA_DESC_ALIGNED_SIZE, rxq->descs, rxq->descs_phys); rxq->descs = NULL; rxq->last_desc = 0; rxq->next_desc_to_proc = 0; rxq->descs_phys = 0; } /* Create and initialize a tx queue */ static int mvneta_txq_init(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { txq->size = pp->tx_ring_size; /* Allocate memory for TX descriptors */ txq->descs = dma_alloc_coherent(pp->dev->dev.parent, txq->size * MVNETA_DESC_ALIGNED_SIZE, &txq->descs_phys, GFP_KERNEL); if (txq->descs == NULL) return -ENOMEM; /* Make sure descriptor address is cache line size aligned */ BUG_ON(txq->descs != PTR_ALIGN(txq->descs, MVNETA_CPU_D_CACHE_LINE_SIZE)); txq->last_desc = txq->size - 1; /* Set maximum bandwidth for enabled TXQs */ mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(txq->id), 0x03ffffff); mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(txq->id), 0x3fffffff); /* Set Tx descriptors queue starting address */ mvreg_write(pp, MVNETA_TXQ_BASE_ADDR_REG(txq->id), txq->descs_phys); mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), txq->size); txq->tx_skb = kmalloc(txq->size * sizeof(*txq->tx_skb), GFP_KERNEL); if (txq->tx_skb == NULL) { dma_free_coherent(pp->dev->dev.parent, txq->size * MVNETA_DESC_ALIGNED_SIZE, txq->descs, txq->descs_phys); return -ENOMEM; } mvneta_tx_done_pkts_coal_set(pp, txq, txq->done_pkts_coal); return 0; } /* Free allocated resources when mvneta_txq_init() fails to allocate memory*/ static void mvneta_txq_deinit(struct mvneta_port *pp, struct mvneta_tx_queue *txq) { kfree(txq->tx_skb); if (txq->descs) dma_free_coherent(pp->dev->dev.parent, txq->size * MVNETA_DESC_ALIGNED_SIZE, txq->descs, txq->descs_phys); txq->descs = NULL; txq->last_desc = 0; txq->next_desc_to_proc = 0; txq->descs_phys = 0; /* Set minimum bandwidth for disabled TXQs */ mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(txq->id), 0); mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(txq->id), 0); /* Set Tx descriptors queue starting address and size */ mvreg_write(pp, MVNETA_TXQ_BASE_ADDR_REG(txq->id), 0); mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), 0); } /* Cleanup all Tx queues */ static void mvneta_cleanup_txqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < txq_number; queue++) mvneta_txq_deinit(pp, &pp->txqs[queue]); } /* Cleanup all Rx queues */ static void mvneta_cleanup_rxqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < rxq_number; queue++) mvneta_rxq_deinit(pp, &pp->rxqs[queue]); } /* Init all Rx queues */ static int mvneta_setup_rxqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < rxq_number; queue++) { int err = mvneta_rxq_init(pp, &pp->rxqs[queue]); if (err) { netdev_err(pp->dev, "%s: can't create rxq=%d\n", __func__, queue); mvneta_cleanup_rxqs(pp); return err; } } return 0; } /* Init all tx queues */ static int mvneta_setup_txqs(struct mvneta_port *pp) { int queue; for (queue = 0; queue < txq_number; queue++) { int err = mvneta_txq_init(pp, &pp->txqs[queue]); if (err) { netdev_err(pp->dev, "%s: can't create txq=%d\n", __func__, queue); mvneta_cleanup_txqs(pp); return err; } } return 0; } static void mvneta_start_dev(struct mvneta_port *pp) { mvneta_max_rx_size_set(pp, pp->pkt_size); mvneta_txq_max_tx_size_set(pp, pp->pkt_size); /* start the Rx/Tx activity */ mvneta_port_enable(pp); /* Enable polling on the port */ napi_enable(&pp->napi); /* Unmask interrupts */ mvreg_write(pp, MVNETA_INTR_NEW_MASK, MVNETA_RX_INTR_MASK(rxq_number) | MVNETA_TX_INTR_MASK(txq_number)); phy_start(pp->phy_dev); netif_tx_start_all_queues(pp->dev); } static void mvneta_stop_dev(struct mvneta_port *pp) { phy_stop(pp->phy_dev); napi_disable(&pp->napi); netif_carrier_off(pp->dev); mvneta_port_down(pp); netif_tx_stop_all_queues(pp->dev); /* Stop the port activity */ mvneta_port_disable(pp); /* Clear all ethernet port interrupts */ mvreg_write(pp, MVNETA_INTR_MISC_CAUSE, 0); mvreg_write(pp, MVNETA_INTR_OLD_CAUSE, 0); /* Mask all ethernet port interrupts */ mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0); mvreg_write(pp, MVNETA_INTR_OLD_MASK, 0); mvreg_write(pp, MVNETA_INTR_MISC_MASK, 0); mvneta_tx_reset(pp); mvneta_rx_reset(pp); } /* Return positive if MTU is valid */ static int mvneta_check_mtu_valid(struct net_device *dev, int mtu) { if (mtu < 68) { netdev_err(dev, "cannot change mtu to less than 68\n"); return -EINVAL; } /* 9676 == 9700 - 20 and rounding to 8 */ if (mtu > 9676) { netdev_info(dev, "Illegal MTU value %d, round to 9676\n", mtu); mtu = 9676; } if (!IS_ALIGNED(MVNETA_RX_PKT_SIZE(mtu), 8)) { netdev_info(dev, "Illegal MTU value %d, rounding to %d\n", mtu, ALIGN(MVNETA_RX_PKT_SIZE(mtu), 8)); mtu = ALIGN(MVNETA_RX_PKT_SIZE(mtu), 8); } return mtu; } /* Change the device mtu */ static int mvneta_change_mtu(struct net_device *dev, int mtu) { struct mvneta_port *pp = netdev_priv(dev); int ret; mtu = mvneta_check_mtu_valid(dev, mtu); if (mtu < 0) return -EINVAL; dev->mtu = mtu; if (!netif_running(dev)) return 0; /* The interface is running, so we have to force a * reallocation of the RXQs */ mvneta_stop_dev(pp); mvneta_cleanup_txqs(pp); mvneta_cleanup_rxqs(pp); pp->pkt_size = MVNETA_RX_PKT_SIZE(pp->dev->mtu); ret = mvneta_setup_rxqs(pp); if (ret) { netdev_err(pp->dev, "unable to setup rxqs after MTU change\n"); return ret; } mvneta_setup_txqs(pp); mvneta_start_dev(pp); mvneta_port_up(pp); return 0; } /* Handle setting mac address */ static int mvneta_set_mac_addr(struct net_device *dev, void *addr) { struct mvneta_port *pp = netdev_priv(dev); u8 *mac = addr + 2; int i; if (netif_running(dev)) return -EBUSY; /* Remove previous address table entry */ mvneta_mac_addr_set(pp, dev->dev_addr, -1); /* Set new addr in hw */ mvneta_mac_addr_set(pp, mac, rxq_def); /* Set addr in the device */ for (i = 0; i < ETH_ALEN; i++) dev->dev_addr[i] = mac[i]; return 0; } static void mvneta_adjust_link(struct net_device *ndev) { struct mvneta_port *pp = netdev_priv(ndev); struct phy_device *phydev = pp->phy_dev; int status_change = 0; if (phydev->link) { if ((pp->speed != phydev->speed) || (pp->duplex != phydev->duplex)) { u32 val; val = mvreg_read(pp, MVNETA_GMAC_AUTONEG_CONFIG); val &= ~(MVNETA_GMAC_CONFIG_MII_SPEED | MVNETA_GMAC_CONFIG_GMII_SPEED | MVNETA_GMAC_CONFIG_FULL_DUPLEX | MVNETA_GMAC_AN_SPEED_EN | MVNETA_GMAC_AN_DUPLEX_EN); if (phydev->duplex) val |= MVNETA_GMAC_CONFIG_FULL_DUPLEX; if (phydev->speed == SPEED_1000) val |= MVNETA_GMAC_CONFIG_GMII_SPEED; else if (phydev->speed == SPEED_100) val |= MVNETA_GMAC_CONFIG_MII_SPEED; mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val); pp->duplex = phydev->duplex; pp->speed = phydev->speed; } } if (phydev->link != pp->link) { if (!phydev->link) { pp->duplex = -1; pp->speed = 0; } pp->link = phydev->link; status_change = 1; } if (status_change) { if (phydev->link) { u32 val = mvreg_read(pp, MVNETA_GMAC_AUTONEG_CONFIG); val |= (MVNETA_GMAC_FORCE_LINK_PASS | MVNETA_GMAC_FORCE_LINK_DOWN); mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val); mvneta_port_up(pp); netdev_info(pp->dev, "link up\n"); } else { mvneta_port_down(pp); netdev_info(pp->dev, "link down\n"); } } } static int mvneta_mdio_probe(struct mvneta_port *pp) { struct phy_device *phy_dev; phy_dev = of_phy_connect(pp->dev, pp->phy_node, mvneta_adjust_link, 0, pp->phy_interface); if (!phy_dev) { netdev_err(pp->dev, "could not find the PHY\n"); return -ENODEV; } phy_dev->supported &= PHY_GBIT_FEATURES; phy_dev->advertising = phy_dev->supported; pp->phy_dev = phy_dev; pp->link = 0; pp->duplex = 0; pp->speed = 0; return 0; } static void mvneta_mdio_remove(struct mvneta_port *pp) { phy_disconnect(pp->phy_dev); pp->phy_dev = NULL; } static int mvneta_open(struct net_device *dev) { struct mvneta_port *pp = netdev_priv(dev); int ret; mvneta_mac_addr_set(pp, dev->dev_addr, rxq_def); pp->pkt_size = MVNETA_RX_PKT_SIZE(pp->dev->mtu); ret = mvneta_setup_rxqs(pp); if (ret) return ret; ret = mvneta_setup_txqs(pp); if (ret) goto err_cleanup_rxqs; /* Connect to port interrupt line */ ret = request_irq(pp->dev->irq, mvneta_isr, 0, MVNETA_DRIVER_NAME, pp); if (ret) { netdev_err(pp->dev, "cannot request irq %d\n", pp->dev->irq); goto err_cleanup_txqs; } /* In default link is down */ netif_carrier_off(pp->dev); ret = mvneta_mdio_probe(pp); if (ret < 0) { netdev_err(dev, "cannot probe MDIO bus\n"); goto err_free_irq; } mvneta_start_dev(pp); return 0; err_free_irq: free_irq(pp->dev->irq, pp); err_cleanup_txqs: mvneta_cleanup_txqs(pp); err_cleanup_rxqs: mvneta_cleanup_rxqs(pp); return ret; } /* Stop the port, free port interrupt line */ static int mvneta_stop(struct net_device *dev) { struct mvneta_port *pp = netdev_priv(dev); mvneta_stop_dev(pp); mvneta_mdio_remove(pp); free_irq(dev->irq, pp); mvneta_cleanup_rxqs(pp); mvneta_cleanup_txqs(pp); return 0; } /* Ethtool methods */ /* Get settings (phy address, speed) for ethtools */ int mvneta_ethtool_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct mvneta_port *pp = netdev_priv(dev); if (!pp->phy_dev) return -ENODEV; return phy_ethtool_gset(pp->phy_dev, cmd); } /* Set settings (phy address, speed) for ethtools */ int mvneta_ethtool_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct mvneta_port *pp = netdev_priv(dev); if (!pp->phy_dev) return -ENODEV; return phy_ethtool_sset(pp->phy_dev, cmd); } /* Set interrupt coalescing for ethtools */ static int mvneta_ethtool_set_coalesce(struct net_device *dev, struct ethtool_coalesce *c) { struct mvneta_port *pp = netdev_priv(dev); int queue; for (queue = 0; queue < rxq_number; queue++) { struct mvneta_rx_queue *rxq = &pp->rxqs[queue]; rxq->time_coal = c->rx_coalesce_usecs; rxq->pkts_coal = c->rx_max_coalesced_frames; mvneta_rx_pkts_coal_set(pp, rxq, rxq->pkts_coal); mvneta_rx_time_coal_set(pp, rxq, rxq->time_coal); } for (queue = 0; queue < txq_number; queue++) { struct mvneta_tx_queue *txq = &pp->txqs[queue]; txq->done_pkts_coal = c->tx_max_coalesced_frames; mvneta_tx_done_pkts_coal_set(pp, txq, txq->done_pkts_coal); } return 0; } /* get coalescing for ethtools */ static int mvneta_ethtool_get_coalesce(struct net_device *dev, struct ethtool_coalesce *c) { struct mvneta_port *pp = netdev_priv(dev); c->rx_coalesce_usecs = pp->rxqs[0].time_coal; c->rx_max_coalesced_frames = pp->rxqs[0].pkts_coal; c->tx_max_coalesced_frames = pp->txqs[0].done_pkts_coal; return 0; } static void mvneta_ethtool_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *drvinfo) { strlcpy(drvinfo->driver, MVNETA_DRIVER_NAME, sizeof(drvinfo->driver)); strlcpy(drvinfo->version, MVNETA_DRIVER_VERSION, sizeof(drvinfo->version)); strlcpy(drvinfo->bus_info, dev_name(&dev->dev), sizeof(drvinfo->bus_info)); } static void mvneta_ethtool_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring) { struct mvneta_port *pp = netdev_priv(netdev); ring->rx_max_pending = MVNETA_MAX_RXD; ring->tx_max_pending = MVNETA_MAX_TXD; ring->rx_pending = pp->rx_ring_size; ring->tx_pending = pp->tx_ring_size; } static int mvneta_ethtool_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ring) { struct mvneta_port *pp = netdev_priv(dev); if ((ring->rx_pending == 0) || (ring->tx_pending == 0)) return -EINVAL; pp->rx_ring_size = ring->rx_pending < MVNETA_MAX_RXD ? ring->rx_pending : MVNETA_MAX_RXD; pp->tx_ring_size = ring->tx_pending < MVNETA_MAX_TXD ? ring->tx_pending : MVNETA_MAX_TXD; if (netif_running(dev)) { mvneta_stop(dev); if (mvneta_open(dev)) { netdev_err(dev, "error on opening device after ring param change\n"); return -ENOMEM; } } return 0; } static const struct net_device_ops mvneta_netdev_ops = { .ndo_open = mvneta_open, .ndo_stop = mvneta_stop, .ndo_start_xmit = mvneta_tx, .ndo_set_rx_mode = mvneta_set_rx_mode, .ndo_set_mac_address = mvneta_set_mac_addr, .ndo_change_mtu = mvneta_change_mtu, .ndo_get_stats64 = mvneta_get_stats64, }; const struct ethtool_ops mvneta_eth_tool_ops = { .get_link = ethtool_op_get_link, .get_settings = mvneta_ethtool_get_settings, .set_settings = mvneta_ethtool_set_settings, .set_coalesce = mvneta_ethtool_set_coalesce, .get_coalesce = mvneta_ethtool_get_coalesce, .get_drvinfo = mvneta_ethtool_get_drvinfo, .get_ringparam = mvneta_ethtool_get_ringparam, .set_ringparam = mvneta_ethtool_set_ringparam, }; /* Initialize hw */ static int mvneta_init(struct mvneta_port *pp, int phy_addr) { int queue; /* Disable port */ mvneta_port_disable(pp); /* Set port default values */ mvneta_defaults_set(pp); pp->txqs = kzalloc(txq_number * sizeof(struct mvneta_tx_queue), GFP_KERNEL); if (!pp->txqs) return -ENOMEM; /* Initialize TX descriptor rings */ for (queue = 0; queue < txq_number; queue++) { struct mvneta_tx_queue *txq = &pp->txqs[queue]; txq->id = queue; txq->size = pp->tx_ring_size; txq->done_pkts_coal = MVNETA_TXDONE_COAL_PKTS; } pp->rxqs = kzalloc(rxq_number * sizeof(struct mvneta_rx_queue), GFP_KERNEL); if (!pp->rxqs) { kfree(pp->txqs); return -ENOMEM; } /* Create Rx descriptor rings */ for (queue = 0; queue < rxq_number; queue++) { struct mvneta_rx_queue *rxq = &pp->rxqs[queue]; rxq->id = queue; rxq->size = pp->rx_ring_size; rxq->pkts_coal = MVNETA_RX_COAL_PKTS; rxq->time_coal = MVNETA_RX_COAL_USEC; } return 0; } static void mvneta_deinit(struct mvneta_port *pp) { kfree(pp->txqs); kfree(pp->rxqs); } /* platform glue : initialize decoding windows */ static void mvneta_conf_mbus_windows(struct mvneta_port *pp, const struct mbus_dram_target_info *dram) { u32 win_enable; u32 win_protect; int i; for (i = 0; i < 6; i++) { mvreg_write(pp, MVNETA_WIN_BASE(i), 0); mvreg_write(pp, MVNETA_WIN_SIZE(i), 0); if (i < 4) mvreg_write(pp, MVNETA_WIN_REMAP(i), 0); } win_enable = 0x3f; win_protect = 0; for (i = 0; i < dram->num_cs; i++) { const struct mbus_dram_window *cs = dram->cs + i; mvreg_write(pp, MVNETA_WIN_BASE(i), (cs->base & 0xffff0000) | (cs->mbus_attr << 8) | dram->mbus_dram_target_id); mvreg_write(pp, MVNETA_WIN_SIZE(i), (cs->size - 1) & 0xffff0000); win_enable &= ~(1 << i); win_protect |= 3 << (2 * i); } mvreg_write(pp, MVNETA_BASE_ADDR_ENABLE, win_enable); } /* Power up the port */ static void mvneta_port_power_up(struct mvneta_port *pp, int phy_mode) { u32 val; /* MAC Cause register should be cleared */ mvreg_write(pp, MVNETA_UNIT_INTR_CAUSE, 0); if (phy_mode == PHY_INTERFACE_MODE_SGMII) mvneta_port_sgmii_config(pp); mvneta_gmac_rgmii_set(pp, 1); /* Cancel Port Reset */ val = mvreg_read(pp, MVNETA_GMAC_CTRL_2); val &= ~MVNETA_GMAC2_PORT_RESET; mvreg_write(pp, MVNETA_GMAC_CTRL_2, val); while ((mvreg_read(pp, MVNETA_GMAC_CTRL_2) & MVNETA_GMAC2_PORT_RESET) != 0) continue; } /* Device initialization routine */ static int mvneta_probe(struct platform_device *pdev) { const struct mbus_dram_target_info *dram_target_info; struct device_node *dn = pdev->dev.of_node; struct device_node *phy_node; u32 phy_addr; struct mvneta_port *pp; struct net_device *dev; const char *mac_addr; int phy_mode; int err; /* Our multiqueue support is not complete, so for now, only * allow the usage of the first RX queue */ if (rxq_def != 0) { dev_err(&pdev->dev, "Invalid rxq_def argument: %d\n", rxq_def); return -EINVAL; } dev = alloc_etherdev_mqs(sizeof(struct mvneta_port), txq_number, rxq_number); if (!dev) return -ENOMEM; dev->irq = irq_of_parse_and_map(dn, 0); if (dev->irq == 0) { err = -EINVAL; goto err_free_netdev; } phy_node = of_parse_phandle(dn, "phy", 0); if (!phy_node) { dev_err(&pdev->dev, "no associated PHY\n"); err = -ENODEV; goto err_free_irq; } phy_mode = of_get_phy_mode(dn); if (phy_mode < 0) { dev_err(&pdev->dev, "incorrect phy-mode\n"); err = -EINVAL; goto err_free_irq; } mac_addr = of_get_mac_address(dn); if (!mac_addr || !is_valid_ether_addr(mac_addr)) eth_hw_addr_random(dev); else memcpy(dev->dev_addr, mac_addr, ETH_ALEN); dev->tx_queue_len = MVNETA_MAX_TXD; dev->watchdog_timeo = 5 * HZ; dev->netdev_ops = &mvneta_netdev_ops; SET_ETHTOOL_OPS(dev, &mvneta_eth_tool_ops); pp = netdev_priv(dev); pp->weight = MVNETA_RX_POLL_WEIGHT; pp->phy_node = phy_node; pp->phy_interface = phy_mode; pp->base = of_iomap(dn, 0); if (pp->base == NULL) { err = -ENOMEM; goto err_free_irq; } pp->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(pp->clk)) { err = PTR_ERR(pp->clk); goto err_unmap; } clk_prepare_enable(pp->clk); /* Alloc per-cpu stats */ pp->stats = alloc_percpu(struct mvneta_pcpu_stats); if (!pp->stats) { err = -ENOMEM; goto err_clk; } pp->tx_ring_size = MVNETA_MAX_TXD; pp->rx_ring_size = MVNETA_MAX_RXD; pp->dev = dev; SET_NETDEV_DEV(dev, &pdev->dev); err = mvneta_init(pp, phy_addr); if (err < 0) { dev_err(&pdev->dev, "can't init eth hal\n"); goto err_free_stats; } mvneta_port_power_up(pp, phy_mode); dram_target_info = mv_mbus_dram_info(); if (dram_target_info) mvneta_conf_mbus_windows(pp, dram_target_info); netif_napi_add(dev, &pp->napi, mvneta_poll, pp->weight); dev->features = NETIF_F_SG | NETIF_F_IP_CSUM; dev->hw_features |= NETIF_F_SG | NETIF_F_IP_CSUM; dev->vlan_features |= NETIF_F_SG | NETIF_F_IP_CSUM; dev->priv_flags |= IFF_UNICAST_FLT; err = register_netdev(dev); if (err < 0) { dev_err(&pdev->dev, "failed to register\n"); goto err_deinit; } netdev_info(dev, "mac: %pM\n", dev->dev_addr); platform_set_drvdata(pdev, pp->dev); return 0; err_deinit: mvneta_deinit(pp); err_free_stats: free_percpu(pp->stats); err_clk: clk_disable_unprepare(pp->clk); err_unmap: iounmap(pp->base); err_free_irq: irq_dispose_mapping(dev->irq); err_free_netdev: free_netdev(dev); return err; } /* Device removal routine */ static int mvneta_remove(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); struct mvneta_port *pp = netdev_priv(dev); unregister_netdev(dev); mvneta_deinit(pp); clk_disable_unprepare(pp->clk); free_percpu(pp->stats); iounmap(pp->base); irq_dispose_mapping(dev->irq); free_netdev(dev); platform_set_drvdata(pdev, NULL); return 0; } static const struct of_device_id mvneta_match[] = { { .compatible = "marvell,armada-370-neta" }, { } }; MODULE_DEVICE_TABLE(of, mvneta_match); static struct platform_driver mvneta_driver = { .probe = mvneta_probe, .remove = mvneta_remove, .driver = { .name = MVNETA_DRIVER_NAME, .of_match_table = mvneta_match, }, }; module_platform_driver(mvneta_driver); MODULE_DESCRIPTION("Marvell NETA Ethernet Driver - www.marvell.com"); MODULE_AUTHOR("Rami Rosen <rosenr@marvell.com>, Thomas Petazzoni <thomas.petazzoni@free-electrons.com>"); MODULE_LICENSE("GPL"); module_param(rxq_number, int, S_IRUGO); module_param(txq_number, int, S_IRUGO); module_param(rxq_def, int, S_IRUGO);
gpl-2.0
JoeGlancy/linux
drivers/irqchip/irq-gic-v3-its-platform-msi.c
458
2821
/* * Copyright (C) 2013-2015 ARM Limited, All Rights Reserved. * Author: Marc Zyngier <marc.zyngier@arm.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/device.h> #include <linux/msi.h> #include <linux/of.h> #include <linux/of_irq.h> static struct irq_chip its_pmsi_irq_chip = { .name = "ITS-pMSI", }; static int its_pmsi_prepare(struct irq_domain *domain, struct device *dev, int nvec, msi_alloc_info_t *info) { struct msi_domain_info *msi_info; u32 dev_id; int ret, index = 0; msi_info = msi_get_domain_info(domain->parent); /* Suck the DeviceID out of the msi-parent property */ do { struct of_phandle_args args; ret = of_parse_phandle_with_args(dev->of_node, "msi-parent", "#msi-cells", index, &args); if (args.np == irq_domain_get_of_node(domain)) { if (WARN_ON(args.args_count != 1)) return -EINVAL; dev_id = args.args[0]; break; } } while (!ret); if (ret) return ret; /* ITS specific DeviceID, as the core ITS ignores dev. */ info->scratchpad[0].ul = dev_id; return msi_info->ops->msi_prepare(domain->parent, dev, nvec, info); } static struct msi_domain_ops its_pmsi_ops = { .msi_prepare = its_pmsi_prepare, }; static struct msi_domain_info its_pmsi_domain_info = { .flags = (MSI_FLAG_USE_DEF_DOM_OPS | MSI_FLAG_USE_DEF_CHIP_OPS), .ops = &its_pmsi_ops, .chip = &its_pmsi_irq_chip, }; static struct of_device_id its_device_id[] = { { .compatible = "arm,gic-v3-its", }, {}, }; static int __init its_pmsi_init(void) { struct device_node *np; struct irq_domain *parent; for (np = of_find_matching_node(NULL, its_device_id); np; np = of_find_matching_node(np, its_device_id)) { if (!of_property_read_bool(np, "msi-controller")) continue; parent = irq_find_matching_host(np, DOMAIN_BUS_NEXUS); if (!parent || !msi_get_domain_info(parent)) { pr_err("%s: unable to locate ITS domain\n", np->full_name); continue; } if (!platform_msi_create_irq_domain(of_node_to_fwnode(np), &its_pmsi_domain_info, parent)) { pr_err("%s: unable to create platform domain\n", np->full_name); continue; } pr_info("Platform MSI: %s domain created\n", np->full_name); } return 0; } early_initcall(its_pmsi_init);
gpl-2.0
hexianren/linux-3.7-Panda
security/selinux/ss/policydb.c
714
70335
/* * Implementation of the policy database. * * Author : Stephen Smalley, <sds@epoch.ncsc.mil> */ /* * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com> * * Support for enhanced MLS infrastructure. * * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com> * * Added conditional policy language extensions * * Updated: Hewlett-Packard <paul@paul-moore.com> * * Added support for the policy capability bitmap * * Copyright (C) 2007 Hewlett-Packard Development Company, L.P. * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc. * Copyright (C) 2003 - 2004 Tresys Technology, LLC * 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. */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/audit.h> #include <linux/flex_array.h> #include "security.h" #include "policydb.h" #include "conditional.h" #include "mls.h" #include "services.h" #define _DEBUG_HASHES #ifdef DEBUG_HASHES static const char *symtab_name[SYM_NUM] = { "common prefixes", "classes", "roles", "types", "users", "bools", "levels", "categories", }; #endif static unsigned int symtab_sizes[SYM_NUM] = { 2, 32, 16, 512, 128, 16, 16, 16, }; struct policydb_compat_info { int version; int sym_num; int ocon_num; }; /* These need to be updated if SYM_NUM or OCON_NUM changes */ static struct policydb_compat_info policydb_compat[] = { { .version = POLICYDB_VERSION_BASE, .sym_num = SYM_NUM - 3, .ocon_num = OCON_NUM - 1, }, { .version = POLICYDB_VERSION_BOOL, .sym_num = SYM_NUM - 2, .ocon_num = OCON_NUM - 1, }, { .version = POLICYDB_VERSION_IPV6, .sym_num = SYM_NUM - 2, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_NLCLASS, .sym_num = SYM_NUM - 2, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_MLS, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_AVTAB, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_RANGETRANS, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_POLCAP, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_PERMISSIVE, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_BOUNDARY, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_FILENAME_TRANS, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_ROLETRANS, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_NEW_OBJECT_DEFAULTS, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, { .version = POLICYDB_VERSION_DEFAULT_TYPE, .sym_num = SYM_NUM, .ocon_num = OCON_NUM, }, }; static struct policydb_compat_info *policydb_lookup_compat(int version) { int i; struct policydb_compat_info *info = NULL; for (i = 0; i < ARRAY_SIZE(policydb_compat); i++) { if (policydb_compat[i].version == version) { info = &policydb_compat[i]; break; } } return info; } /* * Initialize the role table. */ static int roles_init(struct policydb *p) { char *key = NULL; int rc; struct role_datum *role; rc = -ENOMEM; role = kzalloc(sizeof(*role), GFP_KERNEL); if (!role) goto out; rc = -EINVAL; role->value = ++p->p_roles.nprim; if (role->value != OBJECT_R_VAL) goto out; rc = -ENOMEM; key = kstrdup(OBJECT_R, GFP_KERNEL); if (!key) goto out; rc = hashtab_insert(p->p_roles.table, key, role); if (rc) goto out; return 0; out: kfree(key); kfree(role); return rc; } static u32 filenametr_hash(struct hashtab *h, const void *k) { const struct filename_trans *ft = k; unsigned long hash; unsigned int byte_num; unsigned char focus; hash = ft->stype ^ ft->ttype ^ ft->tclass; byte_num = 0; while ((focus = ft->name[byte_num++])) hash = partial_name_hash(focus, hash); return hash & (h->size - 1); } static int filenametr_cmp(struct hashtab *h, const void *k1, const void *k2) { const struct filename_trans *ft1 = k1; const struct filename_trans *ft2 = k2; int v; v = ft1->stype - ft2->stype; if (v) return v; v = ft1->ttype - ft2->ttype; if (v) return v; v = ft1->tclass - ft2->tclass; if (v) return v; return strcmp(ft1->name, ft2->name); } static u32 rangetr_hash(struct hashtab *h, const void *k) { const struct range_trans *key = k; return (key->source_type + (key->target_type << 3) + (key->target_class << 5)) & (h->size - 1); } static int rangetr_cmp(struct hashtab *h, const void *k1, const void *k2) { const struct range_trans *key1 = k1, *key2 = k2; int v; v = key1->source_type - key2->source_type; if (v) return v; v = key1->target_type - key2->target_type; if (v) return v; v = key1->target_class - key2->target_class; return v; } /* * Initialize a policy database structure. */ static int policydb_init(struct policydb *p) { int i, rc; memset(p, 0, sizeof(*p)); for (i = 0; i < SYM_NUM; i++) { rc = symtab_init(&p->symtab[i], symtab_sizes[i]); if (rc) goto out; } rc = avtab_init(&p->te_avtab); if (rc) goto out; rc = roles_init(p); if (rc) goto out; rc = cond_policydb_init(p); if (rc) goto out; p->filename_trans = hashtab_create(filenametr_hash, filenametr_cmp, (1 << 10)); if (!p->filename_trans) goto out; p->range_tr = hashtab_create(rangetr_hash, rangetr_cmp, 256); if (!p->range_tr) goto out; ebitmap_init(&p->filename_trans_ttypes); ebitmap_init(&p->policycaps); ebitmap_init(&p->permissive_map); return 0; out: hashtab_destroy(p->filename_trans); hashtab_destroy(p->range_tr); for (i = 0; i < SYM_NUM; i++) hashtab_destroy(p->symtab[i].table); return rc; } /* * The following *_index functions are used to * define the val_to_name and val_to_struct arrays * in a policy database structure. The val_to_name * arrays are used when converting security context * structures into string representations. The * val_to_struct arrays are used when the attributes * of a class, role, or user are needed. */ static int common_index(void *key, void *datum, void *datap) { struct policydb *p; struct common_datum *comdatum; struct flex_array *fa; comdatum = datum; p = datap; if (!comdatum->value || comdatum->value > p->p_commons.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_COMMONS]; if (flex_array_put_ptr(fa, comdatum->value - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); return 0; } static int class_index(void *key, void *datum, void *datap) { struct policydb *p; struct class_datum *cladatum; struct flex_array *fa; cladatum = datum; p = datap; if (!cladatum->value || cladatum->value > p->p_classes.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_CLASSES]; if (flex_array_put_ptr(fa, cladatum->value - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); p->class_val_to_struct[cladatum->value - 1] = cladatum; return 0; } static int role_index(void *key, void *datum, void *datap) { struct policydb *p; struct role_datum *role; struct flex_array *fa; role = datum; p = datap; if (!role->value || role->value > p->p_roles.nprim || role->bounds > p->p_roles.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_ROLES]; if (flex_array_put_ptr(fa, role->value - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); p->role_val_to_struct[role->value - 1] = role; return 0; } static int type_index(void *key, void *datum, void *datap) { struct policydb *p; struct type_datum *typdatum; struct flex_array *fa; typdatum = datum; p = datap; if (typdatum->primary) { if (!typdatum->value || typdatum->value > p->p_types.nprim || typdatum->bounds > p->p_types.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_TYPES]; if (flex_array_put_ptr(fa, typdatum->value - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); fa = p->type_val_to_struct_array; if (flex_array_put_ptr(fa, typdatum->value - 1, typdatum, GFP_KERNEL | __GFP_ZERO)) BUG(); } return 0; } static int user_index(void *key, void *datum, void *datap) { struct policydb *p; struct user_datum *usrdatum; struct flex_array *fa; usrdatum = datum; p = datap; if (!usrdatum->value || usrdatum->value > p->p_users.nprim || usrdatum->bounds > p->p_users.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_USERS]; if (flex_array_put_ptr(fa, usrdatum->value - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); p->user_val_to_struct[usrdatum->value - 1] = usrdatum; return 0; } static int sens_index(void *key, void *datum, void *datap) { struct policydb *p; struct level_datum *levdatum; struct flex_array *fa; levdatum = datum; p = datap; if (!levdatum->isalias) { if (!levdatum->level->sens || levdatum->level->sens > p->p_levels.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_LEVELS]; if (flex_array_put_ptr(fa, levdatum->level->sens - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); } return 0; } static int cat_index(void *key, void *datum, void *datap) { struct policydb *p; struct cat_datum *catdatum; struct flex_array *fa; catdatum = datum; p = datap; if (!catdatum->isalias) { if (!catdatum->value || catdatum->value > p->p_cats.nprim) return -EINVAL; fa = p->sym_val_to_name[SYM_CATS]; if (flex_array_put_ptr(fa, catdatum->value - 1, key, GFP_KERNEL | __GFP_ZERO)) BUG(); } return 0; } static int (*index_f[SYM_NUM]) (void *key, void *datum, void *datap) = { common_index, class_index, role_index, type_index, user_index, cond_index_bool, sens_index, cat_index, }; #ifdef DEBUG_HASHES static void hash_eval(struct hashtab *h, const char *hash_name) { struct hashtab_info info; hashtab_stat(h, &info); printk(KERN_DEBUG "SELinux: %s: %d entries and %d/%d buckets used, " "longest chain length %d\n", hash_name, h->nel, info.slots_used, h->size, info.max_chain_len); } static void symtab_hash_eval(struct symtab *s) { int i; for (i = 0; i < SYM_NUM; i++) hash_eval(s[i].table, symtab_name[i]); } #else static inline void hash_eval(struct hashtab *h, char *hash_name) { } #endif /* * Define the other val_to_name and val_to_struct arrays * in a policy database structure. * * Caller must clean up on failure. */ static int policydb_index(struct policydb *p) { int i, rc; printk(KERN_DEBUG "SELinux: %d users, %d roles, %d types, %d bools", p->p_users.nprim, p->p_roles.nprim, p->p_types.nprim, p->p_bools.nprim); if (p->mls_enabled) printk(", %d sens, %d cats", p->p_levels.nprim, p->p_cats.nprim); printk("\n"); printk(KERN_DEBUG "SELinux: %d classes, %d rules\n", p->p_classes.nprim, p->te_avtab.nel); #ifdef DEBUG_HASHES avtab_hash_eval(&p->te_avtab, "rules"); symtab_hash_eval(p->symtab); #endif rc = -ENOMEM; p->class_val_to_struct = kmalloc(p->p_classes.nprim * sizeof(*(p->class_val_to_struct)), GFP_KERNEL); if (!p->class_val_to_struct) goto out; rc = -ENOMEM; p->role_val_to_struct = kmalloc(p->p_roles.nprim * sizeof(*(p->role_val_to_struct)), GFP_KERNEL); if (!p->role_val_to_struct) goto out; rc = -ENOMEM; p->user_val_to_struct = kmalloc(p->p_users.nprim * sizeof(*(p->user_val_to_struct)), GFP_KERNEL); if (!p->user_val_to_struct) goto out; /* Yes, I want the sizeof the pointer, not the structure */ rc = -ENOMEM; p->type_val_to_struct_array = flex_array_alloc(sizeof(struct type_datum *), p->p_types.nprim, GFP_KERNEL | __GFP_ZERO); if (!p->type_val_to_struct_array) goto out; rc = flex_array_prealloc(p->type_val_to_struct_array, 0, p->p_types.nprim, GFP_KERNEL | __GFP_ZERO); if (rc) goto out; rc = cond_init_bool_indexes(p); if (rc) goto out; for (i = 0; i < SYM_NUM; i++) { rc = -ENOMEM; p->sym_val_to_name[i] = flex_array_alloc(sizeof(char *), p->symtab[i].nprim, GFP_KERNEL | __GFP_ZERO); if (!p->sym_val_to_name[i]) goto out; rc = flex_array_prealloc(p->sym_val_to_name[i], 0, p->symtab[i].nprim, GFP_KERNEL | __GFP_ZERO); if (rc) goto out; rc = hashtab_map(p->symtab[i].table, index_f[i], p); if (rc) goto out; } rc = 0; out: return rc; } /* * The following *_destroy functions are used to * free any memory allocated for each kind of * symbol data in the policy database. */ static int perm_destroy(void *key, void *datum, void *p) { kfree(key); kfree(datum); return 0; } static int common_destroy(void *key, void *datum, void *p) { struct common_datum *comdatum; kfree(key); if (datum) { comdatum = datum; hashtab_map(comdatum->permissions.table, perm_destroy, NULL); hashtab_destroy(comdatum->permissions.table); } kfree(datum); return 0; } static int cls_destroy(void *key, void *datum, void *p) { struct class_datum *cladatum; struct constraint_node *constraint, *ctemp; struct constraint_expr *e, *etmp; kfree(key); if (datum) { cladatum = datum; hashtab_map(cladatum->permissions.table, perm_destroy, NULL); hashtab_destroy(cladatum->permissions.table); constraint = cladatum->constraints; while (constraint) { e = constraint->expr; while (e) { ebitmap_destroy(&e->names); etmp = e; e = e->next; kfree(etmp); } ctemp = constraint; constraint = constraint->next; kfree(ctemp); } constraint = cladatum->validatetrans; while (constraint) { e = constraint->expr; while (e) { ebitmap_destroy(&e->names); etmp = e; e = e->next; kfree(etmp); } ctemp = constraint; constraint = constraint->next; kfree(ctemp); } kfree(cladatum->comkey); } kfree(datum); return 0; } static int role_destroy(void *key, void *datum, void *p) { struct role_datum *role; kfree(key); if (datum) { role = datum; ebitmap_destroy(&role->dominates); ebitmap_destroy(&role->types); } kfree(datum); return 0; } static int type_destroy(void *key, void *datum, void *p) { kfree(key); kfree(datum); return 0; } static int user_destroy(void *key, void *datum, void *p) { struct user_datum *usrdatum; kfree(key); if (datum) { usrdatum = datum; ebitmap_destroy(&usrdatum->roles); ebitmap_destroy(&usrdatum->range.level[0].cat); ebitmap_destroy(&usrdatum->range.level[1].cat); ebitmap_destroy(&usrdatum->dfltlevel.cat); } kfree(datum); return 0; } static int sens_destroy(void *key, void *datum, void *p) { struct level_datum *levdatum; kfree(key); if (datum) { levdatum = datum; ebitmap_destroy(&levdatum->level->cat); kfree(levdatum->level); } kfree(datum); return 0; } static int cat_destroy(void *key, void *datum, void *p) { kfree(key); kfree(datum); return 0; } static int (*destroy_f[SYM_NUM]) (void *key, void *datum, void *datap) = { common_destroy, cls_destroy, role_destroy, type_destroy, user_destroy, cond_destroy_bool, sens_destroy, cat_destroy, }; static int filenametr_destroy(void *key, void *datum, void *p) { struct filename_trans *ft = key; kfree(ft->name); kfree(key); kfree(datum); cond_resched(); return 0; } static int range_tr_destroy(void *key, void *datum, void *p) { struct mls_range *rt = datum; kfree(key); ebitmap_destroy(&rt->level[0].cat); ebitmap_destroy(&rt->level[1].cat); kfree(datum); cond_resched(); return 0; } static void ocontext_destroy(struct ocontext *c, int i) { if (!c) return; context_destroy(&c->context[0]); context_destroy(&c->context[1]); if (i == OCON_ISID || i == OCON_FS || i == OCON_NETIF || i == OCON_FSUSE) kfree(c->u.name); kfree(c); } /* * Free any memory allocated by a policy database structure. */ void policydb_destroy(struct policydb *p) { struct ocontext *c, *ctmp; struct genfs *g, *gtmp; int i; struct role_allow *ra, *lra = NULL; struct role_trans *tr, *ltr = NULL; for (i = 0; i < SYM_NUM; i++) { cond_resched(); hashtab_map(p->symtab[i].table, destroy_f[i], NULL); hashtab_destroy(p->symtab[i].table); } for (i = 0; i < SYM_NUM; i++) { if (p->sym_val_to_name[i]) flex_array_free(p->sym_val_to_name[i]); } kfree(p->class_val_to_struct); kfree(p->role_val_to_struct); kfree(p->user_val_to_struct); if (p->type_val_to_struct_array) flex_array_free(p->type_val_to_struct_array); avtab_destroy(&p->te_avtab); for (i = 0; i < OCON_NUM; i++) { cond_resched(); c = p->ocontexts[i]; while (c) { ctmp = c; c = c->next; ocontext_destroy(ctmp, i); } p->ocontexts[i] = NULL; } g = p->genfs; while (g) { cond_resched(); kfree(g->fstype); c = g->head; while (c) { ctmp = c; c = c->next; ocontext_destroy(ctmp, OCON_FSUSE); } gtmp = g; g = g->next; kfree(gtmp); } p->genfs = NULL; cond_policydb_destroy(p); for (tr = p->role_tr; tr; tr = tr->next) { cond_resched(); kfree(ltr); ltr = tr; } kfree(ltr); for (ra = p->role_allow; ra; ra = ra->next) { cond_resched(); kfree(lra); lra = ra; } kfree(lra); hashtab_map(p->filename_trans, filenametr_destroy, NULL); hashtab_destroy(p->filename_trans); hashtab_map(p->range_tr, range_tr_destroy, NULL); hashtab_destroy(p->range_tr); if (p->type_attr_map_array) { for (i = 0; i < p->p_types.nprim; i++) { struct ebitmap *e; e = flex_array_get(p->type_attr_map_array, i); if (!e) continue; ebitmap_destroy(e); } flex_array_free(p->type_attr_map_array); } ebitmap_destroy(&p->filename_trans_ttypes); ebitmap_destroy(&p->policycaps); ebitmap_destroy(&p->permissive_map); return; } /* * Load the initial SIDs specified in a policy database * structure into a SID table. */ int policydb_load_isids(struct policydb *p, struct sidtab *s) { struct ocontext *head, *c; int rc; rc = sidtab_init(s); if (rc) { printk(KERN_ERR "SELinux: out of memory on SID table init\n"); goto out; } head = p->ocontexts[OCON_ISID]; for (c = head; c; c = c->next) { rc = -EINVAL; if (!c->context[0].user) { printk(KERN_ERR "SELinux: SID %s was never defined.\n", c->u.name); goto out; } rc = sidtab_insert(s, c->sid[0], &c->context[0]); if (rc) { printk(KERN_ERR "SELinux: unable to load initial SID %s.\n", c->u.name); goto out; } } rc = 0; out: return rc; } int policydb_class_isvalid(struct policydb *p, unsigned int class) { if (!class || class > p->p_classes.nprim) return 0; return 1; } int policydb_role_isvalid(struct policydb *p, unsigned int role) { if (!role || role > p->p_roles.nprim) return 0; return 1; } int policydb_type_isvalid(struct policydb *p, unsigned int type) { if (!type || type > p->p_types.nprim) return 0; return 1; } /* * Return 1 if the fields in the security context * structure `c' are valid. Return 0 otherwise. */ int policydb_context_isvalid(struct policydb *p, struct context *c) { struct role_datum *role; struct user_datum *usrdatum; if (!c->role || c->role > p->p_roles.nprim) return 0; if (!c->user || c->user > p->p_users.nprim) return 0; if (!c->type || c->type > p->p_types.nprim) return 0; if (c->role != OBJECT_R_VAL) { /* * Role must be authorized for the type. */ role = p->role_val_to_struct[c->role - 1]; if (!ebitmap_get_bit(&role->types, c->type - 1)) /* role may not be associated with type */ return 0; /* * User must be authorized for the role. */ usrdatum = p->user_val_to_struct[c->user - 1]; if (!usrdatum) return 0; if (!ebitmap_get_bit(&usrdatum->roles, c->role - 1)) /* user may not be associated with role */ return 0; } if (!mls_context_isvalid(p, c)) return 0; return 1; } /* * Read a MLS range structure from a policydb binary * representation file. */ static int mls_read_range_helper(struct mls_range *r, void *fp) { __le32 buf[2]; u32 items; int rc; rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; rc = -EINVAL; items = le32_to_cpu(buf[0]); if (items > ARRAY_SIZE(buf)) { printk(KERN_ERR "SELinux: mls: range overflow\n"); goto out; } rc = next_entry(buf, fp, sizeof(u32) * items); if (rc) { printk(KERN_ERR "SELinux: mls: truncated range\n"); goto out; } r->level[0].sens = le32_to_cpu(buf[0]); if (items > 1) r->level[1].sens = le32_to_cpu(buf[1]); else r->level[1].sens = r->level[0].sens; rc = ebitmap_read(&r->level[0].cat, fp); if (rc) { printk(KERN_ERR "SELinux: mls: error reading low categories\n"); goto out; } if (items > 1) { rc = ebitmap_read(&r->level[1].cat, fp); if (rc) { printk(KERN_ERR "SELinux: mls: error reading high categories\n"); goto bad_high; } } else { rc = ebitmap_cpy(&r->level[1].cat, &r->level[0].cat); if (rc) { printk(KERN_ERR "SELinux: mls: out of memory\n"); goto bad_high; } } return 0; bad_high: ebitmap_destroy(&r->level[0].cat); out: return rc; } /* * Read and validate a security context structure * from a policydb binary representation file. */ static int context_read_and_validate(struct context *c, struct policydb *p, void *fp) { __le32 buf[3]; int rc; rc = next_entry(buf, fp, sizeof buf); if (rc) { printk(KERN_ERR "SELinux: context truncated\n"); goto out; } c->user = le32_to_cpu(buf[0]); c->role = le32_to_cpu(buf[1]); c->type = le32_to_cpu(buf[2]); if (p->policyvers >= POLICYDB_VERSION_MLS) { rc = mls_read_range_helper(&c->range, fp); if (rc) { printk(KERN_ERR "SELinux: error reading MLS range of context\n"); goto out; } } rc = -EINVAL; if (!policydb_context_isvalid(p, c)) { printk(KERN_ERR "SELinux: invalid security context\n"); context_destroy(c); goto out; } rc = 0; out: return rc; } /* * The following *_read functions are used to * read the symbol data from a policy database * binary representation file. */ static int perm_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct perm_datum *perdatum; int rc; __le32 buf[2]; u32 len; rc = -ENOMEM; perdatum = kzalloc(sizeof(*perdatum), GFP_KERNEL); if (!perdatum) goto bad; rc = next_entry(buf, fp, sizeof buf); if (rc) goto bad; len = le32_to_cpu(buf[0]); perdatum->value = le32_to_cpu(buf[1]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_KERNEL); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; rc = hashtab_insert(h, key, perdatum); if (rc) goto bad; return 0; bad: perm_destroy(key, perdatum, NULL); return rc; } static int common_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct common_datum *comdatum; __le32 buf[4]; u32 len, nel; int i, rc; rc = -ENOMEM; comdatum = kzalloc(sizeof(*comdatum), GFP_KERNEL); if (!comdatum) goto bad; rc = next_entry(buf, fp, sizeof buf); if (rc) goto bad; len = le32_to_cpu(buf[0]); comdatum->value = le32_to_cpu(buf[1]); rc = symtab_init(&comdatum->permissions, PERM_SYMTAB_SIZE); if (rc) goto bad; comdatum->permissions.nprim = le32_to_cpu(buf[2]); nel = le32_to_cpu(buf[3]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_KERNEL); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; for (i = 0; i < nel; i++) { rc = perm_read(p, comdatum->permissions.table, fp); if (rc) goto bad; } rc = hashtab_insert(h, key, comdatum); if (rc) goto bad; return 0; bad: common_destroy(key, comdatum, NULL); return rc; } static int read_cons_helper(struct constraint_node **nodep, int ncons, int allowxtarget, void *fp) { struct constraint_node *c, *lc; struct constraint_expr *e, *le; __le32 buf[3]; u32 nexpr; int rc, i, j, depth; lc = NULL; for (i = 0; i < ncons; i++) { c = kzalloc(sizeof(*c), GFP_KERNEL); if (!c) return -ENOMEM; if (lc) lc->next = c; else *nodep = c; rc = next_entry(buf, fp, (sizeof(u32) * 2)); if (rc) return rc; c->permissions = le32_to_cpu(buf[0]); nexpr = le32_to_cpu(buf[1]); le = NULL; depth = -1; for (j = 0; j < nexpr; j++) { e = kzalloc(sizeof(*e), GFP_KERNEL); if (!e) return -ENOMEM; if (le) le->next = e; else c->expr = e; rc = next_entry(buf, fp, (sizeof(u32) * 3)); if (rc) return rc; e->expr_type = le32_to_cpu(buf[0]); e->attr = le32_to_cpu(buf[1]); e->op = le32_to_cpu(buf[2]); switch (e->expr_type) { case CEXPR_NOT: if (depth < 0) return -EINVAL; break; case CEXPR_AND: case CEXPR_OR: if (depth < 1) return -EINVAL; depth--; break; case CEXPR_ATTR: if (depth == (CEXPR_MAXDEPTH - 1)) return -EINVAL; depth++; break; case CEXPR_NAMES: if (!allowxtarget && (e->attr & CEXPR_XTARGET)) return -EINVAL; if (depth == (CEXPR_MAXDEPTH - 1)) return -EINVAL; depth++; rc = ebitmap_read(&e->names, fp); if (rc) return rc; break; default: return -EINVAL; } le = e; } if (depth != 0) return -EINVAL; lc = c; } return 0; } static int class_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct class_datum *cladatum; __le32 buf[6]; u32 len, len2, ncons, nel; int i, rc; rc = -ENOMEM; cladatum = kzalloc(sizeof(*cladatum), GFP_KERNEL); if (!cladatum) goto bad; rc = next_entry(buf, fp, sizeof(u32)*6); if (rc) goto bad; len = le32_to_cpu(buf[0]); len2 = le32_to_cpu(buf[1]); cladatum->value = le32_to_cpu(buf[2]); rc = symtab_init(&cladatum->permissions, PERM_SYMTAB_SIZE); if (rc) goto bad; cladatum->permissions.nprim = le32_to_cpu(buf[3]); nel = le32_to_cpu(buf[4]); ncons = le32_to_cpu(buf[5]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_KERNEL); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; if (len2) { rc = -ENOMEM; cladatum->comkey = kmalloc(len2 + 1, GFP_KERNEL); if (!cladatum->comkey) goto bad; rc = next_entry(cladatum->comkey, fp, len2); if (rc) goto bad; cladatum->comkey[len2] = '\0'; rc = -EINVAL; cladatum->comdatum = hashtab_search(p->p_commons.table, cladatum->comkey); if (!cladatum->comdatum) { printk(KERN_ERR "SELinux: unknown common %s\n", cladatum->comkey); goto bad; } } for (i = 0; i < nel; i++) { rc = perm_read(p, cladatum->permissions.table, fp); if (rc) goto bad; } rc = read_cons_helper(&cladatum->constraints, ncons, 0, fp); if (rc) goto bad; if (p->policyvers >= POLICYDB_VERSION_VALIDATETRANS) { /* grab the validatetrans rules */ rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto bad; ncons = le32_to_cpu(buf[0]); rc = read_cons_helper(&cladatum->validatetrans, ncons, 1, fp); if (rc) goto bad; } if (p->policyvers >= POLICYDB_VERSION_NEW_OBJECT_DEFAULTS) { rc = next_entry(buf, fp, sizeof(u32) * 3); if (rc) goto bad; cladatum->default_user = le32_to_cpu(buf[0]); cladatum->default_role = le32_to_cpu(buf[1]); cladatum->default_range = le32_to_cpu(buf[2]); } if (p->policyvers >= POLICYDB_VERSION_DEFAULT_TYPE) { rc = next_entry(buf, fp, sizeof(u32) * 1); if (rc) goto bad; cladatum->default_type = le32_to_cpu(buf[0]); } rc = hashtab_insert(h, key, cladatum); if (rc) goto bad; return 0; bad: cls_destroy(key, cladatum, NULL); return rc; } static int role_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct role_datum *role; int rc, to_read = 2; __le32 buf[3]; u32 len; rc = -ENOMEM; role = kzalloc(sizeof(*role), GFP_KERNEL); if (!role) goto bad; if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) to_read = 3; rc = next_entry(buf, fp, sizeof(buf[0]) * to_read); if (rc) goto bad; len = le32_to_cpu(buf[0]); role->value = le32_to_cpu(buf[1]); if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) role->bounds = le32_to_cpu(buf[2]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_KERNEL); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; rc = ebitmap_read(&role->dominates, fp); if (rc) goto bad; rc = ebitmap_read(&role->types, fp); if (rc) goto bad; if (strcmp(key, OBJECT_R) == 0) { rc = -EINVAL; if (role->value != OBJECT_R_VAL) { printk(KERN_ERR "SELinux: Role %s has wrong value %d\n", OBJECT_R, role->value); goto bad; } rc = 0; goto bad; } rc = hashtab_insert(h, key, role); if (rc) goto bad; return 0; bad: role_destroy(key, role, NULL); return rc; } static int type_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct type_datum *typdatum; int rc, to_read = 3; __le32 buf[4]; u32 len; rc = -ENOMEM; typdatum = kzalloc(sizeof(*typdatum), GFP_KERNEL); if (!typdatum) goto bad; if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) to_read = 4; rc = next_entry(buf, fp, sizeof(buf[0]) * to_read); if (rc) goto bad; len = le32_to_cpu(buf[0]); typdatum->value = le32_to_cpu(buf[1]); if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) { u32 prop = le32_to_cpu(buf[2]); if (prop & TYPEDATUM_PROPERTY_PRIMARY) typdatum->primary = 1; if (prop & TYPEDATUM_PROPERTY_ATTRIBUTE) typdatum->attribute = 1; typdatum->bounds = le32_to_cpu(buf[3]); } else { typdatum->primary = le32_to_cpu(buf[2]); } rc = -ENOMEM; key = kmalloc(len + 1, GFP_KERNEL); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; rc = hashtab_insert(h, key, typdatum); if (rc) goto bad; return 0; bad: type_destroy(key, typdatum, NULL); return rc; } /* * Read a MLS level structure from a policydb binary * representation file. */ static int mls_read_level(struct mls_level *lp, void *fp) { __le32 buf[1]; int rc; memset(lp, 0, sizeof(*lp)); rc = next_entry(buf, fp, sizeof buf); if (rc) { printk(KERN_ERR "SELinux: mls: truncated level\n"); return rc; } lp->sens = le32_to_cpu(buf[0]); rc = ebitmap_read(&lp->cat, fp); if (rc) { printk(KERN_ERR "SELinux: mls: error reading level categories\n"); return rc; } return 0; } static int user_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct user_datum *usrdatum; int rc, to_read = 2; __le32 buf[3]; u32 len; rc = -ENOMEM; usrdatum = kzalloc(sizeof(*usrdatum), GFP_KERNEL); if (!usrdatum) goto bad; if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) to_read = 3; rc = next_entry(buf, fp, sizeof(buf[0]) * to_read); if (rc) goto bad; len = le32_to_cpu(buf[0]); usrdatum->value = le32_to_cpu(buf[1]); if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) usrdatum->bounds = le32_to_cpu(buf[2]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_KERNEL); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; rc = ebitmap_read(&usrdatum->roles, fp); if (rc) goto bad; if (p->policyvers >= POLICYDB_VERSION_MLS) { rc = mls_read_range_helper(&usrdatum->range, fp); if (rc) goto bad; rc = mls_read_level(&usrdatum->dfltlevel, fp); if (rc) goto bad; } rc = hashtab_insert(h, key, usrdatum); if (rc) goto bad; return 0; bad: user_destroy(key, usrdatum, NULL); return rc; } static int sens_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct level_datum *levdatum; int rc; __le32 buf[2]; u32 len; rc = -ENOMEM; levdatum = kzalloc(sizeof(*levdatum), GFP_ATOMIC); if (!levdatum) goto bad; rc = next_entry(buf, fp, sizeof buf); if (rc) goto bad; len = le32_to_cpu(buf[0]); levdatum->isalias = le32_to_cpu(buf[1]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_ATOMIC); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; rc = -ENOMEM; levdatum->level = kmalloc(sizeof(struct mls_level), GFP_ATOMIC); if (!levdatum->level) goto bad; rc = mls_read_level(levdatum->level, fp); if (rc) goto bad; rc = hashtab_insert(h, key, levdatum); if (rc) goto bad; return 0; bad: sens_destroy(key, levdatum, NULL); return rc; } static int cat_read(struct policydb *p, struct hashtab *h, void *fp) { char *key = NULL; struct cat_datum *catdatum; int rc; __le32 buf[3]; u32 len; rc = -ENOMEM; catdatum = kzalloc(sizeof(*catdatum), GFP_ATOMIC); if (!catdatum) goto bad; rc = next_entry(buf, fp, sizeof buf); if (rc) goto bad; len = le32_to_cpu(buf[0]); catdatum->value = le32_to_cpu(buf[1]); catdatum->isalias = le32_to_cpu(buf[2]); rc = -ENOMEM; key = kmalloc(len + 1, GFP_ATOMIC); if (!key) goto bad; rc = next_entry(key, fp, len); if (rc) goto bad; key[len] = '\0'; rc = hashtab_insert(h, key, catdatum); if (rc) goto bad; return 0; bad: cat_destroy(key, catdatum, NULL); return rc; } static int (*read_f[SYM_NUM]) (struct policydb *p, struct hashtab *h, void *fp) = { common_read, class_read, role_read, type_read, user_read, cond_read_bool, sens_read, cat_read, }; static int user_bounds_sanity_check(void *key, void *datum, void *datap) { struct user_datum *upper, *user; struct policydb *p = datap; int depth = 0; upper = user = datum; while (upper->bounds) { struct ebitmap_node *node; unsigned long bit; if (++depth == POLICYDB_BOUNDS_MAXDEPTH) { printk(KERN_ERR "SELinux: user %s: " "too deep or looped boundary", (char *) key); return -EINVAL; } upper = p->user_val_to_struct[upper->bounds - 1]; ebitmap_for_each_positive_bit(&user->roles, node, bit) { if (ebitmap_get_bit(&upper->roles, bit)) continue; printk(KERN_ERR "SELinux: boundary violated policy: " "user=%s role=%s bounds=%s\n", sym_name(p, SYM_USERS, user->value - 1), sym_name(p, SYM_ROLES, bit), sym_name(p, SYM_USERS, upper->value - 1)); return -EINVAL; } } return 0; } static int role_bounds_sanity_check(void *key, void *datum, void *datap) { struct role_datum *upper, *role; struct policydb *p = datap; int depth = 0; upper = role = datum; while (upper->bounds) { struct ebitmap_node *node; unsigned long bit; if (++depth == POLICYDB_BOUNDS_MAXDEPTH) { printk(KERN_ERR "SELinux: role %s: " "too deep or looped bounds\n", (char *) key); return -EINVAL; } upper = p->role_val_to_struct[upper->bounds - 1]; ebitmap_for_each_positive_bit(&role->types, node, bit) { if (ebitmap_get_bit(&upper->types, bit)) continue; printk(KERN_ERR "SELinux: boundary violated policy: " "role=%s type=%s bounds=%s\n", sym_name(p, SYM_ROLES, role->value - 1), sym_name(p, SYM_TYPES, bit), sym_name(p, SYM_ROLES, upper->value - 1)); return -EINVAL; } } return 0; } static int type_bounds_sanity_check(void *key, void *datum, void *datap) { struct type_datum *upper; struct policydb *p = datap; int depth = 0; upper = datum; while (upper->bounds) { if (++depth == POLICYDB_BOUNDS_MAXDEPTH) { printk(KERN_ERR "SELinux: type %s: " "too deep or looped boundary\n", (char *) key); return -EINVAL; } upper = flex_array_get_ptr(p->type_val_to_struct_array, upper->bounds - 1); BUG_ON(!upper); if (upper->attribute) { printk(KERN_ERR "SELinux: type %s: " "bounded by attribute %s", (char *) key, sym_name(p, SYM_TYPES, upper->value - 1)); return -EINVAL; } } return 0; } static int policydb_bounds_sanity_check(struct policydb *p) { int rc; if (p->policyvers < POLICYDB_VERSION_BOUNDARY) return 0; rc = hashtab_map(p->p_users.table, user_bounds_sanity_check, p); if (rc) return rc; rc = hashtab_map(p->p_roles.table, role_bounds_sanity_check, p); if (rc) return rc; rc = hashtab_map(p->p_types.table, type_bounds_sanity_check, p); if (rc) return rc; return 0; } u16 string_to_security_class(struct policydb *p, const char *name) { struct class_datum *cladatum; cladatum = hashtab_search(p->p_classes.table, name); if (!cladatum) return 0; return cladatum->value; } u32 string_to_av_perm(struct policydb *p, u16 tclass, const char *name) { struct class_datum *cladatum; struct perm_datum *perdatum = NULL; struct common_datum *comdatum; if (!tclass || tclass > p->p_classes.nprim) return 0; cladatum = p->class_val_to_struct[tclass-1]; comdatum = cladatum->comdatum; if (comdatum) perdatum = hashtab_search(comdatum->permissions.table, name); if (!perdatum) perdatum = hashtab_search(cladatum->permissions.table, name); if (!perdatum) return 0; return 1U << (perdatum->value-1); } static int range_read(struct policydb *p, void *fp) { struct range_trans *rt = NULL; struct mls_range *r = NULL; int i, rc; __le32 buf[2]; u32 nel; if (p->policyvers < POLICYDB_VERSION_MLS) return 0; rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; nel = le32_to_cpu(buf[0]); for (i = 0; i < nel; i++) { rc = -ENOMEM; rt = kzalloc(sizeof(*rt), GFP_KERNEL); if (!rt) goto out; rc = next_entry(buf, fp, (sizeof(u32) * 2)); if (rc) goto out; rt->source_type = le32_to_cpu(buf[0]); rt->target_type = le32_to_cpu(buf[1]); if (p->policyvers >= POLICYDB_VERSION_RANGETRANS) { rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; rt->target_class = le32_to_cpu(buf[0]); } else rt->target_class = p->process_class; rc = -EINVAL; if (!policydb_type_isvalid(p, rt->source_type) || !policydb_type_isvalid(p, rt->target_type) || !policydb_class_isvalid(p, rt->target_class)) goto out; rc = -ENOMEM; r = kzalloc(sizeof(*r), GFP_KERNEL); if (!r) goto out; rc = mls_read_range_helper(r, fp); if (rc) goto out; rc = -EINVAL; if (!mls_range_isvalid(p, r)) { printk(KERN_WARNING "SELinux: rangetrans: invalid range\n"); goto out; } rc = hashtab_insert(p->range_tr, rt, r); if (rc) goto out; rt = NULL; r = NULL; } hash_eval(p->range_tr, "rangetr"); rc = 0; out: kfree(rt); kfree(r); return rc; } static int filename_trans_read(struct policydb *p, void *fp) { struct filename_trans *ft; struct filename_trans_datum *otype; char *name; u32 nel, len; __le32 buf[4]; int rc, i; if (p->policyvers < POLICYDB_VERSION_FILENAME_TRANS) return 0; rc = next_entry(buf, fp, sizeof(u32)); if (rc) return rc; nel = le32_to_cpu(buf[0]); for (i = 0; i < nel; i++) { ft = NULL; otype = NULL; name = NULL; rc = -ENOMEM; ft = kzalloc(sizeof(*ft), GFP_KERNEL); if (!ft) goto out; rc = -ENOMEM; otype = kmalloc(sizeof(*otype), GFP_KERNEL); if (!otype) goto out; /* length of the path component string */ rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; len = le32_to_cpu(buf[0]); rc = -ENOMEM; name = kmalloc(len + 1, GFP_KERNEL); if (!name) goto out; ft->name = name; /* path component string */ rc = next_entry(name, fp, len); if (rc) goto out; name[len] = 0; rc = next_entry(buf, fp, sizeof(u32) * 4); if (rc) goto out; ft->stype = le32_to_cpu(buf[0]); ft->ttype = le32_to_cpu(buf[1]); ft->tclass = le32_to_cpu(buf[2]); otype->otype = le32_to_cpu(buf[3]); rc = ebitmap_set_bit(&p->filename_trans_ttypes, ft->ttype, 1); if (rc) goto out; hashtab_insert(p->filename_trans, ft, otype); } hash_eval(p->filename_trans, "filenametr"); return 0; out: kfree(ft); kfree(name); kfree(otype); return rc; } static int genfs_read(struct policydb *p, void *fp) { int i, j, rc; u32 nel, nel2, len, len2; __le32 buf[1]; struct ocontext *l, *c; struct ocontext *newc = NULL; struct genfs *genfs_p, *genfs; struct genfs *newgenfs = NULL; rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; nel = le32_to_cpu(buf[0]); for (i = 0; i < nel; i++) { rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; len = le32_to_cpu(buf[0]); rc = -ENOMEM; newgenfs = kzalloc(sizeof(*newgenfs), GFP_KERNEL); if (!newgenfs) goto out; rc = -ENOMEM; newgenfs->fstype = kmalloc(len + 1, GFP_KERNEL); if (!newgenfs->fstype) goto out; rc = next_entry(newgenfs->fstype, fp, len); if (rc) goto out; newgenfs->fstype[len] = 0; for (genfs_p = NULL, genfs = p->genfs; genfs; genfs_p = genfs, genfs = genfs->next) { rc = -EINVAL; if (strcmp(newgenfs->fstype, genfs->fstype) == 0) { printk(KERN_ERR "SELinux: dup genfs fstype %s\n", newgenfs->fstype); goto out; } if (strcmp(newgenfs->fstype, genfs->fstype) < 0) break; } newgenfs->next = genfs; if (genfs_p) genfs_p->next = newgenfs; else p->genfs = newgenfs; genfs = newgenfs; newgenfs = NULL; rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; nel2 = le32_to_cpu(buf[0]); for (j = 0; j < nel2; j++) { rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; len = le32_to_cpu(buf[0]); rc = -ENOMEM; newc = kzalloc(sizeof(*newc), GFP_KERNEL); if (!newc) goto out; rc = -ENOMEM; newc->u.name = kmalloc(len + 1, GFP_KERNEL); if (!newc->u.name) goto out; rc = next_entry(newc->u.name, fp, len); if (rc) goto out; newc->u.name[len] = 0; rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; newc->v.sclass = le32_to_cpu(buf[0]); rc = context_read_and_validate(&newc->context[0], p, fp); if (rc) goto out; for (l = NULL, c = genfs->head; c; l = c, c = c->next) { rc = -EINVAL; if (!strcmp(newc->u.name, c->u.name) && (!c->v.sclass || !newc->v.sclass || newc->v.sclass == c->v.sclass)) { printk(KERN_ERR "SELinux: dup genfs entry (%s,%s)\n", genfs->fstype, c->u.name); goto out; } len = strlen(newc->u.name); len2 = strlen(c->u.name); if (len > len2) break; } newc->next = c; if (l) l->next = newc; else genfs->head = newc; newc = NULL; } } rc = 0; out: if (newgenfs) kfree(newgenfs->fstype); kfree(newgenfs); ocontext_destroy(newc, OCON_FSUSE); return rc; } static int ocontext_read(struct policydb *p, struct policydb_compat_info *info, void *fp) { int i, j, rc; u32 nel, len; __le32 buf[3]; struct ocontext *l, *c; u32 nodebuf[8]; for (i = 0; i < info->ocon_num; i++) { rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; nel = le32_to_cpu(buf[0]); l = NULL; for (j = 0; j < nel; j++) { rc = -ENOMEM; c = kzalloc(sizeof(*c), GFP_KERNEL); if (!c) goto out; if (l) l->next = c; else p->ocontexts[i] = c; l = c; switch (i) { case OCON_ISID: rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; c->sid[0] = le32_to_cpu(buf[0]); rc = context_read_and_validate(&c->context[0], p, fp); if (rc) goto out; break; case OCON_FS: case OCON_NETIF: rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto out; len = le32_to_cpu(buf[0]); rc = -ENOMEM; c->u.name = kmalloc(len + 1, GFP_KERNEL); if (!c->u.name) goto out; rc = next_entry(c->u.name, fp, len); if (rc) goto out; c->u.name[len] = 0; rc = context_read_and_validate(&c->context[0], p, fp); if (rc) goto out; rc = context_read_and_validate(&c->context[1], p, fp); if (rc) goto out; break; case OCON_PORT: rc = next_entry(buf, fp, sizeof(u32)*3); if (rc) goto out; c->u.port.protocol = le32_to_cpu(buf[0]); c->u.port.low_port = le32_to_cpu(buf[1]); c->u.port.high_port = le32_to_cpu(buf[2]); rc = context_read_and_validate(&c->context[0], p, fp); if (rc) goto out; break; case OCON_NODE: rc = next_entry(nodebuf, fp, sizeof(u32) * 2); if (rc) goto out; c->u.node.addr = nodebuf[0]; /* network order */ c->u.node.mask = nodebuf[1]; /* network order */ rc = context_read_and_validate(&c->context[0], p, fp); if (rc) goto out; break; case OCON_FSUSE: rc = next_entry(buf, fp, sizeof(u32)*2); if (rc) goto out; rc = -EINVAL; c->v.behavior = le32_to_cpu(buf[0]); if (c->v.behavior > SECURITY_FS_USE_NONE) goto out; rc = -ENOMEM; len = le32_to_cpu(buf[1]); c->u.name = kmalloc(len + 1, GFP_KERNEL); if (!c->u.name) goto out; rc = next_entry(c->u.name, fp, len); if (rc) goto out; c->u.name[len] = 0; rc = context_read_and_validate(&c->context[0], p, fp); if (rc) goto out; break; case OCON_NODE6: { int k; rc = next_entry(nodebuf, fp, sizeof(u32) * 8); if (rc) goto out; for (k = 0; k < 4; k++) c->u.node6.addr[k] = nodebuf[k]; for (k = 0; k < 4; k++) c->u.node6.mask[k] = nodebuf[k+4]; rc = context_read_and_validate(&c->context[0], p, fp); if (rc) goto out; break; } } } } rc = 0; out: return rc; } /* * Read the configuration data from a policy database binary * representation file into a policy database structure. */ int policydb_read(struct policydb *p, void *fp) { struct role_allow *ra, *lra; struct role_trans *tr, *ltr; int i, j, rc; __le32 buf[4]; u32 len, nprim, nel; char *policydb_str; struct policydb_compat_info *info; rc = policydb_init(p); if (rc) return rc; /* Read the magic number and string length. */ rc = next_entry(buf, fp, sizeof(u32) * 2); if (rc) goto bad; rc = -EINVAL; if (le32_to_cpu(buf[0]) != POLICYDB_MAGIC) { printk(KERN_ERR "SELinux: policydb magic number 0x%x does " "not match expected magic number 0x%x\n", le32_to_cpu(buf[0]), POLICYDB_MAGIC); goto bad; } rc = -EINVAL; len = le32_to_cpu(buf[1]); if (len != strlen(POLICYDB_STRING)) { printk(KERN_ERR "SELinux: policydb string length %d does not " "match expected length %Zu\n", len, strlen(POLICYDB_STRING)); goto bad; } rc = -ENOMEM; policydb_str = kmalloc(len + 1, GFP_KERNEL); if (!policydb_str) { printk(KERN_ERR "SELinux: unable to allocate memory for policydb " "string of length %d\n", len); goto bad; } rc = next_entry(policydb_str, fp, len); if (rc) { printk(KERN_ERR "SELinux: truncated policydb string identifier\n"); kfree(policydb_str); goto bad; } rc = -EINVAL; policydb_str[len] = '\0'; if (strcmp(policydb_str, POLICYDB_STRING)) { printk(KERN_ERR "SELinux: policydb string %s does not match " "my string %s\n", policydb_str, POLICYDB_STRING); kfree(policydb_str); goto bad; } /* Done with policydb_str. */ kfree(policydb_str); policydb_str = NULL; /* Read the version and table sizes. */ rc = next_entry(buf, fp, sizeof(u32)*4); if (rc) goto bad; rc = -EINVAL; p->policyvers = le32_to_cpu(buf[0]); if (p->policyvers < POLICYDB_VERSION_MIN || p->policyvers > POLICYDB_VERSION_MAX) { printk(KERN_ERR "SELinux: policydb version %d does not match " "my version range %d-%d\n", le32_to_cpu(buf[0]), POLICYDB_VERSION_MIN, POLICYDB_VERSION_MAX); goto bad; } if ((le32_to_cpu(buf[1]) & POLICYDB_CONFIG_MLS)) { p->mls_enabled = 1; rc = -EINVAL; if (p->policyvers < POLICYDB_VERSION_MLS) { printk(KERN_ERR "SELinux: security policydb version %d " "(MLS) not backwards compatible\n", p->policyvers); goto bad; } } p->reject_unknown = !!(le32_to_cpu(buf[1]) & REJECT_UNKNOWN); p->allow_unknown = !!(le32_to_cpu(buf[1]) & ALLOW_UNKNOWN); if (p->policyvers >= POLICYDB_VERSION_POLCAP) { rc = ebitmap_read(&p->policycaps, fp); if (rc) goto bad; } if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE) { rc = ebitmap_read(&p->permissive_map, fp); if (rc) goto bad; } rc = -EINVAL; info = policydb_lookup_compat(p->policyvers); if (!info) { printk(KERN_ERR "SELinux: unable to find policy compat info " "for version %d\n", p->policyvers); goto bad; } rc = -EINVAL; if (le32_to_cpu(buf[2]) != info->sym_num || le32_to_cpu(buf[3]) != info->ocon_num) { printk(KERN_ERR "SELinux: policydb table sizes (%d,%d) do " "not match mine (%d,%d)\n", le32_to_cpu(buf[2]), le32_to_cpu(buf[3]), info->sym_num, info->ocon_num); goto bad; } for (i = 0; i < info->sym_num; i++) { rc = next_entry(buf, fp, sizeof(u32)*2); if (rc) goto bad; nprim = le32_to_cpu(buf[0]); nel = le32_to_cpu(buf[1]); for (j = 0; j < nel; j++) { rc = read_f[i](p, p->symtab[i].table, fp); if (rc) goto bad; } p->symtab[i].nprim = nprim; } rc = -EINVAL; p->process_class = string_to_security_class(p, "process"); if (!p->process_class) goto bad; rc = avtab_read(&p->te_avtab, fp, p); if (rc) goto bad; if (p->policyvers >= POLICYDB_VERSION_BOOL) { rc = cond_read_list(p, fp); if (rc) goto bad; } rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto bad; nel = le32_to_cpu(buf[0]); ltr = NULL; for (i = 0; i < nel; i++) { rc = -ENOMEM; tr = kzalloc(sizeof(*tr), GFP_KERNEL); if (!tr) goto bad; if (ltr) ltr->next = tr; else p->role_tr = tr; rc = next_entry(buf, fp, sizeof(u32)*3); if (rc) goto bad; rc = -EINVAL; tr->role = le32_to_cpu(buf[0]); tr->type = le32_to_cpu(buf[1]); tr->new_role = le32_to_cpu(buf[2]); if (p->policyvers >= POLICYDB_VERSION_ROLETRANS) { rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto bad; tr->tclass = le32_to_cpu(buf[0]); } else tr->tclass = p->process_class; if (!policydb_role_isvalid(p, tr->role) || !policydb_type_isvalid(p, tr->type) || !policydb_class_isvalid(p, tr->tclass) || !policydb_role_isvalid(p, tr->new_role)) goto bad; ltr = tr; } rc = next_entry(buf, fp, sizeof(u32)); if (rc) goto bad; nel = le32_to_cpu(buf[0]); lra = NULL; for (i = 0; i < nel; i++) { rc = -ENOMEM; ra = kzalloc(sizeof(*ra), GFP_KERNEL); if (!ra) goto bad; if (lra) lra->next = ra; else p->role_allow = ra; rc = next_entry(buf, fp, sizeof(u32)*2); if (rc) goto bad; rc = -EINVAL; ra->role = le32_to_cpu(buf[0]); ra->new_role = le32_to_cpu(buf[1]); if (!policydb_role_isvalid(p, ra->role) || !policydb_role_isvalid(p, ra->new_role)) goto bad; lra = ra; } rc = filename_trans_read(p, fp); if (rc) goto bad; rc = policydb_index(p); if (rc) goto bad; rc = -EINVAL; p->process_trans_perms = string_to_av_perm(p, p->process_class, "transition"); p->process_trans_perms |= string_to_av_perm(p, p->process_class, "dyntransition"); if (!p->process_trans_perms) goto bad; rc = ocontext_read(p, info, fp); if (rc) goto bad; rc = genfs_read(p, fp); if (rc) goto bad; rc = range_read(p, fp); if (rc) goto bad; rc = -ENOMEM; p->type_attr_map_array = flex_array_alloc(sizeof(struct ebitmap), p->p_types.nprim, GFP_KERNEL | __GFP_ZERO); if (!p->type_attr_map_array) goto bad; /* preallocate so we don't have to worry about the put ever failing */ rc = flex_array_prealloc(p->type_attr_map_array, 0, p->p_types.nprim, GFP_KERNEL | __GFP_ZERO); if (rc) goto bad; for (i = 0; i < p->p_types.nprim; i++) { struct ebitmap *e = flex_array_get(p->type_attr_map_array, i); BUG_ON(!e); ebitmap_init(e); if (p->policyvers >= POLICYDB_VERSION_AVTAB) { rc = ebitmap_read(e, fp); if (rc) goto bad; } /* add the type itself as the degenerate case */ rc = ebitmap_set_bit(e, i, 1); if (rc) goto bad; } rc = policydb_bounds_sanity_check(p); if (rc) goto bad; rc = 0; out: return rc; bad: policydb_destroy(p); goto out; } /* * Write a MLS level structure to a policydb binary * representation file. */ static int mls_write_level(struct mls_level *l, void *fp) { __le32 buf[1]; int rc; buf[0] = cpu_to_le32(l->sens); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = ebitmap_write(&l->cat, fp); if (rc) return rc; return 0; } /* * Write a MLS range structure to a policydb binary * representation file. */ static int mls_write_range_helper(struct mls_range *r, void *fp) { __le32 buf[3]; size_t items; int rc, eq; eq = mls_level_eq(&r->level[1], &r->level[0]); if (eq) items = 2; else items = 3; buf[0] = cpu_to_le32(items-1); buf[1] = cpu_to_le32(r->level[0].sens); if (!eq) buf[2] = cpu_to_le32(r->level[1].sens); BUG_ON(items > (sizeof(buf)/sizeof(buf[0]))); rc = put_entry(buf, sizeof(u32), items, fp); if (rc) return rc; rc = ebitmap_write(&r->level[0].cat, fp); if (rc) return rc; if (!eq) { rc = ebitmap_write(&r->level[1].cat, fp); if (rc) return rc; } return 0; } static int sens_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct level_datum *levdatum = datum; struct policy_data *pd = ptr; void *fp = pd->fp; __le32 buf[2]; size_t len; int rc; len = strlen(key); buf[0] = cpu_to_le32(len); buf[1] = cpu_to_le32(levdatum->isalias); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; rc = mls_write_level(levdatum->level, fp); if (rc) return rc; return 0; } static int cat_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct cat_datum *catdatum = datum; struct policy_data *pd = ptr; void *fp = pd->fp; __le32 buf[3]; size_t len; int rc; len = strlen(key); buf[0] = cpu_to_le32(len); buf[1] = cpu_to_le32(catdatum->value); buf[2] = cpu_to_le32(catdatum->isalias); rc = put_entry(buf, sizeof(u32), 3, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; return 0; } static int role_trans_write(struct policydb *p, void *fp) { struct role_trans *r = p->role_tr; struct role_trans *tr; u32 buf[3]; size_t nel; int rc; nel = 0; for (tr = r; tr; tr = tr->next) nel++; buf[0] = cpu_to_le32(nel); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; for (tr = r; tr; tr = tr->next) { buf[0] = cpu_to_le32(tr->role); buf[1] = cpu_to_le32(tr->type); buf[2] = cpu_to_le32(tr->new_role); rc = put_entry(buf, sizeof(u32), 3, fp); if (rc) return rc; if (p->policyvers >= POLICYDB_VERSION_ROLETRANS) { buf[0] = cpu_to_le32(tr->tclass); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; } } return 0; } static int role_allow_write(struct role_allow *r, void *fp) { struct role_allow *ra; u32 buf[2]; size_t nel; int rc; nel = 0; for (ra = r; ra; ra = ra->next) nel++; buf[0] = cpu_to_le32(nel); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; for (ra = r; ra; ra = ra->next) { buf[0] = cpu_to_le32(ra->role); buf[1] = cpu_to_le32(ra->new_role); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; } return 0; } /* * Write a security context structure * to a policydb binary representation file. */ static int context_write(struct policydb *p, struct context *c, void *fp) { int rc; __le32 buf[3]; buf[0] = cpu_to_le32(c->user); buf[1] = cpu_to_le32(c->role); buf[2] = cpu_to_le32(c->type); rc = put_entry(buf, sizeof(u32), 3, fp); if (rc) return rc; rc = mls_write_range_helper(&c->range, fp); if (rc) return rc; return 0; } /* * The following *_write functions are used to * write the symbol data to a policy database * binary representation file. */ static int perm_write(void *vkey, void *datum, void *fp) { char *key = vkey; struct perm_datum *perdatum = datum; __le32 buf[2]; size_t len; int rc; len = strlen(key); buf[0] = cpu_to_le32(len); buf[1] = cpu_to_le32(perdatum->value); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; return 0; } static int common_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct common_datum *comdatum = datum; struct policy_data *pd = ptr; void *fp = pd->fp; __le32 buf[4]; size_t len; int rc; len = strlen(key); buf[0] = cpu_to_le32(len); buf[1] = cpu_to_le32(comdatum->value); buf[2] = cpu_to_le32(comdatum->permissions.nprim); buf[3] = cpu_to_le32(comdatum->permissions.table->nel); rc = put_entry(buf, sizeof(u32), 4, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; rc = hashtab_map(comdatum->permissions.table, perm_write, fp); if (rc) return rc; return 0; } static int write_cons_helper(struct policydb *p, struct constraint_node *node, void *fp) { struct constraint_node *c; struct constraint_expr *e; __le32 buf[3]; u32 nel; int rc; for (c = node; c; c = c->next) { nel = 0; for (e = c->expr; e; e = e->next) nel++; buf[0] = cpu_to_le32(c->permissions); buf[1] = cpu_to_le32(nel); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; for (e = c->expr; e; e = e->next) { buf[0] = cpu_to_le32(e->expr_type); buf[1] = cpu_to_le32(e->attr); buf[2] = cpu_to_le32(e->op); rc = put_entry(buf, sizeof(u32), 3, fp); if (rc) return rc; switch (e->expr_type) { case CEXPR_NAMES: rc = ebitmap_write(&e->names, fp); if (rc) return rc; break; default: break; } } } return 0; } static int class_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct class_datum *cladatum = datum; struct policy_data *pd = ptr; void *fp = pd->fp; struct policydb *p = pd->p; struct constraint_node *c; __le32 buf[6]; u32 ncons; size_t len, len2; int rc; len = strlen(key); if (cladatum->comkey) len2 = strlen(cladatum->comkey); else len2 = 0; ncons = 0; for (c = cladatum->constraints; c; c = c->next) ncons++; buf[0] = cpu_to_le32(len); buf[1] = cpu_to_le32(len2); buf[2] = cpu_to_le32(cladatum->value); buf[3] = cpu_to_le32(cladatum->permissions.nprim); if (cladatum->permissions.table) buf[4] = cpu_to_le32(cladatum->permissions.table->nel); else buf[4] = 0; buf[5] = cpu_to_le32(ncons); rc = put_entry(buf, sizeof(u32), 6, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; if (cladatum->comkey) { rc = put_entry(cladatum->comkey, 1, len2, fp); if (rc) return rc; } rc = hashtab_map(cladatum->permissions.table, perm_write, fp); if (rc) return rc; rc = write_cons_helper(p, cladatum->constraints, fp); if (rc) return rc; /* write out the validatetrans rule */ ncons = 0; for (c = cladatum->validatetrans; c; c = c->next) ncons++; buf[0] = cpu_to_le32(ncons); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = write_cons_helper(p, cladatum->validatetrans, fp); if (rc) return rc; if (p->policyvers >= POLICYDB_VERSION_NEW_OBJECT_DEFAULTS) { buf[0] = cpu_to_le32(cladatum->default_user); buf[1] = cpu_to_le32(cladatum->default_role); buf[2] = cpu_to_le32(cladatum->default_range); rc = put_entry(buf, sizeof(uint32_t), 3, fp); if (rc) return rc; } if (p->policyvers >= POLICYDB_VERSION_DEFAULT_TYPE) { buf[0] = cpu_to_le32(cladatum->default_type); rc = put_entry(buf, sizeof(uint32_t), 1, fp); if (rc) return rc; } return 0; } static int role_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct role_datum *role = datum; struct policy_data *pd = ptr; void *fp = pd->fp; struct policydb *p = pd->p; __le32 buf[3]; size_t items, len; int rc; len = strlen(key); items = 0; buf[items++] = cpu_to_le32(len); buf[items++] = cpu_to_le32(role->value); if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) buf[items++] = cpu_to_le32(role->bounds); BUG_ON(items > (sizeof(buf)/sizeof(buf[0]))); rc = put_entry(buf, sizeof(u32), items, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; rc = ebitmap_write(&role->dominates, fp); if (rc) return rc; rc = ebitmap_write(&role->types, fp); if (rc) return rc; return 0; } static int type_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct type_datum *typdatum = datum; struct policy_data *pd = ptr; struct policydb *p = pd->p; void *fp = pd->fp; __le32 buf[4]; int rc; size_t items, len; len = strlen(key); items = 0; buf[items++] = cpu_to_le32(len); buf[items++] = cpu_to_le32(typdatum->value); if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) { u32 properties = 0; if (typdatum->primary) properties |= TYPEDATUM_PROPERTY_PRIMARY; if (typdatum->attribute) properties |= TYPEDATUM_PROPERTY_ATTRIBUTE; buf[items++] = cpu_to_le32(properties); buf[items++] = cpu_to_le32(typdatum->bounds); } else { buf[items++] = cpu_to_le32(typdatum->primary); } BUG_ON(items > (sizeof(buf) / sizeof(buf[0]))); rc = put_entry(buf, sizeof(u32), items, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; return 0; } static int user_write(void *vkey, void *datum, void *ptr) { char *key = vkey; struct user_datum *usrdatum = datum; struct policy_data *pd = ptr; struct policydb *p = pd->p; void *fp = pd->fp; __le32 buf[3]; size_t items, len; int rc; len = strlen(key); items = 0; buf[items++] = cpu_to_le32(len); buf[items++] = cpu_to_le32(usrdatum->value); if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) buf[items++] = cpu_to_le32(usrdatum->bounds); BUG_ON(items > (sizeof(buf) / sizeof(buf[0]))); rc = put_entry(buf, sizeof(u32), items, fp); if (rc) return rc; rc = put_entry(key, 1, len, fp); if (rc) return rc; rc = ebitmap_write(&usrdatum->roles, fp); if (rc) return rc; rc = mls_write_range_helper(&usrdatum->range, fp); if (rc) return rc; rc = mls_write_level(&usrdatum->dfltlevel, fp); if (rc) return rc; return 0; } static int (*write_f[SYM_NUM]) (void *key, void *datum, void *datap) = { common_write, class_write, role_write, type_write, user_write, cond_write_bool, sens_write, cat_write, }; static int ocontext_write(struct policydb *p, struct policydb_compat_info *info, void *fp) { unsigned int i, j, rc; size_t nel, len; __le32 buf[3]; u32 nodebuf[8]; struct ocontext *c; for (i = 0; i < info->ocon_num; i++) { nel = 0; for (c = p->ocontexts[i]; c; c = c->next) nel++; buf[0] = cpu_to_le32(nel); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; for (c = p->ocontexts[i]; c; c = c->next) { switch (i) { case OCON_ISID: buf[0] = cpu_to_le32(c->sid[0]); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; break; case OCON_FS: case OCON_NETIF: len = strlen(c->u.name); buf[0] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = put_entry(c->u.name, 1, len, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; rc = context_write(p, &c->context[1], fp); if (rc) return rc; break; case OCON_PORT: buf[0] = cpu_to_le32(c->u.port.protocol); buf[1] = cpu_to_le32(c->u.port.low_port); buf[2] = cpu_to_le32(c->u.port.high_port); rc = put_entry(buf, sizeof(u32), 3, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; break; case OCON_NODE: nodebuf[0] = c->u.node.addr; /* network order */ nodebuf[1] = c->u.node.mask; /* network order */ rc = put_entry(nodebuf, sizeof(u32), 2, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; break; case OCON_FSUSE: buf[0] = cpu_to_le32(c->v.behavior); len = strlen(c->u.name); buf[1] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; rc = put_entry(c->u.name, 1, len, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; break; case OCON_NODE6: for (j = 0; j < 4; j++) nodebuf[j] = c->u.node6.addr[j]; /* network order */ for (j = 0; j < 4; j++) nodebuf[j + 4] = c->u.node6.mask[j]; /* network order */ rc = put_entry(nodebuf, sizeof(u32), 8, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; break; } } } return 0; } static int genfs_write(struct policydb *p, void *fp) { struct genfs *genfs; struct ocontext *c; size_t len; __le32 buf[1]; int rc; len = 0; for (genfs = p->genfs; genfs; genfs = genfs->next) len++; buf[0] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; for (genfs = p->genfs; genfs; genfs = genfs->next) { len = strlen(genfs->fstype); buf[0] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = put_entry(genfs->fstype, 1, len, fp); if (rc) return rc; len = 0; for (c = genfs->head; c; c = c->next) len++; buf[0] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; for (c = genfs->head; c; c = c->next) { len = strlen(c->u.name); buf[0] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = put_entry(c->u.name, 1, len, fp); if (rc) return rc; buf[0] = cpu_to_le32(c->v.sclass); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = context_write(p, &c->context[0], fp); if (rc) return rc; } } return 0; } static int hashtab_cnt(void *key, void *data, void *ptr) { int *cnt = ptr; *cnt = *cnt + 1; return 0; } static int range_write_helper(void *key, void *data, void *ptr) { __le32 buf[2]; struct range_trans *rt = key; struct mls_range *r = data; struct policy_data *pd = ptr; void *fp = pd->fp; struct policydb *p = pd->p; int rc; buf[0] = cpu_to_le32(rt->source_type); buf[1] = cpu_to_le32(rt->target_type); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; if (p->policyvers >= POLICYDB_VERSION_RANGETRANS) { buf[0] = cpu_to_le32(rt->target_class); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; } rc = mls_write_range_helper(r, fp); if (rc) return rc; return 0; } static int range_write(struct policydb *p, void *fp) { size_t nel; __le32 buf[1]; int rc; struct policy_data pd; pd.p = p; pd.fp = fp; /* count the number of entries in the hashtab */ nel = 0; rc = hashtab_map(p->range_tr, hashtab_cnt, &nel); if (rc) return rc; buf[0] = cpu_to_le32(nel); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; /* actually write all of the entries */ rc = hashtab_map(p->range_tr, range_write_helper, &pd); if (rc) return rc; return 0; } static int filename_write_helper(void *key, void *data, void *ptr) { __le32 buf[4]; struct filename_trans *ft = key; struct filename_trans_datum *otype = data; void *fp = ptr; int rc; u32 len; len = strlen(ft->name); buf[0] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = put_entry(ft->name, sizeof(char), len, fp); if (rc) return rc; buf[0] = ft->stype; buf[1] = ft->ttype; buf[2] = ft->tclass; buf[3] = otype->otype; rc = put_entry(buf, sizeof(u32), 4, fp); if (rc) return rc; return 0; } static int filename_trans_write(struct policydb *p, void *fp) { u32 nel; __le32 buf[1]; int rc; if (p->policyvers < POLICYDB_VERSION_FILENAME_TRANS) return 0; nel = 0; rc = hashtab_map(p->filename_trans, hashtab_cnt, &nel); if (rc) return rc; buf[0] = cpu_to_le32(nel); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; rc = hashtab_map(p->filename_trans, filename_write_helper, fp); if (rc) return rc; return 0; } /* * Write the configuration data in a policy database * structure to a policy database binary representation * file. */ int policydb_write(struct policydb *p, void *fp) { unsigned int i, num_syms; int rc; __le32 buf[4]; u32 config; size_t len; struct policydb_compat_info *info; /* * refuse to write policy older than compressed avtab * to simplify the writer. There are other tests dropped * since we assume this throughout the writer code. Be * careful if you ever try to remove this restriction */ if (p->policyvers < POLICYDB_VERSION_AVTAB) { printk(KERN_ERR "SELinux: refusing to write policy version %d." " Because it is less than version %d\n", p->policyvers, POLICYDB_VERSION_AVTAB); return -EINVAL; } config = 0; if (p->mls_enabled) config |= POLICYDB_CONFIG_MLS; if (p->reject_unknown) config |= REJECT_UNKNOWN; if (p->allow_unknown) config |= ALLOW_UNKNOWN; /* Write the magic number and string identifiers. */ buf[0] = cpu_to_le32(POLICYDB_MAGIC); len = strlen(POLICYDB_STRING); buf[1] = cpu_to_le32(len); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; rc = put_entry(POLICYDB_STRING, 1, len, fp); if (rc) return rc; /* Write the version, config, and table sizes. */ info = policydb_lookup_compat(p->policyvers); if (!info) { printk(KERN_ERR "SELinux: compatibility lookup failed for policy " "version %d", p->policyvers); return -EINVAL; } buf[0] = cpu_to_le32(p->policyvers); buf[1] = cpu_to_le32(config); buf[2] = cpu_to_le32(info->sym_num); buf[3] = cpu_to_le32(info->ocon_num); rc = put_entry(buf, sizeof(u32), 4, fp); if (rc) return rc; if (p->policyvers >= POLICYDB_VERSION_POLCAP) { rc = ebitmap_write(&p->policycaps, fp); if (rc) return rc; } if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE) { rc = ebitmap_write(&p->permissive_map, fp); if (rc) return rc; } num_syms = info->sym_num; for (i = 0; i < num_syms; i++) { struct policy_data pd; pd.fp = fp; pd.p = p; buf[0] = cpu_to_le32(p->symtab[i].nprim); buf[1] = cpu_to_le32(p->symtab[i].table->nel); rc = put_entry(buf, sizeof(u32), 2, fp); if (rc) return rc; rc = hashtab_map(p->symtab[i].table, write_f[i], &pd); if (rc) return rc; } rc = avtab_write(p, &p->te_avtab, fp); if (rc) return rc; rc = cond_write_list(p, p->cond_list, fp); if (rc) return rc; rc = role_trans_write(p, fp); if (rc) return rc; rc = role_allow_write(p->role_allow, fp); if (rc) return rc; rc = filename_trans_write(p, fp); if (rc) return rc; rc = ocontext_write(p, info, fp); if (rc) return rc; rc = genfs_write(p, fp); if (rc) return rc; rc = range_write(p, fp); if (rc) return rc; for (i = 0; i < p->p_types.nprim; i++) { struct ebitmap *e = flex_array_get(p->type_attr_map_array, i); BUG_ON(!e); rc = ebitmap_write(e, fp); if (rc) return rc; } return 0; }
gpl-2.0
mrg666/nook_kernel
drivers/bluetooth/bcm203x.c
714
7066
/* * * Broadcom Blutonium firmware driver * * Copyright (C) 2003 Maxim Krasnyansky <maxk@qualcomm.com> * Copyright (C) 2003 Marcel Holtmann <marcel@holtmann.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/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/device.h> #include <linux/firmware.h> #include <linux/usb.h> #include <net/bluetooth/bluetooth.h> #define VERSION "1.2" static struct usb_device_id bcm203x_table[] = { /* Broadcom Blutonium (BCM2033) */ { USB_DEVICE(0x0a5c, 0x2033) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, bcm203x_table); #define BCM203X_ERROR 0 #define BCM203X_RESET 1 #define BCM203X_LOAD_MINIDRV 2 #define BCM203X_SELECT_MEMORY 3 #define BCM203X_CHECK_MEMORY 4 #define BCM203X_LOAD_FIRMWARE 5 #define BCM203X_CHECK_FIRMWARE 6 #define BCM203X_IN_EP 0x81 #define BCM203X_OUT_EP 0x02 struct bcm203x_data { struct usb_device *udev; unsigned long state; struct work_struct work; struct urb *urb; unsigned char *buffer; unsigned char *fw_data; unsigned int fw_size; unsigned int fw_sent; }; static void bcm203x_complete(struct urb *urb) { struct bcm203x_data *data = urb->context; struct usb_device *udev = urb->dev; int len; BT_DBG("udev %p urb %p", udev, urb); if (urb->status) { BT_ERR("URB failed with status %d", urb->status); data->state = BCM203X_ERROR; return; } switch (data->state) { case BCM203X_LOAD_MINIDRV: memcpy(data->buffer, "#", 1); usb_fill_bulk_urb(urb, udev, usb_sndbulkpipe(udev, BCM203X_OUT_EP), data->buffer, 1, bcm203x_complete, data); data->state = BCM203X_SELECT_MEMORY; schedule_work(&data->work); break; case BCM203X_SELECT_MEMORY: usb_fill_int_urb(urb, udev, usb_rcvintpipe(udev, BCM203X_IN_EP), data->buffer, 32, bcm203x_complete, data, 1); data->state = BCM203X_CHECK_MEMORY; if (usb_submit_urb(data->urb, GFP_ATOMIC) < 0) BT_ERR("Can't submit URB"); break; case BCM203X_CHECK_MEMORY: if (data->buffer[0] != '#') { BT_ERR("Memory select failed"); data->state = BCM203X_ERROR; break; } data->state = BCM203X_LOAD_FIRMWARE; case BCM203X_LOAD_FIRMWARE: if (data->fw_sent == data->fw_size) { usb_fill_int_urb(urb, udev, usb_rcvintpipe(udev, BCM203X_IN_EP), data->buffer, 32, bcm203x_complete, data, 1); data->state = BCM203X_CHECK_FIRMWARE; } else { len = min_t(uint, data->fw_size - data->fw_sent, 4096); usb_fill_bulk_urb(urb, udev, usb_sndbulkpipe(udev, BCM203X_OUT_EP), data->fw_data + data->fw_sent, len, bcm203x_complete, data); data->fw_sent += len; } if (usb_submit_urb(data->urb, GFP_ATOMIC) < 0) BT_ERR("Can't submit URB"); break; case BCM203X_CHECK_FIRMWARE: if (data->buffer[0] != '.') { BT_ERR("Firmware loading failed"); data->state = BCM203X_ERROR; break; } data->state = BCM203X_RESET; break; } } static void bcm203x_work(struct work_struct *work) { struct bcm203x_data *data = container_of(work, struct bcm203x_data, work); if (usb_submit_urb(data->urb, GFP_ATOMIC) < 0) BT_ERR("Can't submit URB"); } static int bcm203x_probe(struct usb_interface *intf, const struct usb_device_id *id) { const struct firmware *firmware; struct usb_device *udev = interface_to_usbdev(intf); struct bcm203x_data *data; int size; BT_DBG("intf %p id %p", intf, id); if (intf->cur_altsetting->desc.bInterfaceNumber != 0) return -ENODEV; data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) { BT_ERR("Can't allocate memory for data structure"); return -ENOMEM; } data->udev = udev; data->state = BCM203X_LOAD_MINIDRV; data->urb = usb_alloc_urb(0, GFP_KERNEL); if (!data->urb) { BT_ERR("Can't allocate URB"); kfree(data); return -ENOMEM; } if (request_firmware(&firmware, "BCM2033-MD.hex", &udev->dev) < 0) { BT_ERR("Mini driver request failed"); usb_free_urb(data->urb); kfree(data); return -EIO; } BT_DBG("minidrv data %p size %zu", firmware->data, firmware->size); size = max_t(uint, firmware->size, 4096); data->buffer = kmalloc(size, GFP_KERNEL); if (!data->buffer) { BT_ERR("Can't allocate memory for mini driver"); release_firmware(firmware); usb_free_urb(data->urb); kfree(data); return -ENOMEM; } memcpy(data->buffer, firmware->data, firmware->size); usb_fill_bulk_urb(data->urb, udev, usb_sndbulkpipe(udev, BCM203X_OUT_EP), data->buffer, firmware->size, bcm203x_complete, data); release_firmware(firmware); if (request_firmware(&firmware, "BCM2033-FW.bin", &udev->dev) < 0) { BT_ERR("Firmware request failed"); usb_free_urb(data->urb); kfree(data->buffer); kfree(data); return -EIO; } BT_DBG("firmware data %p size %zu", firmware->data, firmware->size); data->fw_data = kmalloc(firmware->size, GFP_KERNEL); if (!data->fw_data) { BT_ERR("Can't allocate memory for firmware image"); release_firmware(firmware); usb_free_urb(data->urb); kfree(data->buffer); kfree(data); return -ENOMEM; } memcpy(data->fw_data, firmware->data, firmware->size); data->fw_size = firmware->size; data->fw_sent = 0; release_firmware(firmware); INIT_WORK(&data->work, bcm203x_work); usb_set_intfdata(intf, data); schedule_work(&data->work); return 0; } static void bcm203x_disconnect(struct usb_interface *intf) { struct bcm203x_data *data = usb_get_intfdata(intf); BT_DBG("intf %p", intf); usb_kill_urb(data->urb); usb_set_intfdata(intf, NULL); usb_free_urb(data->urb); kfree(data->fw_data); kfree(data->buffer); kfree(data); } static struct usb_driver bcm203x_driver = { .name = "bcm203x", .probe = bcm203x_probe, .disconnect = bcm203x_disconnect, .id_table = bcm203x_table, }; static int __init bcm203x_init(void) { int err; BT_INFO("Broadcom Blutonium firmware driver ver %s", VERSION); err = usb_register(&bcm203x_driver); if (err < 0) BT_ERR("Failed to register USB driver"); return err; } static void __exit bcm203x_exit(void) { usb_deregister(&bcm203x_driver); } module_init(bcm203x_init); module_exit(bcm203x_exit); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Broadcom Blutonium firmware driver ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("BCM2033-MD.hex"); MODULE_FIRMWARE("BCM2033-FW.bin");
gpl-2.0
hopkinskong/linux_on_wince_htc
net/bridge/br_ioctl.c
714
9353
/* * Ioctl handler * Linux ethernet bridge * * Authors: * Lennert Buytenhek <buytenh@gnu.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/capability.h> #include <linux/kernel.h> #include <linux/if_bridge.h> #include <linux/netdevice.h> #include <linux/times.h> #include <net/net_namespace.h> #include <asm/uaccess.h> #include "br_private.h" /* called with RTNL */ static int get_bridge_ifindices(struct net *net, int *indices, int num) { struct net_device *dev; int i = 0; for_each_netdev(net, dev) { if (i >= num) break; if (dev->priv_flags & IFF_EBRIDGE) indices[i++] = dev->ifindex; } return i; } /* called with RTNL */ static void get_port_ifindices(struct net_bridge *br, int *ifindices, int num) { struct net_bridge_port *p; list_for_each_entry(p, &br->port_list, list) { if (p->port_no < num) ifindices[p->port_no] = p->dev->ifindex; } } /* * Format up to a page worth of forwarding table entries * userbuf -- where to copy result * maxnum -- maximum number of entries desired * (limited to a page for sanity) * offset -- number of records to skip */ static int get_fdb_entries(struct net_bridge *br, void __user *userbuf, unsigned long maxnum, unsigned long offset) { int num; void *buf; size_t size; /* Clamp size to PAGE_SIZE, test maxnum to avoid overflow */ if (maxnum > PAGE_SIZE/sizeof(struct __fdb_entry)) maxnum = PAGE_SIZE/sizeof(struct __fdb_entry); size = maxnum * sizeof(struct __fdb_entry); buf = kmalloc(size, GFP_USER); if (!buf) return -ENOMEM; num = br_fdb_fillbuf(br, buf, maxnum, offset); if (num > 0) { if (copy_to_user(userbuf, buf, num*sizeof(struct __fdb_entry))) num = -EFAULT; } kfree(buf); return num; } static int add_del_if(struct net_bridge *br, int ifindex, int isadd) { struct net_device *dev; int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; dev = dev_get_by_index(dev_net(br->dev), ifindex); if (dev == NULL) return -EINVAL; if (isadd) ret = br_add_if(br, dev); else ret = br_del_if(br, dev); dev_put(dev); return ret; } /* * Legacy ioctl's through SIOCDEVPRIVATE * This interface is deprecated because it was too difficult to * to do the translation for 32/64bit ioctl compatability. */ static int old_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); unsigned long args[4]; if (copy_from_user(args, rq->ifr_data, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_ADD_IF: case BRCTL_DEL_IF: return add_del_if(br, args[1], args[0] == BRCTL_ADD_IF); case BRCTL_GET_BRIDGE_INFO: { struct __bridge_info b; memset(&b, 0, sizeof(struct __bridge_info)); rcu_read_lock(); memcpy(&b.designated_root, &br->designated_root, 8); memcpy(&b.bridge_id, &br->bridge_id, 8); b.root_path_cost = br->root_path_cost; b.max_age = jiffies_to_clock_t(br->max_age); b.hello_time = jiffies_to_clock_t(br->hello_time); b.forward_delay = br->forward_delay; b.bridge_max_age = br->bridge_max_age; b.bridge_hello_time = br->bridge_hello_time; b.bridge_forward_delay = jiffies_to_clock_t(br->bridge_forward_delay); b.topology_change = br->topology_change; b.topology_change_detected = br->topology_change_detected; b.root_port = br->root_port; b.stp_enabled = (br->stp_enabled != BR_NO_STP); b.ageing_time = jiffies_to_clock_t(br->ageing_time); b.hello_timer_value = br_timer_value(&br->hello_timer); b.tcn_timer_value = br_timer_value(&br->tcn_timer); b.topology_change_timer_value = br_timer_value(&br->topology_change_timer); b.gc_timer_value = br_timer_value(&br->gc_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &b, sizeof(b))) return -EFAULT; return 0; } case BRCTL_GET_PORT_LIST: { int num, *indices; num = args[2]; if (num < 0) return -EINVAL; if (num == 0) num = 256; if (num > BR_MAX_PORTS) num = BR_MAX_PORTS; indices = kcalloc(num, sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; get_port_ifindices(br, indices, num); if (copy_to_user((void __user *)args[1], indices, num*sizeof(int))) num = -EFAULT; kfree(indices); return num; } case BRCTL_SET_BRIDGE_FORWARD_DELAY: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_forward_delay = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->forward_delay = br->bridge_forward_delay; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_BRIDGE_HELLO_TIME: { unsigned long t = clock_t_to_jiffies(args[1]); if (!capable(CAP_NET_ADMIN)) return -EPERM; if (t < HZ) return -EINVAL; spin_lock_bh(&br->lock); br->bridge_hello_time = t; if (br_is_root_bridge(br)) br->hello_time = br->bridge_hello_time; spin_unlock_bh(&br->lock); return 0; } case BRCTL_SET_BRIDGE_MAX_AGE: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_max_age = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->max_age = br->bridge_max_age; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_AGEING_TIME: if (!capable(CAP_NET_ADMIN)) return -EPERM; br->ageing_time = clock_t_to_jiffies(args[1]); return 0; case BRCTL_GET_PORT_INFO: { struct __port_info p; struct net_bridge_port *pt; rcu_read_lock(); if ((pt = br_get_port(br, args[2])) == NULL) { rcu_read_unlock(); return -EINVAL; } memset(&p, 0, sizeof(struct __port_info)); memcpy(&p.designated_root, &pt->designated_root, 8); memcpy(&p.designated_bridge, &pt->designated_bridge, 8); p.port_id = pt->port_id; p.designated_port = pt->designated_port; p.path_cost = pt->path_cost; p.designated_cost = pt->designated_cost; p.state = pt->state; p.top_change_ack = pt->topology_change_ack; p.config_pending = pt->config_pending; p.message_age_timer_value = br_timer_value(&pt->message_age_timer); p.forward_delay_timer_value = br_timer_value(&pt->forward_delay_timer); p.hold_timer_value = br_timer_value(&pt->hold_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &p, sizeof(p))) return -EFAULT; return 0; } case BRCTL_SET_BRIDGE_STP_STATE: if (!capable(CAP_NET_ADMIN)) return -EPERM; br_stp_set_enabled(br, args[1]); return 0; case BRCTL_SET_BRIDGE_PRIORITY: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br_stp_set_bridge_priority(br, args[1]); spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_PORT_PRIORITY: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (args[2] >= (1<<(16-BR_PORT_BITS))) return -ERANGE; spin_lock_bh(&br->lock); if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else br_stp_set_port_priority(p, args[2]); spin_unlock_bh(&br->lock); return ret; } case BRCTL_SET_PATH_COST: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else br_stp_set_path_cost(p, args[2]); return ret; } case BRCTL_GET_FDB_ENTRIES: return get_fdb_entries(br, (void __user *)args[1], args[2], args[3]); } return -EOPNOTSUPP; } static int old_deviceless(struct net *net, void __user *uarg) { unsigned long args[3]; if (copy_from_user(args, uarg, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_GET_VERSION: return BRCTL_VERSION; case BRCTL_GET_BRIDGES: { int *indices; int ret = 0; if (args[2] >= 2048) return -ENOMEM; indices = kcalloc(args[2], sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; args[2] = get_bridge_ifindices(net, indices, args[2]); ret = copy_to_user((void __user *)args[1], indices, args[2]*sizeof(int)) ? -EFAULT : args[2]; kfree(indices); return ret; } case BRCTL_ADD_BRIDGE: case BRCTL_DEL_BRIDGE: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, (void __user *)args[1], IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (args[0] == BRCTL_ADD_BRIDGE) return br_add_bridge(net, buf); return br_del_bridge(net, buf); } } return -EOPNOTSUPP; } int br_ioctl_deviceless_stub(struct net *net, unsigned int cmd, void __user *uarg) { switch (cmd) { case SIOCGIFBR: case SIOCSIFBR: return old_deviceless(net, uarg); case SIOCBRADDBR: case SIOCBRDELBR: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, uarg, IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (cmd == SIOCBRADDBR) return br_add_bridge(net, buf); return br_del_bridge(net, buf); } } return -EOPNOTSUPP; } int br_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); switch(cmd) { case SIOCDEVPRIVATE: return old_dev_ioctl(dev, rq, cmd); case SIOCBRADDIF: case SIOCBRDELIF: return add_del_if(br, rq->ifr_ifindex, cmd == SIOCBRADDIF); } pr_debug("Bridge does not support ioctl 0x%x\n", cmd); return -EOPNOTSUPP; }
gpl-2.0
aapav01/android_kernel_samsung_j7elte
arch/s390/kvm/sigp.c
1994
10074
/* * handling interprocessor communication * * Copyright IBM Corp. 2008, 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2 only) * as published by the Free Software Foundation. * * Author(s): Carsten Otte <cotte@de.ibm.com> * Christian Borntraeger <borntraeger@de.ibm.com> * Christian Ehrhardt <ehrhardt@de.ibm.com> */ #include <linux/kvm.h> #include <linux/kvm_host.h> #include <linux/slab.h> #include <asm/sigp.h> #include "gaccess.h" #include "kvm-s390.h" #include "trace.h" static int __sigp_sense(struct kvm_vcpu *vcpu, u16 cpu_addr, u64 *reg) { struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; int rc; if (cpu_addr >= KVM_MAX_VCPUS) return SIGP_CC_NOT_OPERATIONAL; spin_lock(&fi->lock); if (fi->local_int[cpu_addr] == NULL) rc = SIGP_CC_NOT_OPERATIONAL; else if (!(atomic_read(fi->local_int[cpu_addr]->cpuflags) & (CPUSTAT_ECALL_PEND | CPUSTAT_STOPPED))) rc = SIGP_CC_ORDER_CODE_ACCEPTED; else { *reg &= 0xffffffff00000000UL; if (atomic_read(fi->local_int[cpu_addr]->cpuflags) & CPUSTAT_ECALL_PEND) *reg |= SIGP_STATUS_EXT_CALL_PENDING; if (atomic_read(fi->local_int[cpu_addr]->cpuflags) & CPUSTAT_STOPPED) *reg |= SIGP_STATUS_STOPPED; rc = SIGP_CC_STATUS_STORED; } spin_unlock(&fi->lock); VCPU_EVENT(vcpu, 4, "sensed status of cpu %x rc %x", cpu_addr, rc); return rc; } static int __sigp_emergency(struct kvm_vcpu *vcpu, u16 cpu_addr) { struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; struct kvm_s390_local_interrupt *li; struct kvm_s390_interrupt_info *inti; int rc; if (cpu_addr >= KVM_MAX_VCPUS) return SIGP_CC_NOT_OPERATIONAL; inti = kzalloc(sizeof(*inti), GFP_KERNEL); if (!inti) return -ENOMEM; inti->type = KVM_S390_INT_EMERGENCY; inti->emerg.code = vcpu->vcpu_id; spin_lock(&fi->lock); li = fi->local_int[cpu_addr]; if (li == NULL) { rc = SIGP_CC_NOT_OPERATIONAL; kfree(inti); goto unlock; } spin_lock_bh(&li->lock); list_add_tail(&inti->list, &li->list); atomic_set(&li->active, 1); atomic_set_mask(CPUSTAT_EXT_INT, li->cpuflags); if (waitqueue_active(&li->wq)) wake_up_interruptible(&li->wq); spin_unlock_bh(&li->lock); rc = SIGP_CC_ORDER_CODE_ACCEPTED; VCPU_EVENT(vcpu, 4, "sent sigp emerg to cpu %x", cpu_addr); unlock: spin_unlock(&fi->lock); return rc; } static int __sigp_external_call(struct kvm_vcpu *vcpu, u16 cpu_addr) { struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; struct kvm_s390_local_interrupt *li; struct kvm_s390_interrupt_info *inti; int rc; if (cpu_addr >= KVM_MAX_VCPUS) return SIGP_CC_NOT_OPERATIONAL; inti = kzalloc(sizeof(*inti), GFP_KERNEL); if (!inti) return -ENOMEM; inti->type = KVM_S390_INT_EXTERNAL_CALL; inti->extcall.code = vcpu->vcpu_id; spin_lock(&fi->lock); li = fi->local_int[cpu_addr]; if (li == NULL) { rc = SIGP_CC_NOT_OPERATIONAL; kfree(inti); goto unlock; } spin_lock_bh(&li->lock); list_add_tail(&inti->list, &li->list); atomic_set(&li->active, 1); atomic_set_mask(CPUSTAT_EXT_INT, li->cpuflags); if (waitqueue_active(&li->wq)) wake_up_interruptible(&li->wq); spin_unlock_bh(&li->lock); rc = SIGP_CC_ORDER_CODE_ACCEPTED; VCPU_EVENT(vcpu, 4, "sent sigp ext call to cpu %x", cpu_addr); unlock: spin_unlock(&fi->lock); return rc; } static int __inject_sigp_stop(struct kvm_s390_local_interrupt *li, int action) { struct kvm_s390_interrupt_info *inti; inti = kzalloc(sizeof(*inti), GFP_ATOMIC); if (!inti) return -ENOMEM; inti->type = KVM_S390_SIGP_STOP; spin_lock_bh(&li->lock); if ((atomic_read(li->cpuflags) & CPUSTAT_STOPPED)) { kfree(inti); goto out; } list_add_tail(&inti->list, &li->list); atomic_set(&li->active, 1); atomic_set_mask(CPUSTAT_STOP_INT, li->cpuflags); li->action_bits |= action; if (waitqueue_active(&li->wq)) wake_up_interruptible(&li->wq); out: spin_unlock_bh(&li->lock); return SIGP_CC_ORDER_CODE_ACCEPTED; } static int __sigp_stop(struct kvm_vcpu *vcpu, u16 cpu_addr, int action) { struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; struct kvm_s390_local_interrupt *li; int rc; if (cpu_addr >= KVM_MAX_VCPUS) return SIGP_CC_NOT_OPERATIONAL; spin_lock(&fi->lock); li = fi->local_int[cpu_addr]; if (li == NULL) { rc = SIGP_CC_NOT_OPERATIONAL; goto unlock; } rc = __inject_sigp_stop(li, action); unlock: spin_unlock(&fi->lock); VCPU_EVENT(vcpu, 4, "sent sigp stop to cpu %x", cpu_addr); return rc; } int kvm_s390_inject_sigp_stop(struct kvm_vcpu *vcpu, int action) { struct kvm_s390_local_interrupt *li = &vcpu->arch.local_int; return __inject_sigp_stop(li, action); } static int __sigp_set_arch(struct kvm_vcpu *vcpu, u32 parameter) { int rc; switch (parameter & 0xff) { case 0: rc = SIGP_CC_NOT_OPERATIONAL; break; case 1: case 2: rc = SIGP_CC_ORDER_CODE_ACCEPTED; break; default: rc = -EOPNOTSUPP; } return rc; } static int __sigp_set_prefix(struct kvm_vcpu *vcpu, u16 cpu_addr, u32 address, u64 *reg) { struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; struct kvm_s390_local_interrupt *li = NULL; struct kvm_s390_interrupt_info *inti; int rc; u8 tmp; /* make sure that the new value is valid memory */ address = address & 0x7fffe000u; if (copy_from_guest_absolute(vcpu, &tmp, address, 1) || copy_from_guest_absolute(vcpu, &tmp, address + PAGE_SIZE, 1)) { *reg &= 0xffffffff00000000UL; *reg |= SIGP_STATUS_INVALID_PARAMETER; return SIGP_CC_STATUS_STORED; } inti = kzalloc(sizeof(*inti), GFP_KERNEL); if (!inti) return SIGP_CC_BUSY; spin_lock(&fi->lock); if (cpu_addr < KVM_MAX_VCPUS) li = fi->local_int[cpu_addr]; if (li == NULL) { *reg &= 0xffffffff00000000UL; *reg |= SIGP_STATUS_INCORRECT_STATE; rc = SIGP_CC_STATUS_STORED; kfree(inti); goto out_fi; } spin_lock_bh(&li->lock); /* cpu must be in stopped state */ if (!(atomic_read(li->cpuflags) & CPUSTAT_STOPPED)) { *reg &= 0xffffffff00000000UL; *reg |= SIGP_STATUS_INCORRECT_STATE; rc = SIGP_CC_STATUS_STORED; kfree(inti); goto out_li; } inti->type = KVM_S390_SIGP_SET_PREFIX; inti->prefix.address = address; list_add_tail(&inti->list, &li->list); atomic_set(&li->active, 1); if (waitqueue_active(&li->wq)) wake_up_interruptible(&li->wq); rc = SIGP_CC_ORDER_CODE_ACCEPTED; VCPU_EVENT(vcpu, 4, "set prefix of cpu %02x to %x", cpu_addr, address); out_li: spin_unlock_bh(&li->lock); out_fi: spin_unlock(&fi->lock); return rc; } static int __sigp_sense_running(struct kvm_vcpu *vcpu, u16 cpu_addr, u64 *reg) { int rc; struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; if (cpu_addr >= KVM_MAX_VCPUS) return SIGP_CC_NOT_OPERATIONAL; spin_lock(&fi->lock); if (fi->local_int[cpu_addr] == NULL) rc = SIGP_CC_NOT_OPERATIONAL; else { if (atomic_read(fi->local_int[cpu_addr]->cpuflags) & CPUSTAT_RUNNING) { /* running */ rc = SIGP_CC_ORDER_CODE_ACCEPTED; } else { /* not running */ *reg &= 0xffffffff00000000UL; *reg |= SIGP_STATUS_NOT_RUNNING; rc = SIGP_CC_STATUS_STORED; } } spin_unlock(&fi->lock); VCPU_EVENT(vcpu, 4, "sensed running status of cpu %x rc %x", cpu_addr, rc); return rc; } static int __sigp_restart(struct kvm_vcpu *vcpu, u16 cpu_addr) { struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int; struct kvm_s390_local_interrupt *li; int rc = SIGP_CC_ORDER_CODE_ACCEPTED; if (cpu_addr >= KVM_MAX_VCPUS) return SIGP_CC_NOT_OPERATIONAL; spin_lock(&fi->lock); li = fi->local_int[cpu_addr]; if (li == NULL) { rc = SIGP_CC_NOT_OPERATIONAL; goto out; } spin_lock_bh(&li->lock); if (li->action_bits & ACTION_STOP_ON_STOP) rc = SIGP_CC_BUSY; else VCPU_EVENT(vcpu, 4, "sigp restart %x to handle userspace", cpu_addr); spin_unlock_bh(&li->lock); out: spin_unlock(&fi->lock); return rc; } int kvm_s390_handle_sigp(struct kvm_vcpu *vcpu) { int r1 = (vcpu->arch.sie_block->ipa & 0x00f0) >> 4; int r3 = vcpu->arch.sie_block->ipa & 0x000f; u32 parameter; u16 cpu_addr = vcpu->run->s.regs.gprs[r3]; u8 order_code; int rc; /* sigp in userspace can exit */ if (vcpu->arch.sie_block->gpsw.mask & PSW_MASK_PSTATE) return kvm_s390_inject_program_int(vcpu, PGM_PRIVILEGED_OPERATION); order_code = kvm_s390_get_base_disp_rs(vcpu); if (r1 % 2) parameter = vcpu->run->s.regs.gprs[r1]; else parameter = vcpu->run->s.regs.gprs[r1 + 1]; trace_kvm_s390_handle_sigp(vcpu, order_code, cpu_addr, parameter); switch (order_code) { case SIGP_SENSE: vcpu->stat.instruction_sigp_sense++; rc = __sigp_sense(vcpu, cpu_addr, &vcpu->run->s.regs.gprs[r1]); break; case SIGP_EXTERNAL_CALL: vcpu->stat.instruction_sigp_external_call++; rc = __sigp_external_call(vcpu, cpu_addr); break; case SIGP_EMERGENCY_SIGNAL: vcpu->stat.instruction_sigp_emergency++; rc = __sigp_emergency(vcpu, cpu_addr); break; case SIGP_STOP: vcpu->stat.instruction_sigp_stop++; rc = __sigp_stop(vcpu, cpu_addr, ACTION_STOP_ON_STOP); break; case SIGP_STOP_AND_STORE_STATUS: vcpu->stat.instruction_sigp_stop++; rc = __sigp_stop(vcpu, cpu_addr, ACTION_STORE_ON_STOP | ACTION_STOP_ON_STOP); break; case SIGP_SET_ARCHITECTURE: vcpu->stat.instruction_sigp_arch++; rc = __sigp_set_arch(vcpu, parameter); break; case SIGP_SET_PREFIX: vcpu->stat.instruction_sigp_prefix++; rc = __sigp_set_prefix(vcpu, cpu_addr, parameter, &vcpu->run->s.regs.gprs[r1]); break; case SIGP_SENSE_RUNNING: vcpu->stat.instruction_sigp_sense_running++; rc = __sigp_sense_running(vcpu, cpu_addr, &vcpu->run->s.regs.gprs[r1]); break; case SIGP_RESTART: vcpu->stat.instruction_sigp_restart++; rc = __sigp_restart(vcpu, cpu_addr); if (rc == SIGP_CC_BUSY) break; /* user space must know about restart */ default: return -EOPNOTSUPP; } if (rc < 0) return rc; vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44); vcpu->arch.sie_block->gpsw.mask |= (rc & 3ul) << 44; return 0; }
gpl-2.0
libing64/manifold_linux
arch/mips/cavium-octeon/octeon-platform.c
1994
17910
/* * 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) 2004-2011 Cavium Networks * Copyright (C) 2008 Wind River Systems */ #include <linux/init.h> #include <linux/irq.h> #include <linux/i2c.h> #include <linux/usb.h> #include <linux/dma-mapping.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/of_platform.h> #include <linux/of_fdt.h> #include <linux/libfdt.h> #include <asm/octeon/octeon.h> #include <asm/octeon/cvmx-rnm-defs.h> #include <asm/octeon/cvmx-helper.h> #include <asm/octeon/cvmx-helper-board.h> /* Octeon Random Number Generator. */ static int __init octeon_rng_device_init(void) { struct platform_device *pd; int ret = 0; struct resource rng_resources[] = { { .flags = IORESOURCE_MEM, .start = XKPHYS_TO_PHYS(CVMX_RNM_CTL_STATUS), .end = XKPHYS_TO_PHYS(CVMX_RNM_CTL_STATUS) + 0xf }, { .flags = IORESOURCE_MEM, .start = cvmx_build_io_address(8, 0), .end = cvmx_build_io_address(8, 0) + 0x7 } }; pd = platform_device_alloc("octeon_rng", -1); if (!pd) { ret = -ENOMEM; goto out; } ret = platform_device_add_resources(pd, rng_resources, ARRAY_SIZE(rng_resources)); if (ret) goto fail; ret = platform_device_add(pd); if (ret) goto fail; return ret; fail: platform_device_put(pd); out: return ret; } device_initcall(octeon_rng_device_init); #ifdef CONFIG_USB static int __init octeon_ehci_device_init(void) { struct platform_device *pd; int ret = 0; struct resource usb_resources[] = { { .flags = IORESOURCE_MEM, }, { .flags = IORESOURCE_IRQ, } }; /* Only Octeon2 has ehci/ohci */ if (!OCTEON_IS_MODEL(OCTEON_CN63XX)) return 0; if (octeon_is_simulation() || usb_disabled()) return 0; /* No USB in the simulator. */ pd = platform_device_alloc("octeon-ehci", 0); if (!pd) { ret = -ENOMEM; goto out; } usb_resources[0].start = 0x00016F0000000000ULL; usb_resources[0].end = usb_resources[0].start + 0x100; usb_resources[1].start = OCTEON_IRQ_USB0; usb_resources[1].end = OCTEON_IRQ_USB0; ret = platform_device_add_resources(pd, usb_resources, ARRAY_SIZE(usb_resources)); if (ret) goto fail; ret = platform_device_add(pd); if (ret) goto fail; return ret; fail: platform_device_put(pd); out: return ret; } device_initcall(octeon_ehci_device_init); static int __init octeon_ohci_device_init(void) { struct platform_device *pd; int ret = 0; struct resource usb_resources[] = { { .flags = IORESOURCE_MEM, }, { .flags = IORESOURCE_IRQ, } }; /* Only Octeon2 has ehci/ohci */ if (!OCTEON_IS_MODEL(OCTEON_CN63XX)) return 0; if (octeon_is_simulation() || usb_disabled()) return 0; /* No USB in the simulator. */ pd = platform_device_alloc("octeon-ohci", 0); if (!pd) { ret = -ENOMEM; goto out; } usb_resources[0].start = 0x00016F0000000400ULL; usb_resources[0].end = usb_resources[0].start + 0x100; usb_resources[1].start = OCTEON_IRQ_USB0; usb_resources[1].end = OCTEON_IRQ_USB0; ret = platform_device_add_resources(pd, usb_resources, ARRAY_SIZE(usb_resources)); if (ret) goto fail; ret = platform_device_add(pd); if (ret) goto fail; return ret; fail: platform_device_put(pd); out: return ret; } device_initcall(octeon_ohci_device_init); #endif /* CONFIG_USB */ static struct of_device_id __initdata octeon_ids[] = { { .compatible = "simple-bus", }, { .compatible = "cavium,octeon-6335-uctl", }, { .compatible = "cavium,octeon-3860-bootbus", }, { .compatible = "cavium,mdio-mux", }, { .compatible = "gpio-leds", }, {}, }; static bool __init octeon_has_88e1145(void) { return !OCTEON_IS_MODEL(OCTEON_CN52XX) && !OCTEON_IS_MODEL(OCTEON_CN6XXX) && !OCTEON_IS_MODEL(OCTEON_CN56XX); } static void __init octeon_fdt_set_phy(int eth, int phy_addr) { const __be32 *phy_handle; const __be32 *alt_phy_handle; const __be32 *reg; u32 phandle; int phy; int alt_phy; const char *p; int current_len; char new_name[20]; phy_handle = fdt_getprop(initial_boot_params, eth, "phy-handle", NULL); if (!phy_handle) return; phandle = be32_to_cpup(phy_handle); phy = fdt_node_offset_by_phandle(initial_boot_params, phandle); alt_phy_handle = fdt_getprop(initial_boot_params, eth, "cavium,alt-phy-handle", NULL); if (alt_phy_handle) { u32 alt_phandle = be32_to_cpup(alt_phy_handle); alt_phy = fdt_node_offset_by_phandle(initial_boot_params, alt_phandle); } else { alt_phy = -1; } if (phy_addr < 0 || phy < 0) { /* Delete the PHY things */ fdt_nop_property(initial_boot_params, eth, "phy-handle"); /* This one may fail */ fdt_nop_property(initial_boot_params, eth, "cavium,alt-phy-handle"); if (phy >= 0) fdt_nop_node(initial_boot_params, phy); if (alt_phy >= 0) fdt_nop_node(initial_boot_params, alt_phy); return; } if (phy_addr >= 256 && alt_phy > 0) { const struct fdt_property *phy_prop; struct fdt_property *alt_prop; u32 phy_handle_name; /* Use the alt phy node instead.*/ phy_prop = fdt_get_property(initial_boot_params, eth, "phy-handle", NULL); phy_handle_name = phy_prop->nameoff; fdt_nop_node(initial_boot_params, phy); fdt_nop_property(initial_boot_params, eth, "phy-handle"); alt_prop = fdt_get_property_w(initial_boot_params, eth, "cavium,alt-phy-handle", NULL); alt_prop->nameoff = phy_handle_name; phy = alt_phy; } phy_addr &= 0xff; if (octeon_has_88e1145()) { fdt_nop_property(initial_boot_params, phy, "marvell,reg-init"); memset(new_name, 0, sizeof(new_name)); strcpy(new_name, "marvell,88e1145"); p = fdt_getprop(initial_boot_params, phy, "compatible", &current_len); if (p && current_len >= strlen(new_name)) fdt_setprop_inplace(initial_boot_params, phy, "compatible", new_name, current_len); } reg = fdt_getprop(initial_boot_params, phy, "reg", NULL); if (phy_addr == be32_to_cpup(reg)) return; fdt_setprop_inplace_cell(initial_boot_params, phy, "reg", phy_addr); snprintf(new_name, sizeof(new_name), "ethernet-phy@%x", phy_addr); p = fdt_get_name(initial_boot_params, phy, &current_len); if (p && current_len == strlen(new_name)) fdt_set_name(initial_boot_params, phy, new_name); else pr_err("Error: could not rename ethernet phy: <%s>", p); } static void __init octeon_fdt_set_mac_addr(int n, u64 *pmac) { u8 new_mac[6]; u64 mac = *pmac; int r; new_mac[0] = (mac >> 40) & 0xff; new_mac[1] = (mac >> 32) & 0xff; new_mac[2] = (mac >> 24) & 0xff; new_mac[3] = (mac >> 16) & 0xff; new_mac[4] = (mac >> 8) & 0xff; new_mac[5] = mac & 0xff; r = fdt_setprop_inplace(initial_boot_params, n, "local-mac-address", new_mac, sizeof(new_mac)); if (r) { pr_err("Setting \"local-mac-address\" failed %d", r); return; } *pmac = mac + 1; } static void __init octeon_fdt_rm_ethernet(int node) { const __be32 *phy_handle; phy_handle = fdt_getprop(initial_boot_params, node, "phy-handle", NULL); if (phy_handle) { u32 ph = be32_to_cpup(phy_handle); int p = fdt_node_offset_by_phandle(initial_boot_params, ph); if (p >= 0) fdt_nop_node(initial_boot_params, p); } fdt_nop_node(initial_boot_params, node); } static void __init octeon_fdt_pip_port(int iface, int i, int p, int max, u64 *pmac) { char name_buffer[20]; int eth; int phy_addr; int ipd_port; snprintf(name_buffer, sizeof(name_buffer), "ethernet@%x", p); eth = fdt_subnode_offset(initial_boot_params, iface, name_buffer); if (eth < 0) return; if (p > max) { pr_debug("Deleting port %x:%x\n", i, p); octeon_fdt_rm_ethernet(eth); return; } if (OCTEON_IS_MODEL(OCTEON_CN68XX)) ipd_port = (0x100 * i) + (0x10 * p) + 0x800; else ipd_port = 16 * i + p; phy_addr = cvmx_helper_board_get_mii_address(ipd_port); octeon_fdt_set_phy(eth, phy_addr); octeon_fdt_set_mac_addr(eth, pmac); } static void __init octeon_fdt_pip_iface(int pip, int idx, u64 *pmac) { char name_buffer[20]; int iface; int p; int count; count = cvmx_helper_interface_enumerate(idx); snprintf(name_buffer, sizeof(name_buffer), "interface@%d", idx); iface = fdt_subnode_offset(initial_boot_params, pip, name_buffer); if (iface < 0) return; for (p = 0; p < 16; p++) octeon_fdt_pip_port(iface, idx, p, count - 1, pmac); } int __init octeon_prune_device_tree(void) { int i, max_port, uart_mask; const char *pip_path; const char *alias_prop; char name_buffer[20]; int aliases; u64 mac_addr_base; if (fdt_check_header(initial_boot_params)) panic("Corrupt Device Tree."); aliases = fdt_path_offset(initial_boot_params, "/aliases"); if (aliases < 0) { pr_err("Error: No /aliases node in device tree."); return -EINVAL; } mac_addr_base = ((octeon_bootinfo->mac_addr_base[0] & 0xffull)) << 40 | ((octeon_bootinfo->mac_addr_base[1] & 0xffull)) << 32 | ((octeon_bootinfo->mac_addr_base[2] & 0xffull)) << 24 | ((octeon_bootinfo->mac_addr_base[3] & 0xffull)) << 16 | ((octeon_bootinfo->mac_addr_base[4] & 0xffull)) << 8 | (octeon_bootinfo->mac_addr_base[5] & 0xffull); if (OCTEON_IS_MODEL(OCTEON_CN52XX) || OCTEON_IS_MODEL(OCTEON_CN63XX)) max_port = 2; else if (OCTEON_IS_MODEL(OCTEON_CN56XX) || OCTEON_IS_MODEL(OCTEON_CN68XX)) max_port = 1; else max_port = 0; if (octeon_bootinfo->board_type == CVMX_BOARD_TYPE_NIC10E) max_port = 0; for (i = 0; i < 2; i++) { int mgmt; snprintf(name_buffer, sizeof(name_buffer), "mix%d", i); alias_prop = fdt_getprop(initial_boot_params, aliases, name_buffer, NULL); if (alias_prop) { mgmt = fdt_path_offset(initial_boot_params, alias_prop); if (mgmt < 0) continue; if (i >= max_port) { pr_debug("Deleting mix%d\n", i); octeon_fdt_rm_ethernet(mgmt); fdt_nop_property(initial_boot_params, aliases, name_buffer); } else { int phy_addr = cvmx_helper_board_get_mii_address(CVMX_HELPER_BOARD_MGMT_IPD_PORT + i); octeon_fdt_set_phy(mgmt, phy_addr); octeon_fdt_set_mac_addr(mgmt, &mac_addr_base); } } } pip_path = fdt_getprop(initial_boot_params, aliases, "pip", NULL); if (pip_path) { int pip = fdt_path_offset(initial_boot_params, pip_path); if (pip >= 0) for (i = 0; i <= 4; i++) octeon_fdt_pip_iface(pip, i, &mac_addr_base); } /* I2C */ if (OCTEON_IS_MODEL(OCTEON_CN52XX) || OCTEON_IS_MODEL(OCTEON_CN63XX) || OCTEON_IS_MODEL(OCTEON_CN68XX) || OCTEON_IS_MODEL(OCTEON_CN56XX)) max_port = 2; else max_port = 1; for (i = 0; i < 2; i++) { int i2c; snprintf(name_buffer, sizeof(name_buffer), "twsi%d", i); alias_prop = fdt_getprop(initial_boot_params, aliases, name_buffer, NULL); if (alias_prop) { i2c = fdt_path_offset(initial_boot_params, alias_prop); if (i2c < 0) continue; if (i >= max_port) { pr_debug("Deleting twsi%d\n", i); fdt_nop_node(initial_boot_params, i2c); fdt_nop_property(initial_boot_params, aliases, name_buffer); } } } /* SMI/MDIO */ if (OCTEON_IS_MODEL(OCTEON_CN68XX)) max_port = 4; else if (OCTEON_IS_MODEL(OCTEON_CN52XX) || OCTEON_IS_MODEL(OCTEON_CN63XX) || OCTEON_IS_MODEL(OCTEON_CN56XX)) max_port = 2; else max_port = 1; for (i = 0; i < 2; i++) { int i2c; snprintf(name_buffer, sizeof(name_buffer), "smi%d", i); alias_prop = fdt_getprop(initial_boot_params, aliases, name_buffer, NULL); if (alias_prop) { i2c = fdt_path_offset(initial_boot_params, alias_prop); if (i2c < 0) continue; if (i >= max_port) { pr_debug("Deleting smi%d\n", i); fdt_nop_node(initial_boot_params, i2c); fdt_nop_property(initial_boot_params, aliases, name_buffer); } } } /* Serial */ uart_mask = 3; /* Right now CN52XX is the only chip with a third uart */ if (OCTEON_IS_MODEL(OCTEON_CN52XX)) uart_mask |= 4; /* uart2 */ for (i = 0; i < 3; i++) { int uart; snprintf(name_buffer, sizeof(name_buffer), "uart%d", i); alias_prop = fdt_getprop(initial_boot_params, aliases, name_buffer, NULL); if (alias_prop) { uart = fdt_path_offset(initial_boot_params, alias_prop); if (uart_mask & (1 << i)) continue; pr_debug("Deleting uart%d\n", i); fdt_nop_node(initial_boot_params, uart); fdt_nop_property(initial_boot_params, aliases, name_buffer); } } /* Compact Flash */ alias_prop = fdt_getprop(initial_boot_params, aliases, "cf0", NULL); if (alias_prop) { union cvmx_mio_boot_reg_cfgx mio_boot_reg_cfg; unsigned long base_ptr, region_base, region_size; unsigned long region1_base = 0; unsigned long region1_size = 0; int cs, bootbus; bool is_16bit = false; bool is_true_ide = false; __be32 new_reg[6]; __be32 *ranges; int len; int cf = fdt_path_offset(initial_boot_params, alias_prop); base_ptr = 0; if (octeon_bootinfo->major_version == 1 && octeon_bootinfo->minor_version >= 1) { if (octeon_bootinfo->compact_flash_common_base_addr) base_ptr = octeon_bootinfo->compact_flash_common_base_addr; } else { base_ptr = 0x1d000800; } if (!base_ptr) goto no_cf; /* Find CS0 region. */ for (cs = 0; cs < 8; cs++) { mio_boot_reg_cfg.u64 = cvmx_read_csr(CVMX_MIO_BOOT_REG_CFGX(cs)); region_base = mio_boot_reg_cfg.s.base << 16; region_size = (mio_boot_reg_cfg.s.size + 1) << 16; if (mio_boot_reg_cfg.s.en && base_ptr >= region_base && base_ptr < region_base + region_size) { is_16bit = mio_boot_reg_cfg.s.width; break; } } if (cs >= 7) { /* cs and cs + 1 are CS0 and CS1, both must be less than 8. */ goto no_cf; } if (!(base_ptr & 0xfffful)) { /* * Boot loader signals availability of DMA (true_ide * mode) by setting low order bits of base_ptr to * zero. */ /* Asume that CS1 immediately follows. */ mio_boot_reg_cfg.u64 = cvmx_read_csr(CVMX_MIO_BOOT_REG_CFGX(cs + 1)); region1_base = mio_boot_reg_cfg.s.base << 16; region1_size = (mio_boot_reg_cfg.s.size + 1) << 16; if (!mio_boot_reg_cfg.s.en) goto no_cf; is_true_ide = true; } else { fdt_nop_property(initial_boot_params, cf, "cavium,true-ide"); fdt_nop_property(initial_boot_params, cf, "cavium,dma-engine-handle"); if (!is_16bit) { __be32 width = cpu_to_be32(8); fdt_setprop_inplace(initial_boot_params, cf, "cavium,bus-width", &width, sizeof(width)); } } new_reg[0] = cpu_to_be32(cs); new_reg[1] = cpu_to_be32(0); new_reg[2] = cpu_to_be32(0x10000); new_reg[3] = cpu_to_be32(cs + 1); new_reg[4] = cpu_to_be32(0); new_reg[5] = cpu_to_be32(0x10000); fdt_setprop_inplace(initial_boot_params, cf, "reg", new_reg, sizeof(new_reg)); bootbus = fdt_parent_offset(initial_boot_params, cf); if (bootbus < 0) goto no_cf; ranges = fdt_getprop_w(initial_boot_params, bootbus, "ranges", &len); if (!ranges || len < (5 * 8 * sizeof(__be32))) goto no_cf; ranges[(cs * 5) + 2] = cpu_to_be32(region_base >> 32); ranges[(cs * 5) + 3] = cpu_to_be32(region_base & 0xffffffff); ranges[(cs * 5) + 4] = cpu_to_be32(region_size); if (is_true_ide) { cs++; ranges[(cs * 5) + 2] = cpu_to_be32(region1_base >> 32); ranges[(cs * 5) + 3] = cpu_to_be32(region1_base & 0xffffffff); ranges[(cs * 5) + 4] = cpu_to_be32(region1_size); } goto end_cf; no_cf: fdt_nop_node(initial_boot_params, cf); end_cf: ; } /* 8 char LED */ alias_prop = fdt_getprop(initial_boot_params, aliases, "led0", NULL); if (alias_prop) { union cvmx_mio_boot_reg_cfgx mio_boot_reg_cfg; unsigned long base_ptr, region_base, region_size; int cs, bootbus; __be32 new_reg[6]; __be32 *ranges; int len; int led = fdt_path_offset(initial_boot_params, alias_prop); base_ptr = octeon_bootinfo->led_display_base_addr; if (base_ptr == 0) goto no_led; /* Find CS0 region. */ for (cs = 0; cs < 8; cs++) { mio_boot_reg_cfg.u64 = cvmx_read_csr(CVMX_MIO_BOOT_REG_CFGX(cs)); region_base = mio_boot_reg_cfg.s.base << 16; region_size = (mio_boot_reg_cfg.s.size + 1) << 16; if (mio_boot_reg_cfg.s.en && base_ptr >= region_base && base_ptr < region_base + region_size) break; } if (cs > 7) goto no_led; new_reg[0] = cpu_to_be32(cs); new_reg[1] = cpu_to_be32(0x20); new_reg[2] = cpu_to_be32(0x20); new_reg[3] = cpu_to_be32(cs); new_reg[4] = cpu_to_be32(0); new_reg[5] = cpu_to_be32(0x20); fdt_setprop_inplace(initial_boot_params, led, "reg", new_reg, sizeof(new_reg)); bootbus = fdt_parent_offset(initial_boot_params, led); if (bootbus < 0) goto no_led; ranges = fdt_getprop_w(initial_boot_params, bootbus, "ranges", &len); if (!ranges || len < (5 * 8 * sizeof(__be32))) goto no_led; ranges[(cs * 5) + 2] = cpu_to_be32(region_base >> 32); ranges[(cs * 5) + 3] = cpu_to_be32(region_base & 0xffffffff); ranges[(cs * 5) + 4] = cpu_to_be32(region_size); goto end_led; no_led: fdt_nop_node(initial_boot_params, led); end_led: ; } /* OHCI/UHCI USB */ alias_prop = fdt_getprop(initial_boot_params, aliases, "uctl", NULL); if (alias_prop) { int uctl = fdt_path_offset(initial_boot_params, alias_prop); if (uctl >= 0 && (!OCTEON_IS_MODEL(OCTEON_CN6XXX) || octeon_bootinfo->board_type == CVMX_BOARD_TYPE_NIC2E)) { pr_debug("Deleting uctl\n"); fdt_nop_node(initial_boot_params, uctl); fdt_nop_property(initial_boot_params, aliases, "uctl"); } else if (octeon_bootinfo->board_type == CVMX_BOARD_TYPE_NIC10E || octeon_bootinfo->board_type == CVMX_BOARD_TYPE_NIC4E) { /* Missing "refclk-type" defaults to crystal. */ fdt_nop_property(initial_boot_params, uctl, "refclk-type"); } } return 0; } static int __init octeon_publish_devices(void) { return of_platform_bus_probe(NULL, octeon_ids, NULL); } device_initcall(octeon_publish_devices); MODULE_AUTHOR("David Daney <ddaney@caviumnetworks.com>"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Platform driver for Octeon SOC");
gpl-2.0
googyanas/GoogyMax-N5
drivers/regulator/max8997.c
2250
33336
/* * max8997.c - Regulator driver for the Maxim 8997/8966 * * Copyright (C) 2011 Samsung Electronics * MyungJoo Ham <myungjoo.ham@smasung.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 * * This driver is based on max8998.c */ #include <linux/bug.h> #include <linux/err.h> #include <linux/gpio.h> #include <linux/of_gpio.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/regulator/machine.h> #include <linux/mfd/max8997.h> #include <linux/mfd/max8997-private.h> #include <linux/regulator/of_regulator.h> struct max8997_data { struct device *dev; struct max8997_dev *iodev; int num_regulators; struct regulator_dev **rdev; int ramp_delay; /* in mV/us */ bool buck1_gpiodvs; bool buck2_gpiodvs; bool buck5_gpiodvs; u8 buck1_vol[8]; u8 buck2_vol[8]; u8 buck5_vol[8]; int buck125_gpios[3]; int buck125_gpioindex; bool ignore_gpiodvs_side_effect; u8 saved_states[MAX8997_REG_MAX]; }; static const unsigned int safeoutvolt[] = { 4850000, 4900000, 4950000, 3300000, }; static inline void max8997_set_gpio(struct max8997_data *max8997) { int set3 = (max8997->buck125_gpioindex) & 0x1; int set2 = ((max8997->buck125_gpioindex) >> 1) & 0x1; int set1 = ((max8997->buck125_gpioindex) >> 2) & 0x1; gpio_set_value(max8997->buck125_gpios[0], set1); gpio_set_value(max8997->buck125_gpios[1], set2); gpio_set_value(max8997->buck125_gpios[2], set3); } struct voltage_map_desc { int min; int max; int step; }; /* Voltage maps in uV */ static const struct voltage_map_desc ldo_voltage_map_desc = { .min = 800000, .max = 3950000, .step = 50000, }; /* LDO1 ~ 18, 21 all */ static const struct voltage_map_desc buck1245_voltage_map_desc = { .min = 650000, .max = 2225000, .step = 25000, }; /* Buck1, 2, 4, 5 */ static const struct voltage_map_desc buck37_voltage_map_desc = { .min = 750000, .max = 3900000, .step = 50000, }; /* Buck3, 7 */ /* current map in uA */ static const struct voltage_map_desc charger_current_map_desc = { .min = 200000, .max = 950000, .step = 50000, }; static const struct voltage_map_desc topoff_current_map_desc = { .min = 50000, .max = 200000, .step = 10000, }; static const struct voltage_map_desc *reg_voltage_map[] = { [MAX8997_LDO1] = &ldo_voltage_map_desc, [MAX8997_LDO2] = &ldo_voltage_map_desc, [MAX8997_LDO3] = &ldo_voltage_map_desc, [MAX8997_LDO4] = &ldo_voltage_map_desc, [MAX8997_LDO5] = &ldo_voltage_map_desc, [MAX8997_LDO6] = &ldo_voltage_map_desc, [MAX8997_LDO7] = &ldo_voltage_map_desc, [MAX8997_LDO8] = &ldo_voltage_map_desc, [MAX8997_LDO9] = &ldo_voltage_map_desc, [MAX8997_LDO10] = &ldo_voltage_map_desc, [MAX8997_LDO11] = &ldo_voltage_map_desc, [MAX8997_LDO12] = &ldo_voltage_map_desc, [MAX8997_LDO13] = &ldo_voltage_map_desc, [MAX8997_LDO14] = &ldo_voltage_map_desc, [MAX8997_LDO15] = &ldo_voltage_map_desc, [MAX8997_LDO16] = &ldo_voltage_map_desc, [MAX8997_LDO17] = &ldo_voltage_map_desc, [MAX8997_LDO18] = &ldo_voltage_map_desc, [MAX8997_LDO21] = &ldo_voltage_map_desc, [MAX8997_BUCK1] = &buck1245_voltage_map_desc, [MAX8997_BUCK2] = &buck1245_voltage_map_desc, [MAX8997_BUCK3] = &buck37_voltage_map_desc, [MAX8997_BUCK4] = &buck1245_voltage_map_desc, [MAX8997_BUCK5] = &buck1245_voltage_map_desc, [MAX8997_BUCK6] = NULL, [MAX8997_BUCK7] = &buck37_voltage_map_desc, [MAX8997_EN32KHZ_AP] = NULL, [MAX8997_EN32KHZ_CP] = NULL, [MAX8997_ENVICHG] = NULL, [MAX8997_ESAFEOUT1] = NULL, [MAX8997_ESAFEOUT2] = NULL, [MAX8997_CHARGER_CV] = NULL, [MAX8997_CHARGER] = &charger_current_map_desc, [MAX8997_CHARGER_TOPOFF] = &topoff_current_map_desc, }; static int max8997_list_voltage_charger_cv(struct regulator_dev *rdev, unsigned int selector) { int rid = rdev_get_id(rdev); if (rid != MAX8997_CHARGER_CV) goto err; switch (selector) { case 0x00: return 4200000; case 0x01 ... 0x0E: return 4000000 + 20000 * (selector - 0x01); case 0x0F: return 4350000; default: return -EINVAL; } err: return -EINVAL; } static int max8997_list_voltage(struct regulator_dev *rdev, unsigned int selector) { const struct voltage_map_desc *desc; int rid = rdev_get_id(rdev); int val; if (rid >= ARRAY_SIZE(reg_voltage_map) || rid < 0) return -EINVAL; desc = reg_voltage_map[rid]; if (desc == NULL) return -EINVAL; val = desc->min + desc->step * selector; if (val > desc->max) return -EINVAL; return val; } static int max8997_get_enable_register(struct regulator_dev *rdev, int *reg, int *mask, int *pattern) { int rid = rdev_get_id(rdev); switch (rid) { case MAX8997_LDO1 ... MAX8997_LDO21: *reg = MAX8997_REG_LDO1CTRL + (rid - MAX8997_LDO1); *mask = 0xC0; *pattern = 0xC0; break; case MAX8997_BUCK1: *reg = MAX8997_REG_BUCK1CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_BUCK2: *reg = MAX8997_REG_BUCK2CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_BUCK3: *reg = MAX8997_REG_BUCK3CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_BUCK4: *reg = MAX8997_REG_BUCK4CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_BUCK5: *reg = MAX8997_REG_BUCK5CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_BUCK6: *reg = MAX8997_REG_BUCK6CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_BUCK7: *reg = MAX8997_REG_BUCK7CTRL; *mask = 0x01; *pattern = 0x01; break; case MAX8997_EN32KHZ_AP ... MAX8997_EN32KHZ_CP: *reg = MAX8997_REG_MAINCON1; *mask = 0x01 << (rid - MAX8997_EN32KHZ_AP); *pattern = 0x01 << (rid - MAX8997_EN32KHZ_AP); break; case MAX8997_ENVICHG: *reg = MAX8997_REG_MBCCTRL1; *mask = 0x80; *pattern = 0x80; break; case MAX8997_ESAFEOUT1 ... MAX8997_ESAFEOUT2: *reg = MAX8997_REG_SAFEOUTCTRL; *mask = 0x40 << (rid - MAX8997_ESAFEOUT1); *pattern = 0x40 << (rid - MAX8997_ESAFEOUT1); break; case MAX8997_CHARGER: *reg = MAX8997_REG_MBCCTRL2; *mask = 0x40; *pattern = 0x40; break; default: /* Not controllable or not exists */ return -EINVAL; } return 0; } static int max8997_reg_is_enabled(struct regulator_dev *rdev) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int ret, reg, mask, pattern; u8 val; ret = max8997_get_enable_register(rdev, &reg, &mask, &pattern); if (ret) return ret; ret = max8997_read_reg(i2c, reg, &val); if (ret) return ret; return (val & mask) == pattern; } static int max8997_reg_enable(struct regulator_dev *rdev) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int ret, reg, mask, pattern; ret = max8997_get_enable_register(rdev, &reg, &mask, &pattern); if (ret) return ret; return max8997_update_reg(i2c, reg, pattern, mask); } static int max8997_reg_disable(struct regulator_dev *rdev) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int ret, reg, mask, pattern; ret = max8997_get_enable_register(rdev, &reg, &mask, &pattern); if (ret) return ret; return max8997_update_reg(i2c, reg, ~pattern, mask); } static int max8997_get_voltage_register(struct regulator_dev *rdev, int *_reg, int *_shift, int *_mask) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); int rid = rdev_get_id(rdev); int reg, shift = 0, mask = 0x3f; switch (rid) { case MAX8997_LDO1 ... MAX8997_LDO21: reg = MAX8997_REG_LDO1CTRL + (rid - MAX8997_LDO1); break; case MAX8997_BUCK1: reg = MAX8997_REG_BUCK1DVS1; if (max8997->buck1_gpiodvs) reg += max8997->buck125_gpioindex; break; case MAX8997_BUCK2: reg = MAX8997_REG_BUCK2DVS1; if (max8997->buck2_gpiodvs) reg += max8997->buck125_gpioindex; break; case MAX8997_BUCK3: reg = MAX8997_REG_BUCK3DVS; break; case MAX8997_BUCK4: reg = MAX8997_REG_BUCK4DVS; break; case MAX8997_BUCK5: reg = MAX8997_REG_BUCK5DVS1; if (max8997->buck5_gpiodvs) reg += max8997->buck125_gpioindex; break; case MAX8997_BUCK7: reg = MAX8997_REG_BUCK7DVS; break; case MAX8997_ESAFEOUT1 ... MAX8997_ESAFEOUT2: reg = MAX8997_REG_SAFEOUTCTRL; shift = (rid == MAX8997_ESAFEOUT2) ? 2 : 0; mask = 0x3; break; case MAX8997_CHARGER_CV: reg = MAX8997_REG_MBCCTRL3; shift = 0; mask = 0xf; break; case MAX8997_CHARGER: reg = MAX8997_REG_MBCCTRL4; shift = 0; mask = 0xf; break; case MAX8997_CHARGER_TOPOFF: reg = MAX8997_REG_MBCCTRL5; shift = 0; mask = 0xf; break; default: return -EINVAL; } *_reg = reg; *_shift = shift; *_mask = mask; return 0; } static int max8997_get_voltage_sel(struct regulator_dev *rdev) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int reg, shift, mask, ret; u8 val; ret = max8997_get_voltage_register(rdev, &reg, &shift, &mask); if (ret) return ret; ret = max8997_read_reg(i2c, reg, &val); if (ret) return ret; val >>= shift; val &= mask; return val; } static inline int max8997_get_voltage_proper_val( const struct voltage_map_desc *desc, int min_vol, int max_vol) { int i; if (desc == NULL) return -EINVAL; if (max_vol < desc->min || min_vol > desc->max) return -EINVAL; if (min_vol < desc->min) min_vol = desc->min; i = DIV_ROUND_UP(min_vol - desc->min, desc->step); if (desc->min + desc->step * i > max_vol) return -EINVAL; return i; } static int max8997_set_voltage_charger_cv(struct regulator_dev *rdev, int min_uV, int max_uV, unsigned *selector) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int rid = rdev_get_id(rdev); int lb, ub; int reg, shift = 0, mask, ret = 0; u8 val = 0x0; if (rid != MAX8997_CHARGER_CV) return -EINVAL; ret = max8997_get_voltage_register(rdev, &reg, &shift, &mask); if (ret) return ret; if (max_uV < 4000000 || min_uV > 4350000) return -EINVAL; if (min_uV <= 4000000) { if (max_uV >= 4000000) return -EINVAL; else val = 0x1; } else if (min_uV <= 4200000 && max_uV >= 4200000) val = 0x0; else { lb = (min_uV - 4000001) / 20000 + 2; ub = (max_uV - 4000000) / 20000 + 1; if (lb > ub) return -EINVAL; if (lb < 0xf) val = lb; else { if (ub >= 0xf) val = 0xf; else return -EINVAL; } } *selector = val; ret = max8997_update_reg(i2c, reg, val << shift, mask); return ret; } /* * For LDO1 ~ LDO21, BUCK1~5, BUCK7, CHARGER, CHARGER_TOPOFF * BUCK1, 2, and 5 are available if they are not controlled by gpio */ static int max8997_set_voltage_ldobuck(struct regulator_dev *rdev, int min_uV, int max_uV, unsigned *selector) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; const struct voltage_map_desc *desc; int rid = rdev_get_id(rdev); int i, reg, shift, mask, ret; switch (rid) { case MAX8997_LDO1 ... MAX8997_LDO21: break; case MAX8997_BUCK1 ... MAX8997_BUCK5: break; case MAX8997_BUCK6: return -EINVAL; case MAX8997_BUCK7: break; case MAX8997_CHARGER: break; case MAX8997_CHARGER_TOPOFF: break; default: return -EINVAL; } desc = reg_voltage_map[rid]; i = max8997_get_voltage_proper_val(desc, min_uV, max_uV); if (i < 0) return i; ret = max8997_get_voltage_register(rdev, &reg, &shift, &mask); if (ret) return ret; ret = max8997_update_reg(i2c, reg, i << shift, mask << shift); *selector = i; return ret; } static int max8997_set_voltage_buck_time_sel(struct regulator_dev *rdev, unsigned int old_selector, unsigned int new_selector) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); int rid = rdev_get_id(rdev); const struct voltage_map_desc *desc = reg_voltage_map[rid]; /* Delay is required only if the voltage is increasing */ if (old_selector >= new_selector) return 0; /* No need to delay if gpio_dvs_mode */ switch (rid) { case MAX8997_BUCK1: if (max8997->buck1_gpiodvs) return 0; break; case MAX8997_BUCK2: if (max8997->buck2_gpiodvs) return 0; break; case MAX8997_BUCK5: if (max8997->buck5_gpiodvs) return 0; break; } switch (rid) { case MAX8997_BUCK1: case MAX8997_BUCK2: case MAX8997_BUCK4: case MAX8997_BUCK5: return DIV_ROUND_UP(desc->step * (new_selector - old_selector), max8997->ramp_delay * 1000); } return 0; } /* * Assess the damage on the voltage setting of BUCK1,2,5 by the change. * * When GPIO-DVS mode is used for multiple bucks, changing the voltage value * of one of the bucks may affect that of another buck, which is the side * effect of the change (set_voltage). This function examines the GPIO-DVS * configurations and checks whether such side-effect exists. */ static int max8997_assess_side_effect(struct regulator_dev *rdev, u8 new_val, int *best) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); int rid = rdev_get_id(rdev); u8 *buckx_val[3]; bool buckx_gpiodvs[3]; int side_effect[8]; int min_side_effect = INT_MAX; int i; *best = -1; switch (rid) { case MAX8997_BUCK1: rid = 0; break; case MAX8997_BUCK2: rid = 1; break; case MAX8997_BUCK5: rid = 2; break; default: return -EINVAL; } buckx_val[0] = max8997->buck1_vol; buckx_val[1] = max8997->buck2_vol; buckx_val[2] = max8997->buck5_vol; buckx_gpiodvs[0] = max8997->buck1_gpiodvs; buckx_gpiodvs[1] = max8997->buck2_gpiodvs; buckx_gpiodvs[2] = max8997->buck5_gpiodvs; for (i = 0; i < 8; i++) { int others; if (new_val != (buckx_val[rid])[i]) { side_effect[i] = -1; continue; } side_effect[i] = 0; for (others = 0; others < 3; others++) { int diff; if (others == rid) continue; if (buckx_gpiodvs[others] == false) continue; /* Not affected */ diff = (buckx_val[others])[i] - (buckx_val[others])[max8997->buck125_gpioindex]; if (diff > 0) side_effect[i] += diff; else if (diff < 0) side_effect[i] -= diff; } if (side_effect[i] == 0) { *best = i; return 0; /* NO SIDE EFFECT! Use This! */ } if (side_effect[i] < min_side_effect) { min_side_effect = side_effect[i]; *best = i; } } if (*best == -1) return -EINVAL; return side_effect[*best]; } /* * For Buck 1 ~ 5 and 7. If it is not controlled by GPIO, this calls * max8997_set_voltage_ldobuck to do the job. */ static int max8997_set_voltage_buck(struct regulator_dev *rdev, int min_uV, int max_uV, unsigned *selector) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); int rid = rdev_get_id(rdev); const struct voltage_map_desc *desc; int new_val, new_idx, damage, tmp_val, tmp_idx, tmp_dmg; bool gpio_dvs_mode = false; if (rid < MAX8997_BUCK1 || rid > MAX8997_BUCK7) return -EINVAL; switch (rid) { case MAX8997_BUCK1: if (max8997->buck1_gpiodvs) gpio_dvs_mode = true; break; case MAX8997_BUCK2: if (max8997->buck2_gpiodvs) gpio_dvs_mode = true; break; case MAX8997_BUCK5: if (max8997->buck5_gpiodvs) gpio_dvs_mode = true; break; } if (!gpio_dvs_mode) return max8997_set_voltage_ldobuck(rdev, min_uV, max_uV, selector); desc = reg_voltage_map[rid]; new_val = max8997_get_voltage_proper_val(desc, min_uV, max_uV); if (new_val < 0) return new_val; tmp_dmg = INT_MAX; tmp_idx = -1; tmp_val = -1; do { damage = max8997_assess_side_effect(rdev, new_val, &new_idx); if (damage == 0) goto out; if (tmp_dmg > damage) { tmp_idx = new_idx; tmp_val = new_val; tmp_dmg = damage; } new_val++; } while (desc->min + desc->step * new_val <= desc->max); new_idx = tmp_idx; new_val = tmp_val; if (max8997->ignore_gpiodvs_side_effect == false) return -EINVAL; dev_warn(&rdev->dev, "MAX8997 GPIO-DVS Side Effect Warning: GPIO SET:" " %d -> %d\n", max8997->buck125_gpioindex, tmp_idx); out: if (new_idx < 0 || new_val < 0) return -EINVAL; max8997->buck125_gpioindex = new_idx; max8997_set_gpio(max8997); *selector = new_val; return 0; } /* For SAFEOUT1 and SAFEOUT2 */ static int max8997_set_voltage_safeout_sel(struct regulator_dev *rdev, unsigned selector) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int rid = rdev_get_id(rdev); int reg, shift = 0, mask, ret; if (rid != MAX8997_ESAFEOUT1 && rid != MAX8997_ESAFEOUT2) return -EINVAL; ret = max8997_get_voltage_register(rdev, &reg, &shift, &mask); if (ret) return ret; return max8997_update_reg(i2c, reg, selector << shift, mask << shift); } static int max8997_reg_disable_suspend(struct regulator_dev *rdev) { struct max8997_data *max8997 = rdev_get_drvdata(rdev); struct i2c_client *i2c = max8997->iodev->i2c; int ret, reg, mask, pattern; int rid = rdev_get_id(rdev); ret = max8997_get_enable_register(rdev, &reg, &mask, &pattern); if (ret) return ret; max8997_read_reg(i2c, reg, &max8997->saved_states[rid]); if (rid == MAX8997_LDO1 || rid == MAX8997_LDO10 || rid == MAX8997_LDO21) { dev_dbg(&rdev->dev, "Conditional Power-Off for %s\n", rdev->desc->name); return max8997_update_reg(i2c, reg, 0x40, mask); } dev_dbg(&rdev->dev, "Full Power-Off for %s (%xh -> %xh)\n", rdev->desc->name, max8997->saved_states[rid] & mask, (~pattern) & mask); return max8997_update_reg(i2c, reg, ~pattern, mask); } static struct regulator_ops max8997_ldo_ops = { .list_voltage = max8997_list_voltage, .is_enabled = max8997_reg_is_enabled, .enable = max8997_reg_enable, .disable = max8997_reg_disable, .get_voltage_sel = max8997_get_voltage_sel, .set_voltage = max8997_set_voltage_ldobuck, .set_suspend_disable = max8997_reg_disable_suspend, }; static struct regulator_ops max8997_buck_ops = { .list_voltage = max8997_list_voltage, .is_enabled = max8997_reg_is_enabled, .enable = max8997_reg_enable, .disable = max8997_reg_disable, .get_voltage_sel = max8997_get_voltage_sel, .set_voltage = max8997_set_voltage_buck, .set_voltage_time_sel = max8997_set_voltage_buck_time_sel, .set_suspend_disable = max8997_reg_disable_suspend, }; static struct regulator_ops max8997_fixedvolt_ops = { .list_voltage = max8997_list_voltage, .is_enabled = max8997_reg_is_enabled, .enable = max8997_reg_enable, .disable = max8997_reg_disable, .set_suspend_disable = max8997_reg_disable_suspend, }; static struct regulator_ops max8997_safeout_ops = { .list_voltage = regulator_list_voltage_table, .is_enabled = max8997_reg_is_enabled, .enable = max8997_reg_enable, .disable = max8997_reg_disable, .get_voltage_sel = max8997_get_voltage_sel, .set_voltage_sel = max8997_set_voltage_safeout_sel, .set_suspend_disable = max8997_reg_disable_suspend, }; static struct regulator_ops max8997_fixedstate_ops = { .list_voltage = max8997_list_voltage_charger_cv, .get_voltage_sel = max8997_get_voltage_sel, .set_voltage = max8997_set_voltage_charger_cv, }; static int max8997_set_current_limit(struct regulator_dev *rdev, int min_uA, int max_uA) { unsigned dummy; int rid = rdev_get_id(rdev); if (rid != MAX8997_CHARGER && rid != MAX8997_CHARGER_TOPOFF) return -EINVAL; /* Reuse max8997_set_voltage_ldobuck to set current_limit. */ return max8997_set_voltage_ldobuck(rdev, min_uA, max_uA, &dummy); } static int max8997_get_current_limit(struct regulator_dev *rdev) { int sel, rid = rdev_get_id(rdev); if (rid != MAX8997_CHARGER && rid != MAX8997_CHARGER_TOPOFF) return -EINVAL; sel = max8997_get_voltage_sel(rdev); if (sel < 0) return sel; /* Reuse max8997_list_voltage to get current_limit. */ return max8997_list_voltage(rdev, sel); } static struct regulator_ops max8997_charger_ops = { .is_enabled = max8997_reg_is_enabled, .enable = max8997_reg_enable, .disable = max8997_reg_disable, .get_current_limit = max8997_get_current_limit, .set_current_limit = max8997_set_current_limit, }; static struct regulator_ops max8997_charger_fixedstate_ops = { .get_current_limit = max8997_get_current_limit, .set_current_limit = max8997_set_current_limit, }; #define MAX8997_VOLTAGE_REGULATOR(_name, _ops) {\ .name = #_name, \ .id = MAX8997_##_name, \ .ops = &_ops, \ .type = REGULATOR_VOLTAGE, \ .owner = THIS_MODULE, \ } #define MAX8997_CURRENT_REGULATOR(_name, _ops) {\ .name = #_name, \ .id = MAX8997_##_name, \ .ops = &_ops, \ .type = REGULATOR_CURRENT, \ .owner = THIS_MODULE, \ } static struct regulator_desc regulators[] = { MAX8997_VOLTAGE_REGULATOR(LDO1, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO2, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO3, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO4, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO5, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO6, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO7, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO8, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO9, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO10, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO11, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO12, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO13, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO14, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO15, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO16, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO17, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO18, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(LDO21, max8997_ldo_ops), MAX8997_VOLTAGE_REGULATOR(BUCK1, max8997_buck_ops), MAX8997_VOLTAGE_REGULATOR(BUCK2, max8997_buck_ops), MAX8997_VOLTAGE_REGULATOR(BUCK3, max8997_buck_ops), MAX8997_VOLTAGE_REGULATOR(BUCK4, max8997_buck_ops), MAX8997_VOLTAGE_REGULATOR(BUCK5, max8997_buck_ops), MAX8997_VOLTAGE_REGULATOR(BUCK6, max8997_fixedvolt_ops), MAX8997_VOLTAGE_REGULATOR(BUCK7, max8997_buck_ops), MAX8997_VOLTAGE_REGULATOR(EN32KHZ_AP, max8997_fixedvolt_ops), MAX8997_VOLTAGE_REGULATOR(EN32KHZ_CP, max8997_fixedvolt_ops), MAX8997_VOLTAGE_REGULATOR(ENVICHG, max8997_fixedvolt_ops), MAX8997_VOLTAGE_REGULATOR(ESAFEOUT1, max8997_safeout_ops), MAX8997_VOLTAGE_REGULATOR(ESAFEOUT2, max8997_safeout_ops), MAX8997_VOLTAGE_REGULATOR(CHARGER_CV, max8997_fixedstate_ops), MAX8997_CURRENT_REGULATOR(CHARGER, max8997_charger_ops), MAX8997_CURRENT_REGULATOR(CHARGER_TOPOFF, max8997_charger_fixedstate_ops), }; #ifdef CONFIG_OF static int max8997_pmic_dt_parse_dvs_gpio(struct platform_device *pdev, struct max8997_platform_data *pdata, struct device_node *pmic_np) { int i, gpio; for (i = 0; i < 3; i++) { gpio = of_get_named_gpio(pmic_np, "max8997,pmic-buck125-dvs-gpios", i); if (!gpio_is_valid(gpio)) { dev_err(&pdev->dev, "invalid gpio[%d]: %d\n", i, gpio); return -EINVAL; } pdata->buck125_gpios[i] = gpio; } return 0; } static int max8997_pmic_dt_parse_pdata(struct platform_device *pdev, struct max8997_platform_data *pdata) { struct max8997_dev *iodev = dev_get_drvdata(pdev->dev.parent); struct device_node *pmic_np, *regulators_np, *reg_np; struct max8997_regulator_data *rdata; unsigned int i, dvs_voltage_nr = 1, ret; pmic_np = of_node_get(iodev->dev->of_node); if (!pmic_np) { dev_err(&pdev->dev, "could not find pmic sub-node\n"); return -ENODEV; } regulators_np = of_find_node_by_name(pmic_np, "regulators"); if (!regulators_np) { dev_err(&pdev->dev, "could not find regulators sub-node\n"); return -EINVAL; } /* count the number of regulators to be supported in pmic */ pdata->num_regulators = of_get_child_count(regulators_np); rdata = devm_kzalloc(&pdev->dev, sizeof(*rdata) * pdata->num_regulators, GFP_KERNEL); if (!rdata) { of_node_put(regulators_np); dev_err(&pdev->dev, "could not allocate memory for regulator data\n"); return -ENOMEM; } pdata->regulators = rdata; for_each_child_of_node(regulators_np, reg_np) { for (i = 0; i < ARRAY_SIZE(regulators); i++) if (!of_node_cmp(reg_np->name, regulators[i].name)) break; if (i == ARRAY_SIZE(regulators)) { dev_warn(&pdev->dev, "don't know how to configure regulator %s\n", reg_np->name); continue; } rdata->id = i; rdata->initdata = of_get_regulator_init_data(&pdev->dev, reg_np); rdata->reg_node = reg_np; rdata++; } of_node_put(regulators_np); if (of_get_property(pmic_np, "max8997,pmic-buck1-uses-gpio-dvs", NULL)) pdata->buck1_gpiodvs = true; if (of_get_property(pmic_np, "max8997,pmic-buck2-uses-gpio-dvs", NULL)) pdata->buck2_gpiodvs = true; if (of_get_property(pmic_np, "max8997,pmic-buck5-uses-gpio-dvs", NULL)) pdata->buck5_gpiodvs = true; if (pdata->buck1_gpiodvs || pdata->buck2_gpiodvs || pdata->buck5_gpiodvs) { ret = max8997_pmic_dt_parse_dvs_gpio(pdev, pdata, pmic_np); if (ret) return -EINVAL; if (of_property_read_u32(pmic_np, "max8997,pmic-buck125-default-dvs-idx", &pdata->buck125_default_idx)) { pdata->buck125_default_idx = 0; } else { if (pdata->buck125_default_idx >= 8) { pdata->buck125_default_idx = 0; dev_info(&pdev->dev, "invalid value for default dvs index, using 0 instead\n"); } } if (of_get_property(pmic_np, "max8997,pmic-ignore-gpiodvs-side-effect", NULL)) pdata->ignore_gpiodvs_side_effect = true; dvs_voltage_nr = 8; } if (of_property_read_u32_array(pmic_np, "max8997,pmic-buck1-dvs-voltage", pdata->buck1_voltage, dvs_voltage_nr)) { dev_err(&pdev->dev, "buck1 voltages not specified\n"); return -EINVAL; } if (of_property_read_u32_array(pmic_np, "max8997,pmic-buck2-dvs-voltage", pdata->buck2_voltage, dvs_voltage_nr)) { dev_err(&pdev->dev, "buck2 voltages not specified\n"); return -EINVAL; } if (of_property_read_u32_array(pmic_np, "max8997,pmic-buck5-dvs-voltage", pdata->buck5_voltage, dvs_voltage_nr)) { dev_err(&pdev->dev, "buck5 voltages not specified\n"); return -EINVAL; } return 0; } #else static int max8997_pmic_dt_parse_pdata(struct platform_device *pdev, struct max8997_platform_data *pdata) { return 0; } #endif /* CONFIG_OF */ static int max8997_pmic_probe(struct platform_device *pdev) { struct max8997_dev *iodev = dev_get_drvdata(pdev->dev.parent); struct max8997_platform_data *pdata = iodev->pdata; struct regulator_config config = { }; struct regulator_dev **rdev; struct max8997_data *max8997; struct i2c_client *i2c; int i, ret, size, nr_dvs; u8 max_buck1 = 0, max_buck2 = 0, max_buck5 = 0; if (!pdata) { dev_err(&pdev->dev, "No platform init data supplied.\n"); return -ENODEV; } if (iodev->dev->of_node) { ret = max8997_pmic_dt_parse_pdata(pdev, pdata); if (ret) return ret; } max8997 = devm_kzalloc(&pdev->dev, sizeof(struct max8997_data), GFP_KERNEL); if (!max8997) return -ENOMEM; size = sizeof(struct regulator_dev *) * pdata->num_regulators; max8997->rdev = devm_kzalloc(&pdev->dev, size, GFP_KERNEL); if (!max8997->rdev) return -ENOMEM; rdev = max8997->rdev; max8997->dev = &pdev->dev; max8997->iodev = iodev; max8997->num_regulators = pdata->num_regulators; platform_set_drvdata(pdev, max8997); i2c = max8997->iodev->i2c; max8997->buck125_gpioindex = pdata->buck125_default_idx; max8997->buck1_gpiodvs = pdata->buck1_gpiodvs; max8997->buck2_gpiodvs = pdata->buck2_gpiodvs; max8997->buck5_gpiodvs = pdata->buck5_gpiodvs; memcpy(max8997->buck125_gpios, pdata->buck125_gpios, sizeof(int) * 3); max8997->ignore_gpiodvs_side_effect = pdata->ignore_gpiodvs_side_effect; nr_dvs = (pdata->buck1_gpiodvs || pdata->buck2_gpiodvs || pdata->buck5_gpiodvs) ? 8 : 1; for (i = 0; i < nr_dvs; i++) { max8997->buck1_vol[i] = ret = max8997_get_voltage_proper_val( &buck1245_voltage_map_desc, pdata->buck1_voltage[i], pdata->buck1_voltage[i] + buck1245_voltage_map_desc.step); if (ret < 0) goto err_out; max8997->buck2_vol[i] = ret = max8997_get_voltage_proper_val( &buck1245_voltage_map_desc, pdata->buck2_voltage[i], pdata->buck2_voltage[i] + buck1245_voltage_map_desc.step); if (ret < 0) goto err_out; max8997->buck5_vol[i] = ret = max8997_get_voltage_proper_val( &buck1245_voltage_map_desc, pdata->buck5_voltage[i], pdata->buck5_voltage[i] + buck1245_voltage_map_desc.step); if (ret < 0) goto err_out; if (max_buck1 < max8997->buck1_vol[i]) max_buck1 = max8997->buck1_vol[i]; if (max_buck2 < max8997->buck2_vol[i]) max_buck2 = max8997->buck2_vol[i]; if (max_buck5 < max8997->buck5_vol[i]) max_buck5 = max8997->buck5_vol[i]; } /* For the safety, set max voltage before setting up */ for (i = 0; i < 8; i++) { max8997_update_reg(i2c, MAX8997_REG_BUCK1DVS1 + i, max_buck1, 0x3f); max8997_update_reg(i2c, MAX8997_REG_BUCK2DVS1 + i, max_buck2, 0x3f); max8997_update_reg(i2c, MAX8997_REG_BUCK5DVS1 + i, max_buck5, 0x3f); } /* Initialize all the DVS related BUCK registers */ for (i = 0; i < nr_dvs; i++) { max8997_update_reg(i2c, MAX8997_REG_BUCK1DVS1 + i, max8997->buck1_vol[i], 0x3f); max8997_update_reg(i2c, MAX8997_REG_BUCK2DVS1 + i, max8997->buck2_vol[i], 0x3f); max8997_update_reg(i2c, MAX8997_REG_BUCK5DVS1 + i, max8997->buck5_vol[i], 0x3f); } /* * If buck 1, 2, and 5 do not care DVS GPIO settings, ignore them. * If at least one of them cares, set gpios. */ if (pdata->buck1_gpiodvs || pdata->buck2_gpiodvs || pdata->buck5_gpiodvs) { if (!gpio_is_valid(pdata->buck125_gpios[0]) || !gpio_is_valid(pdata->buck125_gpios[1]) || !gpio_is_valid(pdata->buck125_gpios[2])) { dev_err(&pdev->dev, "GPIO NOT VALID\n"); ret = -EINVAL; goto err_out; } ret = devm_gpio_request(&pdev->dev, pdata->buck125_gpios[0], "MAX8997 SET1"); if (ret) goto err_out; ret = devm_gpio_request(&pdev->dev, pdata->buck125_gpios[1], "MAX8997 SET2"); if (ret) goto err_out; ret = devm_gpio_request(&pdev->dev, pdata->buck125_gpios[2], "MAX8997 SET3"); if (ret) goto err_out; gpio_direction_output(pdata->buck125_gpios[0], (max8997->buck125_gpioindex >> 2) & 0x1); /* SET1 */ gpio_direction_output(pdata->buck125_gpios[1], (max8997->buck125_gpioindex >> 1) & 0x1); /* SET2 */ gpio_direction_output(pdata->buck125_gpios[2], (max8997->buck125_gpioindex >> 0) & 0x1); /* SET3 */ } /* DVS-GPIO disabled */ max8997_update_reg(i2c, MAX8997_REG_BUCK1CTRL, (pdata->buck1_gpiodvs) ? (1 << 1) : (0 << 1), 1 << 1); max8997_update_reg(i2c, MAX8997_REG_BUCK2CTRL, (pdata->buck2_gpiodvs) ? (1 << 1) : (0 << 1), 1 << 1); max8997_update_reg(i2c, MAX8997_REG_BUCK5CTRL, (pdata->buck5_gpiodvs) ? (1 << 1) : (0 << 1), 1 << 1); /* Misc Settings */ max8997->ramp_delay = 10; /* set 10mV/us, which is the default */ max8997_write_reg(i2c, MAX8997_REG_BUCKRAMP, (0xf << 4) | 0x9); for (i = 0; i < pdata->num_regulators; i++) { const struct voltage_map_desc *desc; int id = pdata->regulators[i].id; desc = reg_voltage_map[id]; if (desc) { regulators[id].n_voltages = (desc->max - desc->min) / desc->step + 1; } else if (id == MAX8997_ESAFEOUT1 || id == MAX8997_ESAFEOUT2) { regulators[id].volt_table = safeoutvolt; regulators[id].n_voltages = ARRAY_SIZE(safeoutvolt); } else if (id == MAX8997_CHARGER_CV) { regulators[id].n_voltages = 16; } config.dev = max8997->dev; config.init_data = pdata->regulators[i].initdata; config.driver_data = max8997; config.of_node = pdata->regulators[i].reg_node; rdev[i] = regulator_register(&regulators[id], &config); if (IS_ERR(rdev[i])) { ret = PTR_ERR(rdev[i]); dev_err(max8997->dev, "regulator init failed for %d\n", id); rdev[i] = NULL; goto err; } } return 0; err: while (--i >= 0) regulator_unregister(rdev[i]); err_out: return ret; } static int max8997_pmic_remove(struct platform_device *pdev) { struct max8997_data *max8997 = platform_get_drvdata(pdev); struct regulator_dev **rdev = max8997->rdev; int i; for (i = 0; i < max8997->num_regulators; i++) regulator_unregister(rdev[i]); return 0; } static const struct platform_device_id max8997_pmic_id[] = { { "max8997-pmic", 0}, { }, }; MODULE_DEVICE_TABLE(platform, max8997_pmic_id); static struct platform_driver max8997_pmic_driver = { .driver = { .name = "max8997-pmic", .owner = THIS_MODULE, }, .probe = max8997_pmic_probe, .remove = max8997_pmic_remove, .id_table = max8997_pmic_id, }; static int __init max8997_pmic_init(void) { return platform_driver_register(&max8997_pmic_driver); } subsys_initcall(max8997_pmic_init); static void __exit max8997_pmic_cleanup(void) { platform_driver_unregister(&max8997_pmic_driver); } module_exit(max8997_pmic_cleanup); MODULE_DESCRIPTION("MAXIM 8997/8966 Regulator Driver"); MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>"); MODULE_LICENSE("GPL");
gpl-2.0
EPDCenterSpain/kernel_Archos_97_Titan
drivers/uio/uio.c
2762
19937
/* * drivers/uio/uio.c * * Copyright(C) 2005, Benedikt Spranger <b.spranger@linutronix.de> * Copyright(C) 2005, Thomas Gleixner <tglx@linutronix.de> * Copyright(C) 2006, Hans J. Koch <hjk@hansjkoch.de> * Copyright(C) 2006, Greg Kroah-Hartman <greg@kroah.com> * * Userspace IO * * Base Functions * * Licensed under the GPLv2 only. */ #include <linux/module.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/idr.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/kobject.h> #include <linux/cdev.h> #include <linux/uio_driver.h> #define UIO_MAX_DEVICES (1U << MINORBITS) struct uio_device { struct module *owner; struct device *dev; int minor; atomic_t event; struct fasync_struct *async_queue; wait_queue_head_t wait; int vma_count; struct uio_info *info; struct kobject *map_dir; struct kobject *portio_dir; }; static int uio_major; static struct cdev *uio_cdev; static DEFINE_IDR(uio_idr); static const struct file_operations uio_fops; /* Protect idr accesses */ static DEFINE_MUTEX(minor_lock); /* * attributes */ struct uio_map { struct kobject kobj; struct uio_mem *mem; }; #define to_map(map) container_of(map, struct uio_map, kobj) static ssize_t map_name_show(struct uio_mem *mem, char *buf) { if (unlikely(!mem->name)) mem->name = ""; return sprintf(buf, "%s\n", mem->name); } static ssize_t map_addr_show(struct uio_mem *mem, char *buf) { return sprintf(buf, "0x%lx\n", mem->addr); } static ssize_t map_size_show(struct uio_mem *mem, char *buf) { return sprintf(buf, "0x%lx\n", mem->size); } static ssize_t map_offset_show(struct uio_mem *mem, char *buf) { return sprintf(buf, "0x%lx\n", mem->addr & ~PAGE_MASK); } struct map_sysfs_entry { struct attribute attr; ssize_t (*show)(struct uio_mem *, char *); ssize_t (*store)(struct uio_mem *, const char *, size_t); }; static struct map_sysfs_entry name_attribute = __ATTR(name, S_IRUGO, map_name_show, NULL); static struct map_sysfs_entry addr_attribute = __ATTR(addr, S_IRUGO, map_addr_show, NULL); static struct map_sysfs_entry size_attribute = __ATTR(size, S_IRUGO, map_size_show, NULL); static struct map_sysfs_entry offset_attribute = __ATTR(offset, S_IRUGO, map_offset_show, NULL); static struct attribute *attrs[] = { &name_attribute.attr, &addr_attribute.attr, &size_attribute.attr, &offset_attribute.attr, NULL, /* need to NULL terminate the list of attributes */ }; static void map_release(struct kobject *kobj) { struct uio_map *map = to_map(kobj); kfree(map); } static ssize_t map_type_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct uio_map *map = to_map(kobj); struct uio_mem *mem = map->mem; struct map_sysfs_entry *entry; entry = container_of(attr, struct map_sysfs_entry, attr); if (!entry->show) return -EIO; return entry->show(mem, buf); } static const struct sysfs_ops map_sysfs_ops = { .show = map_type_show, }; static struct kobj_type map_attr_type = { .release = map_release, .sysfs_ops = &map_sysfs_ops, .default_attrs = attrs, }; struct uio_portio { struct kobject kobj; struct uio_port *port; }; #define to_portio(portio) container_of(portio, struct uio_portio, kobj) static ssize_t portio_name_show(struct uio_port *port, char *buf) { if (unlikely(!port->name)) port->name = ""; return sprintf(buf, "%s\n", port->name); } static ssize_t portio_start_show(struct uio_port *port, char *buf) { return sprintf(buf, "0x%lx\n", port->start); } static ssize_t portio_size_show(struct uio_port *port, char *buf) { return sprintf(buf, "0x%lx\n", port->size); } static ssize_t portio_porttype_show(struct uio_port *port, char *buf) { const char *porttypes[] = {"none", "x86", "gpio", "other"}; if ((port->porttype < 0) || (port->porttype > UIO_PORT_OTHER)) return -EINVAL; return sprintf(buf, "port_%s\n", porttypes[port->porttype]); } struct portio_sysfs_entry { struct attribute attr; ssize_t (*show)(struct uio_port *, char *); ssize_t (*store)(struct uio_port *, const char *, size_t); }; static struct portio_sysfs_entry portio_name_attribute = __ATTR(name, S_IRUGO, portio_name_show, NULL); static struct portio_sysfs_entry portio_start_attribute = __ATTR(start, S_IRUGO, portio_start_show, NULL); static struct portio_sysfs_entry portio_size_attribute = __ATTR(size, S_IRUGO, portio_size_show, NULL); static struct portio_sysfs_entry portio_porttype_attribute = __ATTR(porttype, S_IRUGO, portio_porttype_show, NULL); static struct attribute *portio_attrs[] = { &portio_name_attribute.attr, &portio_start_attribute.attr, &portio_size_attribute.attr, &portio_porttype_attribute.attr, NULL, }; static void portio_release(struct kobject *kobj) { struct uio_portio *portio = to_portio(kobj); kfree(portio); } static ssize_t portio_type_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct uio_portio *portio = to_portio(kobj); struct uio_port *port = portio->port; struct portio_sysfs_entry *entry; entry = container_of(attr, struct portio_sysfs_entry, attr); if (!entry->show) return -EIO; return entry->show(port, buf); } static const struct sysfs_ops portio_sysfs_ops = { .show = portio_type_show, }; static struct kobj_type portio_attr_type = { .release = portio_release, .sysfs_ops = &portio_sysfs_ops, .default_attrs = portio_attrs, }; static ssize_t show_name(struct device *dev, struct device_attribute *attr, char *buf) { struct uio_device *idev = dev_get_drvdata(dev); return sprintf(buf, "%s\n", idev->info->name); } static ssize_t show_version(struct device *dev, struct device_attribute *attr, char *buf) { struct uio_device *idev = dev_get_drvdata(dev); return sprintf(buf, "%s\n", idev->info->version); } static ssize_t show_event(struct device *dev, struct device_attribute *attr, char *buf) { struct uio_device *idev = dev_get_drvdata(dev); return sprintf(buf, "%u\n", (unsigned int)atomic_read(&idev->event)); } static struct device_attribute uio_class_attributes[] = { __ATTR(name, S_IRUGO, show_name, NULL), __ATTR(version, S_IRUGO, show_version, NULL), __ATTR(event, S_IRUGO, show_event, NULL), {} }; /* UIO class infrastructure */ static struct class uio_class = { .name = "uio", .dev_attrs = uio_class_attributes, }; /* * device functions */ static int uio_dev_add_attributes(struct uio_device *idev) { int ret; int mi, pi; int map_found = 0; int portio_found = 0; struct uio_mem *mem; struct uio_map *map; struct uio_port *port; struct uio_portio *portio; for (mi = 0; mi < MAX_UIO_MAPS; mi++) { mem = &idev->info->mem[mi]; if (mem->size == 0) break; if (!map_found) { map_found = 1; idev->map_dir = kobject_create_and_add("maps", &idev->dev->kobj); if (!idev->map_dir) goto err_map; } map = kzalloc(sizeof(*map), GFP_KERNEL); if (!map) goto err_map; kobject_init(&map->kobj, &map_attr_type); map->mem = mem; mem->map = map; ret = kobject_add(&map->kobj, idev->map_dir, "map%d", mi); if (ret) goto err_map; ret = kobject_uevent(&map->kobj, KOBJ_ADD); if (ret) goto err_map; } for (pi = 0; pi < MAX_UIO_PORT_REGIONS; pi++) { port = &idev->info->port[pi]; if (port->size == 0) break; if (!portio_found) { portio_found = 1; idev->portio_dir = kobject_create_and_add("portio", &idev->dev->kobj); if (!idev->portio_dir) goto err_portio; } portio = kzalloc(sizeof(*portio), GFP_KERNEL); if (!portio) goto err_portio; kobject_init(&portio->kobj, &portio_attr_type); portio->port = port; port->portio = portio; ret = kobject_add(&portio->kobj, idev->portio_dir, "port%d", pi); if (ret) goto err_portio; ret = kobject_uevent(&portio->kobj, KOBJ_ADD); if (ret) goto err_portio; } return 0; err_portio: for (pi--; pi >= 0; pi--) { port = &idev->info->port[pi]; portio = port->portio; kobject_put(&portio->kobj); } kobject_put(idev->portio_dir); err_map: for (mi--; mi>=0; mi--) { mem = &idev->info->mem[mi]; map = mem->map; kobject_put(&map->kobj); } kobject_put(idev->map_dir); dev_err(idev->dev, "error creating sysfs files (%d)\n", ret); return ret; } static void uio_dev_del_attributes(struct uio_device *idev) { int i; struct uio_mem *mem; struct uio_port *port; for (i = 0; i < MAX_UIO_MAPS; i++) { mem = &idev->info->mem[i]; if (mem->size == 0) break; kobject_put(&mem->map->kobj); } kobject_put(idev->map_dir); for (i = 0; i < MAX_UIO_PORT_REGIONS; i++) { port = &idev->info->port[i]; if (port->size == 0) break; kobject_put(&port->portio->kobj); } kobject_put(idev->portio_dir); } static int uio_get_minor(struct uio_device *idev) { int retval = -ENOMEM; int id; mutex_lock(&minor_lock); if (idr_pre_get(&uio_idr, GFP_KERNEL) == 0) goto exit; retval = idr_get_new(&uio_idr, idev, &id); if (retval < 0) { if (retval == -EAGAIN) retval = -ENOMEM; goto exit; } if (id < UIO_MAX_DEVICES) { idev->minor = id; } else { dev_err(idev->dev, "too many uio devices\n"); retval = -EINVAL; idr_remove(&uio_idr, id); } exit: mutex_unlock(&minor_lock); return retval; } static void uio_free_minor(struct uio_device *idev) { mutex_lock(&minor_lock); idr_remove(&uio_idr, idev->minor); mutex_unlock(&minor_lock); } /** * uio_event_notify - trigger an interrupt event * @info: UIO device capabilities */ void uio_event_notify(struct uio_info *info) { struct uio_device *idev = info->uio_dev; atomic_inc(&idev->event); wake_up_interruptible(&idev->wait); kill_fasync(&idev->async_queue, SIGIO, POLL_IN); } EXPORT_SYMBOL_GPL(uio_event_notify); /** * uio_interrupt - hardware interrupt handler * @irq: IRQ number, can be UIO_IRQ_CYCLIC for cyclic timer * @dev_id: Pointer to the devices uio_device structure */ static irqreturn_t uio_interrupt(int irq, void *dev_id) { struct uio_device *idev = (struct uio_device *)dev_id; irqreturn_t ret = idev->info->handler(irq, idev->info); if (ret == IRQ_HANDLED) uio_event_notify(idev->info); return ret; } struct uio_listener { struct uio_device *dev; s32 event_count; }; static int uio_open(struct inode *inode, struct file *filep) { struct uio_device *idev; struct uio_listener *listener; int ret = 0; mutex_lock(&minor_lock); idev = idr_find(&uio_idr, iminor(inode)); mutex_unlock(&minor_lock); if (!idev) { ret = -ENODEV; goto out; } if (!try_module_get(idev->owner)) { ret = -ENODEV; goto out; } listener = kmalloc(sizeof(*listener), GFP_KERNEL); if (!listener) { ret = -ENOMEM; goto err_alloc_listener; } listener->dev = idev; listener->event_count = atomic_read(&idev->event); filep->private_data = listener; if (idev->info->open) { ret = idev->info->open(idev->info, inode); if (ret) goto err_infoopen; } return 0; err_infoopen: kfree(listener); err_alloc_listener: module_put(idev->owner); out: return ret; } static int uio_fasync(int fd, struct file *filep, int on) { struct uio_listener *listener = filep->private_data; struct uio_device *idev = listener->dev; return fasync_helper(fd, filep, on, &idev->async_queue); } static int uio_release(struct inode *inode, struct file *filep) { int ret = 0; struct uio_listener *listener = filep->private_data; struct uio_device *idev = listener->dev; if (idev->info->release) ret = idev->info->release(idev->info, inode); module_put(idev->owner); kfree(listener); return ret; } static unsigned int uio_poll(struct file *filep, poll_table *wait) { struct uio_listener *listener = filep->private_data; struct uio_device *idev = listener->dev; if (!idev->info->irq) return -EIO; poll_wait(filep, &idev->wait, wait); if (listener->event_count != atomic_read(&idev->event)) return POLLIN | POLLRDNORM; return 0; } static ssize_t uio_read(struct file *filep, char __user *buf, size_t count, loff_t *ppos) { struct uio_listener *listener = filep->private_data; struct uio_device *idev = listener->dev; DECLARE_WAITQUEUE(wait, current); ssize_t retval; s32 event_count; if (!idev->info->irq) return -EIO; if (count != sizeof(s32)) return -EINVAL; add_wait_queue(&idev->wait, &wait); do { set_current_state(TASK_INTERRUPTIBLE); event_count = atomic_read(&idev->event); if (event_count != listener->event_count) { if (copy_to_user(buf, &event_count, count)) retval = -EFAULT; else { listener->event_count = event_count; retval = count; } break; } if (filep->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } if (signal_pending(current)) { retval = -ERESTARTSYS; break; } schedule(); } while (1); __set_current_state(TASK_RUNNING); remove_wait_queue(&idev->wait, &wait); return retval; } static ssize_t uio_write(struct file *filep, const char __user *buf, size_t count, loff_t *ppos) { struct uio_listener *listener = filep->private_data; struct uio_device *idev = listener->dev; ssize_t retval; s32 irq_on; if (!idev->info->irq) return -EIO; if (count != sizeof(s32)) return -EINVAL; if (!idev->info->irqcontrol) return -ENOSYS; if (copy_from_user(&irq_on, buf, count)) return -EFAULT; retval = idev->info->irqcontrol(idev->info, irq_on); return retval ? retval : sizeof(s32); } static int uio_find_mem_index(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; if (vma->vm_pgoff < MAX_UIO_MAPS) { if (idev->info->mem[vma->vm_pgoff].size == 0) return -1; return (int)vma->vm_pgoff; } return -1; } static void uio_vma_open(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; idev->vma_count++; } static void uio_vma_close(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; idev->vma_count--; } static int uio_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct uio_device *idev = vma->vm_private_data; struct page *page; unsigned long offset; int mi = uio_find_mem_index(vma); if (mi < 0) return VM_FAULT_SIGBUS; /* * We need to subtract mi because userspace uses offset = N*PAGE_SIZE * to use mem[N]. */ offset = (vmf->pgoff - mi) << PAGE_SHIFT; if (idev->info->mem[mi].memtype == UIO_MEM_LOGICAL) page = virt_to_page(idev->info->mem[mi].addr + offset); else page = vmalloc_to_page((void *)idev->info->mem[mi].addr + offset); get_page(page); vmf->page = page; return 0; } static const struct vm_operations_struct uio_vm_ops = { .open = uio_vma_open, .close = uio_vma_close, .fault = uio_vma_fault, }; static int uio_mmap_physical(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; int mi = uio_find_mem_index(vma); if (mi < 0) return -EINVAL; vma->vm_flags |= VM_IO | VM_RESERVED; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); return remap_pfn_range(vma, vma->vm_start, idev->info->mem[mi].addr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } static int uio_mmap_logical(struct vm_area_struct *vma) { vma->vm_flags |= VM_RESERVED; vma->vm_ops = &uio_vm_ops; uio_vma_open(vma); return 0; } static int uio_mmap(struct file *filep, struct vm_area_struct *vma) { struct uio_listener *listener = filep->private_data; struct uio_device *idev = listener->dev; int mi; unsigned long requested_pages, actual_pages; int ret = 0; if (vma->vm_end < vma->vm_start) return -EINVAL; vma->vm_private_data = idev; mi = uio_find_mem_index(vma); if (mi < 0) return -EINVAL; requested_pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; actual_pages = ((idev->info->mem[mi].addr & ~PAGE_MASK) + idev->info->mem[mi].size + PAGE_SIZE -1) >> PAGE_SHIFT; if (requested_pages > actual_pages) return -EINVAL; if (idev->info->mmap) { ret = idev->info->mmap(idev->info, vma); return ret; } switch (idev->info->mem[mi].memtype) { case UIO_MEM_PHYS: return uio_mmap_physical(vma); case UIO_MEM_LOGICAL: case UIO_MEM_VIRTUAL: return uio_mmap_logical(vma); default: return -EINVAL; } } static const struct file_operations uio_fops = { .owner = THIS_MODULE, .open = uio_open, .release = uio_release, .read = uio_read, .write = uio_write, .mmap = uio_mmap, .poll = uio_poll, .fasync = uio_fasync, .llseek = noop_llseek, }; static int uio_major_init(void) { static const char name[] = "uio"; struct cdev *cdev = NULL; dev_t uio_dev = 0; int result; result = alloc_chrdev_region(&uio_dev, 0, UIO_MAX_DEVICES, name); if (result) goto out; result = -ENOMEM; cdev = cdev_alloc(); if (!cdev) goto out_unregister; cdev->owner = THIS_MODULE; cdev->ops = &uio_fops; kobject_set_name(&cdev->kobj, "%s", name); result = cdev_add(cdev, uio_dev, UIO_MAX_DEVICES); if (result) goto out_put; uio_major = MAJOR(uio_dev); uio_cdev = cdev; result = 0; out: return result; out_put: kobject_put(&cdev->kobj); out_unregister: unregister_chrdev_region(uio_dev, UIO_MAX_DEVICES); goto out; } static void uio_major_cleanup(void) { unregister_chrdev_region(MKDEV(uio_major, 0), UIO_MAX_DEVICES); cdev_del(uio_cdev); } static int init_uio_class(void) { int ret; /* This is the first time in here, set everything up properly */ ret = uio_major_init(); if (ret) goto exit; ret = class_register(&uio_class); if (ret) { printk(KERN_ERR "class_register failed for uio\n"); goto err_class_register; } return 0; err_class_register: uio_major_cleanup(); exit: return ret; } static void release_uio_class(void) { class_unregister(&uio_class); uio_major_cleanup(); } /** * uio_register_device - register a new userspace IO device * @owner: module that creates the new device * @parent: parent device * @info: UIO device capabilities * * returns zero on success or a negative error code. */ int __uio_register_device(struct module *owner, struct device *parent, struct uio_info *info) { struct uio_device *idev; int ret = 0; if (!parent || !info || !info->name || !info->version) return -EINVAL; info->uio_dev = NULL; idev = kzalloc(sizeof(*idev), GFP_KERNEL); if (!idev) { ret = -ENOMEM; goto err_kzalloc; } idev->owner = owner; idev->info = info; init_waitqueue_head(&idev->wait); atomic_set(&idev->event, 0); ret = uio_get_minor(idev); if (ret) goto err_get_minor; idev->dev = device_create(&uio_class, parent, MKDEV(uio_major, idev->minor), idev, "uio%d", idev->minor); if (IS_ERR(idev->dev)) { printk(KERN_ERR "UIO: device register failed\n"); ret = PTR_ERR(idev->dev); goto err_device_create; } ret = uio_dev_add_attributes(idev); if (ret) goto err_uio_dev_add_attributes; info->uio_dev = idev; if (info->irq && (info->irq != UIO_IRQ_CUSTOM)) { ret = request_irq(info->irq, uio_interrupt, info->irq_flags, info->name, idev); if (ret) goto err_request_irq; } return 0; err_request_irq: uio_dev_del_attributes(idev); err_uio_dev_add_attributes: device_destroy(&uio_class, MKDEV(uio_major, idev->minor)); err_device_create: uio_free_minor(idev); err_get_minor: kfree(idev); err_kzalloc: return ret; } EXPORT_SYMBOL_GPL(__uio_register_device); /** * uio_unregister_device - unregister a industrial IO device * @info: UIO device capabilities * */ void uio_unregister_device(struct uio_info *info) { struct uio_device *idev; if (!info || !info->uio_dev) return; idev = info->uio_dev; uio_free_minor(idev); if (info->irq && (info->irq != UIO_IRQ_CUSTOM)) free_irq(info->irq, idev); uio_dev_del_attributes(idev); device_destroy(&uio_class, MKDEV(uio_major, idev->minor)); kfree(idev); return; } EXPORT_SYMBOL_GPL(uio_unregister_device); static int __init uio_init(void) { return init_uio_class(); } static void __exit uio_exit(void) { release_uio_class(); } module_init(uio_init) module_exit(uio_exit) MODULE_LICENSE("GPL v2");
gpl-2.0
kmihelich/linux
drivers/net/tulip/dmfe.c
2762
60377
/* A Davicom DM9102/DM9102A/DM9102A+DM9801/DM9102A+DM9802 NIC fast ethernet driver for Linux. Copyright (C) 1997 Sten Wang 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. DAVICOM Web-Site: www.davicom.com.tw Author: Sten Wang, 886-3-5798797-8517, E-mail: sten_wang@davicom.com.tw Maintainer: Tobias Ringstrom <tori@unhappy.mine.nu> (C)Copyright 1997-1998 DAVICOM Semiconductor,Inc. All Rights Reserved. Marcelo Tosatti <marcelo@conectiva.com.br> : Made it compile in 2.3 (device to net_device) Alan Cox <alan@lxorguk.ukuu.org.uk> : Cleaned up for kernel merge. Removed the back compatibility support Reformatted, fixing spelling etc as I went Removed IRQ 0-15 assumption Jeff Garzik <jgarzik@pobox.com> : Updated to use new PCI driver API. Resource usage cleanups. Report driver version to user. Tobias Ringstrom <tori@unhappy.mine.nu> : Cleaned up and added SMP safety. Thanks go to Jeff Garzik, Andrew Morton and Frank Davis for the SMP safety fixes. Vojtech Pavlik <vojtech@suse.cz> : Cleaned up pointer arithmetics. Fixed a lot of 64bit issues. Cleaned up printk()s a bit. Fixed some obvious big endian problems. Tobias Ringstrom <tori@unhappy.mine.nu> : Use time_after for jiffies calculation. Added ethtool support. Updated PCI resource allocation. Do not forget to unmap PCI mapped skbs. Alan Cox <alan@lxorguk.ukuu.org.uk> Added new PCI identifiers provided by Clear Zhang at ALi for their 1563 ethernet device. TODO Check on 64 bit boxes. Check and fix on big endian boxes. Test and make sure PCI latency is now correct for all cases. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "dmfe" #define DRV_VERSION "1.36.4" #define DRV_RELDATE "2002-01-17" #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/ptrace.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/skbuff.h> #include <linux/delay.h> #include <linux/spinlock.h> #include <linux/crc32.h> #include <linux/bitops.h> #include <asm/processor.h> #include <asm/io.h> #include <asm/dma.h> #include <asm/uaccess.h> #include <asm/irq.h> #ifdef CONFIG_TULIP_DM910X #include <linux/of.h> #endif /* Board/System/Debug information/definition ---------------- */ #define PCI_DM9132_ID 0x91321282 /* Davicom DM9132 ID */ #define PCI_DM9102_ID 0x91021282 /* Davicom DM9102 ID */ #define PCI_DM9100_ID 0x91001282 /* Davicom DM9100 ID */ #define PCI_DM9009_ID 0x90091282 /* Davicom DM9009 ID */ #define DM9102_IO_SIZE 0x80 #define DM9102A_IO_SIZE 0x100 #define TX_MAX_SEND_CNT 0x1 /* Maximum tx packet per time */ #define TX_DESC_CNT 0x10 /* Allocated Tx descriptors */ #define RX_DESC_CNT 0x20 /* Allocated Rx descriptors */ #define TX_FREE_DESC_CNT (TX_DESC_CNT - 2) /* Max TX packet count */ #define TX_WAKE_DESC_CNT (TX_DESC_CNT - 3) /* TX wakeup count */ #define DESC_ALL_CNT (TX_DESC_CNT + RX_DESC_CNT) #define TX_BUF_ALLOC 0x600 #define RX_ALLOC_SIZE 0x620 #define DM910X_RESET 1 #define CR0_DEFAULT 0x00E00000 /* TX & RX burst mode */ #define CR6_DEFAULT 0x00080000 /* HD */ #define CR7_DEFAULT 0x180c1 #define CR15_DEFAULT 0x06 /* TxJabber RxWatchdog */ #define TDES0_ERR_MASK 0x4302 /* TXJT, LC, EC, FUE */ #define MAX_PACKET_SIZE 1514 #define DMFE_MAX_MULTICAST 14 #define RX_COPY_SIZE 100 #define MAX_CHECK_PACKET 0x8000 #define DM9801_NOISE_FLOOR 8 #define DM9802_NOISE_FLOOR 5 #define DMFE_WOL_LINKCHANGE 0x20000000 #define DMFE_WOL_SAMPLEPACKET 0x10000000 #define DMFE_WOL_MAGICPACKET 0x08000000 #define DMFE_10MHF 0 #define DMFE_100MHF 1 #define DMFE_10MFD 4 #define DMFE_100MFD 5 #define DMFE_AUTO 8 #define DMFE_1M_HPNA 0x10 #define DMFE_TXTH_72 0x400000 /* TX TH 72 byte */ #define DMFE_TXTH_96 0x404000 /* TX TH 96 byte */ #define DMFE_TXTH_128 0x0000 /* TX TH 128 byte */ #define DMFE_TXTH_256 0x4000 /* TX TH 256 byte */ #define DMFE_TXTH_512 0x8000 /* TX TH 512 byte */ #define DMFE_TXTH_1K 0xC000 /* TX TH 1K byte */ #define DMFE_TIMER_WUT (jiffies + HZ * 1)/* timer wakeup time : 1 second */ #define DMFE_TX_TIMEOUT ((3*HZ)/2) /* tx packet time-out time 1.5 s" */ #define DMFE_TX_KICK (HZ/2) /* tx packet Kick-out time 0.5 s" */ #define DMFE_DBUG(dbug_now, msg, value) \ do { \ if (dmfe_debug || (dbug_now)) \ pr_err("%s %lx\n", \ (msg), (long) (value)); \ } while (0) #define SHOW_MEDIA_TYPE(mode) \ pr_info("Change Speed to %sMhz %s duplex\n" , \ (mode & 1) ? "100":"10", \ (mode & 4) ? "full":"half"); /* CR9 definition: SROM/MII */ #define CR9_SROM_READ 0x4800 #define CR9_SRCS 0x1 #define CR9_SRCLK 0x2 #define CR9_CRDOUT 0x8 #define SROM_DATA_0 0x0 #define SROM_DATA_1 0x4 #define PHY_DATA_1 0x20000 #define PHY_DATA_0 0x00000 #define MDCLKH 0x10000 #define PHY_POWER_DOWN 0x800 #define SROM_V41_CODE 0x14 #define SROM_CLK_WRITE(data, ioaddr) \ outl(data|CR9_SROM_READ|CR9_SRCS,ioaddr); \ udelay(5); \ outl(data|CR9_SROM_READ|CR9_SRCS|CR9_SRCLK,ioaddr); \ udelay(5); \ outl(data|CR9_SROM_READ|CR9_SRCS,ioaddr); \ udelay(5); #define __CHK_IO_SIZE(pci_id, dev_rev) \ (( ((pci_id)==PCI_DM9132_ID) || ((dev_rev) >= 0x30) ) ? \ DM9102A_IO_SIZE: DM9102_IO_SIZE) #define CHK_IO_SIZE(pci_dev) \ (__CHK_IO_SIZE(((pci_dev)->device << 16) | (pci_dev)->vendor, \ (pci_dev)->revision)) /* Sten Check */ #define DEVICE net_device /* Structure/enum declaration ------------------------------- */ struct tx_desc { __le32 tdes0, tdes1, tdes2, tdes3; /* Data for the card */ char *tx_buf_ptr; /* Data for us */ struct tx_desc *next_tx_desc; } __attribute__(( aligned(32) )); struct rx_desc { __le32 rdes0, rdes1, rdes2, rdes3; /* Data for the card */ struct sk_buff *rx_skb_ptr; /* Data for us */ struct rx_desc *next_rx_desc; } __attribute__(( aligned(32) )); struct dmfe_board_info { u32 chip_id; /* Chip vendor/Device ID */ u8 chip_revision; /* Chip revision */ struct DEVICE *next_dev; /* next device */ struct pci_dev *pdev; /* PCI device */ spinlock_t lock; long ioaddr; /* I/O base address */ u32 cr0_data; u32 cr5_data; u32 cr6_data; u32 cr7_data; u32 cr15_data; /* pointer for memory physical address */ dma_addr_t buf_pool_dma_ptr; /* Tx buffer pool memory */ dma_addr_t buf_pool_dma_start; /* Tx buffer pool align dword */ dma_addr_t desc_pool_dma_ptr; /* descriptor pool memory */ dma_addr_t first_tx_desc_dma; dma_addr_t first_rx_desc_dma; /* descriptor pointer */ unsigned char *buf_pool_ptr; /* Tx buffer pool memory */ unsigned char *buf_pool_start; /* Tx buffer pool align dword */ unsigned char *desc_pool_ptr; /* descriptor pool memory */ struct tx_desc *first_tx_desc; struct tx_desc *tx_insert_ptr; struct tx_desc *tx_remove_ptr; struct rx_desc *first_rx_desc; struct rx_desc *rx_insert_ptr; struct rx_desc *rx_ready_ptr; /* packet come pointer */ unsigned long tx_packet_cnt; /* transmitted packet count */ unsigned long tx_queue_cnt; /* wait to send packet count */ unsigned long rx_avail_cnt; /* available rx descriptor count */ unsigned long interval_rx_cnt; /* rx packet count a callback time */ u16 HPNA_command; /* For HPNA register 16 */ u16 HPNA_timer; /* For HPNA remote device check */ u16 dbug_cnt; u16 NIC_capability; /* NIC media capability */ u16 PHY_reg4; /* Saved Phyxcer register 4 value */ u8 HPNA_present; /* 0:none, 1:DM9801, 2:DM9802 */ u8 chip_type; /* Keep DM9102A chip type */ u8 media_mode; /* user specify media mode */ u8 op_mode; /* real work media mode */ u8 phy_addr; u8 wait_reset; /* Hardware failed, need to reset */ u8 dm910x_chk_mode; /* Operating mode check */ u8 first_in_callback; /* Flag to record state */ u8 wol_mode; /* user WOL settings */ struct timer_list timer; /* Driver defined statistic counter */ unsigned long tx_fifo_underrun; unsigned long tx_loss_carrier; unsigned long tx_no_carrier; unsigned long tx_late_collision; unsigned long tx_excessive_collision; unsigned long tx_jabber_timeout; unsigned long reset_count; unsigned long reset_cr8; unsigned long reset_fatal; unsigned long reset_TXtimeout; /* NIC SROM data */ unsigned char srom[128]; }; enum dmfe_offsets { DCR0 = 0x00, DCR1 = 0x08, DCR2 = 0x10, DCR3 = 0x18, DCR4 = 0x20, DCR5 = 0x28, DCR6 = 0x30, DCR7 = 0x38, DCR8 = 0x40, DCR9 = 0x48, DCR10 = 0x50, DCR11 = 0x58, DCR12 = 0x60, DCR13 = 0x68, DCR14 = 0x70, DCR15 = 0x78 }; enum dmfe_CR6_bits { CR6_RXSC = 0x2, CR6_PBF = 0x8, CR6_PM = 0x40, CR6_PAM = 0x80, CR6_FDM = 0x200, CR6_TXSC = 0x2000, CR6_STI = 0x100000, CR6_SFT = 0x200000, CR6_RXA = 0x40000000, CR6_NO_PURGE = 0x20000000 }; /* Global variable declaration ----------------------------- */ static int __devinitdata printed_version; static const char version[] __devinitconst = "Davicom DM9xxx net driver, version " DRV_VERSION " (" DRV_RELDATE ")"; static int dmfe_debug; static unsigned char dmfe_media_mode = DMFE_AUTO; static u32 dmfe_cr6_user_set; /* For module input parameter */ static int debug; static u32 cr6set; static unsigned char mode = 8; static u8 chkmode = 1; static u8 HPNA_mode; /* Default: Low Power/High Speed */ static u8 HPNA_rx_cmd; /* Default: Disable Rx remote command */ static u8 HPNA_tx_cmd; /* Default: Don't issue remote command */ static u8 HPNA_NoiseFloor; /* Default: HPNA NoiseFloor */ static u8 SF_mode; /* Special Function: 1:VLAN, 2:RX Flow Control 4: TX pause packet */ /* function declaration ------------------------------------- */ static int dmfe_open(struct DEVICE *); static netdev_tx_t dmfe_start_xmit(struct sk_buff *, struct DEVICE *); static int dmfe_stop(struct DEVICE *); static void dmfe_set_filter_mode(struct DEVICE *); static const struct ethtool_ops netdev_ethtool_ops; static u16 read_srom_word(long ,int); static irqreturn_t dmfe_interrupt(int , void *); #ifdef CONFIG_NET_POLL_CONTROLLER static void poll_dmfe (struct net_device *dev); #endif static void dmfe_descriptor_init(struct dmfe_board_info *, unsigned long); static void allocate_rx_buffer(struct dmfe_board_info *); static void update_cr6(u32, unsigned long); static void send_filter_frame(struct DEVICE *); static void dm9132_id_table(struct DEVICE *); static u16 phy_read(unsigned long, u8, u8, u32); static void phy_write(unsigned long, u8, u8, u16, u32); static void phy_write_1bit(unsigned long, u32); static u16 phy_read_1bit(unsigned long); static u8 dmfe_sense_speed(struct dmfe_board_info *); static void dmfe_process_mode(struct dmfe_board_info *); static void dmfe_timer(unsigned long); static inline u32 cal_CRC(unsigned char *, unsigned int, u8); static void dmfe_rx_packet(struct DEVICE *, struct dmfe_board_info *); static void dmfe_free_tx_pkt(struct DEVICE *, struct dmfe_board_info *); static void dmfe_reuse_skb(struct dmfe_board_info *, struct sk_buff *); static void dmfe_dynamic_reset(struct DEVICE *); static void dmfe_free_rxbuffer(struct dmfe_board_info *); static void dmfe_init_dm910x(struct DEVICE *); static void dmfe_parse_srom(struct dmfe_board_info *); static void dmfe_program_DM9801(struct dmfe_board_info *, int); static void dmfe_program_DM9802(struct dmfe_board_info *); static void dmfe_HPNA_remote_cmd_chk(struct dmfe_board_info * ); static void dmfe_set_phyxcer(struct dmfe_board_info *); /* DM910X network board routine ---------------------------- */ static const struct net_device_ops netdev_ops = { .ndo_open = dmfe_open, .ndo_stop = dmfe_stop, .ndo_start_xmit = dmfe_start_xmit, .ndo_set_multicast_list = dmfe_set_filter_mode, .ndo_change_mtu = eth_change_mtu, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = poll_dmfe, #endif }; /* * Search DM910X board ,allocate space and register it */ static int __devinit dmfe_init_one (struct pci_dev *pdev, const struct pci_device_id *ent) { struct dmfe_board_info *db; /* board information structure */ struct net_device *dev; u32 pci_pmr; int i, err; DMFE_DBUG(0, "dmfe_init_one()", 0); if (!printed_version++) pr_info("%s\n", version); /* * SPARC on-board DM910x chips should be handled by the main * tulip driver, except for early DM9100s. */ #ifdef CONFIG_TULIP_DM910X if ((ent->driver_data == PCI_DM9100_ID && pdev->revision >= 0x30) || ent->driver_data == PCI_DM9102_ID) { struct device_node *dp = pci_device_to_OF_node(pdev); if (dp && of_get_property(dp, "local-mac-address", NULL)) { pr_info("skipping on-board DM910x (use tulip)\n"); return -ENODEV; } } #endif /* Init network device */ dev = alloc_etherdev(sizeof(*db)); if (dev == NULL) return -ENOMEM; SET_NETDEV_DEV(dev, &pdev->dev); if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) { pr_warn("32-bit PCI DMA not available\n"); err = -ENODEV; goto err_out_free; } /* Enable Master/IO access, Disable memory access */ err = pci_enable_device(pdev); if (err) goto err_out_free; if (!pci_resource_start(pdev, 0)) { pr_err("I/O base is zero\n"); err = -ENODEV; goto err_out_disable; } if (pci_resource_len(pdev, 0) < (CHK_IO_SIZE(pdev)) ) { pr_err("Allocated I/O size too small\n"); err = -ENODEV; goto err_out_disable; } #if 0 /* pci_{enable_device,set_master} sets minimum latency for us now */ /* Set Latency Timer 80h */ /* FIXME: setting values > 32 breaks some SiS 559x stuff. Need a PCI quirk.. */ pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0x80); #endif if (pci_request_regions(pdev, DRV_NAME)) { pr_err("Failed to request PCI regions\n"); err = -ENODEV; goto err_out_disable; } /* Init system & device */ db = netdev_priv(dev); /* Allocate Tx/Rx descriptor memory */ db->desc_pool_ptr = pci_alloc_consistent(pdev, sizeof(struct tx_desc) * DESC_ALL_CNT + 0x20, &db->desc_pool_dma_ptr); if (!db->desc_pool_ptr) goto err_out_res; db->buf_pool_ptr = pci_alloc_consistent(pdev, TX_BUF_ALLOC * TX_DESC_CNT + 4, &db->buf_pool_dma_ptr); if (!db->buf_pool_ptr) goto err_out_free_desc; db->first_tx_desc = (struct tx_desc *) db->desc_pool_ptr; db->first_tx_desc_dma = db->desc_pool_dma_ptr; db->buf_pool_start = db->buf_pool_ptr; db->buf_pool_dma_start = db->buf_pool_dma_ptr; db->chip_id = ent->driver_data; db->ioaddr = pci_resource_start(pdev, 0); db->chip_revision = pdev->revision; db->wol_mode = 0; db->pdev = pdev; dev->base_addr = db->ioaddr; dev->irq = pdev->irq; pci_set_drvdata(pdev, dev); dev->netdev_ops = &netdev_ops; dev->ethtool_ops = &netdev_ethtool_ops; netif_carrier_off(dev); spin_lock_init(&db->lock); pci_read_config_dword(pdev, 0x50, &pci_pmr); pci_pmr &= 0x70000; if ( (pci_pmr == 0x10000) && (db->chip_revision == 0x31) ) db->chip_type = 1; /* DM9102A E3 */ else db->chip_type = 0; /* read 64 word srom data */ for (i = 0; i < 64; i++) ((__le16 *) db->srom)[i] = cpu_to_le16(read_srom_word(db->ioaddr, i)); /* Set Node address */ for (i = 0; i < 6; i++) dev->dev_addr[i] = db->srom[20 + i]; err = register_netdev (dev); if (err) goto err_out_free_buf; dev_info(&dev->dev, "Davicom DM%04lx at pci%s, %pM, irq %d\n", ent->driver_data >> 16, pci_name(pdev), dev->dev_addr, dev->irq); pci_set_master(pdev); return 0; err_out_free_buf: pci_free_consistent(pdev, TX_BUF_ALLOC * TX_DESC_CNT + 4, db->buf_pool_ptr, db->buf_pool_dma_ptr); err_out_free_desc: pci_free_consistent(pdev, sizeof(struct tx_desc) * DESC_ALL_CNT + 0x20, db->desc_pool_ptr, db->desc_pool_dma_ptr); err_out_res: pci_release_regions(pdev); err_out_disable: pci_disable_device(pdev); err_out_free: pci_set_drvdata(pdev, NULL); free_netdev(dev); return err; } static void __devexit dmfe_remove_one (struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct dmfe_board_info *db = netdev_priv(dev); DMFE_DBUG(0, "dmfe_remove_one()", 0); if (dev) { unregister_netdev(dev); pci_free_consistent(db->pdev, sizeof(struct tx_desc) * DESC_ALL_CNT + 0x20, db->desc_pool_ptr, db->desc_pool_dma_ptr); pci_free_consistent(db->pdev, TX_BUF_ALLOC * TX_DESC_CNT + 4, db->buf_pool_ptr, db->buf_pool_dma_ptr); pci_release_regions(pdev); free_netdev(dev); /* free board information */ pci_set_drvdata(pdev, NULL); } DMFE_DBUG(0, "dmfe_remove_one() exit", 0); } /* * Open the interface. * The interface is opened whenever "ifconfig" actives it. */ static int dmfe_open(struct DEVICE *dev) { int ret; struct dmfe_board_info *db = netdev_priv(dev); DMFE_DBUG(0, "dmfe_open", 0); ret = request_irq(dev->irq, dmfe_interrupt, IRQF_SHARED, dev->name, dev); if (ret) return ret; /* system variable init */ db->cr6_data = CR6_DEFAULT | dmfe_cr6_user_set; db->tx_packet_cnt = 0; db->tx_queue_cnt = 0; db->rx_avail_cnt = 0; db->wait_reset = 0; db->first_in_callback = 0; db->NIC_capability = 0xf; /* All capability*/ db->PHY_reg4 = 0x1e0; /* CR6 operation mode decision */ if ( !chkmode || (db->chip_id == PCI_DM9132_ID) || (db->chip_revision >= 0x30) ) { db->cr6_data |= DMFE_TXTH_256; db->cr0_data = CR0_DEFAULT; db->dm910x_chk_mode=4; /* Enter the normal mode */ } else { db->cr6_data |= CR6_SFT; /* Store & Forward mode */ db->cr0_data = 0; db->dm910x_chk_mode = 1; /* Enter the check mode */ } /* Initialize DM910X board */ dmfe_init_dm910x(dev); /* Active System Interface */ netif_wake_queue(dev); /* set and active a timer process */ init_timer(&db->timer); db->timer.expires = DMFE_TIMER_WUT + HZ * 2; db->timer.data = (unsigned long)dev; db->timer.function = dmfe_timer; add_timer(&db->timer); return 0; } /* Initialize DM910X board * Reset DM910X board * Initialize TX/Rx descriptor chain structure * Send the set-up frame * Enable Tx/Rx machine */ static void dmfe_init_dm910x(struct DEVICE *dev) { struct dmfe_board_info *db = netdev_priv(dev); unsigned long ioaddr = db->ioaddr; DMFE_DBUG(0, "dmfe_init_dm910x()", 0); /* Reset DM910x MAC controller */ outl(DM910X_RESET, ioaddr + DCR0); /* RESET MAC */ udelay(100); outl(db->cr0_data, ioaddr + DCR0); udelay(5); /* Phy addr : DM910(A)2/DM9132/9801, phy address = 1 */ db->phy_addr = 1; /* Parser SROM and media mode */ dmfe_parse_srom(db); db->media_mode = dmfe_media_mode; /* RESET Phyxcer Chip by GPR port bit 7 */ outl(0x180, ioaddr + DCR12); /* Let bit 7 output port */ if (db->chip_id == PCI_DM9009_ID) { outl(0x80, ioaddr + DCR12); /* Issue RESET signal */ mdelay(300); /* Delay 300 ms */ } outl(0x0, ioaddr + DCR12); /* Clear RESET signal */ /* Process Phyxcer Media Mode */ if ( !(db->media_mode & 0x10) ) /* Force 1M mode */ dmfe_set_phyxcer(db); /* Media Mode Process */ if ( !(db->media_mode & DMFE_AUTO) ) db->op_mode = db->media_mode; /* Force Mode */ /* Initialize Transmit/Receive decriptor and CR3/4 */ dmfe_descriptor_init(db, ioaddr); /* Init CR6 to program DM910x operation */ update_cr6(db->cr6_data, ioaddr); /* Send setup frame */ if (db->chip_id == PCI_DM9132_ID) dm9132_id_table(dev); /* DM9132 */ else send_filter_frame(dev); /* DM9102/DM9102A */ /* Init CR7, interrupt active bit */ db->cr7_data = CR7_DEFAULT; outl(db->cr7_data, ioaddr + DCR7); /* Init CR15, Tx jabber and Rx watchdog timer */ outl(db->cr15_data, ioaddr + DCR15); /* Enable DM910X Tx/Rx function */ db->cr6_data |= CR6_RXSC | CR6_TXSC | 0x40000; update_cr6(db->cr6_data, ioaddr); } /* * Hardware start transmission. * Send a packet to media from the upper layer. */ static netdev_tx_t dmfe_start_xmit(struct sk_buff *skb, struct DEVICE *dev) { struct dmfe_board_info *db = netdev_priv(dev); struct tx_desc *txptr; unsigned long flags; DMFE_DBUG(0, "dmfe_start_xmit", 0); /* Too large packet check */ if (skb->len > MAX_PACKET_SIZE) { pr_err("big packet = %d\n", (u16)skb->len); dev_kfree_skb(skb); return NETDEV_TX_OK; } /* Resource flag check */ netif_stop_queue(dev); spin_lock_irqsave(&db->lock, flags); /* No Tx resource check, it never happen nromally */ if (db->tx_queue_cnt >= TX_FREE_DESC_CNT) { spin_unlock_irqrestore(&db->lock, flags); pr_err("No Tx resource %ld\n", db->tx_queue_cnt); return NETDEV_TX_BUSY; } /* Disable NIC interrupt */ outl(0, dev->base_addr + DCR7); /* transmit this packet */ txptr = db->tx_insert_ptr; skb_copy_from_linear_data(skb, txptr->tx_buf_ptr, skb->len); txptr->tdes1 = cpu_to_le32(0xe1000000 | skb->len); /* Point to next transmit free descriptor */ db->tx_insert_ptr = txptr->next_tx_desc; /* Transmit Packet Process */ if ( (!db->tx_queue_cnt) && (db->tx_packet_cnt < TX_MAX_SEND_CNT) ) { txptr->tdes0 = cpu_to_le32(0x80000000); /* Set owner bit */ db->tx_packet_cnt++; /* Ready to send */ outl(0x1, dev->base_addr + DCR1); /* Issue Tx polling */ dev->trans_start = jiffies; /* saved time stamp */ } else { db->tx_queue_cnt++; /* queue TX packet */ outl(0x1, dev->base_addr + DCR1); /* Issue Tx polling */ } /* Tx resource check */ if ( db->tx_queue_cnt < TX_FREE_DESC_CNT ) netif_wake_queue(dev); /* Restore CR7 to enable interrupt */ spin_unlock_irqrestore(&db->lock, flags); outl(db->cr7_data, dev->base_addr + DCR7); /* free this SKB */ dev_kfree_skb(skb); return NETDEV_TX_OK; } /* * Stop the interface. * The interface is stopped when it is brought. */ static int dmfe_stop(struct DEVICE *dev) { struct dmfe_board_info *db = netdev_priv(dev); unsigned long ioaddr = dev->base_addr; DMFE_DBUG(0, "dmfe_stop", 0); /* disable system */ netif_stop_queue(dev); /* deleted timer */ del_timer_sync(&db->timer); /* Reset & stop DM910X board */ outl(DM910X_RESET, ioaddr + DCR0); udelay(5); phy_write(db->ioaddr, db->phy_addr, 0, 0x8000, db->chip_id); /* free interrupt */ free_irq(dev->irq, dev); /* free allocated rx buffer */ dmfe_free_rxbuffer(db); #if 0 /* show statistic counter */ printk("FU:%lx EC:%lx LC:%lx NC:%lx LOC:%lx TXJT:%lx RESET:%lx RCR8:%lx FAL:%lx TT:%lx\n", db->tx_fifo_underrun, db->tx_excessive_collision, db->tx_late_collision, db->tx_no_carrier, db->tx_loss_carrier, db->tx_jabber_timeout, db->reset_count, db->reset_cr8, db->reset_fatal, db->reset_TXtimeout); #endif return 0; } /* * DM9102 insterrupt handler * receive the packet to upper layer, free the transmitted packet */ static irqreturn_t dmfe_interrupt(int irq, void *dev_id) { struct DEVICE *dev = dev_id; struct dmfe_board_info *db = netdev_priv(dev); unsigned long ioaddr = dev->base_addr; unsigned long flags; DMFE_DBUG(0, "dmfe_interrupt()", 0); spin_lock_irqsave(&db->lock, flags); /* Got DM910X status */ db->cr5_data = inl(ioaddr + DCR5); outl(db->cr5_data, ioaddr + DCR5); if ( !(db->cr5_data & 0xc1) ) { spin_unlock_irqrestore(&db->lock, flags); return IRQ_HANDLED; } /* Disable all interrupt in CR7 to solve the interrupt edge problem */ outl(0, ioaddr + DCR7); /* Check system status */ if (db->cr5_data & 0x2000) { /* system bus error happen */ DMFE_DBUG(1, "System bus error happen. CR5=", db->cr5_data); db->reset_fatal++; db->wait_reset = 1; /* Need to RESET */ spin_unlock_irqrestore(&db->lock, flags); return IRQ_HANDLED; } /* Received the coming packet */ if ( (db->cr5_data & 0x40) && db->rx_avail_cnt ) dmfe_rx_packet(dev, db); /* reallocate rx descriptor buffer */ if (db->rx_avail_cnt<RX_DESC_CNT) allocate_rx_buffer(db); /* Free the transmitted descriptor */ if ( db->cr5_data & 0x01) dmfe_free_tx_pkt(dev, db); /* Mode Check */ if (db->dm910x_chk_mode & 0x2) { db->dm910x_chk_mode = 0x4; db->cr6_data |= 0x100; update_cr6(db->cr6_data, db->ioaddr); } /* Restore CR7 to enable interrupt mask */ outl(db->cr7_data, ioaddr + DCR7); spin_unlock_irqrestore(&db->lock, flags); return IRQ_HANDLED; } #ifdef CONFIG_NET_POLL_CONTROLLER /* * Polling 'interrupt' - used by things like netconsole to send skbs * without having to re-enable interrupts. It's not called while * the interrupt routine is executing. */ static void poll_dmfe (struct net_device *dev) { /* disable_irq here is not very nice, but with the lockless interrupt handler we have no other choice. */ disable_irq(dev->irq); dmfe_interrupt (dev->irq, dev); enable_irq(dev->irq); } #endif /* * Free TX resource after TX complete */ static void dmfe_free_tx_pkt(struct DEVICE *dev, struct dmfe_board_info * db) { struct tx_desc *txptr; unsigned long ioaddr = dev->base_addr; u32 tdes0; txptr = db->tx_remove_ptr; while(db->tx_packet_cnt) { tdes0 = le32_to_cpu(txptr->tdes0); if (tdes0 & 0x80000000) break; /* A packet sent completed */ db->tx_packet_cnt--; dev->stats.tx_packets++; /* Transmit statistic counter */ if ( tdes0 != 0x7fffffff ) { dev->stats.collisions += (tdes0 >> 3) & 0xf; dev->stats.tx_bytes += le32_to_cpu(txptr->tdes1) & 0x7ff; if (tdes0 & TDES0_ERR_MASK) { dev->stats.tx_errors++; if (tdes0 & 0x0002) { /* UnderRun */ db->tx_fifo_underrun++; if ( !(db->cr6_data & CR6_SFT) ) { db->cr6_data = db->cr6_data | CR6_SFT; update_cr6(db->cr6_data, db->ioaddr); } } if (tdes0 & 0x0100) db->tx_excessive_collision++; if (tdes0 & 0x0200) db->tx_late_collision++; if (tdes0 & 0x0400) db->tx_no_carrier++; if (tdes0 & 0x0800) db->tx_loss_carrier++; if (tdes0 & 0x4000) db->tx_jabber_timeout++; } } txptr = txptr->next_tx_desc; }/* End of while */ /* Update TX remove pointer to next */ db->tx_remove_ptr = txptr; /* Send the Tx packet in queue */ if ( (db->tx_packet_cnt < TX_MAX_SEND_CNT) && db->tx_queue_cnt ) { txptr->tdes0 = cpu_to_le32(0x80000000); /* Set owner bit */ db->tx_packet_cnt++; /* Ready to send */ db->tx_queue_cnt--; outl(0x1, ioaddr + DCR1); /* Issue Tx polling */ dev->trans_start = jiffies; /* saved time stamp */ } /* Resource available check */ if ( db->tx_queue_cnt < TX_WAKE_DESC_CNT ) netif_wake_queue(dev); /* Active upper layer, send again */ } /* * Calculate the CRC valude of the Rx packet * flag = 1 : return the reverse CRC (for the received packet CRC) * 0 : return the normal CRC (for Hash Table index) */ static inline u32 cal_CRC(unsigned char * Data, unsigned int Len, u8 flag) { u32 crc = crc32(~0, Data, Len); if (flag) crc = ~crc; return crc; } /* * Receive the come packet and pass to upper layer */ static void dmfe_rx_packet(struct DEVICE *dev, struct dmfe_board_info * db) { struct rx_desc *rxptr; struct sk_buff *skb, *newskb; int rxlen; u32 rdes0; rxptr = db->rx_ready_ptr; while(db->rx_avail_cnt) { rdes0 = le32_to_cpu(rxptr->rdes0); if (rdes0 & 0x80000000) /* packet owner check */ break; db->rx_avail_cnt--; db->interval_rx_cnt++; pci_unmap_single(db->pdev, le32_to_cpu(rxptr->rdes2), RX_ALLOC_SIZE, PCI_DMA_FROMDEVICE); if ( (rdes0 & 0x300) != 0x300) { /* A packet without First/Last flag */ /* reuse this SKB */ DMFE_DBUG(0, "Reuse SK buffer, rdes0", rdes0); dmfe_reuse_skb(db, rxptr->rx_skb_ptr); } else { /* A packet with First/Last flag */ rxlen = ( (rdes0 >> 16) & 0x3fff) - 4; /* error summary bit check */ if (rdes0 & 0x8000) { /* This is a error packet */ dev->stats.rx_errors++; if (rdes0 & 1) dev->stats.rx_fifo_errors++; if (rdes0 & 2) dev->stats.rx_crc_errors++; if (rdes0 & 0x80) dev->stats.rx_length_errors++; } if ( !(rdes0 & 0x8000) || ((db->cr6_data & CR6_PM) && (rxlen>6)) ) { skb = rxptr->rx_skb_ptr; /* Received Packet CRC check need or not */ if ( (db->dm910x_chk_mode & 1) && (cal_CRC(skb->data, rxlen, 1) != (*(u32 *) (skb->data+rxlen) ))) { /* FIXME (?) */ /* Found a error received packet */ dmfe_reuse_skb(db, rxptr->rx_skb_ptr); db->dm910x_chk_mode = 3; } else { /* Good packet, send to upper layer */ /* Shorst packet used new SKB */ if ((rxlen < RX_COPY_SIZE) && ((newskb = dev_alloc_skb(rxlen + 2)) != NULL)) { skb = newskb; /* size less than COPY_SIZE, allocate a rxlen SKB */ skb_reserve(skb, 2); /* 16byte align */ skb_copy_from_linear_data(rxptr->rx_skb_ptr, skb_put(skb, rxlen), rxlen); dmfe_reuse_skb(db, rxptr->rx_skb_ptr); } else skb_put(skb, rxlen); skb->protocol = eth_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += rxlen; } } else { /* Reuse SKB buffer when the packet is error */ DMFE_DBUG(0, "Reuse SK buffer, rdes0", rdes0); dmfe_reuse_skb(db, rxptr->rx_skb_ptr); } } rxptr = rxptr->next_rx_desc; } db->rx_ready_ptr = rxptr; } /* * Set DM910X multicast address */ static void dmfe_set_filter_mode(struct DEVICE * dev) { struct dmfe_board_info *db = netdev_priv(dev); unsigned long flags; int mc_count = netdev_mc_count(dev); DMFE_DBUG(0, "dmfe_set_filter_mode()", 0); spin_lock_irqsave(&db->lock, flags); if (dev->flags & IFF_PROMISC) { DMFE_DBUG(0, "Enable PROM Mode", 0); db->cr6_data |= CR6_PM | CR6_PBF; update_cr6(db->cr6_data, db->ioaddr); spin_unlock_irqrestore(&db->lock, flags); return; } if (dev->flags & IFF_ALLMULTI || mc_count > DMFE_MAX_MULTICAST) { DMFE_DBUG(0, "Pass all multicast address", mc_count); db->cr6_data &= ~(CR6_PM | CR6_PBF); db->cr6_data |= CR6_PAM; spin_unlock_irqrestore(&db->lock, flags); return; } DMFE_DBUG(0, "Set multicast address", mc_count); if (db->chip_id == PCI_DM9132_ID) dm9132_id_table(dev); /* DM9132 */ else send_filter_frame(dev); /* DM9102/DM9102A */ spin_unlock_irqrestore(&db->lock, flags); } /* * Ethtool interace */ static void dmfe_ethtool_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct dmfe_board_info *np = netdev_priv(dev); strcpy(info->driver, DRV_NAME); strcpy(info->version, DRV_VERSION); if (np->pdev) strcpy(info->bus_info, pci_name(np->pdev)); else sprintf(info->bus_info, "EISA 0x%lx %d", dev->base_addr, dev->irq); } static int dmfe_ethtool_set_wol(struct net_device *dev, struct ethtool_wolinfo *wolinfo) { struct dmfe_board_info *db = netdev_priv(dev); if (wolinfo->wolopts & (WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_ARP | WAKE_MAGICSECURE)) return -EOPNOTSUPP; db->wol_mode = wolinfo->wolopts; return 0; } static void dmfe_ethtool_get_wol(struct net_device *dev, struct ethtool_wolinfo *wolinfo) { struct dmfe_board_info *db = netdev_priv(dev); wolinfo->supported = WAKE_PHY | WAKE_MAGIC; wolinfo->wolopts = db->wol_mode; } static const struct ethtool_ops netdev_ethtool_ops = { .get_drvinfo = dmfe_ethtool_get_drvinfo, .get_link = ethtool_op_get_link, .set_wol = dmfe_ethtool_set_wol, .get_wol = dmfe_ethtool_get_wol, }; /* * A periodic timer routine * Dynamic media sense, allocate Rx buffer... */ static void dmfe_timer(unsigned long data) { u32 tmp_cr8; unsigned char tmp_cr12; struct DEVICE *dev = (struct DEVICE *) data; struct dmfe_board_info *db = netdev_priv(dev); unsigned long flags; int link_ok, link_ok_phy; DMFE_DBUG(0, "dmfe_timer()", 0); spin_lock_irqsave(&db->lock, flags); /* Media mode process when Link OK before enter this route */ if (db->first_in_callback == 0) { db->first_in_callback = 1; if (db->chip_type && (db->chip_id==PCI_DM9102_ID)) { db->cr6_data &= ~0x40000; update_cr6(db->cr6_data, db->ioaddr); phy_write(db->ioaddr, db->phy_addr, 0, 0x1000, db->chip_id); db->cr6_data |= 0x40000; update_cr6(db->cr6_data, db->ioaddr); db->timer.expires = DMFE_TIMER_WUT + HZ * 2; add_timer(&db->timer); spin_unlock_irqrestore(&db->lock, flags); return; } } /* Operating Mode Check */ if ( (db->dm910x_chk_mode & 0x1) && (dev->stats.rx_packets > MAX_CHECK_PACKET) ) db->dm910x_chk_mode = 0x4; /* Dynamic reset DM910X : system error or transmit time-out */ tmp_cr8 = inl(db->ioaddr + DCR8); if ( (db->interval_rx_cnt==0) && (tmp_cr8) ) { db->reset_cr8++; db->wait_reset = 1; } db->interval_rx_cnt = 0; /* TX polling kick monitor */ if ( db->tx_packet_cnt && time_after(jiffies, dev_trans_start(dev) + DMFE_TX_KICK) ) { outl(0x1, dev->base_addr + DCR1); /* Tx polling again */ /* TX Timeout */ if (time_after(jiffies, dev_trans_start(dev) + DMFE_TX_TIMEOUT) ) { db->reset_TXtimeout++; db->wait_reset = 1; dev_warn(&dev->dev, "Tx timeout - resetting\n"); } } if (db->wait_reset) { DMFE_DBUG(0, "Dynamic Reset device", db->tx_packet_cnt); db->reset_count++; dmfe_dynamic_reset(dev); db->first_in_callback = 0; db->timer.expires = DMFE_TIMER_WUT; add_timer(&db->timer); spin_unlock_irqrestore(&db->lock, flags); return; } /* Link status check, Dynamic media type change */ if (db->chip_id == PCI_DM9132_ID) tmp_cr12 = inb(db->ioaddr + DCR9 + 3); /* DM9132 */ else tmp_cr12 = inb(db->ioaddr + DCR12); /* DM9102/DM9102A */ if ( ((db->chip_id == PCI_DM9102_ID) && (db->chip_revision == 0x30)) || ((db->chip_id == PCI_DM9132_ID) && (db->chip_revision == 0x10)) ) { /* DM9102A Chip */ if (tmp_cr12 & 2) link_ok = 0; else link_ok = 1; } else /*0x43 is used instead of 0x3 because bit 6 should represent link status of external PHY */ link_ok = (tmp_cr12 & 0x43) ? 1 : 0; /* If chip reports that link is failed it could be because external PHY link status pin is not connected correctly to chip To be sure ask PHY too. */ /* need a dummy read because of PHY's register latch*/ phy_read (db->ioaddr, db->phy_addr, 1, db->chip_id); link_ok_phy = (phy_read (db->ioaddr, db->phy_addr, 1, db->chip_id) & 0x4) ? 1 : 0; if (link_ok_phy != link_ok) { DMFE_DBUG (0, "PHY and chip report different link status", 0); link_ok = link_ok | link_ok_phy; } if ( !link_ok && netif_carrier_ok(dev)) { /* Link Failed */ DMFE_DBUG(0, "Link Failed", tmp_cr12); netif_carrier_off(dev); /* For Force 10/100M Half/Full mode: Enable Auto-Nego mode */ /* AUTO or force 1M Homerun/Longrun don't need */ if ( !(db->media_mode & 0x38) ) phy_write(db->ioaddr, db->phy_addr, 0, 0x1000, db->chip_id); /* AUTO mode, if INT phyxcer link failed, select EXT device */ if (db->media_mode & DMFE_AUTO) { /* 10/100M link failed, used 1M Home-Net */ db->cr6_data|=0x00040000; /* bit18=1, MII */ db->cr6_data&=~0x00000200; /* bit9=0, HD mode */ update_cr6(db->cr6_data, db->ioaddr); } } else if (!netif_carrier_ok(dev)) { DMFE_DBUG(0, "Link link OK", tmp_cr12); /* Auto Sense Speed */ if ( !(db->media_mode & DMFE_AUTO) || !dmfe_sense_speed(db)) { netif_carrier_on(dev); SHOW_MEDIA_TYPE(db->op_mode); } dmfe_process_mode(db); } /* HPNA remote command check */ if (db->HPNA_command & 0xf00) { db->HPNA_timer--; if (!db->HPNA_timer) dmfe_HPNA_remote_cmd_chk(db); } /* Timer active again */ db->timer.expires = DMFE_TIMER_WUT; add_timer(&db->timer); spin_unlock_irqrestore(&db->lock, flags); } /* * Dynamic reset the DM910X board * Stop DM910X board * Free Tx/Rx allocated memory * Reset DM910X board * Re-initialize DM910X board */ static void dmfe_dynamic_reset(struct DEVICE *dev) { struct dmfe_board_info *db = netdev_priv(dev); DMFE_DBUG(0, "dmfe_dynamic_reset()", 0); /* Sopt MAC controller */ db->cr6_data &= ~(CR6_RXSC | CR6_TXSC); /* Disable Tx/Rx */ update_cr6(db->cr6_data, dev->base_addr); outl(0, dev->base_addr + DCR7); /* Disable Interrupt */ outl(inl(dev->base_addr + DCR5), dev->base_addr + DCR5); /* Disable upper layer interface */ netif_stop_queue(dev); /* Free Rx Allocate buffer */ dmfe_free_rxbuffer(db); /* system variable init */ db->tx_packet_cnt = 0; db->tx_queue_cnt = 0; db->rx_avail_cnt = 0; netif_carrier_off(dev); db->wait_reset = 0; /* Re-initialize DM910X board */ dmfe_init_dm910x(dev); /* Restart upper layer interface */ netif_wake_queue(dev); } /* * free all allocated rx buffer */ static void dmfe_free_rxbuffer(struct dmfe_board_info * db) { DMFE_DBUG(0, "dmfe_free_rxbuffer()", 0); /* free allocated rx buffer */ while (db->rx_avail_cnt) { dev_kfree_skb(db->rx_ready_ptr->rx_skb_ptr); db->rx_ready_ptr = db->rx_ready_ptr->next_rx_desc; db->rx_avail_cnt--; } } /* * Reuse the SK buffer */ static void dmfe_reuse_skb(struct dmfe_board_info *db, struct sk_buff * skb) { struct rx_desc *rxptr = db->rx_insert_ptr; if (!(rxptr->rdes0 & cpu_to_le32(0x80000000))) { rxptr->rx_skb_ptr = skb; rxptr->rdes2 = cpu_to_le32( pci_map_single(db->pdev, skb->data, RX_ALLOC_SIZE, PCI_DMA_FROMDEVICE) ); wmb(); rxptr->rdes0 = cpu_to_le32(0x80000000); db->rx_avail_cnt++; db->rx_insert_ptr = rxptr->next_rx_desc; } else DMFE_DBUG(0, "SK Buffer reuse method error", db->rx_avail_cnt); } /* * Initialize transmit/Receive descriptor * Using Chain structure, and allocate Tx/Rx buffer */ static void dmfe_descriptor_init(struct dmfe_board_info *db, unsigned long ioaddr) { struct tx_desc *tmp_tx; struct rx_desc *tmp_rx; unsigned char *tmp_buf; dma_addr_t tmp_tx_dma, tmp_rx_dma; dma_addr_t tmp_buf_dma; int i; DMFE_DBUG(0, "dmfe_descriptor_init()", 0); /* tx descriptor start pointer */ db->tx_insert_ptr = db->first_tx_desc; db->tx_remove_ptr = db->first_tx_desc; outl(db->first_tx_desc_dma, ioaddr + DCR4); /* TX DESC address */ /* rx descriptor start pointer */ db->first_rx_desc = (void *)db->first_tx_desc + sizeof(struct tx_desc) * TX_DESC_CNT; db->first_rx_desc_dma = db->first_tx_desc_dma + sizeof(struct tx_desc) * TX_DESC_CNT; db->rx_insert_ptr = db->first_rx_desc; db->rx_ready_ptr = db->first_rx_desc; outl(db->first_rx_desc_dma, ioaddr + DCR3); /* RX DESC address */ /* Init Transmit chain */ tmp_buf = db->buf_pool_start; tmp_buf_dma = db->buf_pool_dma_start; tmp_tx_dma = db->first_tx_desc_dma; for (tmp_tx = db->first_tx_desc, i = 0; i < TX_DESC_CNT; i++, tmp_tx++) { tmp_tx->tx_buf_ptr = tmp_buf; tmp_tx->tdes0 = cpu_to_le32(0); tmp_tx->tdes1 = cpu_to_le32(0x81000000); /* IC, chain */ tmp_tx->tdes2 = cpu_to_le32(tmp_buf_dma); tmp_tx_dma += sizeof(struct tx_desc); tmp_tx->tdes3 = cpu_to_le32(tmp_tx_dma); tmp_tx->next_tx_desc = tmp_tx + 1; tmp_buf = tmp_buf + TX_BUF_ALLOC; tmp_buf_dma = tmp_buf_dma + TX_BUF_ALLOC; } (--tmp_tx)->tdes3 = cpu_to_le32(db->first_tx_desc_dma); tmp_tx->next_tx_desc = db->first_tx_desc; /* Init Receive descriptor chain */ tmp_rx_dma=db->first_rx_desc_dma; for (tmp_rx = db->first_rx_desc, i = 0; i < RX_DESC_CNT; i++, tmp_rx++) { tmp_rx->rdes0 = cpu_to_le32(0); tmp_rx->rdes1 = cpu_to_le32(0x01000600); tmp_rx_dma += sizeof(struct rx_desc); tmp_rx->rdes3 = cpu_to_le32(tmp_rx_dma); tmp_rx->next_rx_desc = tmp_rx + 1; } (--tmp_rx)->rdes3 = cpu_to_le32(db->first_rx_desc_dma); tmp_rx->next_rx_desc = db->first_rx_desc; /* pre-allocate Rx buffer */ allocate_rx_buffer(db); } /* * Update CR6 value * Firstly stop DM910X , then written value and start */ static void update_cr6(u32 cr6_data, unsigned long ioaddr) { u32 cr6_tmp; cr6_tmp = cr6_data & ~0x2002; /* stop Tx/Rx */ outl(cr6_tmp, ioaddr + DCR6); udelay(5); outl(cr6_data, ioaddr + DCR6); udelay(5); } /* * Send a setup frame for DM9132 * This setup frame initialize DM910X address filter mode */ static void dm9132_id_table(struct DEVICE *dev) { struct netdev_hw_addr *ha; u16 * addrptr; unsigned long ioaddr = dev->base_addr+0xc0; /* ID Table */ u32 hash_val; u16 i, hash_table[4]; DMFE_DBUG(0, "dm9132_id_table()", 0); /* Node address */ addrptr = (u16 *) dev->dev_addr; outw(addrptr[0], ioaddr); ioaddr += 4; outw(addrptr[1], ioaddr); ioaddr += 4; outw(addrptr[2], ioaddr); ioaddr += 4; /* Clear Hash Table */ memset(hash_table, 0, sizeof(hash_table)); /* broadcast address */ hash_table[3] = 0x8000; /* the multicast address in Hash Table : 64 bits */ netdev_for_each_mc_addr(ha, dev) { hash_val = cal_CRC((char *) ha->addr, 6, 0) & 0x3f; hash_table[hash_val / 16] |= (u16) 1 << (hash_val % 16); } /* Write the hash table to MAC MD table */ for (i = 0; i < 4; i++, ioaddr += 4) outw(hash_table[i], ioaddr); } /* * Send a setup frame for DM9102/DM9102A * This setup frame initialize DM910X address filter mode */ static void send_filter_frame(struct DEVICE *dev) { struct dmfe_board_info *db = netdev_priv(dev); struct netdev_hw_addr *ha; struct tx_desc *txptr; u16 * addrptr; u32 * suptr; int i; DMFE_DBUG(0, "send_filter_frame()", 0); txptr = db->tx_insert_ptr; suptr = (u32 *) txptr->tx_buf_ptr; /* Node address */ addrptr = (u16 *) dev->dev_addr; *suptr++ = addrptr[0]; *suptr++ = addrptr[1]; *suptr++ = addrptr[2]; /* broadcast address */ *suptr++ = 0xffff; *suptr++ = 0xffff; *suptr++ = 0xffff; /* fit the multicast address */ netdev_for_each_mc_addr(ha, dev) { addrptr = (u16 *) ha->addr; *suptr++ = addrptr[0]; *suptr++ = addrptr[1]; *suptr++ = addrptr[2]; } for (i = netdev_mc_count(dev); i < 14; i++) { *suptr++ = 0xffff; *suptr++ = 0xffff; *suptr++ = 0xffff; } /* prepare the setup frame */ db->tx_insert_ptr = txptr->next_tx_desc; txptr->tdes1 = cpu_to_le32(0x890000c0); /* Resource Check and Send the setup packet */ if (!db->tx_packet_cnt) { /* Resource Empty */ db->tx_packet_cnt++; txptr->tdes0 = cpu_to_le32(0x80000000); update_cr6(db->cr6_data | 0x2000, dev->base_addr); outl(0x1, dev->base_addr + DCR1); /* Issue Tx polling */ update_cr6(db->cr6_data, dev->base_addr); dev->trans_start = jiffies; } else db->tx_queue_cnt++; /* Put in TX queue */ } /* * Allocate rx buffer, * As possible as allocate maxiumn Rx buffer */ static void allocate_rx_buffer(struct dmfe_board_info *db) { struct rx_desc *rxptr; struct sk_buff *skb; rxptr = db->rx_insert_ptr; while(db->rx_avail_cnt < RX_DESC_CNT) { if ( ( skb = dev_alloc_skb(RX_ALLOC_SIZE) ) == NULL ) break; rxptr->rx_skb_ptr = skb; /* FIXME (?) */ rxptr->rdes2 = cpu_to_le32( pci_map_single(db->pdev, skb->data, RX_ALLOC_SIZE, PCI_DMA_FROMDEVICE) ); wmb(); rxptr->rdes0 = cpu_to_le32(0x80000000); rxptr = rxptr->next_rx_desc; db->rx_avail_cnt++; } db->rx_insert_ptr = rxptr; } /* * Read one word data from the serial ROM */ static u16 read_srom_word(long ioaddr, int offset) { int i; u16 srom_data = 0; long cr9_ioaddr = ioaddr + DCR9; outl(CR9_SROM_READ, cr9_ioaddr); outl(CR9_SROM_READ | CR9_SRCS, cr9_ioaddr); /* Send the Read Command 110b */ SROM_CLK_WRITE(SROM_DATA_1, cr9_ioaddr); SROM_CLK_WRITE(SROM_DATA_1, cr9_ioaddr); SROM_CLK_WRITE(SROM_DATA_0, cr9_ioaddr); /* Send the offset */ for (i = 5; i >= 0; i--) { srom_data = (offset & (1 << i)) ? SROM_DATA_1 : SROM_DATA_0; SROM_CLK_WRITE(srom_data, cr9_ioaddr); } outl(CR9_SROM_READ | CR9_SRCS, cr9_ioaddr); for (i = 16; i > 0; i--) { outl(CR9_SROM_READ | CR9_SRCS | CR9_SRCLK, cr9_ioaddr); udelay(5); srom_data = (srom_data << 1) | ((inl(cr9_ioaddr) & CR9_CRDOUT) ? 1 : 0); outl(CR9_SROM_READ | CR9_SRCS, cr9_ioaddr); udelay(5); } outl(CR9_SROM_READ, cr9_ioaddr); return srom_data; } /* * Auto sense the media mode */ static u8 dmfe_sense_speed(struct dmfe_board_info * db) { u8 ErrFlag = 0; u16 phy_mode; /* CR6 bit18=0, select 10/100M */ update_cr6( (db->cr6_data & ~0x40000), db->ioaddr); phy_mode = phy_read(db->ioaddr, db->phy_addr, 1, db->chip_id); phy_mode = phy_read(db->ioaddr, db->phy_addr, 1, db->chip_id); if ( (phy_mode & 0x24) == 0x24 ) { if (db->chip_id == PCI_DM9132_ID) /* DM9132 */ phy_mode = phy_read(db->ioaddr, db->phy_addr, 7, db->chip_id) & 0xf000; else /* DM9102/DM9102A */ phy_mode = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id) & 0xf000; switch (phy_mode) { case 0x1000: db->op_mode = DMFE_10MHF; break; case 0x2000: db->op_mode = DMFE_10MFD; break; case 0x4000: db->op_mode = DMFE_100MHF; break; case 0x8000: db->op_mode = DMFE_100MFD; break; default: db->op_mode = DMFE_10MHF; ErrFlag = 1; break; } } else { db->op_mode = DMFE_10MHF; DMFE_DBUG(0, "Link Failed :", phy_mode); ErrFlag = 1; } return ErrFlag; } /* * Set 10/100 phyxcer capability * AUTO mode : phyxcer register4 is NIC capability * Force mode: phyxcer register4 is the force media */ static void dmfe_set_phyxcer(struct dmfe_board_info *db) { u16 phy_reg; /* Select 10/100M phyxcer */ db->cr6_data &= ~0x40000; update_cr6(db->cr6_data, db->ioaddr); /* DM9009 Chip: Phyxcer reg18 bit12=0 */ if (db->chip_id == PCI_DM9009_ID) { phy_reg = phy_read(db->ioaddr, db->phy_addr, 18, db->chip_id) & ~0x1000; phy_write(db->ioaddr, db->phy_addr, 18, phy_reg, db->chip_id); } /* Phyxcer capability setting */ phy_reg = phy_read(db->ioaddr, db->phy_addr, 4, db->chip_id) & ~0x01e0; if (db->media_mode & DMFE_AUTO) { /* AUTO Mode */ phy_reg |= db->PHY_reg4; } else { /* Force Mode */ switch(db->media_mode) { case DMFE_10MHF: phy_reg |= 0x20; break; case DMFE_10MFD: phy_reg |= 0x40; break; case DMFE_100MHF: phy_reg |= 0x80; break; case DMFE_100MFD: phy_reg |= 0x100; break; } if (db->chip_id == PCI_DM9009_ID) phy_reg &= 0x61; } /* Write new capability to Phyxcer Reg4 */ if ( !(phy_reg & 0x01e0)) { phy_reg|=db->PHY_reg4; db->media_mode|=DMFE_AUTO; } phy_write(db->ioaddr, db->phy_addr, 4, phy_reg, db->chip_id); /* Restart Auto-Negotiation */ if ( db->chip_type && (db->chip_id == PCI_DM9102_ID) ) phy_write(db->ioaddr, db->phy_addr, 0, 0x1800, db->chip_id); if ( !db->chip_type ) phy_write(db->ioaddr, db->phy_addr, 0, 0x1200, db->chip_id); } /* * Process op-mode * AUTO mode : PHY controller in Auto-negotiation Mode * Force mode: PHY controller in force mode with HUB * N-way force capability with SWITCH */ static void dmfe_process_mode(struct dmfe_board_info *db) { u16 phy_reg; /* Full Duplex Mode Check */ if (db->op_mode & 0x4) db->cr6_data |= CR6_FDM; /* Set Full Duplex Bit */ else db->cr6_data &= ~CR6_FDM; /* Clear Full Duplex Bit */ /* Transciver Selection */ if (db->op_mode & 0x10) /* 1M HomePNA */ db->cr6_data |= 0x40000;/* External MII select */ else db->cr6_data &= ~0x40000;/* Internal 10/100 transciver */ update_cr6(db->cr6_data, db->ioaddr); /* 10/100M phyxcer force mode need */ if ( !(db->media_mode & 0x18)) { /* Forece Mode */ phy_reg = phy_read(db->ioaddr, db->phy_addr, 6, db->chip_id); if ( !(phy_reg & 0x1) ) { /* parter without N-Way capability */ phy_reg = 0x0; switch(db->op_mode) { case DMFE_10MHF: phy_reg = 0x0; break; case DMFE_10MFD: phy_reg = 0x100; break; case DMFE_100MHF: phy_reg = 0x2000; break; case DMFE_100MFD: phy_reg = 0x2100; break; } phy_write(db->ioaddr, db->phy_addr, 0, phy_reg, db->chip_id); if ( db->chip_type && (db->chip_id == PCI_DM9102_ID) ) mdelay(20); phy_write(db->ioaddr, db->phy_addr, 0, phy_reg, db->chip_id); } } } /* * Write a word to Phy register */ static void phy_write(unsigned long iobase, u8 phy_addr, u8 offset, u16 phy_data, u32 chip_id) { u16 i; unsigned long ioaddr; if (chip_id == PCI_DM9132_ID) { ioaddr = iobase + 0x80 + offset * 4; outw(phy_data, ioaddr); } else { /* DM9102/DM9102A Chip */ ioaddr = iobase + DCR9; /* Send 33 synchronization clock to Phy controller */ for (i = 0; i < 35; i++) phy_write_1bit(ioaddr, PHY_DATA_1); /* Send start command(01) to Phy */ phy_write_1bit(ioaddr, PHY_DATA_0); phy_write_1bit(ioaddr, PHY_DATA_1); /* Send write command(01) to Phy */ phy_write_1bit(ioaddr, PHY_DATA_0); phy_write_1bit(ioaddr, PHY_DATA_1); /* Send Phy address */ for (i = 0x10; i > 0; i = i >> 1) phy_write_1bit(ioaddr, phy_addr & i ? PHY_DATA_1 : PHY_DATA_0); /* Send register address */ for (i = 0x10; i > 0; i = i >> 1) phy_write_1bit(ioaddr, offset & i ? PHY_DATA_1 : PHY_DATA_0); /* written trasnition */ phy_write_1bit(ioaddr, PHY_DATA_1); phy_write_1bit(ioaddr, PHY_DATA_0); /* Write a word data to PHY controller */ for ( i = 0x8000; i > 0; i >>= 1) phy_write_1bit(ioaddr, phy_data & i ? PHY_DATA_1 : PHY_DATA_0); } } /* * Read a word data from phy register */ static u16 phy_read(unsigned long iobase, u8 phy_addr, u8 offset, u32 chip_id) { int i; u16 phy_data; unsigned long ioaddr; if (chip_id == PCI_DM9132_ID) { /* DM9132 Chip */ ioaddr = iobase + 0x80 + offset * 4; phy_data = inw(ioaddr); } else { /* DM9102/DM9102A Chip */ ioaddr = iobase + DCR9; /* Send 33 synchronization clock to Phy controller */ for (i = 0; i < 35; i++) phy_write_1bit(ioaddr, PHY_DATA_1); /* Send start command(01) to Phy */ phy_write_1bit(ioaddr, PHY_DATA_0); phy_write_1bit(ioaddr, PHY_DATA_1); /* Send read command(10) to Phy */ phy_write_1bit(ioaddr, PHY_DATA_1); phy_write_1bit(ioaddr, PHY_DATA_0); /* Send Phy address */ for (i = 0x10; i > 0; i = i >> 1) phy_write_1bit(ioaddr, phy_addr & i ? PHY_DATA_1 : PHY_DATA_0); /* Send register address */ for (i = 0x10; i > 0; i = i >> 1) phy_write_1bit(ioaddr, offset & i ? PHY_DATA_1 : PHY_DATA_0); /* Skip transition state */ phy_read_1bit(ioaddr); /* read 16bit data */ for (phy_data = 0, i = 0; i < 16; i++) { phy_data <<= 1; phy_data |= phy_read_1bit(ioaddr); } } return phy_data; } /* * Write one bit data to Phy Controller */ static void phy_write_1bit(unsigned long ioaddr, u32 phy_data) { outl(phy_data, ioaddr); /* MII Clock Low */ udelay(1); outl(phy_data | MDCLKH, ioaddr); /* MII Clock High */ udelay(1); outl(phy_data, ioaddr); /* MII Clock Low */ udelay(1); } /* * Read one bit phy data from PHY controller */ static u16 phy_read_1bit(unsigned long ioaddr) { u16 phy_data; outl(0x50000, ioaddr); udelay(1); phy_data = ( inl(ioaddr) >> 19 ) & 0x1; outl(0x40000, ioaddr); udelay(1); return phy_data; } /* * Parser SROM and media mode */ static void dmfe_parse_srom(struct dmfe_board_info * db) { char * srom = db->srom; int dmfe_mode, tmp_reg; DMFE_DBUG(0, "dmfe_parse_srom() ", 0); /* Init CR15 */ db->cr15_data = CR15_DEFAULT; /* Check SROM Version */ if ( ( (int) srom[18] & 0xff) == SROM_V41_CODE) { /* SROM V4.01 */ /* Get NIC support media mode */ db->NIC_capability = le16_to_cpup((__le16 *) (srom + 34)); db->PHY_reg4 = 0; for (tmp_reg = 1; tmp_reg < 0x10; tmp_reg <<= 1) { switch( db->NIC_capability & tmp_reg ) { case 0x1: db->PHY_reg4 |= 0x0020; break; case 0x2: db->PHY_reg4 |= 0x0040; break; case 0x4: db->PHY_reg4 |= 0x0080; break; case 0x8: db->PHY_reg4 |= 0x0100; break; } } /* Media Mode Force or not check */ dmfe_mode = (le32_to_cpup((__le32 *) (srom + 34)) & le32_to_cpup((__le32 *) (srom + 36))); switch(dmfe_mode) { case 0x4: dmfe_media_mode = DMFE_100MHF; break; /* 100MHF */ case 0x2: dmfe_media_mode = DMFE_10MFD; break; /* 10MFD */ case 0x8: dmfe_media_mode = DMFE_100MFD; break; /* 100MFD */ case 0x100: case 0x200: dmfe_media_mode = DMFE_1M_HPNA; break;/* HomePNA */ } /* Special Function setting */ /* VLAN function */ if ( (SF_mode & 0x1) || (srom[43] & 0x80) ) db->cr15_data |= 0x40; /* Flow Control */ if ( (SF_mode & 0x2) || (srom[40] & 0x1) ) db->cr15_data |= 0x400; /* TX pause packet */ if ( (SF_mode & 0x4) || (srom[40] & 0xe) ) db->cr15_data |= 0x9800; } /* Parse HPNA parameter */ db->HPNA_command = 1; /* Accept remote command or not */ if (HPNA_rx_cmd == 0) db->HPNA_command |= 0x8000; /* Issue remote command & operation mode */ if (HPNA_tx_cmd == 1) switch(HPNA_mode) { /* Issue Remote Command */ case 0: db->HPNA_command |= 0x0904; break; case 1: db->HPNA_command |= 0x0a00; break; case 2: db->HPNA_command |= 0x0506; break; case 3: db->HPNA_command |= 0x0602; break; } else switch(HPNA_mode) { /* Don't Issue */ case 0: db->HPNA_command |= 0x0004; break; case 1: db->HPNA_command |= 0x0000; break; case 2: db->HPNA_command |= 0x0006; break; case 3: db->HPNA_command |= 0x0002; break; } /* Check DM9801 or DM9802 present or not */ db->HPNA_present = 0; update_cr6(db->cr6_data|0x40000, db->ioaddr); tmp_reg = phy_read(db->ioaddr, db->phy_addr, 3, db->chip_id); if ( ( tmp_reg & 0xfff0 ) == 0xb900 ) { /* DM9801 or DM9802 present */ db->HPNA_timer = 8; if ( phy_read(db->ioaddr, db->phy_addr, 31, db->chip_id) == 0x4404) { /* DM9801 HomeRun */ db->HPNA_present = 1; dmfe_program_DM9801(db, tmp_reg); } else { /* DM9802 LongRun */ db->HPNA_present = 2; dmfe_program_DM9802(db); } } } /* * Init HomeRun DM9801 */ static void dmfe_program_DM9801(struct dmfe_board_info * db, int HPNA_rev) { uint reg17, reg25; if ( !HPNA_NoiseFloor ) HPNA_NoiseFloor = DM9801_NOISE_FLOOR; switch(HPNA_rev) { case 0xb900: /* DM9801 E3 */ db->HPNA_command |= 0x1000; reg25 = phy_read(db->ioaddr, db->phy_addr, 24, db->chip_id); reg25 = ( (reg25 + HPNA_NoiseFloor) & 0xff) | 0xf000; reg17 = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id); break; case 0xb901: /* DM9801 E4 */ reg25 = phy_read(db->ioaddr, db->phy_addr, 25, db->chip_id); reg25 = (reg25 & 0xff00) + HPNA_NoiseFloor; reg17 = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id); reg17 = (reg17 & 0xfff0) + HPNA_NoiseFloor + 3; break; case 0xb902: /* DM9801 E5 */ case 0xb903: /* DM9801 E6 */ default: db->HPNA_command |= 0x1000; reg25 = phy_read(db->ioaddr, db->phy_addr, 25, db->chip_id); reg25 = (reg25 & 0xff00) + HPNA_NoiseFloor - 5; reg17 = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id); reg17 = (reg17 & 0xfff0) + HPNA_NoiseFloor; break; } phy_write(db->ioaddr, db->phy_addr, 16, db->HPNA_command, db->chip_id); phy_write(db->ioaddr, db->phy_addr, 17, reg17, db->chip_id); phy_write(db->ioaddr, db->phy_addr, 25, reg25, db->chip_id); } /* * Init HomeRun DM9802 */ static void dmfe_program_DM9802(struct dmfe_board_info * db) { uint phy_reg; if ( !HPNA_NoiseFloor ) HPNA_NoiseFloor = DM9802_NOISE_FLOOR; phy_write(db->ioaddr, db->phy_addr, 16, db->HPNA_command, db->chip_id); phy_reg = phy_read(db->ioaddr, db->phy_addr, 25, db->chip_id); phy_reg = ( phy_reg & 0xff00) + HPNA_NoiseFloor; phy_write(db->ioaddr, db->phy_addr, 25, phy_reg, db->chip_id); } /* * Check remote HPNA power and speed status. If not correct, * issue command again. */ static void dmfe_HPNA_remote_cmd_chk(struct dmfe_board_info * db) { uint phy_reg; /* Got remote device status */ phy_reg = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id) & 0x60; switch(phy_reg) { case 0x00: phy_reg = 0x0a00;break; /* LP/LS */ case 0x20: phy_reg = 0x0900;break; /* LP/HS */ case 0x40: phy_reg = 0x0600;break; /* HP/LS */ case 0x60: phy_reg = 0x0500;break; /* HP/HS */ } /* Check remote device status match our setting ot not */ if ( phy_reg != (db->HPNA_command & 0x0f00) ) { phy_write(db->ioaddr, db->phy_addr, 16, db->HPNA_command, db->chip_id); db->HPNA_timer=8; } else db->HPNA_timer=600; /* Match, every 10 minutes, check */ } static DEFINE_PCI_DEVICE_TABLE(dmfe_pci_tbl) = { { 0x1282, 0x9132, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9132_ID }, { 0x1282, 0x9102, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9102_ID }, { 0x1282, 0x9100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9100_ID }, { 0x1282, 0x9009, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9009_ID }, { 0, } }; MODULE_DEVICE_TABLE(pci, dmfe_pci_tbl); #ifdef CONFIG_PM static int dmfe_suspend(struct pci_dev *pci_dev, pm_message_t state) { struct net_device *dev = pci_get_drvdata(pci_dev); struct dmfe_board_info *db = netdev_priv(dev); u32 tmp; /* Disable upper layer interface */ netif_device_detach(dev); /* Disable Tx/Rx */ db->cr6_data &= ~(CR6_RXSC | CR6_TXSC); update_cr6(db->cr6_data, dev->base_addr); /* Disable Interrupt */ outl(0, dev->base_addr + DCR7); outl(inl (dev->base_addr + DCR5), dev->base_addr + DCR5); /* Fre RX buffers */ dmfe_free_rxbuffer(db); /* Enable WOL */ pci_read_config_dword(pci_dev, 0x40, &tmp); tmp &= ~(DMFE_WOL_LINKCHANGE|DMFE_WOL_MAGICPACKET); if (db->wol_mode & WAKE_PHY) tmp |= DMFE_WOL_LINKCHANGE; if (db->wol_mode & WAKE_MAGIC) tmp |= DMFE_WOL_MAGICPACKET; pci_write_config_dword(pci_dev, 0x40, tmp); pci_enable_wake(pci_dev, PCI_D3hot, 1); pci_enable_wake(pci_dev, PCI_D3cold, 1); /* Power down device*/ pci_save_state(pci_dev); pci_set_power_state(pci_dev, pci_choose_state (pci_dev, state)); return 0; } static int dmfe_resume(struct pci_dev *pci_dev) { struct net_device *dev = pci_get_drvdata(pci_dev); u32 tmp; pci_set_power_state(pci_dev, PCI_D0); pci_restore_state(pci_dev); /* Re-initialize DM910X board */ dmfe_init_dm910x(dev); /* Disable WOL */ pci_read_config_dword(pci_dev, 0x40, &tmp); tmp &= ~(DMFE_WOL_LINKCHANGE | DMFE_WOL_MAGICPACKET); pci_write_config_dword(pci_dev, 0x40, tmp); pci_enable_wake(pci_dev, PCI_D3hot, 0); pci_enable_wake(pci_dev, PCI_D3cold, 0); /* Restart upper layer interface */ netif_device_attach(dev); return 0; } #else #define dmfe_suspend NULL #define dmfe_resume NULL #endif static struct pci_driver dmfe_driver = { .name = "dmfe", .id_table = dmfe_pci_tbl, .probe = dmfe_init_one, .remove = __devexit_p(dmfe_remove_one), .suspend = dmfe_suspend, .resume = dmfe_resume }; MODULE_AUTHOR("Sten Wang, sten_wang@davicom.com.tw"); MODULE_DESCRIPTION("Davicom DM910X fast ethernet driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); module_param(debug, int, 0); module_param(mode, byte, 0); module_param(cr6set, int, 0); module_param(chkmode, byte, 0); module_param(HPNA_mode, byte, 0); module_param(HPNA_rx_cmd, byte, 0); module_param(HPNA_tx_cmd, byte, 0); module_param(HPNA_NoiseFloor, byte, 0); module_param(SF_mode, byte, 0); MODULE_PARM_DESC(debug, "Davicom DM9xxx enable debugging (0-1)"); MODULE_PARM_DESC(mode, "Davicom DM9xxx: " "Bit 0: 10/100Mbps, bit 2: duplex, bit 8: HomePNA"); MODULE_PARM_DESC(SF_mode, "Davicom DM9xxx special function " "(bit 0: VLAN, bit 1 Flow Control, bit 2: TX pause packet)"); /* Description: * when user used insmod to add module, system invoked init_module() * to initialize and register. */ static int __init dmfe_init_module(void) { int rc; pr_info("%s\n", version); printed_version = 1; DMFE_DBUG(0, "init_module() ", debug); if (debug) dmfe_debug = debug; /* set debug flag */ if (cr6set) dmfe_cr6_user_set = cr6set; switch(mode) { case DMFE_10MHF: case DMFE_100MHF: case DMFE_10MFD: case DMFE_100MFD: case DMFE_1M_HPNA: dmfe_media_mode = mode; break; default:dmfe_media_mode = DMFE_AUTO; break; } if (HPNA_mode > 4) HPNA_mode = 0; /* Default: LP/HS */ if (HPNA_rx_cmd > 1) HPNA_rx_cmd = 0; /* Default: Ignored remote cmd */ if (HPNA_tx_cmd > 1) HPNA_tx_cmd = 0; /* Default: Don't issue remote cmd */ if (HPNA_NoiseFloor > 15) HPNA_NoiseFloor = 0; rc = pci_register_driver(&dmfe_driver); if (rc < 0) return rc; return 0; } /* * Description: * when user used rmmod to delete module, system invoked clean_module() * to un-register all registered services. */ static void __exit dmfe_cleanup_module(void) { DMFE_DBUG(0, "dmfe_clean_module() ", debug); pci_unregister_driver(&dmfe_driver); } module_init(dmfe_init_module); module_exit(dmfe_cleanup_module);
gpl-2.0
carlocaione/geniatech-kernel
drivers/net/wireless/iwlegacy/iwl-sta.c
3018
23310
/****************************************************************************** * * Copyright(c) 2003 - 2011 Intel Corporation. All rights reserved. * * Portions of this file are derived from the ipw3945 project, as well * as portions of the ieee80211 subsystem header files. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * Intel Linux Wireless <ilw@linux.intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * *****************************************************************************/ #include <net/mac80211.h> #include <linux/etherdevice.h> #include <linux/sched.h> #include <linux/lockdep.h> #include "iwl-dev.h" #include "iwl-core.h" #include "iwl-sta.h" /* priv->sta_lock must be held */ static void iwl_legacy_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id) { if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u addr %pM\n", sta_id, priv->stations[sta_id].sta.sta.addr); if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_ASSOC(priv, "STA id %u addr %pM already present" " in uCode (according to driver)\n", sta_id, priv->stations[sta_id].sta.sta.addr); } else { priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE; IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n", sta_id, priv->stations[sta_id].sta.sta.addr); } } static int iwl_legacy_process_add_sta_resp(struct iwl_priv *priv, struct iwl_legacy_addsta_cmd *addsta, struct iwl_rx_packet *pkt, bool sync) { u8 sta_id = addsta->sta.sta_id; unsigned long flags; int ret = -EIO; if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) { IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n", pkt->hdr.flags); return ret; } IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n", sta_id); spin_lock_irqsave(&priv->sta_lock, flags); switch (pkt->u.add_sta.status) { case ADD_STA_SUCCESS_MSK: IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n"); iwl_legacy_sta_ucode_activate(priv, sta_id); ret = 0; break; case ADD_STA_NO_ROOM_IN_TABLE: IWL_ERR(priv, "Adding station %d failed, no room in table.\n", sta_id); break; case ADD_STA_NO_BLOCK_ACK_RESOURCE: IWL_ERR(priv, "Adding station %d failed, no block ack resource.\n", sta_id); break; case ADD_STA_MODIFY_NON_EXIST_STA: IWL_ERR(priv, "Attempting to modify non-existing station %d\n", sta_id); break; default: IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n", pkt->u.add_sta.status); break; } IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n", priv->stations[sta_id].sta.mode == STA_CONTROL_MODIFY_MSK ? "Modified" : "Added", sta_id, priv->stations[sta_id].sta.sta.addr); /* * XXX: The MAC address in the command buffer is often changed from * the original sent to the device. That is, the MAC address * written to the command buffer often is not the same MAC address * read from the command buffer when the command returns. This * issue has not yet been resolved and this debugging is left to * observe the problem. */ IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n", priv->stations[sta_id].sta.mode == STA_CONTROL_MODIFY_MSK ? "Modified" : "Added", addsta->sta.addr); spin_unlock_irqrestore(&priv->sta_lock, flags); return ret; } static void iwl_legacy_add_sta_callback(struct iwl_priv *priv, struct iwl_device_cmd *cmd, struct iwl_rx_packet *pkt) { struct iwl_legacy_addsta_cmd *addsta = (struct iwl_legacy_addsta_cmd *)cmd->cmd.payload; iwl_legacy_process_add_sta_resp(priv, addsta, pkt, false); } int iwl_legacy_send_add_sta(struct iwl_priv *priv, struct iwl_legacy_addsta_cmd *sta, u8 flags) { struct iwl_rx_packet *pkt = NULL; int ret = 0; u8 data[sizeof(*sta)]; struct iwl_host_cmd cmd = { .id = REPLY_ADD_STA, .flags = flags, .data = data, }; u8 sta_id __maybe_unused = sta->sta.sta_id; IWL_DEBUG_INFO(priv, "Adding sta %u (%pM) %ssynchronously\n", sta_id, sta->sta.addr, flags & CMD_ASYNC ? "a" : ""); if (flags & CMD_ASYNC) cmd.callback = iwl_legacy_add_sta_callback; else { cmd.flags |= CMD_WANT_SKB; might_sleep(); } cmd.len = priv->cfg->ops->utils->build_addsta_hcmd(sta, data); ret = iwl_legacy_send_cmd(priv, &cmd); if (ret || (flags & CMD_ASYNC)) return ret; if (ret == 0) { pkt = (struct iwl_rx_packet *)cmd.reply_page; ret = iwl_legacy_process_add_sta_resp(priv, sta, pkt, true); } iwl_legacy_free_pages(priv, cmd.reply_page); return ret; } EXPORT_SYMBOL(iwl_legacy_send_add_sta); static void iwl_legacy_set_ht_add_station(struct iwl_priv *priv, u8 index, struct ieee80211_sta *sta, struct iwl_rxon_context *ctx) { struct ieee80211_sta_ht_cap *sta_ht_inf = &sta->ht_cap; __le32 sta_flags; u8 mimo_ps_mode; if (!sta || !sta_ht_inf->ht_supported) goto done; mimo_ps_mode = (sta_ht_inf->cap & IEEE80211_HT_CAP_SM_PS) >> 2; IWL_DEBUG_ASSOC(priv, "spatial multiplexing power save mode: %s\n", (mimo_ps_mode == WLAN_HT_CAP_SM_PS_STATIC) ? "static" : (mimo_ps_mode == WLAN_HT_CAP_SM_PS_DYNAMIC) ? "dynamic" : "disabled"); sta_flags = priv->stations[index].sta.station_flags; sta_flags &= ~(STA_FLG_RTS_MIMO_PROT_MSK | STA_FLG_MIMO_DIS_MSK); switch (mimo_ps_mode) { case WLAN_HT_CAP_SM_PS_STATIC: sta_flags |= STA_FLG_MIMO_DIS_MSK; break; case WLAN_HT_CAP_SM_PS_DYNAMIC: sta_flags |= STA_FLG_RTS_MIMO_PROT_MSK; break; case WLAN_HT_CAP_SM_PS_DISABLED: break; default: IWL_WARN(priv, "Invalid MIMO PS mode %d\n", mimo_ps_mode); break; } sta_flags |= cpu_to_le32( (u32)sta_ht_inf->ampdu_factor << STA_FLG_MAX_AGG_SIZE_POS); sta_flags |= cpu_to_le32( (u32)sta_ht_inf->ampdu_density << STA_FLG_AGG_MPDU_DENSITY_POS); if (iwl_legacy_is_ht40_tx_allowed(priv, ctx, &sta->ht_cap)) sta_flags |= STA_FLG_HT40_EN_MSK; else sta_flags &= ~STA_FLG_HT40_EN_MSK; priv->stations[index].sta.station_flags = sta_flags; done: return; } /** * iwl_legacy_prep_station - Prepare station information for addition * * should be called with sta_lock held */ u8 iwl_legacy_prep_station(struct iwl_priv *priv, struct iwl_rxon_context *ctx, const u8 *addr, bool is_ap, struct ieee80211_sta *sta) { struct iwl_station_entry *station; int i; u8 sta_id = IWL_INVALID_STATION; u16 rate; if (is_ap) sta_id = ctx->ap_sta_id; else if (is_broadcast_ether_addr(addr)) sta_id = ctx->bcast_sta_id; else for (i = IWL_STA_ID; i < priv->hw_params.max_stations; i++) { if (!compare_ether_addr(priv->stations[i].sta.sta.addr, addr)) { sta_id = i; break; } if (!priv->stations[i].used && sta_id == IWL_INVALID_STATION) sta_id = i; } /* * These two conditions have the same outcome, but keep them * separate */ if (unlikely(sta_id == IWL_INVALID_STATION)) return sta_id; /* * uCode is not able to deal with multiple requests to add a * station. Keep track if one is in progress so that we do not send * another. */ if (priv->stations[sta_id].used & IWL_STA_UCODE_INPROGRESS) { IWL_DEBUG_INFO(priv, "STA %d already in process of being added.\n", sta_id); return sta_id; } if ((priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE) && (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) && !compare_ether_addr(priv->stations[sta_id].sta.sta.addr, addr)) { IWL_DEBUG_ASSOC(priv, "STA %d (%pM) already added, not adding again.\n", sta_id, addr); return sta_id; } station = &priv->stations[sta_id]; station->used = IWL_STA_DRIVER_ACTIVE; IWL_DEBUG_ASSOC(priv, "Add STA to driver ID %d: %pM\n", sta_id, addr); priv->num_stations++; /* Set up the REPLY_ADD_STA command to send to device */ memset(&station->sta, 0, sizeof(struct iwl_legacy_addsta_cmd)); memcpy(station->sta.sta.addr, addr, ETH_ALEN); station->sta.mode = 0; station->sta.sta.sta_id = sta_id; station->sta.station_flags = ctx->station_flags; station->ctxid = ctx->ctxid; if (sta) { struct iwl_station_priv_common *sta_priv; sta_priv = (void *)sta->drv_priv; sta_priv->ctx = ctx; } /* * OK to call unconditionally, since local stations (IBSS BSSID * STA and broadcast STA) pass in a NULL sta, and mac80211 * doesn't allow HT IBSS. */ iwl_legacy_set_ht_add_station(priv, sta_id, sta, ctx); /* 3945 only */ rate = (priv->band == IEEE80211_BAND_5GHZ) ? IWL_RATE_6M_PLCP : IWL_RATE_1M_PLCP; /* Turn on both antennas for the station... */ station->sta.rate_n_flags = cpu_to_le16(rate | RATE_MCS_ANT_AB_MSK); return sta_id; } EXPORT_SYMBOL_GPL(iwl_legacy_prep_station); #define STA_WAIT_TIMEOUT (HZ/2) /** * iwl_legacy_add_station_common - */ int iwl_legacy_add_station_common(struct iwl_priv *priv, struct iwl_rxon_context *ctx, const u8 *addr, bool is_ap, struct ieee80211_sta *sta, u8 *sta_id_r) { unsigned long flags_spin; int ret = 0; u8 sta_id; struct iwl_legacy_addsta_cmd sta_cmd; *sta_id_r = 0; spin_lock_irqsave(&priv->sta_lock, flags_spin); sta_id = iwl_legacy_prep_station(priv, ctx, addr, is_ap, sta); if (sta_id == IWL_INVALID_STATION) { IWL_ERR(priv, "Unable to prepare station %pM for addition\n", addr); spin_unlock_irqrestore(&priv->sta_lock, flags_spin); return -EINVAL; } /* * uCode is not able to deal with multiple requests to add a * station. Keep track if one is in progress so that we do not send * another. */ if (priv->stations[sta_id].used & IWL_STA_UCODE_INPROGRESS) { IWL_DEBUG_INFO(priv, "STA %d already in process of being added.\n", sta_id); spin_unlock_irqrestore(&priv->sta_lock, flags_spin); return -EEXIST; } if ((priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE) && (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE)) { IWL_DEBUG_ASSOC(priv, "STA %d (%pM) already added, not adding again.\n", sta_id, addr); spin_unlock_irqrestore(&priv->sta_lock, flags_spin); return -EEXIST; } priv->stations[sta_id].used |= IWL_STA_UCODE_INPROGRESS; memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(struct iwl_legacy_addsta_cmd)); spin_unlock_irqrestore(&priv->sta_lock, flags_spin); /* Add station to device's station table */ ret = iwl_legacy_send_add_sta(priv, &sta_cmd, CMD_SYNC); if (ret) { spin_lock_irqsave(&priv->sta_lock, flags_spin); IWL_ERR(priv, "Adding station %pM failed.\n", priv->stations[sta_id].sta.sta.addr); priv->stations[sta_id].used &= ~IWL_STA_DRIVER_ACTIVE; priv->stations[sta_id].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_irqrestore(&priv->sta_lock, flags_spin); } *sta_id_r = sta_id; return ret; } EXPORT_SYMBOL(iwl_legacy_add_station_common); /** * iwl_legacy_sta_ucode_deactivate - deactivate ucode status for a station * * priv->sta_lock must be held */ static void iwl_legacy_sta_ucode_deactivate(struct iwl_priv *priv, u8 sta_id) { /* Ucode must be active and driver must be non active */ if ((priv->stations[sta_id].used & (IWL_STA_UCODE_ACTIVE | IWL_STA_DRIVER_ACTIVE)) != IWL_STA_UCODE_ACTIVE) IWL_ERR(priv, "removed non active STA %u\n", sta_id); priv->stations[sta_id].used &= ~IWL_STA_UCODE_ACTIVE; memset(&priv->stations[sta_id], 0, sizeof(struct iwl_station_entry)); IWL_DEBUG_ASSOC(priv, "Removed STA %u\n", sta_id); } static int iwl_legacy_send_remove_station(struct iwl_priv *priv, const u8 *addr, int sta_id, bool temporary) { struct iwl_rx_packet *pkt; int ret; unsigned long flags_spin; struct iwl_rem_sta_cmd rm_sta_cmd; struct iwl_host_cmd cmd = { .id = REPLY_REMOVE_STA, .len = sizeof(struct iwl_rem_sta_cmd), .flags = CMD_SYNC, .data = &rm_sta_cmd, }; memset(&rm_sta_cmd, 0, sizeof(rm_sta_cmd)); rm_sta_cmd.num_sta = 1; memcpy(&rm_sta_cmd.addr, addr, ETH_ALEN); cmd.flags |= CMD_WANT_SKB; ret = iwl_legacy_send_cmd(priv, &cmd); if (ret) return ret; pkt = (struct iwl_rx_packet *)cmd.reply_page; if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) { IWL_ERR(priv, "Bad return from REPLY_REMOVE_STA (0x%08X)\n", pkt->hdr.flags); ret = -EIO; } if (!ret) { switch (pkt->u.rem_sta.status) { case REM_STA_SUCCESS_MSK: if (!temporary) { spin_lock_irqsave(&priv->sta_lock, flags_spin); iwl_legacy_sta_ucode_deactivate(priv, sta_id); spin_unlock_irqrestore(&priv->sta_lock, flags_spin); } IWL_DEBUG_ASSOC(priv, "REPLY_REMOVE_STA PASSED\n"); break; default: ret = -EIO; IWL_ERR(priv, "REPLY_REMOVE_STA failed\n"); break; } } iwl_legacy_free_pages(priv, cmd.reply_page); return ret; } /** * iwl_legacy_remove_station - Remove driver's knowledge of station. */ int iwl_legacy_remove_station(struct iwl_priv *priv, const u8 sta_id, const u8 *addr) { unsigned long flags; if (!iwl_legacy_is_ready(priv)) { IWL_DEBUG_INFO(priv, "Unable to remove station %pM, device not ready.\n", addr); /* * It is typical for stations to be removed when we are * going down. Return success since device will be down * soon anyway */ return 0; } IWL_DEBUG_ASSOC(priv, "Removing STA from driver:%d %pM\n", sta_id, addr); if (WARN_ON(sta_id == IWL_INVALID_STATION)) return -EINVAL; spin_lock_irqsave(&priv->sta_lock, flags); if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) { IWL_DEBUG_INFO(priv, "Removing %pM but non DRIVER active\n", addr); goto out_err; } if (!(priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE)) { IWL_DEBUG_INFO(priv, "Removing %pM but non UCODE active\n", addr); goto out_err; } if (priv->stations[sta_id].used & IWL_STA_LOCAL) { kfree(priv->stations[sta_id].lq); priv->stations[sta_id].lq = NULL; } priv->stations[sta_id].used &= ~IWL_STA_DRIVER_ACTIVE; priv->num_stations--; BUG_ON(priv->num_stations < 0); spin_unlock_irqrestore(&priv->sta_lock, flags); return iwl_legacy_send_remove_station(priv, addr, sta_id, false); out_err: spin_unlock_irqrestore(&priv->sta_lock, flags); return -EINVAL; } EXPORT_SYMBOL_GPL(iwl_legacy_remove_station); /** * iwl_legacy_clear_ucode_stations - clear ucode station table bits * * This function clears all the bits in the driver indicating * which stations are active in the ucode. Call when something * other than explicit station management would cause this in * the ucode, e.g. unassociated RXON. */ void iwl_legacy_clear_ucode_stations(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { int i; unsigned long flags_spin; bool cleared = false; IWL_DEBUG_INFO(priv, "Clearing ucode stations in driver\n"); spin_lock_irqsave(&priv->sta_lock, flags_spin); for (i = 0; i < priv->hw_params.max_stations; i++) { if (ctx && ctx->ctxid != priv->stations[i].ctxid) continue; if (priv->stations[i].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_INFO(priv, "Clearing ucode active for station %d\n", i); priv->stations[i].used &= ~IWL_STA_UCODE_ACTIVE; cleared = true; } } spin_unlock_irqrestore(&priv->sta_lock, flags_spin); if (!cleared) IWL_DEBUG_INFO(priv, "No active stations found to be cleared\n"); } EXPORT_SYMBOL(iwl_legacy_clear_ucode_stations); /** * iwl_legacy_restore_stations() - Restore driver known stations to device * * All stations considered active by driver, but not present in ucode, is * restored. * * Function sleeps. */ void iwl_legacy_restore_stations(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { struct iwl_legacy_addsta_cmd sta_cmd; struct iwl_link_quality_cmd lq; unsigned long flags_spin; int i; bool found = false; int ret; bool send_lq; if (!iwl_legacy_is_ready(priv)) { IWL_DEBUG_INFO(priv, "Not ready yet, not restoring any stations.\n"); return; } IWL_DEBUG_ASSOC(priv, "Restoring all known stations ... start.\n"); spin_lock_irqsave(&priv->sta_lock, flags_spin); for (i = 0; i < priv->hw_params.max_stations; i++) { if (ctx->ctxid != priv->stations[i].ctxid) continue; if ((priv->stations[i].used & IWL_STA_DRIVER_ACTIVE) && !(priv->stations[i].used & IWL_STA_UCODE_ACTIVE)) { IWL_DEBUG_ASSOC(priv, "Restoring sta %pM\n", priv->stations[i].sta.sta.addr); priv->stations[i].sta.mode = 0; priv->stations[i].used |= IWL_STA_UCODE_INPROGRESS; found = true; } } for (i = 0; i < priv->hw_params.max_stations; i++) { if ((priv->stations[i].used & IWL_STA_UCODE_INPROGRESS)) { memcpy(&sta_cmd, &priv->stations[i].sta, sizeof(struct iwl_legacy_addsta_cmd)); send_lq = false; if (priv->stations[i].lq) { memcpy(&lq, priv->stations[i].lq, sizeof(struct iwl_link_quality_cmd)); send_lq = true; } spin_unlock_irqrestore(&priv->sta_lock, flags_spin); ret = iwl_legacy_send_add_sta(priv, &sta_cmd, CMD_SYNC); if (ret) { spin_lock_irqsave(&priv->sta_lock, flags_spin); IWL_ERR(priv, "Adding station %pM failed.\n", priv->stations[i].sta.sta.addr); priv->stations[i].used &= ~IWL_STA_DRIVER_ACTIVE; priv->stations[i].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_irqrestore(&priv->sta_lock, flags_spin); } /* * Rate scaling has already been initialized, send * current LQ command */ if (send_lq) iwl_legacy_send_lq_cmd(priv, ctx, &lq, CMD_SYNC, true); spin_lock_irqsave(&priv->sta_lock, flags_spin); priv->stations[i].used &= ~IWL_STA_UCODE_INPROGRESS; } } spin_unlock_irqrestore(&priv->sta_lock, flags_spin); if (!found) IWL_DEBUG_INFO(priv, "Restoring all known stations" " .... no stations to be restored.\n"); else IWL_DEBUG_INFO(priv, "Restoring all known stations" " .... complete.\n"); } EXPORT_SYMBOL(iwl_legacy_restore_stations); int iwl_legacy_get_free_ucode_key_index(struct iwl_priv *priv) { int i; for (i = 0; i < priv->sta_key_max_num; i++) if (!test_and_set_bit(i, &priv->ucode_key_table)) return i; return WEP_INVALID_OFFSET; } EXPORT_SYMBOL(iwl_legacy_get_free_ucode_key_index); void iwl_legacy_dealloc_bcast_stations(struct iwl_priv *priv) { unsigned long flags; int i; spin_lock_irqsave(&priv->sta_lock, flags); for (i = 0; i < priv->hw_params.max_stations; i++) { if (!(priv->stations[i].used & IWL_STA_BCAST)) continue; priv->stations[i].used &= ~IWL_STA_UCODE_ACTIVE; priv->num_stations--; BUG_ON(priv->num_stations < 0); kfree(priv->stations[i].lq); priv->stations[i].lq = NULL; } spin_unlock_irqrestore(&priv->sta_lock, flags); } EXPORT_SYMBOL_GPL(iwl_legacy_dealloc_bcast_stations); #ifdef CONFIG_IWLWIFI_LEGACY_DEBUG static void iwl_legacy_dump_lq_cmd(struct iwl_priv *priv, struct iwl_link_quality_cmd *lq) { int i; IWL_DEBUG_RATE(priv, "lq station id 0x%x\n", lq->sta_id); IWL_DEBUG_RATE(priv, "lq ant 0x%X 0x%X\n", lq->general_params.single_stream_ant_msk, lq->general_params.dual_stream_ant_msk); for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) IWL_DEBUG_RATE(priv, "lq index %d 0x%X\n", i, lq->rs_table[i].rate_n_flags); } #else static inline void iwl_legacy_dump_lq_cmd(struct iwl_priv *priv, struct iwl_link_quality_cmd *lq) { } #endif /** * iwl_legacy_is_lq_table_valid() - Test one aspect of LQ cmd for validity * * It sometimes happens when a HT rate has been in use and we * loose connectivity with AP then mac80211 will first tell us that the * current channel is not HT anymore before removing the station. In such a * scenario the RXON flags will be updated to indicate we are not * communicating HT anymore, but the LQ command may still contain HT rates. * Test for this to prevent driver from sending LQ command between the time * RXON flags are updated and when LQ command is updated. */ static bool iwl_legacy_is_lq_table_valid(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct iwl_link_quality_cmd *lq) { int i; if (ctx->ht.enabled) return true; IWL_DEBUG_INFO(priv, "Channel %u is not an HT channel\n", ctx->active.channel); for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) { if (le32_to_cpu(lq->rs_table[i].rate_n_flags) & RATE_MCS_HT_MSK) { IWL_DEBUG_INFO(priv, "index %d of LQ expects HT channel\n", i); return false; } } return true; } /** * iwl_legacy_send_lq_cmd() - Send link quality command * @init: This command is sent as part of station initialization right * after station has been added. * * The link quality command is sent as the last step of station creation. * This is the special case in which init is set and we call a callback in * this case to clear the state indicating that station creation is in * progress. */ int iwl_legacy_send_lq_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct iwl_link_quality_cmd *lq, u8 flags, bool init) { int ret = 0; unsigned long flags_spin; struct iwl_host_cmd cmd = { .id = REPLY_TX_LINK_QUALITY_CMD, .len = sizeof(struct iwl_link_quality_cmd), .flags = flags, .data = lq, }; if (WARN_ON(lq->sta_id == IWL_INVALID_STATION)) return -EINVAL; spin_lock_irqsave(&priv->sta_lock, flags_spin); if (!(priv->stations[lq->sta_id].used & IWL_STA_DRIVER_ACTIVE)) { spin_unlock_irqrestore(&priv->sta_lock, flags_spin); return -EINVAL; } spin_unlock_irqrestore(&priv->sta_lock, flags_spin); iwl_legacy_dump_lq_cmd(priv, lq); BUG_ON(init && (cmd.flags & CMD_ASYNC)); if (iwl_legacy_is_lq_table_valid(priv, ctx, lq)) ret = iwl_legacy_send_cmd(priv, &cmd); else ret = -EINVAL; if (cmd.flags & CMD_ASYNC) return ret; if (init) { IWL_DEBUG_INFO(priv, "init LQ command complete," " clearing sta addition status for sta %d\n", lq->sta_id); spin_lock_irqsave(&priv->sta_lock, flags_spin); priv->stations[lq->sta_id].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_irqrestore(&priv->sta_lock, flags_spin); } return ret; } EXPORT_SYMBOL(iwl_legacy_send_lq_cmd); int iwl_legacy_mac_sta_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta) { struct iwl_priv *priv = hw->priv; struct iwl_station_priv_common *sta_common = (void *)sta->drv_priv; int ret; IWL_DEBUG_INFO(priv, "received request to remove station %pM\n", sta->addr); mutex_lock(&priv->mutex); IWL_DEBUG_INFO(priv, "proceeding to remove station %pM\n", sta->addr); ret = iwl_legacy_remove_station(priv, sta_common->sta_id, sta->addr); if (ret) IWL_ERR(priv, "Error removing station %pM\n", sta->addr); mutex_unlock(&priv->mutex); return ret; } EXPORT_SYMBOL(iwl_legacy_mac_sta_remove);
gpl-2.0
fishbowlFX/CM11-LGD325ds_kernel
net/tipc/core.c
4810
5119
/* * net/tipc/core.c: TIPC module code * * Copyright (c) 2003-2006, Ericsson AB * Copyright (c) 2005-2006, 2010-2011, Wind River Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <linux/module.h> #include "core.h" #include "ref.h" #include "name_table.h" #include "subscr.h" #include "config.h" #ifndef CONFIG_TIPC_PORTS #define CONFIG_TIPC_PORTS 8191 #endif #ifndef CONFIG_TIPC_LOG #define CONFIG_TIPC_LOG 0 #endif /* global variables used by multiple sub-systems within TIPC */ int tipc_random; const char tipc_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."; /* configurable TIPC parameters */ u32 tipc_own_addr; int tipc_max_ports; int tipc_max_subscriptions; int tipc_max_publications; int tipc_net_id; int tipc_remote_management; /** * tipc_buf_acquire - creates a TIPC message buffer * @size: message size (including TIPC header) * * Returns a new buffer with data pointers set to the specified size. * * NOTE: Headroom is reserved to allow prepending of a data link header. * There may also be unrequested tailroom present at the buffer's end. */ struct sk_buff *tipc_buf_acquire(u32 size) { struct sk_buff *skb; unsigned int buf_size = (BUF_HEADROOM + size + 3) & ~3u; skb = alloc_skb_fclone(buf_size, GFP_ATOMIC); if (skb) { skb_reserve(skb, BUF_HEADROOM); skb_put(skb, size); skb->next = NULL; } return skb; } /** * tipc_core_stop_net - shut down TIPC networking sub-systems */ static void tipc_core_stop_net(void) { tipc_net_stop(); tipc_eth_media_stop(); } /** * start_net - start TIPC networking sub-systems */ int tipc_core_start_net(unsigned long addr) { int res; res = tipc_net_start(addr); if (!res) res = tipc_eth_media_start(); if (res) tipc_core_stop_net(); return res; } /** * tipc_core_stop - switch TIPC from SINGLE NODE to NOT RUNNING mode */ static void tipc_core_stop(void) { tipc_netlink_stop(); tipc_handler_stop(); tipc_cfg_stop(); tipc_subscr_stop(); tipc_nametbl_stop(); tipc_ref_table_stop(); tipc_socket_stop(); tipc_log_resize(0); } /** * tipc_core_start - switch TIPC from NOT RUNNING to SINGLE NODE mode */ static int tipc_core_start(void) { int res; get_random_bytes(&tipc_random, sizeof(tipc_random)); res = tipc_handler_start(); if (!res) res = tipc_ref_table_init(tipc_max_ports, tipc_random); if (!res) res = tipc_nametbl_init(); if (!res) res = tipc_k_signal((Handler)tipc_subscr_start, 0); if (!res) res = tipc_k_signal((Handler)tipc_cfg_init, 0); if (!res) res = tipc_netlink_start(); if (!res) res = tipc_socket_init(); if (res) tipc_core_stop(); return res; } static int __init tipc_init(void) { int res; if (tipc_log_resize(CONFIG_TIPC_LOG) != 0) warn("Unable to create log buffer\n"); info("Activated (version " TIPC_MOD_VER ")\n"); tipc_own_addr = 0; tipc_remote_management = 1; tipc_max_publications = 10000; tipc_max_subscriptions = 2000; tipc_max_ports = CONFIG_TIPC_PORTS; tipc_net_id = 4711; res = tipc_core_start(); if (res) err("Unable to start in single node mode\n"); else info("Started in single node mode\n"); return res; } static void __exit tipc_exit(void) { tipc_core_stop_net(); tipc_core_stop(); info("Deactivated\n"); } module_init(tipc_init); module_exit(tipc_exit); MODULE_DESCRIPTION("TIPC: Transparent Inter Process Communication"); MODULE_LICENSE("Dual BSD/GPL"); MODULE_VERSION(TIPC_MOD_VER);
gpl-2.0
AndroidDeveloperAlliance/ZenKernel_Grouper
sound/isa/adlib.c
4810
3006
/* * AdLib FM card driver. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/isa.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/opl3.h> #define CRD_NAME "AdLib FM" #define DEV_NAME "adlib" MODULE_DESCRIPTION(CRD_NAME); MODULE_AUTHOR("Rene Herman"); MODULE_LICENSE("GPL"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for " CRD_NAME " soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for " CRD_NAME " soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable " CRD_NAME " soundcard."); module_param_array(port, long, NULL, 0444); MODULE_PARM_DESC(port, "Port # for " CRD_NAME " driver."); static int __devinit snd_adlib_match(struct device *dev, unsigned int n) { if (!enable[n]) return 0; if (port[n] == SNDRV_AUTO_PORT) { dev_err(dev, "please specify port\n"); return 0; } return 1; } static void snd_adlib_free(struct snd_card *card) { release_and_free_resource(card->private_data); } static int __devinit snd_adlib_probe(struct device *dev, unsigned int n) { struct snd_card *card; struct snd_opl3 *opl3; int error; error = snd_card_create(index[n], id[n], THIS_MODULE, 0, &card); if (error < 0) { dev_err(dev, "could not create card\n"); return error; } card->private_data = request_region(port[n], 4, CRD_NAME); if (!card->private_data) { dev_err(dev, "could not grab ports\n"); error = -EBUSY; goto out; } card->private_free = snd_adlib_free; strcpy(card->driver, DEV_NAME); strcpy(card->shortname, CRD_NAME); sprintf(card->longname, CRD_NAME " at %#lx", port[n]); error = snd_opl3_create(card, port[n], port[n] + 2, OPL3_HW_AUTO, 1, &opl3); if (error < 0) { dev_err(dev, "could not create OPL\n"); goto out; } error = snd_opl3_hwdep_new(opl3, 0, 0, NULL); if (error < 0) { dev_err(dev, "could not create FM\n"); goto out; } snd_card_set_dev(card, dev); error = snd_card_register(card); if (error < 0) { dev_err(dev, "could not register card\n"); goto out; } dev_set_drvdata(dev, card); return 0; out: snd_card_free(card); return error; } static int __devexit snd_adlib_remove(struct device *dev, unsigned int n) { snd_card_free(dev_get_drvdata(dev)); dev_set_drvdata(dev, NULL); return 0; } static struct isa_driver snd_adlib_driver = { .match = snd_adlib_match, .probe = snd_adlib_probe, .remove = __devexit_p(snd_adlib_remove), .driver = { .name = DEV_NAME } }; static int __init alsa_card_adlib_init(void) { return isa_register_driver(&snd_adlib_driver, SNDRV_CARDS); } static void __exit alsa_card_adlib_exit(void) { isa_unregister_driver(&snd_adlib_driver); } module_init(alsa_card_adlib_init); module_exit(alsa_card_adlib_exit);
gpl-2.0
XPerience-AOSP-Lollipop/android_kernel_xiaomi_cancro
sound/pci/hda/hda_jack.c
4810
10079
/* * Jack-detection handling for HD-audio * * Copyright (c) 2011 Takashi Iwai <tiwai@suse.de> * * This driver 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/init.h> #include <linux/slab.h> #include <linux/export.h> #include <sound/core.h> #include <sound/control.h> #include <sound/jack.h> #include "hda_codec.h" #include "hda_local.h" #include "hda_jack.h" bool is_jack_detectable(struct hda_codec *codec, hda_nid_t nid) { if (codec->no_jack_detect) return false; if (!(snd_hda_query_pin_caps(codec, nid) & AC_PINCAP_PRES_DETECT)) return false; if (!codec->ignore_misc_bit && (get_defcfg_misc(snd_hda_codec_get_pincfg(codec, nid)) & AC_DEFCFG_MISC_NO_PRESENCE)) return false; if (!(get_wcaps(codec, nid) & AC_WCAP_UNSOL_CAP)) return false; return true; } EXPORT_SYMBOL_HDA(is_jack_detectable); /* execute pin sense measurement */ static u32 read_pin_sense(struct hda_codec *codec, hda_nid_t nid) { u32 pincap; if (!codec->no_trigger_sense) { pincap = snd_hda_query_pin_caps(codec, nid); if (pincap & AC_PINCAP_TRIG_REQ) /* need trigger? */ snd_hda_codec_read(codec, nid, 0, AC_VERB_SET_PIN_SENSE, 0); } return snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_SENSE, 0); } /** * snd_hda_jack_tbl_get - query the jack-table entry for the given NID */ struct hda_jack_tbl * snd_hda_jack_tbl_get(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; if (!nid || !jack) return NULL; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid == nid) return jack; return NULL; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_get); /** * snd_hda_jack_tbl_get_from_tag - query the jack-table entry for the given tag */ struct hda_jack_tbl * snd_hda_jack_tbl_get_from_tag(struct hda_codec *codec, unsigned char tag) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; if (!tag || !jack) return NULL; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->tag == tag) return jack; return NULL; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_get_from_tag); /** * snd_hda_jack_tbl_new - create a jack-table entry for the given NID */ struct hda_jack_tbl * snd_hda_jack_tbl_new(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_get(codec, nid); if (jack) return jack; snd_array_init(&codec->jacktbl, sizeof(*jack), 16); jack = snd_array_new(&codec->jacktbl); if (!jack) return NULL; jack->nid = nid; jack->jack_dirty = 1; jack->tag = codec->jacktbl.used; return jack; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_new); void snd_hda_jack_tbl_clear(struct hda_codec *codec) { #ifdef CONFIG_SND_HDA_INPUT_JACK /* free jack instances manually when clearing/reconfiguring */ if (!codec->bus->shutdown && codec->jacktbl.list) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; for (i = 0; i < codec->jacktbl.used; i++, jack++) { if (jack->jack) snd_device_free(codec->bus->card, jack->jack); } } #endif snd_array_free(&codec->jacktbl); } /* update the cached value and notification flag if needed */ static void jack_detect_update(struct hda_codec *codec, struct hda_jack_tbl *jack) { if (jack->jack_dirty || !jack->jack_detect) { jack->pin_sense = read_pin_sense(codec, jack->nid); jack->jack_dirty = 0; } } /** * snd_hda_set_dirty_all - Mark all the cached as dirty * * This function sets the dirty flag to all entries of jack table. * It's called from the resume path in hda_codec.c. */ void snd_hda_jack_set_dirty_all(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) jack->jack_dirty = 1; } EXPORT_SYMBOL_HDA(snd_hda_jack_set_dirty_all); /** * snd_hda_pin_sense - execute pin sense measurement * @codec: the CODEC to sense * @nid: the pin NID to sense * * Execute necessary pin sense measurement and return its Presence Detect, * Impedance, ELD Valid etc. status bits. */ u32 snd_hda_pin_sense(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_get(codec, nid); if (jack) { jack_detect_update(codec, jack); return jack->pin_sense; } return read_pin_sense(codec, nid); } EXPORT_SYMBOL_HDA(snd_hda_pin_sense); #define get_jack_plug_state(sense) !!(sense & AC_PINSENSE_PRESENCE) /** * snd_hda_jack_detect - query pin Presence Detect status * @codec: the CODEC to sense * @nid: the pin NID to sense * * Query and return the pin's Presence Detect status. */ int snd_hda_jack_detect(struct hda_codec *codec, hda_nid_t nid) { u32 sense = snd_hda_pin_sense(codec, nid); return get_jack_plug_state(sense); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect); /** * snd_hda_jack_detect_enable - enable the jack-detection */ int snd_hda_jack_detect_enable(struct hda_codec *codec, hda_nid_t nid, unsigned char action) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_new(codec, nid); if (!jack) return -ENOMEM; if (jack->jack_detect) return 0; /* already registered */ jack->jack_detect = 1; if (action) jack->action = action; return snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | jack->tag); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect_enable); /** * snd_hda_jack_report_sync - sync the states of all jacks and report if changed */ void snd_hda_jack_report_sync(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i, state; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) { jack_detect_update(codec, jack); if (!jack->kctl) continue; state = get_jack_plug_state(jack->pin_sense); snd_kctl_jack_report(codec->bus->card, jack->kctl, state); #ifdef CONFIG_SND_HDA_INPUT_JACK if (jack->jack) snd_jack_report(jack->jack, state ? jack->type : 0); #endif } } EXPORT_SYMBOL_HDA(snd_hda_jack_report_sync); #ifdef CONFIG_SND_HDA_INPUT_JACK /* guess the jack type from the pin-config */ static int get_input_jack_type(struct hda_codec *codec, hda_nid_t nid) { unsigned int def_conf = snd_hda_codec_get_pincfg(codec, nid); switch (get_defcfg_device(def_conf)) { case AC_JACK_LINE_OUT: case AC_JACK_SPEAKER: return SND_JACK_LINEOUT; case AC_JACK_HP_OUT: return SND_JACK_HEADPHONE; case AC_JACK_SPDIF_OUT: case AC_JACK_DIG_OTHER_OUT: return SND_JACK_AVOUT; case AC_JACK_MIC_IN: return SND_JACK_MICROPHONE; default: return SND_JACK_LINEIN; } } static void hda_free_jack_priv(struct snd_jack *jack) { struct hda_jack_tbl *jacks = jack->private_data; jacks->nid = 0; jacks->jack = NULL; } #endif /** * snd_hda_jack_add_kctl - Add a kctl for the given pin * * This assigns a jack-detection kctl to the given pin. The kcontrol * will have the given name and index. */ int snd_hda_jack_add_kctl(struct hda_codec *codec, hda_nid_t nid, const char *name, int idx) { struct hda_jack_tbl *jack; struct snd_kcontrol *kctl; int err, state; jack = snd_hda_jack_tbl_new(codec, nid); if (!jack) return 0; if (jack->kctl) return 0; /* already created */ kctl = snd_kctl_jack_new(name, idx, codec); if (!kctl) return -ENOMEM; err = snd_hda_ctl_add(codec, nid, kctl); if (err < 0) return err; jack->kctl = kctl; state = snd_hda_jack_detect(codec, nid); snd_kctl_jack_report(codec->bus->card, kctl, state); #ifdef CONFIG_SND_HDA_INPUT_JACK jack->type = get_input_jack_type(codec, nid); err = snd_jack_new(codec->bus->card, name, jack->type, &jack->jack); if (err < 0) return err; jack->jack->private_data = jack; jack->jack->private_free = hda_free_jack_priv; snd_jack_report(jack->jack, state ? jack->type : 0); #endif return 0; } EXPORT_SYMBOL_HDA(snd_hda_jack_add_kctl); static int add_jack_kctl(struct hda_codec *codec, hda_nid_t nid, const struct auto_pin_cfg *cfg, char *lastname, int *lastidx) { unsigned int def_conf, conn; char name[44]; int idx, err; if (!nid) return 0; if (!is_jack_detectable(codec, nid)) return 0; def_conf = snd_hda_codec_get_pincfg(codec, nid); conn = get_defcfg_connect(def_conf); if (conn != AC_JACK_PORT_COMPLEX) return 0; snd_hda_get_pin_label(codec, nid, cfg, name, sizeof(name), &idx); if (!strcmp(name, lastname) && idx == *lastidx) idx++; strncpy(lastname, name, 44); *lastidx = idx; err = snd_hda_jack_add_kctl(codec, nid, name, idx); if (err < 0) return err; return snd_hda_jack_detect_enable(codec, nid, 0); } /** * snd_hda_jack_add_kctls - Add kctls for all pins included in the given pincfg */ int snd_hda_jack_add_kctls(struct hda_codec *codec, const struct auto_pin_cfg *cfg) { const hda_nid_t *p; int i, err, lastidx = 0; char lastname[44] = ""; for (i = 0, p = cfg->line_out_pins; i < cfg->line_outs; i++, p++) { err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0, p = cfg->hp_pins; i < cfg->hp_outs; i++, p++) { if (*p == *cfg->line_out_pins) /* might be duplicated */ break; err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0, p = cfg->speaker_pins; i < cfg->speaker_outs; i++, p++) { if (*p == *cfg->line_out_pins) /* might be duplicated */ break; err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0; i < cfg->num_inputs; i++) { err = add_jack_kctl(codec, cfg->inputs[i].pin, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0, p = cfg->dig_out_pins; i < cfg->dig_outs; i++, p++) { err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } err = add_jack_kctl(codec, cfg->dig_in_pin, cfg, lastname, &lastidx); if (err < 0) return err; err = add_jack_kctl(codec, cfg->mono_out_pin, cfg, lastname, &lastidx); if (err < 0) return err; return 0; } EXPORT_SYMBOL_HDA(snd_hda_jack_add_kctls);
gpl-2.0
boa19861105/Killx-Kernel
drivers/net/ethernet/mellanox/mlx4/fw.c
4810
44637
/* * Copyright (c) 2004, 2005 Topspin Communications. All rights reserved. * Copyright (c) 2005, 2006, 2007, 2008 Mellanox Technologies. All rights reserved. * Copyright (c) 2005, 2006, 2007 Cisco Systems, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/etherdevice.h> #include <linux/mlx4/cmd.h> #include <linux/module.h> #include <linux/cache.h> #include "fw.h" #include "icm.h" enum { MLX4_COMMAND_INTERFACE_MIN_REV = 2, MLX4_COMMAND_INTERFACE_MAX_REV = 3, MLX4_COMMAND_INTERFACE_NEW_PORT_CMDS = 3, }; extern void __buggy_use_of_MLX4_GET(void); extern void __buggy_use_of_MLX4_PUT(void); static bool enable_qos; module_param(enable_qos, bool, 0444); MODULE_PARM_DESC(enable_qos, "Enable Quality of Service support in the HCA (default: off)"); #define MLX4_GET(dest, source, offset) \ do { \ void *__p = (char *) (source) + (offset); \ switch (sizeof (dest)) { \ case 1: (dest) = *(u8 *) __p; break; \ case 2: (dest) = be16_to_cpup(__p); break; \ case 4: (dest) = be32_to_cpup(__p); break; \ case 8: (dest) = be64_to_cpup(__p); break; \ default: __buggy_use_of_MLX4_GET(); \ } \ } while (0) #define MLX4_PUT(dest, source, offset) \ do { \ void *__d = ((char *) (dest) + (offset)); \ switch (sizeof(source)) { \ case 1: *(u8 *) __d = (source); break; \ case 2: *(__be16 *) __d = cpu_to_be16(source); break; \ case 4: *(__be32 *) __d = cpu_to_be32(source); break; \ case 8: *(__be64 *) __d = cpu_to_be64(source); break; \ default: __buggy_use_of_MLX4_PUT(); \ } \ } while (0) static void dump_dev_cap_flags(struct mlx4_dev *dev, u64 flags) { static const char *fname[] = { [ 0] = "RC transport", [ 1] = "UC transport", [ 2] = "UD transport", [ 3] = "XRC transport", [ 4] = "reliable multicast", [ 5] = "FCoIB support", [ 6] = "SRQ support", [ 7] = "IPoIB checksum offload", [ 8] = "P_Key violation counter", [ 9] = "Q_Key violation counter", [10] = "VMM", [12] = "DPDP", [15] = "Big LSO headers", [16] = "MW support", [17] = "APM support", [18] = "Atomic ops support", [19] = "Raw multicast support", [20] = "Address vector port checking support", [21] = "UD multicast support", [24] = "Demand paging support", [25] = "Router support", [30] = "IBoE support", [32] = "Unicast loopback support", [34] = "FCS header control", [38] = "Wake On LAN support", [40] = "UDP RSS support", [41] = "Unicast VEP steering support", [42] = "Multicast VEP steering support", [48] = "Counters support", }; int i; mlx4_dbg(dev, "DEV_CAP flags:\n"); for (i = 0; i < ARRAY_SIZE(fname); ++i) if (fname[i] && (flags & (1LL << i))) mlx4_dbg(dev, " %s\n", fname[i]); } int mlx4_MOD_STAT_CFG(struct mlx4_dev *dev, struct mlx4_mod_stat_cfg *cfg) { struct mlx4_cmd_mailbox *mailbox; u32 *inbox; int err = 0; #define MOD_STAT_CFG_IN_SIZE 0x100 #define MOD_STAT_CFG_PG_SZ_M_OFFSET 0x002 #define MOD_STAT_CFG_PG_SZ_OFFSET 0x003 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; memset(inbox, 0, MOD_STAT_CFG_IN_SIZE); MLX4_PUT(inbox, cfg->log_pg_sz, MOD_STAT_CFG_PG_SZ_OFFSET); MLX4_PUT(inbox, cfg->log_pg_sz_m, MOD_STAT_CFG_PG_SZ_M_OFFSET); err = mlx4_cmd(dev, mailbox->dma, 0, 0, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_FUNC_CAP_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { u8 field; u32 size; int err = 0; #define QUERY_FUNC_CAP_FLAGS_OFFSET 0x0 #define QUERY_FUNC_CAP_NUM_PORTS_OFFSET 0x1 #define QUERY_FUNC_CAP_PF_BHVR_OFFSET 0x4 #define QUERY_FUNC_CAP_QP_QUOTA_OFFSET 0x10 #define QUERY_FUNC_CAP_CQ_QUOTA_OFFSET 0x14 #define QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET 0x18 #define QUERY_FUNC_CAP_MPT_QUOTA_OFFSET 0x20 #define QUERY_FUNC_CAP_MTT_QUOTA_OFFSET 0x24 #define QUERY_FUNC_CAP_MCG_QUOTA_OFFSET 0x28 #define QUERY_FUNC_CAP_MAX_EQ_OFFSET 0x2c #define QUERY_FUNC_CAP_RESERVED_EQ_OFFSET 0X30 #define QUERY_FUNC_CAP_PHYS_PORT_OFFSET 0x3 #define QUERY_FUNC_CAP_ETH_PROPS_OFFSET 0xc if (vhcr->op_modifier == 1) { field = vhcr->in_modifier; MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_PHYS_PORT_OFFSET); field = 0; /* ensure fvl bit is not set */ MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_ETH_PROPS_OFFSET); } else if (vhcr->op_modifier == 0) { field = 1 << 7; /* enable only ethernet interface */ MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_FLAGS_OFFSET); field = dev->caps.num_ports; MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_NUM_PORTS_OFFSET); size = 0; /* no PF behavious is set for now */ MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_PF_BHVR_OFFSET); size = dev->caps.num_qps; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_QP_QUOTA_OFFSET); size = dev->caps.num_srqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET); size = dev->caps.num_cqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_CQ_QUOTA_OFFSET); size = dev->caps.num_eqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MAX_EQ_OFFSET); size = dev->caps.reserved_eqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_RESERVED_EQ_OFFSET); size = dev->caps.num_mpts; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MPT_QUOTA_OFFSET); size = dev->caps.num_mtts; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MTT_QUOTA_OFFSET); size = dev->caps.num_mgms + dev->caps.num_amgms; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MCG_QUOTA_OFFSET); } else err = -EINVAL; return err; } int mlx4_QUERY_FUNC_CAP(struct mlx4_dev *dev, struct mlx4_func_cap *func_cap) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u8 field; u32 size; int i; int err = 0; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_FUNC_CAP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); if (err) goto out; outbox = mailbox->buf; MLX4_GET(field, outbox, QUERY_FUNC_CAP_FLAGS_OFFSET); if (!(field & (1 << 7))) { mlx4_err(dev, "The host doesn't support eth interface\n"); err = -EPROTONOSUPPORT; goto out; } MLX4_GET(field, outbox, QUERY_FUNC_CAP_NUM_PORTS_OFFSET); func_cap->num_ports = field; MLX4_GET(size, outbox, QUERY_FUNC_CAP_PF_BHVR_OFFSET); func_cap->pf_context_behaviour = size; MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP_QUOTA_OFFSET); func_cap->qp_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET); func_cap->srq_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_CQ_QUOTA_OFFSET); func_cap->cq_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MAX_EQ_OFFSET); func_cap->max_eq = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_RESERVED_EQ_OFFSET); func_cap->reserved_eq = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MPT_QUOTA_OFFSET); func_cap->mpt_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MTT_QUOTA_OFFSET); func_cap->mtt_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MCG_QUOTA_OFFSET); func_cap->mcg_quota = size & 0xFFFFFF; for (i = 1; i <= func_cap->num_ports; ++i) { err = mlx4_cmd_box(dev, 0, mailbox->dma, i, 1, MLX4_CMD_QUERY_FUNC_CAP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); if (err) goto out; MLX4_GET(field, outbox, QUERY_FUNC_CAP_ETH_PROPS_OFFSET); if (field & (1 << 7)) { mlx4_err(dev, "VLAN is enforced on this port\n"); err = -EPROTONOSUPPORT; goto out; } if (field & (1 << 6)) { mlx4_err(dev, "Force mac is enabled on this port\n"); err = -EPROTONOSUPPORT; goto out; } MLX4_GET(field, outbox, QUERY_FUNC_CAP_PHYS_PORT_OFFSET); func_cap->physical_port[i] = field; } /* All other resources are allocated by the master, but we still report * 'num' and 'reserved' capabilities as follows: * - num remains the maximum resource index * - 'num - reserved' is the total available objects of a resource, but * resource indices may be less than 'reserved' * TODO: set per-resource quotas */ out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_DEV_CAP(struct mlx4_dev *dev, struct mlx4_dev_cap *dev_cap) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u8 field; u32 field32, flags, ext_flags; u16 size; u16 stat_rate; int err; int i; #define QUERY_DEV_CAP_OUT_SIZE 0x100 #define QUERY_DEV_CAP_MAX_SRQ_SZ_OFFSET 0x10 #define QUERY_DEV_CAP_MAX_QP_SZ_OFFSET 0x11 #define QUERY_DEV_CAP_RSVD_QP_OFFSET 0x12 #define QUERY_DEV_CAP_MAX_QP_OFFSET 0x13 #define QUERY_DEV_CAP_RSVD_SRQ_OFFSET 0x14 #define QUERY_DEV_CAP_MAX_SRQ_OFFSET 0x15 #define QUERY_DEV_CAP_RSVD_EEC_OFFSET 0x16 #define QUERY_DEV_CAP_MAX_EEC_OFFSET 0x17 #define QUERY_DEV_CAP_MAX_CQ_SZ_OFFSET 0x19 #define QUERY_DEV_CAP_RSVD_CQ_OFFSET 0x1a #define QUERY_DEV_CAP_MAX_CQ_OFFSET 0x1b #define QUERY_DEV_CAP_MAX_MPT_OFFSET 0x1d #define QUERY_DEV_CAP_RSVD_EQ_OFFSET 0x1e #define QUERY_DEV_CAP_MAX_EQ_OFFSET 0x1f #define QUERY_DEV_CAP_RSVD_MTT_OFFSET 0x20 #define QUERY_DEV_CAP_MAX_MRW_SZ_OFFSET 0x21 #define QUERY_DEV_CAP_RSVD_MRW_OFFSET 0x22 #define QUERY_DEV_CAP_MAX_MTT_SEG_OFFSET 0x23 #define QUERY_DEV_CAP_MAX_AV_OFFSET 0x27 #define QUERY_DEV_CAP_MAX_REQ_QP_OFFSET 0x29 #define QUERY_DEV_CAP_MAX_RES_QP_OFFSET 0x2b #define QUERY_DEV_CAP_MAX_GSO_OFFSET 0x2d #define QUERY_DEV_CAP_MAX_RDMA_OFFSET 0x2f #define QUERY_DEV_CAP_RSZ_SRQ_OFFSET 0x33 #define QUERY_DEV_CAP_ACK_DELAY_OFFSET 0x35 #define QUERY_DEV_CAP_MTU_WIDTH_OFFSET 0x36 #define QUERY_DEV_CAP_VL_PORT_OFFSET 0x37 #define QUERY_DEV_CAP_MAX_MSG_SZ_OFFSET 0x38 #define QUERY_DEV_CAP_MAX_GID_OFFSET 0x3b #define QUERY_DEV_CAP_RATE_SUPPORT_OFFSET 0x3c #define QUERY_DEV_CAP_MAX_PKEY_OFFSET 0x3f #define QUERY_DEV_CAP_EXT_FLAGS_OFFSET 0x40 #define QUERY_DEV_CAP_FLAGS_OFFSET 0x44 #define QUERY_DEV_CAP_RSVD_UAR_OFFSET 0x48 #define QUERY_DEV_CAP_UAR_SZ_OFFSET 0x49 #define QUERY_DEV_CAP_PAGE_SZ_OFFSET 0x4b #define QUERY_DEV_CAP_BF_OFFSET 0x4c #define QUERY_DEV_CAP_LOG_BF_REG_SZ_OFFSET 0x4d #define QUERY_DEV_CAP_LOG_MAX_BF_REGS_PER_PAGE_OFFSET 0x4e #define QUERY_DEV_CAP_LOG_MAX_BF_PAGES_OFFSET 0x4f #define QUERY_DEV_CAP_MAX_SG_SQ_OFFSET 0x51 #define QUERY_DEV_CAP_MAX_DESC_SZ_SQ_OFFSET 0x52 #define QUERY_DEV_CAP_MAX_SG_RQ_OFFSET 0x55 #define QUERY_DEV_CAP_MAX_DESC_SZ_RQ_OFFSET 0x56 #define QUERY_DEV_CAP_MAX_QP_MCG_OFFSET 0x61 #define QUERY_DEV_CAP_RSVD_MCG_OFFSET 0x62 #define QUERY_DEV_CAP_MAX_MCG_OFFSET 0x63 #define QUERY_DEV_CAP_RSVD_PD_OFFSET 0x64 #define QUERY_DEV_CAP_MAX_PD_OFFSET 0x65 #define QUERY_DEV_CAP_RSVD_XRC_OFFSET 0x66 #define QUERY_DEV_CAP_MAX_XRC_OFFSET 0x67 #define QUERY_DEV_CAP_MAX_COUNTERS_OFFSET 0x68 #define QUERY_DEV_CAP_RDMARC_ENTRY_SZ_OFFSET 0x80 #define QUERY_DEV_CAP_QPC_ENTRY_SZ_OFFSET 0x82 #define QUERY_DEV_CAP_AUX_ENTRY_SZ_OFFSET 0x84 #define QUERY_DEV_CAP_ALTC_ENTRY_SZ_OFFSET 0x86 #define QUERY_DEV_CAP_EQC_ENTRY_SZ_OFFSET 0x88 #define QUERY_DEV_CAP_CQC_ENTRY_SZ_OFFSET 0x8a #define QUERY_DEV_CAP_SRQ_ENTRY_SZ_OFFSET 0x8c #define QUERY_DEV_CAP_C_MPT_ENTRY_SZ_OFFSET 0x8e #define QUERY_DEV_CAP_MTT_ENTRY_SZ_OFFSET 0x90 #define QUERY_DEV_CAP_D_MPT_ENTRY_SZ_OFFSET 0x92 #define QUERY_DEV_CAP_BMME_FLAGS_OFFSET 0x94 #define QUERY_DEV_CAP_RSVD_LKEY_OFFSET 0x98 #define QUERY_DEV_CAP_MAX_ICM_SZ_OFFSET 0xa0 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_DEV_CAP, MLX4_CMD_TIME_CLASS_A, !mlx4_is_slave(dev)); if (err) goto out; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_QP_OFFSET); dev_cap->reserved_qps = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_QP_OFFSET); dev_cap->max_qps = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_SRQ_OFFSET); dev_cap->reserved_srqs = 1 << (field >> 4); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SRQ_OFFSET); dev_cap->max_srqs = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_CQ_SZ_OFFSET); dev_cap->max_cq_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_CQ_OFFSET); dev_cap->reserved_cqs = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_CQ_OFFSET); dev_cap->max_cqs = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MPT_OFFSET); dev_cap->max_mpts = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_EQ_OFFSET); dev_cap->reserved_eqs = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_EQ_OFFSET); dev_cap->max_eqs = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_MTT_OFFSET); dev_cap->reserved_mtts = 1 << (field >> 4); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MRW_SZ_OFFSET); dev_cap->max_mrw_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_MRW_OFFSET); dev_cap->reserved_mrws = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MTT_SEG_OFFSET); dev_cap->max_mtt_seg = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_REQ_QP_OFFSET); dev_cap->max_requester_per_qp = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_RES_QP_OFFSET); dev_cap->max_responder_per_qp = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_GSO_OFFSET); field &= 0x1f; if (!field) dev_cap->max_gso_sz = 0; else dev_cap->max_gso_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_RDMA_OFFSET); dev_cap->max_rdma_global = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_ACK_DELAY_OFFSET); dev_cap->local_ca_ack_delay = field & 0x1f; MLX4_GET(field, outbox, QUERY_DEV_CAP_VL_PORT_OFFSET); dev_cap->num_ports = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MSG_SZ_OFFSET); dev_cap->max_msg_sz = 1 << (field & 0x1f); MLX4_GET(stat_rate, outbox, QUERY_DEV_CAP_RATE_SUPPORT_OFFSET); dev_cap->stat_rate_support = stat_rate; MLX4_GET(ext_flags, outbox, QUERY_DEV_CAP_EXT_FLAGS_OFFSET); MLX4_GET(flags, outbox, QUERY_DEV_CAP_FLAGS_OFFSET); dev_cap->flags = flags | (u64)ext_flags << 32; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_UAR_OFFSET); dev_cap->reserved_uars = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_UAR_SZ_OFFSET); dev_cap->uar_size = 1 << ((field & 0x3f) + 20); MLX4_GET(field, outbox, QUERY_DEV_CAP_PAGE_SZ_OFFSET); dev_cap->min_page_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_BF_OFFSET); if (field & 0x80) { MLX4_GET(field, outbox, QUERY_DEV_CAP_LOG_BF_REG_SZ_OFFSET); dev_cap->bf_reg_size = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_LOG_MAX_BF_REGS_PER_PAGE_OFFSET); if ((1 << (field & 0x3f)) > (PAGE_SIZE / dev_cap->bf_reg_size)) field = 3; dev_cap->bf_regs_per_page = 1 << (field & 0x3f); mlx4_dbg(dev, "BlueFlame available (reg size %d, regs/page %d)\n", dev_cap->bf_reg_size, dev_cap->bf_regs_per_page); } else { dev_cap->bf_reg_size = 0; mlx4_dbg(dev, "BlueFlame not available\n"); } MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SG_SQ_OFFSET); dev_cap->max_sq_sg = field; MLX4_GET(size, outbox, QUERY_DEV_CAP_MAX_DESC_SZ_SQ_OFFSET); dev_cap->max_sq_desc_sz = size; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_QP_MCG_OFFSET); dev_cap->max_qp_per_mcg = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_MCG_OFFSET); dev_cap->reserved_mgms = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MCG_OFFSET); dev_cap->max_mcgs = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_PD_OFFSET); dev_cap->reserved_pds = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_PD_OFFSET); dev_cap->max_pds = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_XRC_OFFSET); dev_cap->reserved_xrcds = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_PD_OFFSET); dev_cap->max_xrcds = 1 << (field & 0x1f); MLX4_GET(size, outbox, QUERY_DEV_CAP_RDMARC_ENTRY_SZ_OFFSET); dev_cap->rdmarc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_QPC_ENTRY_SZ_OFFSET); dev_cap->qpc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_AUX_ENTRY_SZ_OFFSET); dev_cap->aux_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_ALTC_ENTRY_SZ_OFFSET); dev_cap->altc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_EQC_ENTRY_SZ_OFFSET); dev_cap->eqc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_CQC_ENTRY_SZ_OFFSET); dev_cap->cqc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_SRQ_ENTRY_SZ_OFFSET); dev_cap->srq_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_C_MPT_ENTRY_SZ_OFFSET); dev_cap->cmpt_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_MTT_ENTRY_SZ_OFFSET); dev_cap->mtt_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_D_MPT_ENTRY_SZ_OFFSET); dev_cap->dmpt_entry_sz = size; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SRQ_SZ_OFFSET); dev_cap->max_srq_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_QP_SZ_OFFSET); dev_cap->max_qp_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSZ_SRQ_OFFSET); dev_cap->resize_srq = field & 1; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SG_RQ_OFFSET); dev_cap->max_rq_sg = field; MLX4_GET(size, outbox, QUERY_DEV_CAP_MAX_DESC_SZ_RQ_OFFSET); dev_cap->max_rq_desc_sz = size; MLX4_GET(dev_cap->bmme_flags, outbox, QUERY_DEV_CAP_BMME_FLAGS_OFFSET); MLX4_GET(dev_cap->reserved_lkey, outbox, QUERY_DEV_CAP_RSVD_LKEY_OFFSET); MLX4_GET(dev_cap->max_icm_sz, outbox, QUERY_DEV_CAP_MAX_ICM_SZ_OFFSET); if (dev_cap->flags & MLX4_DEV_CAP_FLAG_COUNTERS) MLX4_GET(dev_cap->max_counters, outbox, QUERY_DEV_CAP_MAX_COUNTERS_OFFSET); if (dev->flags & MLX4_FLAG_OLD_PORT_CMDS) { for (i = 1; i <= dev_cap->num_ports; ++i) { MLX4_GET(field, outbox, QUERY_DEV_CAP_VL_PORT_OFFSET); dev_cap->max_vl[i] = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_MTU_WIDTH_OFFSET); dev_cap->ib_mtu[i] = field >> 4; dev_cap->max_port_width[i] = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_GID_OFFSET); dev_cap->max_gids[i] = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_PKEY_OFFSET); dev_cap->max_pkeys[i] = 1 << (field & 0xf); } } else { #define QUERY_PORT_SUPPORTED_TYPE_OFFSET 0x00 #define QUERY_PORT_MTU_OFFSET 0x01 #define QUERY_PORT_ETH_MTU_OFFSET 0x02 #define QUERY_PORT_WIDTH_OFFSET 0x06 #define QUERY_PORT_MAX_GID_PKEY_OFFSET 0x07 #define QUERY_PORT_MAX_MACVLAN_OFFSET 0x0a #define QUERY_PORT_MAX_VL_OFFSET 0x0b #define QUERY_PORT_MAC_OFFSET 0x10 #define QUERY_PORT_TRANS_VENDOR_OFFSET 0x18 #define QUERY_PORT_WAVELENGTH_OFFSET 0x1c #define QUERY_PORT_TRANS_CODE_OFFSET 0x20 for (i = 1; i <= dev_cap->num_ports; ++i) { err = mlx4_cmd_box(dev, 0, mailbox->dma, i, 0, MLX4_CMD_QUERY_PORT, MLX4_CMD_TIME_CLASS_B, !mlx4_is_slave(dev)); if (err) goto out; MLX4_GET(field, outbox, QUERY_PORT_SUPPORTED_TYPE_OFFSET); dev_cap->supported_port_types[i] = field & 3; dev_cap->suggested_type[i] = (field >> 3) & 1; dev_cap->default_sense[i] = (field >> 4) & 1; MLX4_GET(field, outbox, QUERY_PORT_MTU_OFFSET); dev_cap->ib_mtu[i] = field & 0xf; MLX4_GET(field, outbox, QUERY_PORT_WIDTH_OFFSET); dev_cap->max_port_width[i] = field & 0xf; MLX4_GET(field, outbox, QUERY_PORT_MAX_GID_PKEY_OFFSET); dev_cap->max_gids[i] = 1 << (field >> 4); dev_cap->max_pkeys[i] = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_PORT_MAX_VL_OFFSET); dev_cap->max_vl[i] = field & 0xf; MLX4_GET(field, outbox, QUERY_PORT_MAX_MACVLAN_OFFSET); dev_cap->log_max_macs[i] = field & 0xf; dev_cap->log_max_vlans[i] = field >> 4; MLX4_GET(dev_cap->eth_mtu[i], outbox, QUERY_PORT_ETH_MTU_OFFSET); MLX4_GET(dev_cap->def_mac[i], outbox, QUERY_PORT_MAC_OFFSET); MLX4_GET(field32, outbox, QUERY_PORT_TRANS_VENDOR_OFFSET); dev_cap->trans_type[i] = field32 >> 24; dev_cap->vendor_oui[i] = field32 & 0xffffff; MLX4_GET(dev_cap->wavelength[i], outbox, QUERY_PORT_WAVELENGTH_OFFSET); MLX4_GET(dev_cap->trans_code[i], outbox, QUERY_PORT_TRANS_CODE_OFFSET); } } mlx4_dbg(dev, "Base MM extensions: flags %08x, rsvd L_Key %08x\n", dev_cap->bmme_flags, dev_cap->reserved_lkey); /* * Each UAR has 4 EQ doorbells; so if a UAR is reserved, then * we can't use any EQs whose doorbell falls on that page, * even if the EQ itself isn't reserved. */ dev_cap->reserved_eqs = max(dev_cap->reserved_uars * 4, dev_cap->reserved_eqs); mlx4_dbg(dev, "Max ICM size %lld MB\n", (unsigned long long) dev_cap->max_icm_sz >> 20); mlx4_dbg(dev, "Max QPs: %d, reserved QPs: %d, entry size: %d\n", dev_cap->max_qps, dev_cap->reserved_qps, dev_cap->qpc_entry_sz); mlx4_dbg(dev, "Max SRQs: %d, reserved SRQs: %d, entry size: %d\n", dev_cap->max_srqs, dev_cap->reserved_srqs, dev_cap->srq_entry_sz); mlx4_dbg(dev, "Max CQs: %d, reserved CQs: %d, entry size: %d\n", dev_cap->max_cqs, dev_cap->reserved_cqs, dev_cap->cqc_entry_sz); mlx4_dbg(dev, "Max EQs: %d, reserved EQs: %d, entry size: %d\n", dev_cap->max_eqs, dev_cap->reserved_eqs, dev_cap->eqc_entry_sz); mlx4_dbg(dev, "reserved MPTs: %d, reserved MTTs: %d\n", dev_cap->reserved_mrws, dev_cap->reserved_mtts); mlx4_dbg(dev, "Max PDs: %d, reserved PDs: %d, reserved UARs: %d\n", dev_cap->max_pds, dev_cap->reserved_pds, dev_cap->reserved_uars); mlx4_dbg(dev, "Max QP/MCG: %d, reserved MGMs: %d\n", dev_cap->max_pds, dev_cap->reserved_mgms); mlx4_dbg(dev, "Max CQEs: %d, max WQEs: %d, max SRQ WQEs: %d\n", dev_cap->max_cq_sz, dev_cap->max_qp_sz, dev_cap->max_srq_sz); mlx4_dbg(dev, "Local CA ACK delay: %d, max MTU: %d, port width cap: %d\n", dev_cap->local_ca_ack_delay, 128 << dev_cap->ib_mtu[1], dev_cap->max_port_width[1]); mlx4_dbg(dev, "Max SQ desc size: %d, max SQ S/G: %d\n", dev_cap->max_sq_desc_sz, dev_cap->max_sq_sg); mlx4_dbg(dev, "Max RQ desc size: %d, max RQ S/G: %d\n", dev_cap->max_rq_desc_sz, dev_cap->max_rq_sg); mlx4_dbg(dev, "Max GSO size: %d\n", dev_cap->max_gso_sz); mlx4_dbg(dev, "Max counters: %d\n", dev_cap->max_counters); dump_dev_cap_flags(dev, dev_cap->flags); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_PORT_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { u64 def_mac; u8 port_type; int err; #define MLX4_PORT_SUPPORT_IB (1 << 0) #define MLX4_PORT_SUGGEST_TYPE (1 << 3) #define MLX4_PORT_DEFAULT_SENSE (1 << 4) #define MLX4_VF_PORT_ETH_ONLY_MASK (0xff & ~MLX4_PORT_SUPPORT_IB & \ ~MLX4_PORT_SUGGEST_TYPE & \ ~MLX4_PORT_DEFAULT_SENSE) err = mlx4_cmd_box(dev, 0, outbox->dma, vhcr->in_modifier, 0, MLX4_CMD_QUERY_PORT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (!err && dev->caps.function != slave) { /* set slave default_mac address */ MLX4_GET(def_mac, outbox->buf, QUERY_PORT_MAC_OFFSET); def_mac += slave << 8; MLX4_PUT(outbox->buf, def_mac, QUERY_PORT_MAC_OFFSET); /* get port type - currently only eth is enabled */ MLX4_GET(port_type, outbox->buf, QUERY_PORT_SUPPORTED_TYPE_OFFSET); /* Allow only Eth port, no link sensing allowed */ port_type &= MLX4_VF_PORT_ETH_ONLY_MASK; /* check eth is enabled for this port */ if (!(port_type & 2)) mlx4_dbg(dev, "QUERY PORT: eth not supported by host"); MLX4_PUT(outbox->buf, port_type, QUERY_PORT_SUPPORTED_TYPE_OFFSET); } return err; } int mlx4_map_cmd(struct mlx4_dev *dev, u16 op, struct mlx4_icm *icm, u64 virt) { struct mlx4_cmd_mailbox *mailbox; struct mlx4_icm_iter iter; __be64 *pages; int lg; int nent = 0; int i; int err = 0; int ts = 0, tc = 0; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); memset(mailbox->buf, 0, MLX4_MAILBOX_SIZE); pages = mailbox->buf; for (mlx4_icm_first(icm, &iter); !mlx4_icm_last(&iter); mlx4_icm_next(&iter)) { /* * We have to pass pages that are aligned to their * size, so find the least significant 1 in the * address or size and use that as our log2 size. */ lg = ffs(mlx4_icm_addr(&iter) | mlx4_icm_size(&iter)) - 1; if (lg < MLX4_ICM_PAGE_SHIFT) { mlx4_warn(dev, "Got FW area not aligned to %d (%llx/%lx).\n", MLX4_ICM_PAGE_SIZE, (unsigned long long) mlx4_icm_addr(&iter), mlx4_icm_size(&iter)); err = -EINVAL; goto out; } for (i = 0; i < mlx4_icm_size(&iter) >> lg; ++i) { if (virt != -1) { pages[nent * 2] = cpu_to_be64(virt); virt += 1 << lg; } pages[nent * 2 + 1] = cpu_to_be64((mlx4_icm_addr(&iter) + (i << lg)) | (lg - MLX4_ICM_PAGE_SHIFT)); ts += 1 << (lg - 10); ++tc; if (++nent == MLX4_MAILBOX_SIZE / 16) { err = mlx4_cmd(dev, mailbox->dma, nent, 0, op, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) goto out; nent = 0; } } } if (nent) err = mlx4_cmd(dev, mailbox->dma, nent, 0, op, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) goto out; switch (op) { case MLX4_CMD_MAP_FA: mlx4_dbg(dev, "Mapped %d chunks/%d KB for FW.\n", tc, ts); break; case MLX4_CMD_MAP_ICM_AUX: mlx4_dbg(dev, "Mapped %d chunks/%d KB for ICM aux.\n", tc, ts); break; case MLX4_CMD_MAP_ICM: mlx4_dbg(dev, "Mapped %d chunks/%d KB at %llx for ICM.\n", tc, ts, (unsigned long long) virt - (ts << 10)); break; } out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_MAP_FA(struct mlx4_dev *dev, struct mlx4_icm *icm) { return mlx4_map_cmd(dev, MLX4_CMD_MAP_FA, icm, -1); } int mlx4_UNMAP_FA(struct mlx4_dev *dev) { return mlx4_cmd(dev, 0, 0, 0, MLX4_CMD_UNMAP_FA, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); } int mlx4_RUN_FW(struct mlx4_dev *dev) { return mlx4_cmd(dev, 0, 0, 0, MLX4_CMD_RUN_FW, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } int mlx4_QUERY_FW(struct mlx4_dev *dev) { struct mlx4_fw *fw = &mlx4_priv(dev)->fw; struct mlx4_cmd *cmd = &mlx4_priv(dev)->cmd; struct mlx4_cmd_mailbox *mailbox; u32 *outbox; int err = 0; u64 fw_ver; u16 cmd_if_rev; u8 lg; #define QUERY_FW_OUT_SIZE 0x100 #define QUERY_FW_VER_OFFSET 0x00 #define QUERY_FW_PPF_ID 0x09 #define QUERY_FW_CMD_IF_REV_OFFSET 0x0a #define QUERY_FW_MAX_CMD_OFFSET 0x0f #define QUERY_FW_ERR_START_OFFSET 0x30 #define QUERY_FW_ERR_SIZE_OFFSET 0x38 #define QUERY_FW_ERR_BAR_OFFSET 0x3c #define QUERY_FW_SIZE_OFFSET 0x00 #define QUERY_FW_CLR_INT_BASE_OFFSET 0x20 #define QUERY_FW_CLR_INT_BAR_OFFSET 0x28 #define QUERY_FW_COMM_BASE_OFFSET 0x40 #define QUERY_FW_COMM_BAR_OFFSET 0x48 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_FW, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(fw_ver, outbox, QUERY_FW_VER_OFFSET); /* * FW subminor version is at more significant bits than minor * version, so swap here. */ dev->caps.fw_ver = (fw_ver & 0xffff00000000ull) | ((fw_ver & 0xffff0000ull) >> 16) | ((fw_ver & 0x0000ffffull) << 16); MLX4_GET(lg, outbox, QUERY_FW_PPF_ID); dev->caps.function = lg; MLX4_GET(cmd_if_rev, outbox, QUERY_FW_CMD_IF_REV_OFFSET); if (cmd_if_rev < MLX4_COMMAND_INTERFACE_MIN_REV || cmd_if_rev > MLX4_COMMAND_INTERFACE_MAX_REV) { mlx4_err(dev, "Installed FW has unsupported " "command interface revision %d.\n", cmd_if_rev); mlx4_err(dev, "(Installed FW version is %d.%d.%03d)\n", (int) (dev->caps.fw_ver >> 32), (int) (dev->caps.fw_ver >> 16) & 0xffff, (int) dev->caps.fw_ver & 0xffff); mlx4_err(dev, "This driver version supports only revisions %d to %d.\n", MLX4_COMMAND_INTERFACE_MIN_REV, MLX4_COMMAND_INTERFACE_MAX_REV); err = -ENODEV; goto out; } if (cmd_if_rev < MLX4_COMMAND_INTERFACE_NEW_PORT_CMDS) dev->flags |= MLX4_FLAG_OLD_PORT_CMDS; MLX4_GET(lg, outbox, QUERY_FW_MAX_CMD_OFFSET); cmd->max_cmds = 1 << lg; mlx4_dbg(dev, "FW version %d.%d.%03d (cmd intf rev %d), max commands %d\n", (int) (dev->caps.fw_ver >> 32), (int) (dev->caps.fw_ver >> 16) & 0xffff, (int) dev->caps.fw_ver & 0xffff, cmd_if_rev, cmd->max_cmds); MLX4_GET(fw->catas_offset, outbox, QUERY_FW_ERR_START_OFFSET); MLX4_GET(fw->catas_size, outbox, QUERY_FW_ERR_SIZE_OFFSET); MLX4_GET(fw->catas_bar, outbox, QUERY_FW_ERR_BAR_OFFSET); fw->catas_bar = (fw->catas_bar >> 6) * 2; mlx4_dbg(dev, "Catastrophic error buffer at 0x%llx, size 0x%x, BAR %d\n", (unsigned long long) fw->catas_offset, fw->catas_size, fw->catas_bar); MLX4_GET(fw->fw_pages, outbox, QUERY_FW_SIZE_OFFSET); MLX4_GET(fw->clr_int_base, outbox, QUERY_FW_CLR_INT_BASE_OFFSET); MLX4_GET(fw->clr_int_bar, outbox, QUERY_FW_CLR_INT_BAR_OFFSET); fw->clr_int_bar = (fw->clr_int_bar >> 6) * 2; MLX4_GET(fw->comm_base, outbox, QUERY_FW_COMM_BASE_OFFSET); MLX4_GET(fw->comm_bar, outbox, QUERY_FW_COMM_BAR_OFFSET); fw->comm_bar = (fw->comm_bar >> 6) * 2; mlx4_dbg(dev, "Communication vector bar:%d offset:0x%llx\n", fw->comm_bar, fw->comm_base); mlx4_dbg(dev, "FW size %d KB\n", fw->fw_pages >> 2); /* * Round up number of system pages needed in case * MLX4_ICM_PAGE_SIZE < PAGE_SIZE. */ fw->fw_pages = ALIGN(fw->fw_pages, PAGE_SIZE / MLX4_ICM_PAGE_SIZE) >> (PAGE_SHIFT - MLX4_ICM_PAGE_SHIFT); mlx4_dbg(dev, "Clear int @ %llx, BAR %d\n", (unsigned long long) fw->clr_int_base, fw->clr_int_bar); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } static void get_board_id(void *vsd, char *board_id) { int i; #define VSD_OFFSET_SIG1 0x00 #define VSD_OFFSET_SIG2 0xde #define VSD_OFFSET_MLX_BOARD_ID 0xd0 #define VSD_OFFSET_TS_BOARD_ID 0x20 #define VSD_SIGNATURE_TOPSPIN 0x5ad memset(board_id, 0, MLX4_BOARD_ID_LEN); if (be16_to_cpup(vsd + VSD_OFFSET_SIG1) == VSD_SIGNATURE_TOPSPIN && be16_to_cpup(vsd + VSD_OFFSET_SIG2) == VSD_SIGNATURE_TOPSPIN) { strlcpy(board_id, vsd + VSD_OFFSET_TS_BOARD_ID, MLX4_BOARD_ID_LEN); } else { /* * The board ID is a string but the firmware byte * swaps each 4-byte word before passing it back to * us. Therefore we need to swab it before printing. */ for (i = 0; i < 4; ++i) ((u32 *) board_id)[i] = swab32(*(u32 *) (vsd + VSD_OFFSET_MLX_BOARD_ID + i * 4)); } } int mlx4_QUERY_ADAPTER(struct mlx4_dev *dev, struct mlx4_adapter *adapter) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; int err; #define QUERY_ADAPTER_OUT_SIZE 0x100 #define QUERY_ADAPTER_INTA_PIN_OFFSET 0x10 #define QUERY_ADAPTER_VSD_OFFSET 0x20 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_ADAPTER, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(adapter->inta_pin, outbox, QUERY_ADAPTER_INTA_PIN_OFFSET); get_board_id(outbox + QUERY_ADAPTER_VSD_OFFSET / 4, adapter->board_id); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_INIT_HCA(struct mlx4_dev *dev, struct mlx4_init_hca_param *param) { struct mlx4_cmd_mailbox *mailbox; __be32 *inbox; int err; #define INIT_HCA_IN_SIZE 0x200 #define INIT_HCA_VERSION_OFFSET 0x000 #define INIT_HCA_VERSION 2 #define INIT_HCA_CACHELINE_SZ_OFFSET 0x0e #define INIT_HCA_FLAGS_OFFSET 0x014 #define INIT_HCA_QPC_OFFSET 0x020 #define INIT_HCA_QPC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x10) #define INIT_HCA_LOG_QP_OFFSET (INIT_HCA_QPC_OFFSET + 0x17) #define INIT_HCA_SRQC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x28) #define INIT_HCA_LOG_SRQ_OFFSET (INIT_HCA_QPC_OFFSET + 0x2f) #define INIT_HCA_CQC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x30) #define INIT_HCA_LOG_CQ_OFFSET (INIT_HCA_QPC_OFFSET + 0x37) #define INIT_HCA_EQE_CQE_OFFSETS (INIT_HCA_QPC_OFFSET + 0x38) #define INIT_HCA_ALTC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x40) #define INIT_HCA_AUXC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x50) #define INIT_HCA_EQC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x60) #define INIT_HCA_LOG_EQ_OFFSET (INIT_HCA_QPC_OFFSET + 0x67) #define INIT_HCA_RDMARC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x70) #define INIT_HCA_LOG_RD_OFFSET (INIT_HCA_QPC_OFFSET + 0x77) #define INIT_HCA_MCAST_OFFSET 0x0c0 #define INIT_HCA_MC_BASE_OFFSET (INIT_HCA_MCAST_OFFSET + 0x00) #define INIT_HCA_LOG_MC_ENTRY_SZ_OFFSET (INIT_HCA_MCAST_OFFSET + 0x12) #define INIT_HCA_LOG_MC_HASH_SZ_OFFSET (INIT_HCA_MCAST_OFFSET + 0x16) #define INIT_HCA_UC_STEERING_OFFSET (INIT_HCA_MCAST_OFFSET + 0x18) #define INIT_HCA_LOG_MC_TABLE_SZ_OFFSET (INIT_HCA_MCAST_OFFSET + 0x1b) #define INIT_HCA_TPT_OFFSET 0x0f0 #define INIT_HCA_DMPT_BASE_OFFSET (INIT_HCA_TPT_OFFSET + 0x00) #define INIT_HCA_LOG_MPT_SZ_OFFSET (INIT_HCA_TPT_OFFSET + 0x0b) #define INIT_HCA_MTT_BASE_OFFSET (INIT_HCA_TPT_OFFSET + 0x10) #define INIT_HCA_CMPT_BASE_OFFSET (INIT_HCA_TPT_OFFSET + 0x18) #define INIT_HCA_UAR_OFFSET 0x120 #define INIT_HCA_LOG_UAR_SZ_OFFSET (INIT_HCA_UAR_OFFSET + 0x0a) #define INIT_HCA_UAR_PAGE_SZ_OFFSET (INIT_HCA_UAR_OFFSET + 0x0b) mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; memset(inbox, 0, INIT_HCA_IN_SIZE); *((u8 *) mailbox->buf + INIT_HCA_VERSION_OFFSET) = INIT_HCA_VERSION; *((u8 *) mailbox->buf + INIT_HCA_CACHELINE_SZ_OFFSET) = (ilog2(cache_line_size()) - 4) << 5; #if defined(__LITTLE_ENDIAN) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) &= ~cpu_to_be32(1 << 1); #elif defined(__BIG_ENDIAN) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 1); #else #error Host endianness not defined #endif /* Check port for UD address vector: */ *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1); /* Enable IPoIB checksumming if we can: */ if (dev->caps.flags & MLX4_DEV_CAP_FLAG_IPOIB_CSUM) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 3); /* Enable QoS support if module parameter set */ if (enable_qos) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 2); /* enable counters */ if (dev->caps.flags & MLX4_DEV_CAP_FLAG_COUNTERS) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 4); /* QPC/EEC/CQC/EQC/RDMARC attributes */ MLX4_PUT(inbox, param->qpc_base, INIT_HCA_QPC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_qps, INIT_HCA_LOG_QP_OFFSET); MLX4_PUT(inbox, param->srqc_base, INIT_HCA_SRQC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_srqs, INIT_HCA_LOG_SRQ_OFFSET); MLX4_PUT(inbox, param->cqc_base, INIT_HCA_CQC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_cqs, INIT_HCA_LOG_CQ_OFFSET); MLX4_PUT(inbox, param->altc_base, INIT_HCA_ALTC_BASE_OFFSET); MLX4_PUT(inbox, param->auxc_base, INIT_HCA_AUXC_BASE_OFFSET); MLX4_PUT(inbox, param->eqc_base, INIT_HCA_EQC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_eqs, INIT_HCA_LOG_EQ_OFFSET); MLX4_PUT(inbox, param->rdmarc_base, INIT_HCA_RDMARC_BASE_OFFSET); MLX4_PUT(inbox, param->log_rd_per_qp, INIT_HCA_LOG_RD_OFFSET); /* multicast attributes */ MLX4_PUT(inbox, param->mc_base, INIT_HCA_MC_BASE_OFFSET); MLX4_PUT(inbox, param->log_mc_entry_sz, INIT_HCA_LOG_MC_ENTRY_SZ_OFFSET); MLX4_PUT(inbox, param->log_mc_hash_sz, INIT_HCA_LOG_MC_HASH_SZ_OFFSET); if (dev->caps.flags & MLX4_DEV_CAP_FLAG_VEP_MC_STEER) MLX4_PUT(inbox, (u8) (1 << 3), INIT_HCA_UC_STEERING_OFFSET); MLX4_PUT(inbox, param->log_mc_table_sz, INIT_HCA_LOG_MC_TABLE_SZ_OFFSET); /* TPT attributes */ MLX4_PUT(inbox, param->dmpt_base, INIT_HCA_DMPT_BASE_OFFSET); MLX4_PUT(inbox, param->log_mpt_sz, INIT_HCA_LOG_MPT_SZ_OFFSET); MLX4_PUT(inbox, param->mtt_base, INIT_HCA_MTT_BASE_OFFSET); MLX4_PUT(inbox, param->cmpt_base, INIT_HCA_CMPT_BASE_OFFSET); /* UAR attributes */ MLX4_PUT(inbox, param->uar_page_sz, INIT_HCA_UAR_PAGE_SZ_OFFSET); MLX4_PUT(inbox, param->log_uar_sz, INIT_HCA_LOG_UAR_SZ_OFFSET); err = mlx4_cmd(dev, mailbox->dma, 0, 0, MLX4_CMD_INIT_HCA, 10000, MLX4_CMD_NATIVE); if (err) mlx4_err(dev, "INIT_HCA returns %d\n", err); mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_HCA(struct mlx4_dev *dev, struct mlx4_init_hca_param *param) { struct mlx4_cmd_mailbox *mailbox; __be32 *outbox; int err; #define QUERY_HCA_GLOBAL_CAPS_OFFSET 0x04 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_HCA, MLX4_CMD_TIME_CLASS_B, !mlx4_is_slave(dev)); if (err) goto out; MLX4_GET(param->global_caps, outbox, QUERY_HCA_GLOBAL_CAPS_OFFSET); /* QPC/EEC/CQC/EQC/RDMARC attributes */ MLX4_GET(param->qpc_base, outbox, INIT_HCA_QPC_BASE_OFFSET); MLX4_GET(param->log_num_qps, outbox, INIT_HCA_LOG_QP_OFFSET); MLX4_GET(param->srqc_base, outbox, INIT_HCA_SRQC_BASE_OFFSET); MLX4_GET(param->log_num_srqs, outbox, INIT_HCA_LOG_SRQ_OFFSET); MLX4_GET(param->cqc_base, outbox, INIT_HCA_CQC_BASE_OFFSET); MLX4_GET(param->log_num_cqs, outbox, INIT_HCA_LOG_CQ_OFFSET); MLX4_GET(param->altc_base, outbox, INIT_HCA_ALTC_BASE_OFFSET); MLX4_GET(param->auxc_base, outbox, INIT_HCA_AUXC_BASE_OFFSET); MLX4_GET(param->eqc_base, outbox, INIT_HCA_EQC_BASE_OFFSET); MLX4_GET(param->log_num_eqs, outbox, INIT_HCA_LOG_EQ_OFFSET); MLX4_GET(param->rdmarc_base, outbox, INIT_HCA_RDMARC_BASE_OFFSET); MLX4_GET(param->log_rd_per_qp, outbox, INIT_HCA_LOG_RD_OFFSET); /* multicast attributes */ MLX4_GET(param->mc_base, outbox, INIT_HCA_MC_BASE_OFFSET); MLX4_GET(param->log_mc_entry_sz, outbox, INIT_HCA_LOG_MC_ENTRY_SZ_OFFSET); MLX4_GET(param->log_mc_hash_sz, outbox, INIT_HCA_LOG_MC_HASH_SZ_OFFSET); MLX4_GET(param->log_mc_table_sz, outbox, INIT_HCA_LOG_MC_TABLE_SZ_OFFSET); /* TPT attributes */ MLX4_GET(param->dmpt_base, outbox, INIT_HCA_DMPT_BASE_OFFSET); MLX4_GET(param->log_mpt_sz, outbox, INIT_HCA_LOG_MPT_SZ_OFFSET); MLX4_GET(param->mtt_base, outbox, INIT_HCA_MTT_BASE_OFFSET); MLX4_GET(param->cmpt_base, outbox, INIT_HCA_CMPT_BASE_OFFSET); /* UAR attributes */ MLX4_GET(param->uar_page_sz, outbox, INIT_HCA_UAR_PAGE_SZ_OFFSET); MLX4_GET(param->log_uar_sz, outbox, INIT_HCA_LOG_UAR_SZ_OFFSET); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_INIT_PORT_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_priv *priv = mlx4_priv(dev); int port = vhcr->in_modifier; int err; if (priv->mfunc.master.slave_state[slave].init_port_mask & (1 << port)) return 0; if (dev->caps.port_mask[port] == MLX4_PORT_TYPE_IB) return -ENODEV; /* Enable port only if it was previously disabled */ if (!priv->mfunc.master.init_port_ref[port]) { err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; priv->mfunc.master.slave_state[slave].init_port_mask |= (1 << port); } ++priv->mfunc.master.init_port_ref[port]; return 0; } int mlx4_INIT_PORT(struct mlx4_dev *dev, int port) { struct mlx4_cmd_mailbox *mailbox; u32 *inbox; int err; u32 flags; u16 field; if (dev->flags & MLX4_FLAG_OLD_PORT_CMDS) { #define INIT_PORT_IN_SIZE 256 #define INIT_PORT_FLAGS_OFFSET 0x00 #define INIT_PORT_FLAG_SIG (1 << 18) #define INIT_PORT_FLAG_NG (1 << 17) #define INIT_PORT_FLAG_G0 (1 << 16) #define INIT_PORT_VL_SHIFT 4 #define INIT_PORT_PORT_WIDTH_SHIFT 8 #define INIT_PORT_MTU_OFFSET 0x04 #define INIT_PORT_MAX_GID_OFFSET 0x06 #define INIT_PORT_MAX_PKEY_OFFSET 0x0a #define INIT_PORT_GUID0_OFFSET 0x10 #define INIT_PORT_NODE_GUID_OFFSET 0x18 #define INIT_PORT_SI_GUID_OFFSET 0x20 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; memset(inbox, 0, INIT_PORT_IN_SIZE); flags = 0; flags |= (dev->caps.vl_cap[port] & 0xf) << INIT_PORT_VL_SHIFT; flags |= (dev->caps.port_width_cap[port] & 0xf) << INIT_PORT_PORT_WIDTH_SHIFT; MLX4_PUT(inbox, flags, INIT_PORT_FLAGS_OFFSET); field = 128 << dev->caps.ib_mtu_cap[port]; MLX4_PUT(inbox, field, INIT_PORT_MTU_OFFSET); field = dev->caps.gid_table_len[port]; MLX4_PUT(inbox, field, INIT_PORT_MAX_GID_OFFSET); field = dev->caps.pkey_table_len[port]; MLX4_PUT(inbox, field, INIT_PORT_MAX_PKEY_OFFSET); err = mlx4_cmd(dev, mailbox->dma, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); } else err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); return err; } EXPORT_SYMBOL_GPL(mlx4_INIT_PORT); int mlx4_CLOSE_PORT_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_priv *priv = mlx4_priv(dev); int port = vhcr->in_modifier; int err; if (!(priv->mfunc.master.slave_state[slave].init_port_mask & (1 << port))) return 0; if (dev->caps.port_mask[port] == MLX4_PORT_TYPE_IB) return -ENODEV; if (priv->mfunc.master.init_port_ref[port] == 1) { err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_CLOSE_PORT, 1000, MLX4_CMD_NATIVE); if (err) return err; } priv->mfunc.master.slave_state[slave].init_port_mask &= ~(1 << port); --priv->mfunc.master.init_port_ref[port]; return 0; } int mlx4_CLOSE_PORT(struct mlx4_dev *dev, int port) { return mlx4_cmd(dev, 0, port, 0, MLX4_CMD_CLOSE_PORT, 1000, MLX4_CMD_WRAPPED); } EXPORT_SYMBOL_GPL(mlx4_CLOSE_PORT); int mlx4_CLOSE_HCA(struct mlx4_dev *dev, int panic) { return mlx4_cmd(dev, 0, 0, panic, MLX4_CMD_CLOSE_HCA, 1000, MLX4_CMD_NATIVE); } int mlx4_SET_ICM_SIZE(struct mlx4_dev *dev, u64 icm_size, u64 *aux_pages) { int ret = mlx4_cmd_imm(dev, icm_size, aux_pages, 0, 0, MLX4_CMD_SET_ICM_SIZE, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (ret) return ret; /* * Round up number of system pages needed in case * MLX4_ICM_PAGE_SIZE < PAGE_SIZE. */ *aux_pages = ALIGN(*aux_pages, PAGE_SIZE / MLX4_ICM_PAGE_SIZE) >> (PAGE_SHIFT - MLX4_ICM_PAGE_SHIFT); return 0; } int mlx4_NOP(struct mlx4_dev *dev) { /* Input modifier of 0x1f means "finish as soon as possible." */ return mlx4_cmd(dev, 0, 0x1f, 0, MLX4_CMD_NOP, 100, MLX4_CMD_NATIVE); } #define MLX4_WOL_SETUP_MODE (5 << 28) int mlx4_wol_read(struct mlx4_dev *dev, u64 *config, int port) { u32 in_mod = MLX4_WOL_SETUP_MODE | port << 8; return mlx4_cmd_imm(dev, 0, config, in_mod, 0x3, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } EXPORT_SYMBOL_GPL(mlx4_wol_read); int mlx4_wol_write(struct mlx4_dev *dev, u64 config, int port) { u32 in_mod = MLX4_WOL_SETUP_MODE | port << 8; return mlx4_cmd(dev, config, in_mod, 0x1, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } EXPORT_SYMBOL_GPL(mlx4_wol_write);
gpl-2.0
travarilo/redkancut_cancro
drivers/net/ethernet/myricom/myri10ge/myri10ge.c
4810
118612
/************************************************************************* * myri10ge.c: Myricom Myri-10G Ethernet driver. * * Copyright (C) 2005 - 2011 Myricom, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Myricom, Inc. nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * If the eeprom on your board is not recent enough, you will need to get a * newer firmware image at: * http://www.myri.com/scs/download-Myri10GE.html * * Contact Information: * <help@myri.com> * Myricom, Inc., 325N Santa Anita Avenue, Arcadia, CA 91006 *************************************************************************/ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/tcp.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/string.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/etherdevice.h> #include <linux/if_ether.h> #include <linux/if_vlan.h> #include <linux/inet_lro.h> #include <linux/dca.h> #include <linux/ip.h> #include <linux/inet.h> #include <linux/in.h> #include <linux/ethtool.h> #include <linux/firmware.h> #include <linux/delay.h> #include <linux/timer.h> #include <linux/vmalloc.h> #include <linux/crc32.h> #include <linux/moduleparam.h> #include <linux/io.h> #include <linux/log2.h> #include <linux/slab.h> #include <linux/prefetch.h> #include <net/checksum.h> #include <net/ip.h> #include <net/tcp.h> #include <asm/byteorder.h> #include <asm/io.h> #include <asm/processor.h> #ifdef CONFIG_MTRR #include <asm/mtrr.h> #endif #include "myri10ge_mcp.h" #include "myri10ge_mcp_gen_header.h" #define MYRI10GE_VERSION_STR "1.5.3-1.534" MODULE_DESCRIPTION("Myricom 10G driver (10GbE)"); MODULE_AUTHOR("Maintainer: help@myri.com"); MODULE_VERSION(MYRI10GE_VERSION_STR); MODULE_LICENSE("Dual BSD/GPL"); #define MYRI10GE_MAX_ETHER_MTU 9014 #define MYRI10GE_ETH_STOPPED 0 #define MYRI10GE_ETH_STOPPING 1 #define MYRI10GE_ETH_STARTING 2 #define MYRI10GE_ETH_RUNNING 3 #define MYRI10GE_ETH_OPEN_FAILED 4 #define MYRI10GE_EEPROM_STRINGS_SIZE 256 #define MYRI10GE_MAX_SEND_DESC_TSO ((65536 / 2048) * 2) #define MYRI10GE_MAX_LRO_DESCRIPTORS 8 #define MYRI10GE_LRO_MAX_PKTS 64 #define MYRI10GE_NO_CONFIRM_DATA htonl(0xffffffff) #define MYRI10GE_NO_RESPONSE_RESULT 0xffffffff #define MYRI10GE_ALLOC_ORDER 0 #define MYRI10GE_ALLOC_SIZE ((1 << MYRI10GE_ALLOC_ORDER) * PAGE_SIZE) #define MYRI10GE_MAX_FRAGS_PER_FRAME (MYRI10GE_MAX_ETHER_MTU/MYRI10GE_ALLOC_SIZE + 1) #define MYRI10GE_MAX_SLICES 32 struct myri10ge_rx_buffer_state { struct page *page; int page_offset; DEFINE_DMA_UNMAP_ADDR(bus); DEFINE_DMA_UNMAP_LEN(len); }; struct myri10ge_tx_buffer_state { struct sk_buff *skb; int last; DEFINE_DMA_UNMAP_ADDR(bus); DEFINE_DMA_UNMAP_LEN(len); }; struct myri10ge_cmd { u32 data0; u32 data1; u32 data2; }; struct myri10ge_rx_buf { struct mcp_kreq_ether_recv __iomem *lanai; /* lanai ptr for recv ring */ struct mcp_kreq_ether_recv *shadow; /* host shadow of recv ring */ struct myri10ge_rx_buffer_state *info; struct page *page; dma_addr_t bus; int page_offset; int cnt; int fill_cnt; int alloc_fail; int mask; /* number of rx slots -1 */ int watchdog_needed; }; struct myri10ge_tx_buf { struct mcp_kreq_ether_send __iomem *lanai; /* lanai ptr for sendq */ __be32 __iomem *send_go; /* "go" doorbell ptr */ __be32 __iomem *send_stop; /* "stop" doorbell ptr */ struct mcp_kreq_ether_send *req_list; /* host shadow of sendq */ char *req_bytes; struct myri10ge_tx_buffer_state *info; int mask; /* number of transmit slots -1 */ int req ____cacheline_aligned; /* transmit slots submitted */ int pkt_start; /* packets started */ int stop_queue; int linearized; int done ____cacheline_aligned; /* transmit slots completed */ int pkt_done; /* packets completed */ int wake_queue; int queue_active; }; struct myri10ge_rx_done { struct mcp_slot *entry; dma_addr_t bus; int cnt; int idx; struct net_lro_mgr lro_mgr; struct net_lro_desc lro_desc[MYRI10GE_MAX_LRO_DESCRIPTORS]; }; struct myri10ge_slice_netstats { unsigned long rx_packets; unsigned long tx_packets; unsigned long rx_bytes; unsigned long tx_bytes; unsigned long rx_dropped; unsigned long tx_dropped; }; struct myri10ge_slice_state { struct myri10ge_tx_buf tx; /* transmit ring */ struct myri10ge_rx_buf rx_small; struct myri10ge_rx_buf rx_big; struct myri10ge_rx_done rx_done; struct net_device *dev; struct napi_struct napi; struct myri10ge_priv *mgp; struct myri10ge_slice_netstats stats; __be32 __iomem *irq_claim; struct mcp_irq_data *fw_stats; dma_addr_t fw_stats_bus; int watchdog_tx_done; int watchdog_tx_req; int watchdog_rx_done; int stuck; #ifdef CONFIG_MYRI10GE_DCA int cached_dca_tag; int cpu; __be32 __iomem *dca_tag; #endif char irq_desc[32]; }; struct myri10ge_priv { struct myri10ge_slice_state *ss; int tx_boundary; /* boundary transmits cannot cross */ int num_slices; int running; /* running? */ int small_bytes; int big_bytes; int max_intr_slots; struct net_device *dev; u8 __iomem *sram; int sram_size; unsigned long board_span; unsigned long iomem_base; __be32 __iomem *irq_deassert; char *mac_addr_string; struct mcp_cmd_response *cmd; dma_addr_t cmd_bus; struct pci_dev *pdev; int msi_enabled; int msix_enabled; struct msix_entry *msix_vectors; #ifdef CONFIG_MYRI10GE_DCA int dca_enabled; int relaxed_order; #endif u32 link_state; unsigned int rdma_tags_available; int intr_coal_delay; __be32 __iomem *intr_coal_delay_ptr; int mtrr; int wc_enabled; int down_cnt; wait_queue_head_t down_wq; struct work_struct watchdog_work; struct timer_list watchdog_timer; int watchdog_resets; int watchdog_pause; int pause; bool fw_name_allocated; char *fw_name; char eeprom_strings[MYRI10GE_EEPROM_STRINGS_SIZE]; char *product_code_string; char fw_version[128]; int fw_ver_major; int fw_ver_minor; int fw_ver_tiny; int adopted_rx_filter_bug; u8 mac_addr[6]; /* eeprom mac address */ unsigned long serial_number; int vendor_specific_offset; int fw_multicast_support; u32 features; u32 max_tso6; u32 read_dma; u32 write_dma; u32 read_write_dma; u32 link_changes; u32 msg_enable; unsigned int board_number; int rebooted; }; static char *myri10ge_fw_unaligned = "myri10ge_ethp_z8e.dat"; static char *myri10ge_fw_aligned = "myri10ge_eth_z8e.dat"; static char *myri10ge_fw_rss_unaligned = "myri10ge_rss_ethp_z8e.dat"; static char *myri10ge_fw_rss_aligned = "myri10ge_rss_eth_z8e.dat"; MODULE_FIRMWARE("myri10ge_ethp_z8e.dat"); MODULE_FIRMWARE("myri10ge_eth_z8e.dat"); MODULE_FIRMWARE("myri10ge_rss_ethp_z8e.dat"); MODULE_FIRMWARE("myri10ge_rss_eth_z8e.dat"); /* Careful: must be accessed under kparam_block_sysfs_write */ static char *myri10ge_fw_name = NULL; module_param(myri10ge_fw_name, charp, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(myri10ge_fw_name, "Firmware image name"); #define MYRI10GE_MAX_BOARDS 8 static char *myri10ge_fw_names[MYRI10GE_MAX_BOARDS] = {[0 ... (MYRI10GE_MAX_BOARDS - 1)] = NULL }; module_param_array_named(myri10ge_fw_names, myri10ge_fw_names, charp, NULL, 0444); MODULE_PARM_DESC(myri10ge_fw_name, "Firmware image names per board"); static int myri10ge_ecrc_enable = 1; module_param(myri10ge_ecrc_enable, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_ecrc_enable, "Enable Extended CRC on PCI-E"); static int myri10ge_small_bytes = -1; /* -1 == auto */ module_param(myri10ge_small_bytes, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(myri10ge_small_bytes, "Threshold of small packets"); static int myri10ge_msi = 1; /* enable msi by default */ module_param(myri10ge_msi, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(myri10ge_msi, "Enable Message Signalled Interrupts"); static int myri10ge_intr_coal_delay = 75; module_param(myri10ge_intr_coal_delay, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_intr_coal_delay, "Interrupt coalescing delay"); static int myri10ge_flow_control = 1; module_param(myri10ge_flow_control, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_flow_control, "Pause parameter"); static int myri10ge_deassert_wait = 1; module_param(myri10ge_deassert_wait, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(myri10ge_deassert_wait, "Wait when deasserting legacy interrupts"); static int myri10ge_force_firmware = 0; module_param(myri10ge_force_firmware, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_force_firmware, "Force firmware to assume aligned completions"); static int myri10ge_initial_mtu = MYRI10GE_MAX_ETHER_MTU - ETH_HLEN; module_param(myri10ge_initial_mtu, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_initial_mtu, "Initial MTU"); static int myri10ge_napi_weight = 64; module_param(myri10ge_napi_weight, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_napi_weight, "Set NAPI weight"); static int myri10ge_watchdog_timeout = 1; module_param(myri10ge_watchdog_timeout, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_watchdog_timeout, "Set watchdog timeout"); static int myri10ge_max_irq_loops = 1048576; module_param(myri10ge_max_irq_loops, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_max_irq_loops, "Set stuck legacy IRQ detection threshold"); #define MYRI10GE_MSG_DEFAULT NETIF_MSG_LINK static int myri10ge_debug = -1; /* defaults above */ module_param(myri10ge_debug, int, 0); MODULE_PARM_DESC(myri10ge_debug, "Debug level (0=none,...,16=all)"); static int myri10ge_lro_max_pkts = MYRI10GE_LRO_MAX_PKTS; module_param(myri10ge_lro_max_pkts, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_lro_max_pkts, "Number of LRO packets to be aggregated"); static int myri10ge_fill_thresh = 256; module_param(myri10ge_fill_thresh, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(myri10ge_fill_thresh, "Number of empty rx slots allowed"); static int myri10ge_reset_recover = 1; static int myri10ge_max_slices = 1; module_param(myri10ge_max_slices, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_max_slices, "Max tx/rx queues"); static int myri10ge_rss_hash = MXGEFW_RSS_HASH_TYPE_SRC_DST_PORT; module_param(myri10ge_rss_hash, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_rss_hash, "Type of RSS hashing to do"); static int myri10ge_dca = 1; module_param(myri10ge_dca, int, S_IRUGO); MODULE_PARM_DESC(myri10ge_dca, "Enable DCA if possible"); #define MYRI10GE_FW_OFFSET 1024*1024 #define MYRI10GE_HIGHPART_TO_U32(X) \ (sizeof (X) == 8) ? ((u32)((u64)(X) >> 32)) : (0) #define MYRI10GE_LOWPART_TO_U32(X) ((u32)(X)) #define myri10ge_pio_copy(to,from,size) __iowrite64_copy(to,from,size/8) static void myri10ge_set_multicast_list(struct net_device *dev); static netdev_tx_t myri10ge_sw_tso(struct sk_buff *skb, struct net_device *dev); static inline void put_be32(__be32 val, __be32 __iomem * p) { __raw_writel((__force __u32) val, (__force void __iomem *)p); } static struct rtnl_link_stats64 *myri10ge_get_stats(struct net_device *dev, struct rtnl_link_stats64 *stats); static void set_fw_name(struct myri10ge_priv *mgp, char *name, bool allocated) { if (mgp->fw_name_allocated) kfree(mgp->fw_name); mgp->fw_name = name; mgp->fw_name_allocated = allocated; } static int myri10ge_send_cmd(struct myri10ge_priv *mgp, u32 cmd, struct myri10ge_cmd *data, int atomic) { struct mcp_cmd *buf; char buf_bytes[sizeof(*buf) + 8]; struct mcp_cmd_response *response = mgp->cmd; char __iomem *cmd_addr = mgp->sram + MXGEFW_ETH_CMD; u32 dma_low, dma_high, result, value; int sleep_total = 0; /* ensure buf is aligned to 8 bytes */ buf = (struct mcp_cmd *)ALIGN((unsigned long)buf_bytes, 8); buf->data0 = htonl(data->data0); buf->data1 = htonl(data->data1); buf->data2 = htonl(data->data2); buf->cmd = htonl(cmd); dma_low = MYRI10GE_LOWPART_TO_U32(mgp->cmd_bus); dma_high = MYRI10GE_HIGHPART_TO_U32(mgp->cmd_bus); buf->response_addr.low = htonl(dma_low); buf->response_addr.high = htonl(dma_high); response->result = htonl(MYRI10GE_NO_RESPONSE_RESULT); mb(); myri10ge_pio_copy(cmd_addr, buf, sizeof(*buf)); /* wait up to 15ms. Longest command is the DMA benchmark, * which is capped at 5ms, but runs from a timeout handler * that runs every 7.8ms. So a 15ms timeout leaves us with * a 2.2ms margin */ if (atomic) { /* if atomic is set, do not sleep, * and try to get the completion quickly * (1ms will be enough for those commands) */ for (sleep_total = 0; sleep_total < 1000 && response->result == htonl(MYRI10GE_NO_RESPONSE_RESULT); sleep_total += 10) { udelay(10); mb(); } } else { /* use msleep for most command */ for (sleep_total = 0; sleep_total < 15 && response->result == htonl(MYRI10GE_NO_RESPONSE_RESULT); sleep_total++) msleep(1); } result = ntohl(response->result); value = ntohl(response->data); if (result != MYRI10GE_NO_RESPONSE_RESULT) { if (result == 0) { data->data0 = value; return 0; } else if (result == MXGEFW_CMD_UNKNOWN) { return -ENOSYS; } else if (result == MXGEFW_CMD_ERROR_UNALIGNED) { return -E2BIG; } else if (result == MXGEFW_CMD_ERROR_RANGE && cmd == MXGEFW_CMD_ENABLE_RSS_QUEUES && (data-> data1 & MXGEFW_SLICE_ENABLE_MULTIPLE_TX_QUEUES) != 0) { return -ERANGE; } else { dev_err(&mgp->pdev->dev, "command %d failed, result = %d\n", cmd, result); return -ENXIO; } } dev_err(&mgp->pdev->dev, "command %d timed out, result = %d\n", cmd, result); return -EAGAIN; } /* * The eeprom strings on the lanaiX have the format * SN=x\0 * MAC=x:x:x:x:x:x\0 * PT:ddd mmm xx xx:xx:xx xx\0 * PV:ddd mmm xx xx:xx:xx xx\0 */ static int myri10ge_read_mac_addr(struct myri10ge_priv *mgp) { char *ptr, *limit; int i; ptr = mgp->eeprom_strings; limit = mgp->eeprom_strings + MYRI10GE_EEPROM_STRINGS_SIZE; while (*ptr != '\0' && ptr < limit) { if (memcmp(ptr, "MAC=", 4) == 0) { ptr += 4; mgp->mac_addr_string = ptr; for (i = 0; i < 6; i++) { if ((ptr + 2) > limit) goto abort; mgp->mac_addr[i] = simple_strtoul(ptr, &ptr, 16); ptr += 1; } } if (memcmp(ptr, "PC=", 3) == 0) { ptr += 3; mgp->product_code_string = ptr; } if (memcmp((const void *)ptr, "SN=", 3) == 0) { ptr += 3; mgp->serial_number = simple_strtoul(ptr, &ptr, 10); } while (ptr < limit && *ptr++) ; } return 0; abort: dev_err(&mgp->pdev->dev, "failed to parse eeprom_strings\n"); return -ENXIO; } /* * Enable or disable periodic RDMAs from the host to make certain * chipsets resend dropped PCIe messages */ static void myri10ge_dummy_rdma(struct myri10ge_priv *mgp, int enable) { char __iomem *submit; __be32 buf[16] __attribute__ ((__aligned__(8))); u32 dma_low, dma_high; int i; /* clear confirmation addr */ mgp->cmd->data = 0; mb(); /* send a rdma command to the PCIe engine, and wait for the * response in the confirmation address. The firmware should * write a -1 there to indicate it is alive and well */ dma_low = MYRI10GE_LOWPART_TO_U32(mgp->cmd_bus); dma_high = MYRI10GE_HIGHPART_TO_U32(mgp->cmd_bus); buf[0] = htonl(dma_high); /* confirm addr MSW */ buf[1] = htonl(dma_low); /* confirm addr LSW */ buf[2] = MYRI10GE_NO_CONFIRM_DATA; /* confirm data */ buf[3] = htonl(dma_high); /* dummy addr MSW */ buf[4] = htonl(dma_low); /* dummy addr LSW */ buf[5] = htonl(enable); /* enable? */ submit = mgp->sram + MXGEFW_BOOT_DUMMY_RDMA; myri10ge_pio_copy(submit, &buf, sizeof(buf)); for (i = 0; mgp->cmd->data != MYRI10GE_NO_CONFIRM_DATA && i < 20; i++) msleep(1); if (mgp->cmd->data != MYRI10GE_NO_CONFIRM_DATA) dev_err(&mgp->pdev->dev, "dummy rdma %s failed\n", (enable ? "enable" : "disable")); } static int myri10ge_validate_firmware(struct myri10ge_priv *mgp, struct mcp_gen_header *hdr) { struct device *dev = &mgp->pdev->dev; /* check firmware type */ if (ntohl(hdr->mcp_type) != MCP_TYPE_ETH) { dev_err(dev, "Bad firmware type: 0x%x\n", ntohl(hdr->mcp_type)); return -EINVAL; } /* save firmware version for ethtool */ strncpy(mgp->fw_version, hdr->version, sizeof(mgp->fw_version)); sscanf(mgp->fw_version, "%d.%d.%d", &mgp->fw_ver_major, &mgp->fw_ver_minor, &mgp->fw_ver_tiny); if (!(mgp->fw_ver_major == MXGEFW_VERSION_MAJOR && mgp->fw_ver_minor == MXGEFW_VERSION_MINOR)) { dev_err(dev, "Found firmware version %s\n", mgp->fw_version); dev_err(dev, "Driver needs %d.%d\n", MXGEFW_VERSION_MAJOR, MXGEFW_VERSION_MINOR); return -EINVAL; } return 0; } static int myri10ge_load_hotplug_firmware(struct myri10ge_priv *mgp, u32 * size) { unsigned crc, reread_crc; const struct firmware *fw; struct device *dev = &mgp->pdev->dev; unsigned char *fw_readback; struct mcp_gen_header *hdr; size_t hdr_offset; int status; unsigned i; if ((status = request_firmware(&fw, mgp->fw_name, dev)) < 0) { dev_err(dev, "Unable to load %s firmware image via hotplug\n", mgp->fw_name); status = -EINVAL; goto abort_with_nothing; } /* check size */ if (fw->size >= mgp->sram_size - MYRI10GE_FW_OFFSET || fw->size < MCP_HEADER_PTR_OFFSET + 4) { dev_err(dev, "Firmware size invalid:%d\n", (int)fw->size); status = -EINVAL; goto abort_with_fw; } /* check id */ hdr_offset = ntohl(*(__be32 *) (fw->data + MCP_HEADER_PTR_OFFSET)); if ((hdr_offset & 3) || hdr_offset + sizeof(*hdr) > fw->size) { dev_err(dev, "Bad firmware file\n"); status = -EINVAL; goto abort_with_fw; } hdr = (void *)(fw->data + hdr_offset); status = myri10ge_validate_firmware(mgp, hdr); if (status != 0) goto abort_with_fw; crc = crc32(~0, fw->data, fw->size); for (i = 0; i < fw->size; i += 256) { myri10ge_pio_copy(mgp->sram + MYRI10GE_FW_OFFSET + i, fw->data + i, min(256U, (unsigned)(fw->size - i))); mb(); readb(mgp->sram); } fw_readback = vmalloc(fw->size); if (!fw_readback) { status = -ENOMEM; goto abort_with_fw; } /* corruption checking is good for parity recovery and buggy chipset */ memcpy_fromio(fw_readback, mgp->sram + MYRI10GE_FW_OFFSET, fw->size); reread_crc = crc32(~0, fw_readback, fw->size); vfree(fw_readback); if (crc != reread_crc) { dev_err(dev, "CRC failed(fw-len=%u), got 0x%x (expect 0x%x)\n", (unsigned)fw->size, reread_crc, crc); status = -EIO; goto abort_with_fw; } *size = (u32) fw->size; abort_with_fw: release_firmware(fw); abort_with_nothing: return status; } static int myri10ge_adopt_running_firmware(struct myri10ge_priv *mgp) { struct mcp_gen_header *hdr; struct device *dev = &mgp->pdev->dev; const size_t bytes = sizeof(struct mcp_gen_header); size_t hdr_offset; int status; /* find running firmware header */ hdr_offset = swab32(readl(mgp->sram + MCP_HEADER_PTR_OFFSET)); if ((hdr_offset & 3) || hdr_offset + sizeof(*hdr) > mgp->sram_size) { dev_err(dev, "Running firmware has bad header offset (%d)\n", (int)hdr_offset); return -EIO; } /* copy header of running firmware from SRAM to host memory to * validate firmware */ hdr = kmalloc(bytes, GFP_KERNEL); if (hdr == NULL) { dev_err(dev, "could not malloc firmware hdr\n"); return -ENOMEM; } memcpy_fromio(hdr, mgp->sram + hdr_offset, bytes); status = myri10ge_validate_firmware(mgp, hdr); kfree(hdr); /* check to see if adopted firmware has bug where adopting * it will cause broadcasts to be filtered unless the NIC * is kept in ALLMULTI mode */ if (mgp->fw_ver_major == 1 && mgp->fw_ver_minor == 4 && mgp->fw_ver_tiny >= 4 && mgp->fw_ver_tiny <= 11) { mgp->adopted_rx_filter_bug = 1; dev_warn(dev, "Adopting fw %d.%d.%d: " "working around rx filter bug\n", mgp->fw_ver_major, mgp->fw_ver_minor, mgp->fw_ver_tiny); } return status; } static int myri10ge_get_firmware_capabilities(struct myri10ge_priv *mgp) { struct myri10ge_cmd cmd; int status; /* probe for IPv6 TSO support */ mgp->features = NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_TSO; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_MAX_TSO6_HDR_SIZE, &cmd, 0); if (status == 0) { mgp->max_tso6 = cmd.data0; mgp->features |= NETIF_F_TSO6; } status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_RX_RING_SIZE, &cmd, 0); if (status != 0) { dev_err(&mgp->pdev->dev, "failed MXGEFW_CMD_GET_RX_RING_SIZE\n"); return -ENXIO; } mgp->max_intr_slots = 2 * (cmd.data0 / sizeof(struct mcp_dma_addr)); return 0; } static int myri10ge_load_firmware(struct myri10ge_priv *mgp, int adopt) { char __iomem *submit; __be32 buf[16] __attribute__ ((__aligned__(8))); u32 dma_low, dma_high, size; int status, i; size = 0; status = myri10ge_load_hotplug_firmware(mgp, &size); if (status) { if (!adopt) return status; dev_warn(&mgp->pdev->dev, "hotplug firmware loading failed\n"); /* Do not attempt to adopt firmware if there * was a bad crc */ if (status == -EIO) return status; status = myri10ge_adopt_running_firmware(mgp); if (status != 0) { dev_err(&mgp->pdev->dev, "failed to adopt running firmware\n"); return status; } dev_info(&mgp->pdev->dev, "Successfully adopted running firmware\n"); if (mgp->tx_boundary == 4096) { dev_warn(&mgp->pdev->dev, "Using firmware currently running on NIC" ". For optimal\n"); dev_warn(&mgp->pdev->dev, "performance consider loading optimized " "firmware\n"); dev_warn(&mgp->pdev->dev, "via hotplug\n"); } set_fw_name(mgp, "adopted", false); mgp->tx_boundary = 2048; myri10ge_dummy_rdma(mgp, 1); status = myri10ge_get_firmware_capabilities(mgp); return status; } /* clear confirmation addr */ mgp->cmd->data = 0; mb(); /* send a reload command to the bootstrap MCP, and wait for the * response in the confirmation address. The firmware should * write a -1 there to indicate it is alive and well */ dma_low = MYRI10GE_LOWPART_TO_U32(mgp->cmd_bus); dma_high = MYRI10GE_HIGHPART_TO_U32(mgp->cmd_bus); buf[0] = htonl(dma_high); /* confirm addr MSW */ buf[1] = htonl(dma_low); /* confirm addr LSW */ buf[2] = MYRI10GE_NO_CONFIRM_DATA; /* confirm data */ /* FIX: All newest firmware should un-protect the bottom of * the sram before handoff. However, the very first interfaces * do not. Therefore the handoff copy must skip the first 8 bytes */ buf[3] = htonl(MYRI10GE_FW_OFFSET + 8); /* where the code starts */ buf[4] = htonl(size - 8); /* length of code */ buf[5] = htonl(8); /* where to copy to */ buf[6] = htonl(0); /* where to jump to */ submit = mgp->sram + MXGEFW_BOOT_HANDOFF; myri10ge_pio_copy(submit, &buf, sizeof(buf)); mb(); msleep(1); mb(); i = 0; while (mgp->cmd->data != MYRI10GE_NO_CONFIRM_DATA && i < 9) { msleep(1 << i); i++; } if (mgp->cmd->data != MYRI10GE_NO_CONFIRM_DATA) { dev_err(&mgp->pdev->dev, "handoff failed\n"); return -ENXIO; } myri10ge_dummy_rdma(mgp, 1); status = myri10ge_get_firmware_capabilities(mgp); return status; } static int myri10ge_update_mac_address(struct myri10ge_priv *mgp, u8 * addr) { struct myri10ge_cmd cmd; int status; cmd.data0 = ((addr[0] << 24) | (addr[1] << 16) | (addr[2] << 8) | addr[3]); cmd.data1 = ((addr[4] << 8) | (addr[5])); status = myri10ge_send_cmd(mgp, MXGEFW_SET_MAC_ADDRESS, &cmd, 0); return status; } static int myri10ge_change_pause(struct myri10ge_priv *mgp, int pause) { struct myri10ge_cmd cmd; int status, ctl; ctl = pause ? MXGEFW_ENABLE_FLOW_CONTROL : MXGEFW_DISABLE_FLOW_CONTROL; status = myri10ge_send_cmd(mgp, ctl, &cmd, 0); if (status) { netdev_err(mgp->dev, "Failed to set flow control mode\n"); return status; } mgp->pause = pause; return 0; } static void myri10ge_change_promisc(struct myri10ge_priv *mgp, int promisc, int atomic) { struct myri10ge_cmd cmd; int status, ctl; ctl = promisc ? MXGEFW_ENABLE_PROMISC : MXGEFW_DISABLE_PROMISC; status = myri10ge_send_cmd(mgp, ctl, &cmd, atomic); if (status) netdev_err(mgp->dev, "Failed to set promisc mode\n"); } static int myri10ge_dma_test(struct myri10ge_priv *mgp, int test_type) { struct myri10ge_cmd cmd; int status; u32 len; struct page *dmatest_page; dma_addr_t dmatest_bus; char *test = " "; dmatest_page = alloc_page(GFP_KERNEL); if (!dmatest_page) return -ENOMEM; dmatest_bus = pci_map_page(mgp->pdev, dmatest_page, 0, PAGE_SIZE, DMA_BIDIRECTIONAL); /* Run a small DMA test. * The magic multipliers to the length tell the firmware * to do DMA read, write, or read+write tests. The * results are returned in cmd.data0. The upper 16 * bits or the return is the number of transfers completed. * The lower 16 bits is the time in 0.5us ticks that the * transfers took to complete. */ len = mgp->tx_boundary; cmd.data0 = MYRI10GE_LOWPART_TO_U32(dmatest_bus); cmd.data1 = MYRI10GE_HIGHPART_TO_U32(dmatest_bus); cmd.data2 = len * 0x10000; status = myri10ge_send_cmd(mgp, test_type, &cmd, 0); if (status != 0) { test = "read"; goto abort; } mgp->read_dma = ((cmd.data0 >> 16) * len * 2) / (cmd.data0 & 0xffff); cmd.data0 = MYRI10GE_LOWPART_TO_U32(dmatest_bus); cmd.data1 = MYRI10GE_HIGHPART_TO_U32(dmatest_bus); cmd.data2 = len * 0x1; status = myri10ge_send_cmd(mgp, test_type, &cmd, 0); if (status != 0) { test = "write"; goto abort; } mgp->write_dma = ((cmd.data0 >> 16) * len * 2) / (cmd.data0 & 0xffff); cmd.data0 = MYRI10GE_LOWPART_TO_U32(dmatest_bus); cmd.data1 = MYRI10GE_HIGHPART_TO_U32(dmatest_bus); cmd.data2 = len * 0x10001; status = myri10ge_send_cmd(mgp, test_type, &cmd, 0); if (status != 0) { test = "read/write"; goto abort; } mgp->read_write_dma = ((cmd.data0 >> 16) * len * 2 * 2) / (cmd.data0 & 0xffff); abort: pci_unmap_page(mgp->pdev, dmatest_bus, PAGE_SIZE, DMA_BIDIRECTIONAL); put_page(dmatest_page); if (status != 0 && test_type != MXGEFW_CMD_UNALIGNED_TEST) dev_warn(&mgp->pdev->dev, "DMA %s benchmark failed: %d\n", test, status); return status; } static int myri10ge_reset(struct myri10ge_priv *mgp) { struct myri10ge_cmd cmd; struct myri10ge_slice_state *ss; int i, status; size_t bytes; #ifdef CONFIG_MYRI10GE_DCA unsigned long dca_tag_off; #endif /* try to send a reset command to the card to see if it * is alive */ memset(&cmd, 0, sizeof(cmd)); status = myri10ge_send_cmd(mgp, MXGEFW_CMD_RESET, &cmd, 0); if (status != 0) { dev_err(&mgp->pdev->dev, "failed reset\n"); return -ENXIO; } (void)myri10ge_dma_test(mgp, MXGEFW_DMA_TEST); /* * Use non-ndis mcp_slot (eg, 4 bytes total, * no toeplitz hash value returned. Older firmware will * not understand this command, but will use the correct * sized mcp_slot, so we ignore error returns */ cmd.data0 = MXGEFW_RSS_MCP_SLOT_TYPE_MIN; (void)myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_RSS_MCP_SLOT_TYPE, &cmd, 0); /* Now exchange information about interrupts */ bytes = mgp->max_intr_slots * sizeof(*mgp->ss[0].rx_done.entry); cmd.data0 = (u32) bytes; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_INTRQ_SIZE, &cmd, 0); /* * Even though we already know how many slices are supported * via myri10ge_probe_slices() MXGEFW_CMD_GET_MAX_RSS_QUEUES * has magic side effects, and must be called after a reset. * It must be called prior to calling any RSS related cmds, * including assigning an interrupt queue for anything but * slice 0. It must also be called *after* * MXGEFW_CMD_SET_INTRQ_SIZE, since the intrq size is used by * the firmware to compute offsets. */ if (mgp->num_slices > 1) { /* ask the maximum number of slices it supports */ status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_MAX_RSS_QUEUES, &cmd, 0); if (status != 0) { dev_err(&mgp->pdev->dev, "failed to get number of slices\n"); } /* * MXGEFW_CMD_ENABLE_RSS_QUEUES must be called prior * to setting up the interrupt queue DMA */ cmd.data0 = mgp->num_slices; cmd.data1 = MXGEFW_SLICE_INTR_MODE_ONE_PER_SLICE; if (mgp->dev->real_num_tx_queues > 1) cmd.data1 |= MXGEFW_SLICE_ENABLE_MULTIPLE_TX_QUEUES; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_ENABLE_RSS_QUEUES, &cmd, 0); /* Firmware older than 1.4.32 only supports multiple * RX queues, so if we get an error, first retry using a * single TX queue before giving up */ if (status != 0 && mgp->dev->real_num_tx_queues > 1) { netif_set_real_num_tx_queues(mgp->dev, 1); cmd.data0 = mgp->num_slices; cmd.data1 = MXGEFW_SLICE_INTR_MODE_ONE_PER_SLICE; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_ENABLE_RSS_QUEUES, &cmd, 0); } if (status != 0) { dev_err(&mgp->pdev->dev, "failed to set number of slices\n"); return status; } } for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; cmd.data0 = MYRI10GE_LOWPART_TO_U32(ss->rx_done.bus); cmd.data1 = MYRI10GE_HIGHPART_TO_U32(ss->rx_done.bus); cmd.data2 = i; status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_INTRQ_DMA, &cmd, 0); } status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_IRQ_ACK_OFFSET, &cmd, 0); for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; ss->irq_claim = (__iomem __be32 *) (mgp->sram + cmd.data0 + 8 * i); } status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_IRQ_DEASSERT_OFFSET, &cmd, 0); mgp->irq_deassert = (__iomem __be32 *) (mgp->sram + cmd.data0); status |= myri10ge_send_cmd (mgp, MXGEFW_CMD_GET_INTR_COAL_DELAY_OFFSET, &cmd, 0); mgp->intr_coal_delay_ptr = (__iomem __be32 *) (mgp->sram + cmd.data0); if (status != 0) { dev_err(&mgp->pdev->dev, "failed set interrupt parameters\n"); return status; } put_be32(htonl(mgp->intr_coal_delay), mgp->intr_coal_delay_ptr); #ifdef CONFIG_MYRI10GE_DCA status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_DCA_OFFSET, &cmd, 0); dca_tag_off = cmd.data0; for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; if (status == 0) { ss->dca_tag = (__iomem __be32 *) (mgp->sram + dca_tag_off + 4 * i); } else { ss->dca_tag = NULL; } } #endif /* CONFIG_MYRI10GE_DCA */ /* reset mcp/driver shared state back to 0 */ mgp->link_changes = 0; for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; memset(ss->rx_done.entry, 0, bytes); ss->tx.req = 0; ss->tx.done = 0; ss->tx.pkt_start = 0; ss->tx.pkt_done = 0; ss->rx_big.cnt = 0; ss->rx_small.cnt = 0; ss->rx_done.idx = 0; ss->rx_done.cnt = 0; ss->tx.wake_queue = 0; ss->tx.stop_queue = 0; } status = myri10ge_update_mac_address(mgp, mgp->dev->dev_addr); myri10ge_change_pause(mgp, mgp->pause); myri10ge_set_multicast_list(mgp->dev); return status; } #ifdef CONFIG_MYRI10GE_DCA static int myri10ge_toggle_relaxed(struct pci_dev *pdev, int on) { int ret, cap, err; u16 ctl; cap = pci_pcie_cap(pdev); if (!cap) return 0; err = pci_read_config_word(pdev, cap + PCI_EXP_DEVCTL, &ctl); if (err) return 0; ret = (ctl & PCI_EXP_DEVCTL_RELAX_EN) >> 4; if (ret != on) { ctl &= ~PCI_EXP_DEVCTL_RELAX_EN; ctl |= (on << 4); pci_write_config_word(pdev, cap + PCI_EXP_DEVCTL, ctl); } return ret; } static void myri10ge_write_dca(struct myri10ge_slice_state *ss, int cpu, int tag) { ss->cached_dca_tag = tag; put_be32(htonl(tag), ss->dca_tag); } static inline void myri10ge_update_dca(struct myri10ge_slice_state *ss) { int cpu = get_cpu(); int tag; if (cpu != ss->cpu) { tag = dca3_get_tag(&ss->mgp->pdev->dev, cpu); if (ss->cached_dca_tag != tag) myri10ge_write_dca(ss, cpu, tag); ss->cpu = cpu; } put_cpu(); } static void myri10ge_setup_dca(struct myri10ge_priv *mgp) { int err, i; struct pci_dev *pdev = mgp->pdev; if (mgp->ss[0].dca_tag == NULL || mgp->dca_enabled) return; if (!myri10ge_dca) { dev_err(&pdev->dev, "dca disabled by administrator\n"); return; } err = dca_add_requester(&pdev->dev); if (err) { if (err != -ENODEV) dev_err(&pdev->dev, "dca_add_requester() failed, err=%d\n", err); return; } mgp->relaxed_order = myri10ge_toggle_relaxed(pdev, 0); mgp->dca_enabled = 1; for (i = 0; i < mgp->num_slices; i++) { mgp->ss[i].cpu = -1; mgp->ss[i].cached_dca_tag = -1; myri10ge_update_dca(&mgp->ss[i]); } } static void myri10ge_teardown_dca(struct myri10ge_priv *mgp) { struct pci_dev *pdev = mgp->pdev; if (!mgp->dca_enabled) return; mgp->dca_enabled = 0; if (mgp->relaxed_order) myri10ge_toggle_relaxed(pdev, 1); dca_remove_requester(&pdev->dev); } static int myri10ge_notify_dca_device(struct device *dev, void *data) { struct myri10ge_priv *mgp; unsigned long event; mgp = dev_get_drvdata(dev); event = *(unsigned long *)data; if (event == DCA_PROVIDER_ADD) myri10ge_setup_dca(mgp); else if (event == DCA_PROVIDER_REMOVE) myri10ge_teardown_dca(mgp); return 0; } #endif /* CONFIG_MYRI10GE_DCA */ static inline void myri10ge_submit_8rx(struct mcp_kreq_ether_recv __iomem * dst, struct mcp_kreq_ether_recv *src) { __be32 low; low = src->addr_low; src->addr_low = htonl(DMA_BIT_MASK(32)); myri10ge_pio_copy(dst, src, 4 * sizeof(*src)); mb(); myri10ge_pio_copy(dst + 4, src + 4, 4 * sizeof(*src)); mb(); src->addr_low = low; put_be32(low, &dst->addr_low); mb(); } static inline void myri10ge_vlan_ip_csum(struct sk_buff *skb, __wsum hw_csum) { struct vlan_hdr *vh = (struct vlan_hdr *)(skb->data); if ((skb->protocol == htons(ETH_P_8021Q)) && (vh->h_vlan_encapsulated_proto == htons(ETH_P_IP) || vh->h_vlan_encapsulated_proto == htons(ETH_P_IPV6))) { skb->csum = hw_csum; skb->ip_summed = CHECKSUM_COMPLETE; } } static inline void myri10ge_rx_skb_build(struct sk_buff *skb, u8 * va, struct skb_frag_struct *rx_frags, int len, int hlen) { struct skb_frag_struct *skb_frags; skb->len = skb->data_len = len; /* attach the page(s) */ skb_frags = skb_shinfo(skb)->frags; while (len > 0) { memcpy(skb_frags, rx_frags, sizeof(*skb_frags)); len -= skb_frag_size(rx_frags); skb_frags++; rx_frags++; skb_shinfo(skb)->nr_frags++; } /* pskb_may_pull is not available in irq context, but * skb_pull() (for ether_pad and eth_type_trans()) requires * the beginning of the packet in skb_headlen(), move it * manually */ skb_copy_to_linear_data(skb, va, hlen); skb_shinfo(skb)->frags[0].page_offset += hlen; skb_frag_size_sub(&skb_shinfo(skb)->frags[0], hlen); skb->data_len -= hlen; skb->tail += hlen; skb_pull(skb, MXGEFW_PAD); } static void myri10ge_alloc_rx_pages(struct myri10ge_priv *mgp, struct myri10ge_rx_buf *rx, int bytes, int watchdog) { struct page *page; int idx; #if MYRI10GE_ALLOC_SIZE > 4096 int end_offset; #endif if (unlikely(rx->watchdog_needed && !watchdog)) return; /* try to refill entire ring */ while (rx->fill_cnt != (rx->cnt + rx->mask + 1)) { idx = rx->fill_cnt & rx->mask; if (rx->page_offset + bytes <= MYRI10GE_ALLOC_SIZE) { /* we can use part of previous page */ get_page(rx->page); } else { /* we need a new page */ page = alloc_pages(GFP_ATOMIC | __GFP_COMP, MYRI10GE_ALLOC_ORDER); if (unlikely(page == NULL)) { if (rx->fill_cnt - rx->cnt < 16) rx->watchdog_needed = 1; return; } rx->page = page; rx->page_offset = 0; rx->bus = pci_map_page(mgp->pdev, page, 0, MYRI10GE_ALLOC_SIZE, PCI_DMA_FROMDEVICE); } rx->info[idx].page = rx->page; rx->info[idx].page_offset = rx->page_offset; /* note that this is the address of the start of the * page */ dma_unmap_addr_set(&rx->info[idx], bus, rx->bus); rx->shadow[idx].addr_low = htonl(MYRI10GE_LOWPART_TO_U32(rx->bus) + rx->page_offset); rx->shadow[idx].addr_high = htonl(MYRI10GE_HIGHPART_TO_U32(rx->bus)); /* start next packet on a cacheline boundary */ rx->page_offset += SKB_DATA_ALIGN(bytes); #if MYRI10GE_ALLOC_SIZE > 4096 /* don't cross a 4KB boundary */ end_offset = rx->page_offset + bytes - 1; if ((unsigned)(rx->page_offset ^ end_offset) > 4095) rx->page_offset = end_offset & ~4095; #endif rx->fill_cnt++; /* copy 8 descriptors to the firmware at a time */ if ((idx & 7) == 7) { myri10ge_submit_8rx(&rx->lanai[idx - 7], &rx->shadow[idx - 7]); } } } static inline void myri10ge_unmap_rx_page(struct pci_dev *pdev, struct myri10ge_rx_buffer_state *info, int bytes) { /* unmap the recvd page if we're the only or last user of it */ if (bytes >= MYRI10GE_ALLOC_SIZE / 2 || (info->page_offset + 2 * bytes) > MYRI10GE_ALLOC_SIZE) { pci_unmap_page(pdev, (dma_unmap_addr(info, bus) & ~(MYRI10GE_ALLOC_SIZE - 1)), MYRI10GE_ALLOC_SIZE, PCI_DMA_FROMDEVICE); } } #define MYRI10GE_HLEN 64 /* The number of bytes to copy from a * page into an skb */ static inline int myri10ge_rx_done(struct myri10ge_slice_state *ss, int len, __wsum csum, bool lro_enabled) { struct myri10ge_priv *mgp = ss->mgp; struct sk_buff *skb; struct skb_frag_struct rx_frags[MYRI10GE_MAX_FRAGS_PER_FRAME]; struct myri10ge_rx_buf *rx; int i, idx, hlen, remainder, bytes; struct pci_dev *pdev = mgp->pdev; struct net_device *dev = mgp->dev; u8 *va; if (len <= mgp->small_bytes) { rx = &ss->rx_small; bytes = mgp->small_bytes; } else { rx = &ss->rx_big; bytes = mgp->big_bytes; } len += MXGEFW_PAD; idx = rx->cnt & rx->mask; va = page_address(rx->info[idx].page) + rx->info[idx].page_offset; prefetch(va); /* Fill skb_frag_struct(s) with data from our receive */ for (i = 0, remainder = len; remainder > 0; i++) { myri10ge_unmap_rx_page(pdev, &rx->info[idx], bytes); __skb_frag_set_page(&rx_frags[i], rx->info[idx].page); rx_frags[i].page_offset = rx->info[idx].page_offset; if (remainder < MYRI10GE_ALLOC_SIZE) skb_frag_size_set(&rx_frags[i], remainder); else skb_frag_size_set(&rx_frags[i], MYRI10GE_ALLOC_SIZE); rx->cnt++; idx = rx->cnt & rx->mask; remainder -= MYRI10GE_ALLOC_SIZE; } if (lro_enabled) { rx_frags[0].page_offset += MXGEFW_PAD; skb_frag_size_sub(&rx_frags[0], MXGEFW_PAD); len -= MXGEFW_PAD; lro_receive_frags(&ss->rx_done.lro_mgr, rx_frags, /* opaque, will come back in get_frag_header */ len, len, (void *)(__force unsigned long)csum, csum); return 1; } hlen = MYRI10GE_HLEN > len ? len : MYRI10GE_HLEN; /* allocate an skb to attach the page(s) to. This is done * after trying LRO, so as to avoid skb allocation overheads */ skb = netdev_alloc_skb(dev, MYRI10GE_HLEN + 16); if (unlikely(skb == NULL)) { ss->stats.rx_dropped++; do { i--; __skb_frag_unref(&rx_frags[i]); } while (i != 0); return 0; } /* Attach the pages to the skb, and trim off any padding */ myri10ge_rx_skb_build(skb, va, rx_frags, len, hlen); if (skb_frag_size(&skb_shinfo(skb)->frags[0]) <= 0) { skb_frag_unref(skb, 0); skb_shinfo(skb)->nr_frags = 0; } else { skb->truesize += bytes * skb_shinfo(skb)->nr_frags; } skb->protocol = eth_type_trans(skb, dev); skb_record_rx_queue(skb, ss - &mgp->ss[0]); if (dev->features & NETIF_F_RXCSUM) { if ((skb->protocol == htons(ETH_P_IP)) || (skb->protocol == htons(ETH_P_IPV6))) { skb->csum = csum; skb->ip_summed = CHECKSUM_COMPLETE; } else myri10ge_vlan_ip_csum(skb, csum); } netif_receive_skb(skb); return 1; } static inline void myri10ge_tx_done(struct myri10ge_slice_state *ss, int mcp_index) { struct pci_dev *pdev = ss->mgp->pdev; struct myri10ge_tx_buf *tx = &ss->tx; struct netdev_queue *dev_queue; struct sk_buff *skb; int idx, len; while (tx->pkt_done != mcp_index) { idx = tx->done & tx->mask; skb = tx->info[idx].skb; /* Mark as free */ tx->info[idx].skb = NULL; if (tx->info[idx].last) { tx->pkt_done++; tx->info[idx].last = 0; } tx->done++; len = dma_unmap_len(&tx->info[idx], len); dma_unmap_len_set(&tx->info[idx], len, 0); if (skb) { ss->stats.tx_bytes += skb->len; ss->stats.tx_packets++; dev_kfree_skb_irq(skb); if (len) pci_unmap_single(pdev, dma_unmap_addr(&tx->info[idx], bus), len, PCI_DMA_TODEVICE); } else { if (len) pci_unmap_page(pdev, dma_unmap_addr(&tx->info[idx], bus), len, PCI_DMA_TODEVICE); } } dev_queue = netdev_get_tx_queue(ss->dev, ss - ss->mgp->ss); /* * Make a minimal effort to prevent the NIC from polling an * idle tx queue. If we can't get the lock we leave the queue * active. In this case, either a thread was about to start * using the queue anyway, or we lost a race and the NIC will * waste some of its resources polling an inactive queue for a * while. */ if ((ss->mgp->dev->real_num_tx_queues > 1) && __netif_tx_trylock(dev_queue)) { if (tx->req == tx->done) { tx->queue_active = 0; put_be32(htonl(1), tx->send_stop); mb(); mmiowb(); } __netif_tx_unlock(dev_queue); } /* start the queue if we've stopped it */ if (netif_tx_queue_stopped(dev_queue) && tx->req - tx->done < (tx->mask >> 1) && ss->mgp->running == MYRI10GE_ETH_RUNNING) { tx->wake_queue++; netif_tx_wake_queue(dev_queue); } } static inline int myri10ge_clean_rx_done(struct myri10ge_slice_state *ss, int budget) { struct myri10ge_rx_done *rx_done = &ss->rx_done; struct myri10ge_priv *mgp = ss->mgp; unsigned long rx_bytes = 0; unsigned long rx_packets = 0; unsigned long rx_ok; int idx = rx_done->idx; int cnt = rx_done->cnt; int work_done = 0; u16 length; __wsum checksum; /* * Prevent compiler from generating more than one ->features memory * access to avoid theoretical race condition with functions that * change NETIF_F_LRO flag at runtime. */ bool lro_enabled = !!(ACCESS_ONCE(mgp->dev->features) & NETIF_F_LRO); while (rx_done->entry[idx].length != 0 && work_done < budget) { length = ntohs(rx_done->entry[idx].length); rx_done->entry[idx].length = 0; checksum = csum_unfold(rx_done->entry[idx].checksum); rx_ok = myri10ge_rx_done(ss, length, checksum, lro_enabled); rx_packets += rx_ok; rx_bytes += rx_ok * (unsigned long)length; cnt++; idx = cnt & (mgp->max_intr_slots - 1); work_done++; } rx_done->idx = idx; rx_done->cnt = cnt; ss->stats.rx_packets += rx_packets; ss->stats.rx_bytes += rx_bytes; if (lro_enabled) lro_flush_all(&rx_done->lro_mgr); /* restock receive rings if needed */ if (ss->rx_small.fill_cnt - ss->rx_small.cnt < myri10ge_fill_thresh) myri10ge_alloc_rx_pages(mgp, &ss->rx_small, mgp->small_bytes + MXGEFW_PAD, 0); if (ss->rx_big.fill_cnt - ss->rx_big.cnt < myri10ge_fill_thresh) myri10ge_alloc_rx_pages(mgp, &ss->rx_big, mgp->big_bytes, 0); return work_done; } static inline void myri10ge_check_statblock(struct myri10ge_priv *mgp) { struct mcp_irq_data *stats = mgp->ss[0].fw_stats; if (unlikely(stats->stats_updated)) { unsigned link_up = ntohl(stats->link_up); if (mgp->link_state != link_up) { mgp->link_state = link_up; if (mgp->link_state == MXGEFW_LINK_UP) { netif_info(mgp, link, mgp->dev, "link up\n"); netif_carrier_on(mgp->dev); mgp->link_changes++; } else { netif_info(mgp, link, mgp->dev, "link %s\n", (link_up == MXGEFW_LINK_MYRINET ? "mismatch (Myrinet detected)" : "down")); netif_carrier_off(mgp->dev); mgp->link_changes++; } } if (mgp->rdma_tags_available != ntohl(stats->rdma_tags_available)) { mgp->rdma_tags_available = ntohl(stats->rdma_tags_available); netdev_warn(mgp->dev, "RDMA timed out! %d tags left\n", mgp->rdma_tags_available); } mgp->down_cnt += stats->link_down; if (stats->link_down) wake_up(&mgp->down_wq); } } static int myri10ge_poll(struct napi_struct *napi, int budget) { struct myri10ge_slice_state *ss = container_of(napi, struct myri10ge_slice_state, napi); int work_done; #ifdef CONFIG_MYRI10GE_DCA if (ss->mgp->dca_enabled) myri10ge_update_dca(ss); #endif /* process as many rx events as NAPI will allow */ work_done = myri10ge_clean_rx_done(ss, budget); if (work_done < budget) { napi_complete(napi); put_be32(htonl(3), ss->irq_claim); } return work_done; } static irqreturn_t myri10ge_intr(int irq, void *arg) { struct myri10ge_slice_state *ss = arg; struct myri10ge_priv *mgp = ss->mgp; struct mcp_irq_data *stats = ss->fw_stats; struct myri10ge_tx_buf *tx = &ss->tx; u32 send_done_count; int i; /* an interrupt on a non-zero receive-only slice is implicitly * valid since MSI-X irqs are not shared */ if ((mgp->dev->real_num_tx_queues == 1) && (ss != mgp->ss)) { napi_schedule(&ss->napi); return IRQ_HANDLED; } /* make sure it is our IRQ, and that the DMA has finished */ if (unlikely(!stats->valid)) return IRQ_NONE; /* low bit indicates receives are present, so schedule * napi poll handler */ if (stats->valid & 1) napi_schedule(&ss->napi); if (!mgp->msi_enabled && !mgp->msix_enabled) { put_be32(0, mgp->irq_deassert); if (!myri10ge_deassert_wait) stats->valid = 0; mb(); } else stats->valid = 0; /* Wait for IRQ line to go low, if using INTx */ i = 0; while (1) { i++; /* check for transmit completes and receives */ send_done_count = ntohl(stats->send_done_count); if (send_done_count != tx->pkt_done) myri10ge_tx_done(ss, (int)send_done_count); if (unlikely(i > myri10ge_max_irq_loops)) { netdev_warn(mgp->dev, "irq stuck?\n"); stats->valid = 0; schedule_work(&mgp->watchdog_work); } if (likely(stats->valid == 0)) break; cpu_relax(); barrier(); } /* Only slice 0 updates stats */ if (ss == mgp->ss) myri10ge_check_statblock(mgp); put_be32(htonl(3), ss->irq_claim + 1); return IRQ_HANDLED; } static int myri10ge_get_settings(struct net_device *netdev, struct ethtool_cmd *cmd) { struct myri10ge_priv *mgp = netdev_priv(netdev); char *ptr; int i; cmd->autoneg = AUTONEG_DISABLE; ethtool_cmd_speed_set(cmd, SPEED_10000); cmd->duplex = DUPLEX_FULL; /* * parse the product code to deterimine the interface type * (CX4, XFP, Quad Ribbon Fiber) by looking at the character * after the 3rd dash in the driver's cached copy of the * EEPROM's product code string. */ ptr = mgp->product_code_string; if (ptr == NULL) { netdev_err(netdev, "Missing product code\n"); return 0; } for (i = 0; i < 3; i++, ptr++) { ptr = strchr(ptr, '-'); if (ptr == NULL) { netdev_err(netdev, "Invalid product code %s\n", mgp->product_code_string); return 0; } } if (*ptr == '2') ptr++; if (*ptr == 'R' || *ptr == 'Q' || *ptr == 'S') { /* We've found either an XFP, quad ribbon fiber, or SFP+ */ cmd->port = PORT_FIBRE; cmd->supported |= SUPPORTED_FIBRE; cmd->advertising |= ADVERTISED_FIBRE; } else { cmd->port = PORT_OTHER; } if (*ptr == 'R' || *ptr == 'S') cmd->transceiver = XCVR_EXTERNAL; else cmd->transceiver = XCVR_INTERNAL; return 0; } static void myri10ge_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *info) { struct myri10ge_priv *mgp = netdev_priv(netdev); strlcpy(info->driver, "myri10ge", sizeof(info->driver)); strlcpy(info->version, MYRI10GE_VERSION_STR, sizeof(info->version)); strlcpy(info->fw_version, mgp->fw_version, sizeof(info->fw_version)); strlcpy(info->bus_info, pci_name(mgp->pdev), sizeof(info->bus_info)); } static int myri10ge_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *coal) { struct myri10ge_priv *mgp = netdev_priv(netdev); coal->rx_coalesce_usecs = mgp->intr_coal_delay; return 0; } static int myri10ge_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *coal) { struct myri10ge_priv *mgp = netdev_priv(netdev); mgp->intr_coal_delay = coal->rx_coalesce_usecs; put_be32(htonl(mgp->intr_coal_delay), mgp->intr_coal_delay_ptr); return 0; } static void myri10ge_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct myri10ge_priv *mgp = netdev_priv(netdev); pause->autoneg = 0; pause->rx_pause = mgp->pause; pause->tx_pause = mgp->pause; } static int myri10ge_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct myri10ge_priv *mgp = netdev_priv(netdev); if (pause->tx_pause != mgp->pause) return myri10ge_change_pause(mgp, pause->tx_pause); if (pause->rx_pause != mgp->pause) return myri10ge_change_pause(mgp, pause->rx_pause); if (pause->autoneg != 0) return -EINVAL; return 0; } static void myri10ge_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring) { struct myri10ge_priv *mgp = netdev_priv(netdev); ring->rx_mini_max_pending = mgp->ss[0].rx_small.mask + 1; ring->rx_max_pending = mgp->ss[0].rx_big.mask + 1; ring->rx_jumbo_max_pending = 0; ring->tx_max_pending = mgp->ss[0].tx.mask + 1; ring->rx_mini_pending = ring->rx_mini_max_pending; ring->rx_pending = ring->rx_max_pending; ring->rx_jumbo_pending = ring->rx_jumbo_max_pending; ring->tx_pending = ring->tx_max_pending; } static const char myri10ge_gstrings_main_stats[][ETH_GSTRING_LEN] = { "rx_packets", "tx_packets", "rx_bytes", "tx_bytes", "rx_errors", "tx_errors", "rx_dropped", "tx_dropped", "multicast", "collisions", "rx_length_errors", "rx_over_errors", "rx_crc_errors", "rx_frame_errors", "rx_fifo_errors", "rx_missed_errors", "tx_aborted_errors", "tx_carrier_errors", "tx_fifo_errors", "tx_heartbeat_errors", "tx_window_errors", /* device-specific stats */ "tx_boundary", "WC", "irq", "MSI", "MSIX", "read_dma_bw_MBs", "write_dma_bw_MBs", "read_write_dma_bw_MBs", "serial_number", "watchdog_resets", #ifdef CONFIG_MYRI10GE_DCA "dca_capable_firmware", "dca_device_present", #endif "link_changes", "link_up", "dropped_link_overflow", "dropped_link_error_or_filtered", "dropped_pause", "dropped_bad_phy", "dropped_bad_crc32", "dropped_unicast_filtered", "dropped_multicast_filtered", "dropped_runt", "dropped_overrun", "dropped_no_small_buffer", "dropped_no_big_buffer" }; static const char myri10ge_gstrings_slice_stats[][ETH_GSTRING_LEN] = { "----------- slice ---------", "tx_pkt_start", "tx_pkt_done", "tx_req", "tx_done", "rx_small_cnt", "rx_big_cnt", "wake_queue", "stop_queue", "tx_linearized", "LRO aggregated", "LRO flushed", "LRO avg aggr", "LRO no_desc", }; #define MYRI10GE_NET_STATS_LEN 21 #define MYRI10GE_MAIN_STATS_LEN ARRAY_SIZE(myri10ge_gstrings_main_stats) #define MYRI10GE_SLICE_STATS_LEN ARRAY_SIZE(myri10ge_gstrings_slice_stats) static void myri10ge_get_strings(struct net_device *netdev, u32 stringset, u8 * data) { struct myri10ge_priv *mgp = netdev_priv(netdev); int i; switch (stringset) { case ETH_SS_STATS: memcpy(data, *myri10ge_gstrings_main_stats, sizeof(myri10ge_gstrings_main_stats)); data += sizeof(myri10ge_gstrings_main_stats); for (i = 0; i < mgp->num_slices; i++) { memcpy(data, *myri10ge_gstrings_slice_stats, sizeof(myri10ge_gstrings_slice_stats)); data += sizeof(myri10ge_gstrings_slice_stats); } break; } } static int myri10ge_get_sset_count(struct net_device *netdev, int sset) { struct myri10ge_priv *mgp = netdev_priv(netdev); switch (sset) { case ETH_SS_STATS: return MYRI10GE_MAIN_STATS_LEN + mgp->num_slices * MYRI10GE_SLICE_STATS_LEN; default: return -EOPNOTSUPP; } } static void myri10ge_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats *stats, u64 * data) { struct myri10ge_priv *mgp = netdev_priv(netdev); struct myri10ge_slice_state *ss; struct rtnl_link_stats64 link_stats; int slice; int i; /* force stats update */ memset(&link_stats, 0, sizeof(link_stats)); (void)myri10ge_get_stats(netdev, &link_stats); for (i = 0; i < MYRI10GE_NET_STATS_LEN; i++) data[i] = ((u64 *)&link_stats)[i]; data[i++] = (unsigned int)mgp->tx_boundary; data[i++] = (unsigned int)mgp->wc_enabled; data[i++] = (unsigned int)mgp->pdev->irq; data[i++] = (unsigned int)mgp->msi_enabled; data[i++] = (unsigned int)mgp->msix_enabled; data[i++] = (unsigned int)mgp->read_dma; data[i++] = (unsigned int)mgp->write_dma; data[i++] = (unsigned int)mgp->read_write_dma; data[i++] = (unsigned int)mgp->serial_number; data[i++] = (unsigned int)mgp->watchdog_resets; #ifdef CONFIG_MYRI10GE_DCA data[i++] = (unsigned int)(mgp->ss[0].dca_tag != NULL); data[i++] = (unsigned int)(mgp->dca_enabled); #endif data[i++] = (unsigned int)mgp->link_changes; /* firmware stats are useful only in the first slice */ ss = &mgp->ss[0]; data[i++] = (unsigned int)ntohl(ss->fw_stats->link_up); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_link_overflow); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_link_error_or_filtered); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_pause); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_bad_phy); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_bad_crc32); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_unicast_filtered); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_multicast_filtered); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_runt); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_overrun); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_no_small_buffer); data[i++] = (unsigned int)ntohl(ss->fw_stats->dropped_no_big_buffer); for (slice = 0; slice < mgp->num_slices; slice++) { ss = &mgp->ss[slice]; data[i++] = slice; data[i++] = (unsigned int)ss->tx.pkt_start; data[i++] = (unsigned int)ss->tx.pkt_done; data[i++] = (unsigned int)ss->tx.req; data[i++] = (unsigned int)ss->tx.done; data[i++] = (unsigned int)ss->rx_small.cnt; data[i++] = (unsigned int)ss->rx_big.cnt; data[i++] = (unsigned int)ss->tx.wake_queue; data[i++] = (unsigned int)ss->tx.stop_queue; data[i++] = (unsigned int)ss->tx.linearized; data[i++] = ss->rx_done.lro_mgr.stats.aggregated; data[i++] = ss->rx_done.lro_mgr.stats.flushed; if (ss->rx_done.lro_mgr.stats.flushed) data[i++] = ss->rx_done.lro_mgr.stats.aggregated / ss->rx_done.lro_mgr.stats.flushed; else data[i++] = 0; data[i++] = ss->rx_done.lro_mgr.stats.no_desc; } } static void myri10ge_set_msglevel(struct net_device *netdev, u32 value) { struct myri10ge_priv *mgp = netdev_priv(netdev); mgp->msg_enable = value; } static u32 myri10ge_get_msglevel(struct net_device *netdev) { struct myri10ge_priv *mgp = netdev_priv(netdev); return mgp->msg_enable; } /* * Use a low-level command to change the LED behavior. Rather than * blinking (which is the normal case), when identify is used, the * yellow LED turns solid. */ static int myri10ge_led(struct myri10ge_priv *mgp, int on) { struct mcp_gen_header *hdr; struct device *dev = &mgp->pdev->dev; size_t hdr_off, pattern_off, hdr_len; u32 pattern = 0xfffffffe; /* find running firmware header */ hdr_off = swab32(readl(mgp->sram + MCP_HEADER_PTR_OFFSET)); if ((hdr_off & 3) || hdr_off + sizeof(*hdr) > mgp->sram_size) { dev_err(dev, "Running firmware has bad header offset (%d)\n", (int)hdr_off); return -EIO; } hdr_len = swab32(readl(mgp->sram + hdr_off + offsetof(struct mcp_gen_header, header_length))); pattern_off = hdr_off + offsetof(struct mcp_gen_header, led_pattern); if (pattern_off >= (hdr_len + hdr_off)) { dev_info(dev, "Firmware does not support LED identification\n"); return -EINVAL; } if (!on) pattern = swab32(readl(mgp->sram + pattern_off + 4)); writel(htonl(pattern), mgp->sram + pattern_off); return 0; } static int myri10ge_phys_id(struct net_device *netdev, enum ethtool_phys_id_state state) { struct myri10ge_priv *mgp = netdev_priv(netdev); int rc; switch (state) { case ETHTOOL_ID_ACTIVE: rc = myri10ge_led(mgp, 1); break; case ETHTOOL_ID_INACTIVE: rc = myri10ge_led(mgp, 0); break; default: rc = -EINVAL; } return rc; } static const struct ethtool_ops myri10ge_ethtool_ops = { .get_settings = myri10ge_get_settings, .get_drvinfo = myri10ge_get_drvinfo, .get_coalesce = myri10ge_get_coalesce, .set_coalesce = myri10ge_set_coalesce, .get_pauseparam = myri10ge_get_pauseparam, .set_pauseparam = myri10ge_set_pauseparam, .get_ringparam = myri10ge_get_ringparam, .get_link = ethtool_op_get_link, .get_strings = myri10ge_get_strings, .get_sset_count = myri10ge_get_sset_count, .get_ethtool_stats = myri10ge_get_ethtool_stats, .set_msglevel = myri10ge_set_msglevel, .get_msglevel = myri10ge_get_msglevel, .set_phys_id = myri10ge_phys_id, }; static int myri10ge_allocate_rings(struct myri10ge_slice_state *ss) { struct myri10ge_priv *mgp = ss->mgp; struct myri10ge_cmd cmd; struct net_device *dev = mgp->dev; int tx_ring_size, rx_ring_size; int tx_ring_entries, rx_ring_entries; int i, slice, status; size_t bytes; /* get ring sizes */ slice = ss - mgp->ss; cmd.data0 = slice; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_SEND_RING_SIZE, &cmd, 0); tx_ring_size = cmd.data0; cmd.data0 = slice; status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_RX_RING_SIZE, &cmd, 0); if (status != 0) return status; rx_ring_size = cmd.data0; tx_ring_entries = tx_ring_size / sizeof(struct mcp_kreq_ether_send); rx_ring_entries = rx_ring_size / sizeof(struct mcp_dma_addr); ss->tx.mask = tx_ring_entries - 1; ss->rx_small.mask = ss->rx_big.mask = rx_ring_entries - 1; status = -ENOMEM; /* allocate the host shadow rings */ bytes = 8 + (MYRI10GE_MAX_SEND_DESC_TSO + 4) * sizeof(*ss->tx.req_list); ss->tx.req_bytes = kzalloc(bytes, GFP_KERNEL); if (ss->tx.req_bytes == NULL) goto abort_with_nothing; /* ensure req_list entries are aligned to 8 bytes */ ss->tx.req_list = (struct mcp_kreq_ether_send *) ALIGN((unsigned long)ss->tx.req_bytes, 8); ss->tx.queue_active = 0; bytes = rx_ring_entries * sizeof(*ss->rx_small.shadow); ss->rx_small.shadow = kzalloc(bytes, GFP_KERNEL); if (ss->rx_small.shadow == NULL) goto abort_with_tx_req_bytes; bytes = rx_ring_entries * sizeof(*ss->rx_big.shadow); ss->rx_big.shadow = kzalloc(bytes, GFP_KERNEL); if (ss->rx_big.shadow == NULL) goto abort_with_rx_small_shadow; /* allocate the host info rings */ bytes = tx_ring_entries * sizeof(*ss->tx.info); ss->tx.info = kzalloc(bytes, GFP_KERNEL); if (ss->tx.info == NULL) goto abort_with_rx_big_shadow; bytes = rx_ring_entries * sizeof(*ss->rx_small.info); ss->rx_small.info = kzalloc(bytes, GFP_KERNEL); if (ss->rx_small.info == NULL) goto abort_with_tx_info; bytes = rx_ring_entries * sizeof(*ss->rx_big.info); ss->rx_big.info = kzalloc(bytes, GFP_KERNEL); if (ss->rx_big.info == NULL) goto abort_with_rx_small_info; /* Fill the receive rings */ ss->rx_big.cnt = 0; ss->rx_small.cnt = 0; ss->rx_big.fill_cnt = 0; ss->rx_small.fill_cnt = 0; ss->rx_small.page_offset = MYRI10GE_ALLOC_SIZE; ss->rx_big.page_offset = MYRI10GE_ALLOC_SIZE; ss->rx_small.watchdog_needed = 0; ss->rx_big.watchdog_needed = 0; if (mgp->small_bytes == 0) { ss->rx_small.fill_cnt = ss->rx_small.mask + 1; } else { myri10ge_alloc_rx_pages(mgp, &ss->rx_small, mgp->small_bytes + MXGEFW_PAD, 0); } if (ss->rx_small.fill_cnt < ss->rx_small.mask + 1) { netdev_err(dev, "slice-%d: alloced only %d small bufs\n", slice, ss->rx_small.fill_cnt); goto abort_with_rx_small_ring; } myri10ge_alloc_rx_pages(mgp, &ss->rx_big, mgp->big_bytes, 0); if (ss->rx_big.fill_cnt < ss->rx_big.mask + 1) { netdev_err(dev, "slice-%d: alloced only %d big bufs\n", slice, ss->rx_big.fill_cnt); goto abort_with_rx_big_ring; } return 0; abort_with_rx_big_ring: for (i = ss->rx_big.cnt; i < ss->rx_big.fill_cnt; i++) { int idx = i & ss->rx_big.mask; myri10ge_unmap_rx_page(mgp->pdev, &ss->rx_big.info[idx], mgp->big_bytes); put_page(ss->rx_big.info[idx].page); } abort_with_rx_small_ring: if (mgp->small_bytes == 0) ss->rx_small.fill_cnt = ss->rx_small.cnt; for (i = ss->rx_small.cnt; i < ss->rx_small.fill_cnt; i++) { int idx = i & ss->rx_small.mask; myri10ge_unmap_rx_page(mgp->pdev, &ss->rx_small.info[idx], mgp->small_bytes + MXGEFW_PAD); put_page(ss->rx_small.info[idx].page); } kfree(ss->rx_big.info); abort_with_rx_small_info: kfree(ss->rx_small.info); abort_with_tx_info: kfree(ss->tx.info); abort_with_rx_big_shadow: kfree(ss->rx_big.shadow); abort_with_rx_small_shadow: kfree(ss->rx_small.shadow); abort_with_tx_req_bytes: kfree(ss->tx.req_bytes); ss->tx.req_bytes = NULL; ss->tx.req_list = NULL; abort_with_nothing: return status; } static void myri10ge_free_rings(struct myri10ge_slice_state *ss) { struct myri10ge_priv *mgp = ss->mgp; struct sk_buff *skb; struct myri10ge_tx_buf *tx; int i, len, idx; /* If not allocated, skip it */ if (ss->tx.req_list == NULL) return; for (i = ss->rx_big.cnt; i < ss->rx_big.fill_cnt; i++) { idx = i & ss->rx_big.mask; if (i == ss->rx_big.fill_cnt - 1) ss->rx_big.info[idx].page_offset = MYRI10GE_ALLOC_SIZE; myri10ge_unmap_rx_page(mgp->pdev, &ss->rx_big.info[idx], mgp->big_bytes); put_page(ss->rx_big.info[idx].page); } if (mgp->small_bytes == 0) ss->rx_small.fill_cnt = ss->rx_small.cnt; for (i = ss->rx_small.cnt; i < ss->rx_small.fill_cnt; i++) { idx = i & ss->rx_small.mask; if (i == ss->rx_small.fill_cnt - 1) ss->rx_small.info[idx].page_offset = MYRI10GE_ALLOC_SIZE; myri10ge_unmap_rx_page(mgp->pdev, &ss->rx_small.info[idx], mgp->small_bytes + MXGEFW_PAD); put_page(ss->rx_small.info[idx].page); } tx = &ss->tx; while (tx->done != tx->req) { idx = tx->done & tx->mask; skb = tx->info[idx].skb; /* Mark as free */ tx->info[idx].skb = NULL; tx->done++; len = dma_unmap_len(&tx->info[idx], len); dma_unmap_len_set(&tx->info[idx], len, 0); if (skb) { ss->stats.tx_dropped++; dev_kfree_skb_any(skb); if (len) pci_unmap_single(mgp->pdev, dma_unmap_addr(&tx->info[idx], bus), len, PCI_DMA_TODEVICE); } else { if (len) pci_unmap_page(mgp->pdev, dma_unmap_addr(&tx->info[idx], bus), len, PCI_DMA_TODEVICE); } } kfree(ss->rx_big.info); kfree(ss->rx_small.info); kfree(ss->tx.info); kfree(ss->rx_big.shadow); kfree(ss->rx_small.shadow); kfree(ss->tx.req_bytes); ss->tx.req_bytes = NULL; ss->tx.req_list = NULL; } static int myri10ge_request_irq(struct myri10ge_priv *mgp) { struct pci_dev *pdev = mgp->pdev; struct myri10ge_slice_state *ss; struct net_device *netdev = mgp->dev; int i; int status; mgp->msi_enabled = 0; mgp->msix_enabled = 0; status = 0; if (myri10ge_msi) { if (mgp->num_slices > 1) { status = pci_enable_msix(pdev, mgp->msix_vectors, mgp->num_slices); if (status == 0) { mgp->msix_enabled = 1; } else { dev_err(&pdev->dev, "Error %d setting up MSI-X\n", status); return status; } } if (mgp->msix_enabled == 0) { status = pci_enable_msi(pdev); if (status != 0) { dev_err(&pdev->dev, "Error %d setting up MSI; falling back to xPIC\n", status); } else { mgp->msi_enabled = 1; } } } if (mgp->msix_enabled) { for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; snprintf(ss->irq_desc, sizeof(ss->irq_desc), "%s:slice-%d", netdev->name, i); status = request_irq(mgp->msix_vectors[i].vector, myri10ge_intr, 0, ss->irq_desc, ss); if (status != 0) { dev_err(&pdev->dev, "slice %d failed to allocate IRQ\n", i); i--; while (i >= 0) { free_irq(mgp->msix_vectors[i].vector, &mgp->ss[i]); i--; } pci_disable_msix(pdev); return status; } } } else { status = request_irq(pdev->irq, myri10ge_intr, IRQF_SHARED, mgp->dev->name, &mgp->ss[0]); if (status != 0) { dev_err(&pdev->dev, "failed to allocate IRQ\n"); if (mgp->msi_enabled) pci_disable_msi(pdev); } } return status; } static void myri10ge_free_irq(struct myri10ge_priv *mgp) { struct pci_dev *pdev = mgp->pdev; int i; if (mgp->msix_enabled) { for (i = 0; i < mgp->num_slices; i++) free_irq(mgp->msix_vectors[i].vector, &mgp->ss[i]); } else { free_irq(pdev->irq, &mgp->ss[0]); } if (mgp->msi_enabled) pci_disable_msi(pdev); if (mgp->msix_enabled) pci_disable_msix(pdev); } static int myri10ge_get_frag_header(struct skb_frag_struct *frag, void **mac_hdr, void **ip_hdr, void **tcpudp_hdr, u64 * hdr_flags, void *priv) { struct ethhdr *eh; struct vlan_ethhdr *veh; struct iphdr *iph; u8 *va = skb_frag_address(frag); unsigned long ll_hlen; /* passed opaque through lro_receive_frags() */ __wsum csum = (__force __wsum) (unsigned long)priv; /* find the mac header, aborting if not IPv4 */ eh = (struct ethhdr *)va; *mac_hdr = eh; ll_hlen = ETH_HLEN; if (eh->h_proto != htons(ETH_P_IP)) { if (eh->h_proto == htons(ETH_P_8021Q)) { veh = (struct vlan_ethhdr *)va; if (veh->h_vlan_encapsulated_proto != htons(ETH_P_IP)) return -1; ll_hlen += VLAN_HLEN; /* * HW checksum starts ETH_HLEN bytes into * frame, so we must subtract off the VLAN * header's checksum before csum can be used */ csum = csum_sub(csum, csum_partial(va + ETH_HLEN, VLAN_HLEN, 0)); } else { return -1; } } *hdr_flags = LRO_IPV4; iph = (struct iphdr *)(va + ll_hlen); *ip_hdr = iph; if (iph->protocol != IPPROTO_TCP) return -1; if (ip_is_fragment(iph)) return -1; *hdr_flags |= LRO_TCP; *tcpudp_hdr = (u8 *) (*ip_hdr) + (iph->ihl << 2); /* verify the IP checksum */ if (unlikely(ip_fast_csum((u8 *) iph, iph->ihl))) return -1; /* verify the checksum */ if (unlikely(csum_tcpudp_magic(iph->saddr, iph->daddr, ntohs(iph->tot_len) - (iph->ihl << 2), IPPROTO_TCP, csum))) return -1; return 0; } static int myri10ge_get_txrx(struct myri10ge_priv *mgp, int slice) { struct myri10ge_cmd cmd; struct myri10ge_slice_state *ss; int status; ss = &mgp->ss[slice]; status = 0; if (slice == 0 || (mgp->dev->real_num_tx_queues > 1)) { cmd.data0 = slice; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_SEND_OFFSET, &cmd, 0); ss->tx.lanai = (struct mcp_kreq_ether_send __iomem *) (mgp->sram + cmd.data0); } cmd.data0 = slice; status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_SMALL_RX_OFFSET, &cmd, 0); ss->rx_small.lanai = (struct mcp_kreq_ether_recv __iomem *) (mgp->sram + cmd.data0); cmd.data0 = slice; status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_BIG_RX_OFFSET, &cmd, 0); ss->rx_big.lanai = (struct mcp_kreq_ether_recv __iomem *) (mgp->sram + cmd.data0); ss->tx.send_go = (__iomem __be32 *) (mgp->sram + MXGEFW_ETH_SEND_GO + 64 * slice); ss->tx.send_stop = (__iomem __be32 *) (mgp->sram + MXGEFW_ETH_SEND_STOP + 64 * slice); return status; } static int myri10ge_set_stats(struct myri10ge_priv *mgp, int slice) { struct myri10ge_cmd cmd; struct myri10ge_slice_state *ss; int status; ss = &mgp->ss[slice]; cmd.data0 = MYRI10GE_LOWPART_TO_U32(ss->fw_stats_bus); cmd.data1 = MYRI10GE_HIGHPART_TO_U32(ss->fw_stats_bus); cmd.data2 = sizeof(struct mcp_irq_data) | (slice << 16); status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_STATS_DMA_V2, &cmd, 0); if (status == -ENOSYS) { dma_addr_t bus = ss->fw_stats_bus; if (slice != 0) return -EINVAL; bus += offsetof(struct mcp_irq_data, send_done_count); cmd.data0 = MYRI10GE_LOWPART_TO_U32(bus); cmd.data1 = MYRI10GE_HIGHPART_TO_U32(bus); status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_STATS_DMA_OBSOLETE, &cmd, 0); /* Firmware cannot support multicast without STATS_DMA_V2 */ mgp->fw_multicast_support = 0; } else { mgp->fw_multicast_support = 1; } return 0; } static int myri10ge_open(struct net_device *dev) { struct myri10ge_slice_state *ss; struct myri10ge_priv *mgp = netdev_priv(dev); struct myri10ge_cmd cmd; int i, status, big_pow2, slice; u8 *itable; struct net_lro_mgr *lro_mgr; if (mgp->running != MYRI10GE_ETH_STOPPED) return -EBUSY; mgp->running = MYRI10GE_ETH_STARTING; status = myri10ge_reset(mgp); if (status != 0) { netdev_err(dev, "failed reset\n"); goto abort_with_nothing; } if (mgp->num_slices > 1) { cmd.data0 = mgp->num_slices; cmd.data1 = MXGEFW_SLICE_INTR_MODE_ONE_PER_SLICE; if (mgp->dev->real_num_tx_queues > 1) cmd.data1 |= MXGEFW_SLICE_ENABLE_MULTIPLE_TX_QUEUES; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_ENABLE_RSS_QUEUES, &cmd, 0); if (status != 0) { netdev_err(dev, "failed to set number of slices\n"); goto abort_with_nothing; } /* setup the indirection table */ cmd.data0 = mgp->num_slices; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_RSS_TABLE_SIZE, &cmd, 0); status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_RSS_TABLE_OFFSET, &cmd, 0); if (status != 0) { netdev_err(dev, "failed to setup rss tables\n"); goto abort_with_nothing; } /* just enable an identity mapping */ itable = mgp->sram + cmd.data0; for (i = 0; i < mgp->num_slices; i++) __raw_writeb(i, &itable[i]); cmd.data0 = 1; cmd.data1 = myri10ge_rss_hash; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_RSS_ENABLE, &cmd, 0); if (status != 0) { netdev_err(dev, "failed to enable slices\n"); goto abort_with_nothing; } } status = myri10ge_request_irq(mgp); if (status != 0) goto abort_with_nothing; /* decide what small buffer size to use. For good TCP rx * performance, it is important to not receive 1514 byte * frames into jumbo buffers, as it confuses the socket buffer * accounting code, leading to drops and erratic performance. */ if (dev->mtu <= ETH_DATA_LEN) /* enough for a TCP header */ mgp->small_bytes = (128 > SMP_CACHE_BYTES) ? (128 - MXGEFW_PAD) : (SMP_CACHE_BYTES - MXGEFW_PAD); else /* enough for a vlan encapsulated ETH_DATA_LEN frame */ mgp->small_bytes = VLAN_ETH_FRAME_LEN; /* Override the small buffer size? */ if (myri10ge_small_bytes >= 0) mgp->small_bytes = myri10ge_small_bytes; /* Firmware needs the big buff size as a power of 2. Lie and * tell him the buffer is larger, because we only use 1 * buffer/pkt, and the mtu will prevent overruns. */ big_pow2 = dev->mtu + ETH_HLEN + VLAN_HLEN + MXGEFW_PAD; if (big_pow2 < MYRI10GE_ALLOC_SIZE / 2) { while (!is_power_of_2(big_pow2)) big_pow2++; mgp->big_bytes = dev->mtu + ETH_HLEN + VLAN_HLEN + MXGEFW_PAD; } else { big_pow2 = MYRI10GE_ALLOC_SIZE; mgp->big_bytes = big_pow2; } /* setup the per-slice data structures */ for (slice = 0; slice < mgp->num_slices; slice++) { ss = &mgp->ss[slice]; status = myri10ge_get_txrx(mgp, slice); if (status != 0) { netdev_err(dev, "failed to get ring sizes or locations\n"); goto abort_with_rings; } status = myri10ge_allocate_rings(ss); if (status != 0) goto abort_with_rings; /* only firmware which supports multiple TX queues * supports setting up the tx stats on non-zero * slices */ if (slice == 0 || mgp->dev->real_num_tx_queues > 1) status = myri10ge_set_stats(mgp, slice); if (status) { netdev_err(dev, "Couldn't set stats DMA\n"); goto abort_with_rings; } lro_mgr = &ss->rx_done.lro_mgr; lro_mgr->dev = dev; lro_mgr->features = LRO_F_NAPI; lro_mgr->ip_summed = CHECKSUM_COMPLETE; lro_mgr->ip_summed_aggr = CHECKSUM_UNNECESSARY; lro_mgr->max_desc = MYRI10GE_MAX_LRO_DESCRIPTORS; lro_mgr->lro_arr = ss->rx_done.lro_desc; lro_mgr->get_frag_header = myri10ge_get_frag_header; lro_mgr->max_aggr = myri10ge_lro_max_pkts; lro_mgr->frag_align_pad = 2; if (lro_mgr->max_aggr > MAX_SKB_FRAGS) lro_mgr->max_aggr = MAX_SKB_FRAGS; /* must happen prior to any irq */ napi_enable(&(ss)->napi); } /* now give firmware buffers sizes, and MTU */ cmd.data0 = dev->mtu + ETH_HLEN + VLAN_HLEN; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_MTU, &cmd, 0); cmd.data0 = mgp->small_bytes; status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_SMALL_BUFFER_SIZE, &cmd, 0); cmd.data0 = big_pow2; status |= myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_BIG_BUFFER_SIZE, &cmd, 0); if (status) { netdev_err(dev, "Couldn't set buffer sizes\n"); goto abort_with_rings; } /* * Set Linux style TSO mode; this is needed only on newer * firmware versions. Older versions default to Linux * style TSO */ cmd.data0 = 0; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_TSO_MODE, &cmd, 0); if (status && status != -ENOSYS) { netdev_err(dev, "Couldn't set TSO mode\n"); goto abort_with_rings; } mgp->link_state = ~0U; mgp->rdma_tags_available = 15; status = myri10ge_send_cmd(mgp, MXGEFW_CMD_ETHERNET_UP, &cmd, 0); if (status) { netdev_err(dev, "Couldn't bring up link\n"); goto abort_with_rings; } mgp->running = MYRI10GE_ETH_RUNNING; mgp->watchdog_timer.expires = jiffies + myri10ge_watchdog_timeout * HZ; add_timer(&mgp->watchdog_timer); netif_tx_wake_all_queues(dev); return 0; abort_with_rings: while (slice) { slice--; napi_disable(&mgp->ss[slice].napi); } for (i = 0; i < mgp->num_slices; i++) myri10ge_free_rings(&mgp->ss[i]); myri10ge_free_irq(mgp); abort_with_nothing: mgp->running = MYRI10GE_ETH_STOPPED; return -ENOMEM; } static int myri10ge_close(struct net_device *dev) { struct myri10ge_priv *mgp = netdev_priv(dev); struct myri10ge_cmd cmd; int status, old_down_cnt; int i; if (mgp->running != MYRI10GE_ETH_RUNNING) return 0; if (mgp->ss[0].tx.req_bytes == NULL) return 0; del_timer_sync(&mgp->watchdog_timer); mgp->running = MYRI10GE_ETH_STOPPING; for (i = 0; i < mgp->num_slices; i++) { napi_disable(&mgp->ss[i].napi); } netif_carrier_off(dev); netif_tx_stop_all_queues(dev); if (mgp->rebooted == 0) { old_down_cnt = mgp->down_cnt; mb(); status = myri10ge_send_cmd(mgp, MXGEFW_CMD_ETHERNET_DOWN, &cmd, 0); if (status) netdev_err(dev, "Couldn't bring down link\n"); wait_event_timeout(mgp->down_wq, old_down_cnt != mgp->down_cnt, HZ); if (old_down_cnt == mgp->down_cnt) netdev_err(dev, "never got down irq\n"); } netif_tx_disable(dev); myri10ge_free_irq(mgp); for (i = 0; i < mgp->num_slices; i++) myri10ge_free_rings(&mgp->ss[i]); mgp->running = MYRI10GE_ETH_STOPPED; return 0; } /* copy an array of struct mcp_kreq_ether_send's to the mcp. Copy * backwards one at a time and handle ring wraps */ static inline void myri10ge_submit_req_backwards(struct myri10ge_tx_buf *tx, struct mcp_kreq_ether_send *src, int cnt) { int idx, starting_slot; starting_slot = tx->req; while (cnt > 1) { cnt--; idx = (starting_slot + cnt) & tx->mask; myri10ge_pio_copy(&tx->lanai[idx], &src[cnt], sizeof(*src)); mb(); } } /* * copy an array of struct mcp_kreq_ether_send's to the mcp. Copy * at most 32 bytes at a time, so as to avoid involving the software * pio handler in the nic. We re-write the first segment's flags * to mark them valid only after writing the entire chain. */ static inline void myri10ge_submit_req(struct myri10ge_tx_buf *tx, struct mcp_kreq_ether_send *src, int cnt) { int idx, i; struct mcp_kreq_ether_send __iomem *dstp, *dst; struct mcp_kreq_ether_send *srcp; u8 last_flags; idx = tx->req & tx->mask; last_flags = src->flags; src->flags = 0; mb(); dst = dstp = &tx->lanai[idx]; srcp = src; if ((idx + cnt) < tx->mask) { for (i = 0; i < (cnt - 1); i += 2) { myri10ge_pio_copy(dstp, srcp, 2 * sizeof(*src)); mb(); /* force write every 32 bytes */ srcp += 2; dstp += 2; } } else { /* submit all but the first request, and ensure * that it is submitted below */ myri10ge_submit_req_backwards(tx, src, cnt); i = 0; } if (i < cnt) { /* submit the first request */ myri10ge_pio_copy(dstp, srcp, sizeof(*src)); mb(); /* barrier before setting valid flag */ } /* re-write the last 32-bits with the valid flags */ src->flags = last_flags; put_be32(*((__be32 *) src + 3), (__be32 __iomem *) dst + 3); tx->req += cnt; mb(); } /* * Transmit a packet. We need to split the packet so that a single * segment does not cross myri10ge->tx_boundary, so this makes segment * counting tricky. So rather than try to count segments up front, we * just give up if there are too few segments to hold a reasonably * fragmented packet currently available. If we run * out of segments while preparing a packet for DMA, we just linearize * it and try again. */ static netdev_tx_t myri10ge_xmit(struct sk_buff *skb, struct net_device *dev) { struct myri10ge_priv *mgp = netdev_priv(dev); struct myri10ge_slice_state *ss; struct mcp_kreq_ether_send *req; struct myri10ge_tx_buf *tx; struct skb_frag_struct *frag; struct netdev_queue *netdev_queue; dma_addr_t bus; u32 low; __be32 high_swapped; unsigned int len; int idx, last_idx, avail, frag_cnt, frag_idx, count, mss, max_segments; u16 pseudo_hdr_offset, cksum_offset, queue; int cum_len, seglen, boundary, rdma_count; u8 flags, odd_flag; queue = skb_get_queue_mapping(skb); ss = &mgp->ss[queue]; netdev_queue = netdev_get_tx_queue(mgp->dev, queue); tx = &ss->tx; again: req = tx->req_list; avail = tx->mask - 1 - (tx->req - tx->done); mss = 0; max_segments = MXGEFW_MAX_SEND_DESC; if (skb_is_gso(skb)) { mss = skb_shinfo(skb)->gso_size; max_segments = MYRI10GE_MAX_SEND_DESC_TSO; } if ((unlikely(avail < max_segments))) { /* we are out of transmit resources */ tx->stop_queue++; netif_tx_stop_queue(netdev_queue); return NETDEV_TX_BUSY; } /* Setup checksum offloading, if needed */ cksum_offset = 0; pseudo_hdr_offset = 0; odd_flag = 0; flags = (MXGEFW_FLAGS_NO_TSO | MXGEFW_FLAGS_FIRST); if (likely(skb->ip_summed == CHECKSUM_PARTIAL)) { cksum_offset = skb_checksum_start_offset(skb); pseudo_hdr_offset = cksum_offset + skb->csum_offset; /* If the headers are excessively large, then we must * fall back to a software checksum */ if (unlikely(!mss && (cksum_offset > 255 || pseudo_hdr_offset > 127))) { if (skb_checksum_help(skb)) goto drop; cksum_offset = 0; pseudo_hdr_offset = 0; } else { odd_flag = MXGEFW_FLAGS_ALIGN_ODD; flags |= MXGEFW_FLAGS_CKSUM; } } cum_len = 0; if (mss) { /* TSO */ /* this removes any CKSUM flag from before */ flags = (MXGEFW_FLAGS_TSO_HDR | MXGEFW_FLAGS_FIRST); /* negative cum_len signifies to the * send loop that we are still in the * header portion of the TSO packet. * TSO header can be at most 1KB long */ cum_len = -(skb_transport_offset(skb) + tcp_hdrlen(skb)); /* for IPv6 TSO, the checksum offset stores the * TCP header length, to save the firmware from * the need to parse the headers */ if (skb_is_gso_v6(skb)) { cksum_offset = tcp_hdrlen(skb); /* Can only handle headers <= max_tso6 long */ if (unlikely(-cum_len > mgp->max_tso6)) return myri10ge_sw_tso(skb, dev); } /* for TSO, pseudo_hdr_offset holds mss. * The firmware figures out where to put * the checksum by parsing the header. */ pseudo_hdr_offset = mss; } else /* Mark small packets, and pad out tiny packets */ if (skb->len <= MXGEFW_SEND_SMALL_SIZE) { flags |= MXGEFW_FLAGS_SMALL; /* pad frames to at least ETH_ZLEN bytes */ if (unlikely(skb->len < ETH_ZLEN)) { if (skb_padto(skb, ETH_ZLEN)) { /* The packet is gone, so we must * return 0 */ ss->stats.tx_dropped += 1; return NETDEV_TX_OK; } /* adjust the len to account for the zero pad * so that the nic can know how long it is */ skb->len = ETH_ZLEN; } } /* map the skb for DMA */ len = skb_headlen(skb); idx = tx->req & tx->mask; tx->info[idx].skb = skb; bus = pci_map_single(mgp->pdev, skb->data, len, PCI_DMA_TODEVICE); dma_unmap_addr_set(&tx->info[idx], bus, bus); dma_unmap_len_set(&tx->info[idx], len, len); frag_cnt = skb_shinfo(skb)->nr_frags; frag_idx = 0; count = 0; rdma_count = 0; /* "rdma_count" is the number of RDMAs belonging to the * current packet BEFORE the current send request. For * non-TSO packets, this is equal to "count". * For TSO packets, rdma_count needs to be reset * to 0 after a segment cut. * * The rdma_count field of the send request is * the number of RDMAs of the packet starting at * that request. For TSO send requests with one ore more cuts * in the middle, this is the number of RDMAs starting * after the last cut in the request. All previous * segments before the last cut implicitly have 1 RDMA. * * Since the number of RDMAs is not known beforehand, * it must be filled-in retroactively - after each * segmentation cut or at the end of the entire packet. */ while (1) { /* Break the SKB or Fragment up into pieces which * do not cross mgp->tx_boundary */ low = MYRI10GE_LOWPART_TO_U32(bus); high_swapped = htonl(MYRI10GE_HIGHPART_TO_U32(bus)); while (len) { u8 flags_next; int cum_len_next; if (unlikely(count == max_segments)) goto abort_linearize; boundary = (low + mgp->tx_boundary) & ~(mgp->tx_boundary - 1); seglen = boundary - low; if (seglen > len) seglen = len; flags_next = flags & ~MXGEFW_FLAGS_FIRST; cum_len_next = cum_len + seglen; if (mss) { /* TSO */ (req - rdma_count)->rdma_count = rdma_count + 1; if (likely(cum_len >= 0)) { /* payload */ int next_is_first, chop; chop = (cum_len_next > mss); cum_len_next = cum_len_next % mss; next_is_first = (cum_len_next == 0); flags |= chop * MXGEFW_FLAGS_TSO_CHOP; flags_next |= next_is_first * MXGEFW_FLAGS_FIRST; rdma_count |= -(chop | next_is_first); rdma_count += chop & !next_is_first; } else if (likely(cum_len_next >= 0)) { /* header ends */ int small; rdma_count = -1; cum_len_next = 0; seglen = -cum_len; small = (mss <= MXGEFW_SEND_SMALL_SIZE); flags_next = MXGEFW_FLAGS_TSO_PLD | MXGEFW_FLAGS_FIRST | (small * MXGEFW_FLAGS_SMALL); } } req->addr_high = high_swapped; req->addr_low = htonl(low); req->pseudo_hdr_offset = htons(pseudo_hdr_offset); req->pad = 0; /* complete solid 16-byte block; does this matter? */ req->rdma_count = 1; req->length = htons(seglen); req->cksum_offset = cksum_offset; req->flags = flags | ((cum_len & 1) * odd_flag); low += seglen; len -= seglen; cum_len = cum_len_next; flags = flags_next; req++; count++; rdma_count++; if (cksum_offset != 0 && !(mss && skb_is_gso_v6(skb))) { if (unlikely(cksum_offset > seglen)) cksum_offset -= seglen; else cksum_offset = 0; } } if (frag_idx == frag_cnt) break; /* map next fragment for DMA */ idx = (count + tx->req) & tx->mask; frag = &skb_shinfo(skb)->frags[frag_idx]; frag_idx++; len = skb_frag_size(frag); bus = skb_frag_dma_map(&mgp->pdev->dev, frag, 0, len, DMA_TO_DEVICE); dma_unmap_addr_set(&tx->info[idx], bus, bus); dma_unmap_len_set(&tx->info[idx], len, len); } (req - rdma_count)->rdma_count = rdma_count; if (mss) do { req--; req->flags |= MXGEFW_FLAGS_TSO_LAST; } while (!(req->flags & (MXGEFW_FLAGS_TSO_CHOP | MXGEFW_FLAGS_FIRST))); idx = ((count - 1) + tx->req) & tx->mask; tx->info[idx].last = 1; myri10ge_submit_req(tx, tx->req_list, count); /* if using multiple tx queues, make sure NIC polls the * current slice */ if ((mgp->dev->real_num_tx_queues > 1) && tx->queue_active == 0) { tx->queue_active = 1; put_be32(htonl(1), tx->send_go); mb(); mmiowb(); } tx->pkt_start++; if ((avail - count) < MXGEFW_MAX_SEND_DESC) { tx->stop_queue++; netif_tx_stop_queue(netdev_queue); } return NETDEV_TX_OK; abort_linearize: /* Free any DMA resources we've alloced and clear out the skb * slot so as to not trip up assertions, and to avoid a * double-free if linearizing fails */ last_idx = (idx + 1) & tx->mask; idx = tx->req & tx->mask; tx->info[idx].skb = NULL; do { len = dma_unmap_len(&tx->info[idx], len); if (len) { if (tx->info[idx].skb != NULL) pci_unmap_single(mgp->pdev, dma_unmap_addr(&tx->info[idx], bus), len, PCI_DMA_TODEVICE); else pci_unmap_page(mgp->pdev, dma_unmap_addr(&tx->info[idx], bus), len, PCI_DMA_TODEVICE); dma_unmap_len_set(&tx->info[idx], len, 0); tx->info[idx].skb = NULL; } idx = (idx + 1) & tx->mask; } while (idx != last_idx); if (skb_is_gso(skb)) { netdev_err(mgp->dev, "TSO but wanted to linearize?!?!?\n"); goto drop; } if (skb_linearize(skb)) goto drop; tx->linearized++; goto again; drop: dev_kfree_skb_any(skb); ss->stats.tx_dropped += 1; return NETDEV_TX_OK; } static netdev_tx_t myri10ge_sw_tso(struct sk_buff *skb, struct net_device *dev) { struct sk_buff *segs, *curr; struct myri10ge_priv *mgp = netdev_priv(dev); struct myri10ge_slice_state *ss; netdev_tx_t status; segs = skb_gso_segment(skb, dev->features & ~NETIF_F_TSO6); if (IS_ERR(segs)) goto drop; while (segs) { curr = segs; segs = segs->next; curr->next = NULL; status = myri10ge_xmit(curr, dev); if (status != 0) { dev_kfree_skb_any(curr); if (segs != NULL) { curr = segs; segs = segs->next; curr->next = NULL; dev_kfree_skb_any(segs); } goto drop; } } dev_kfree_skb_any(skb); return NETDEV_TX_OK; drop: ss = &mgp->ss[skb_get_queue_mapping(skb)]; dev_kfree_skb_any(skb); ss->stats.tx_dropped += 1; return NETDEV_TX_OK; } static struct rtnl_link_stats64 *myri10ge_get_stats(struct net_device *dev, struct rtnl_link_stats64 *stats) { const struct myri10ge_priv *mgp = netdev_priv(dev); const struct myri10ge_slice_netstats *slice_stats; int i; for (i = 0; i < mgp->num_slices; i++) { slice_stats = &mgp->ss[i].stats; stats->rx_packets += slice_stats->rx_packets; stats->tx_packets += slice_stats->tx_packets; stats->rx_bytes += slice_stats->rx_bytes; stats->tx_bytes += slice_stats->tx_bytes; stats->rx_dropped += slice_stats->rx_dropped; stats->tx_dropped += slice_stats->tx_dropped; } return stats; } static void myri10ge_set_multicast_list(struct net_device *dev) { struct myri10ge_priv *mgp = netdev_priv(dev); struct myri10ge_cmd cmd; struct netdev_hw_addr *ha; __be32 data[2] = { 0, 0 }; int err; /* can be called from atomic contexts, * pass 1 to force atomicity in myri10ge_send_cmd() */ myri10ge_change_promisc(mgp, dev->flags & IFF_PROMISC, 1); /* This firmware is known to not support multicast */ if (!mgp->fw_multicast_support) return; /* Disable multicast filtering */ err = myri10ge_send_cmd(mgp, MXGEFW_ENABLE_ALLMULTI, &cmd, 1); if (err != 0) { netdev_err(dev, "Failed MXGEFW_ENABLE_ALLMULTI, error status: %d\n", err); goto abort; } if ((dev->flags & IFF_ALLMULTI) || mgp->adopted_rx_filter_bug) { /* request to disable multicast filtering, so quit here */ return; } /* Flush the filters */ err = myri10ge_send_cmd(mgp, MXGEFW_LEAVE_ALL_MULTICAST_GROUPS, &cmd, 1); if (err != 0) { netdev_err(dev, "Failed MXGEFW_LEAVE_ALL_MULTICAST_GROUPS, error status: %d\n", err); goto abort; } /* Walk the multicast list, and add each address */ netdev_for_each_mc_addr(ha, dev) { memcpy(data, &ha->addr, 6); cmd.data0 = ntohl(data[0]); cmd.data1 = ntohl(data[1]); err = myri10ge_send_cmd(mgp, MXGEFW_JOIN_MULTICAST_GROUP, &cmd, 1); if (err != 0) { netdev_err(dev, "Failed MXGEFW_JOIN_MULTICAST_GROUP, error status:%d %pM\n", err, ha->addr); goto abort; } } /* Enable multicast filtering */ err = myri10ge_send_cmd(mgp, MXGEFW_DISABLE_ALLMULTI, &cmd, 1); if (err != 0) { netdev_err(dev, "Failed MXGEFW_DISABLE_ALLMULTI, error status: %d\n", err); goto abort; } return; abort: return; } static int myri10ge_set_mac_address(struct net_device *dev, void *addr) { struct sockaddr *sa = addr; struct myri10ge_priv *mgp = netdev_priv(dev); int status; if (!is_valid_ether_addr(sa->sa_data)) return -EADDRNOTAVAIL; status = myri10ge_update_mac_address(mgp, sa->sa_data); if (status != 0) { netdev_err(dev, "changing mac address failed with %d\n", status); return status; } /* change the dev structure */ memcpy(dev->dev_addr, sa->sa_data, 6); return 0; } static netdev_features_t myri10ge_fix_features(struct net_device *dev, netdev_features_t features) { if (!(features & NETIF_F_RXCSUM)) features &= ~NETIF_F_LRO; return features; } static int myri10ge_change_mtu(struct net_device *dev, int new_mtu) { struct myri10ge_priv *mgp = netdev_priv(dev); int error = 0; if ((new_mtu < 68) || (ETH_HLEN + new_mtu > MYRI10GE_MAX_ETHER_MTU)) { netdev_err(dev, "new mtu (%d) is not valid\n", new_mtu); return -EINVAL; } netdev_info(dev, "changing mtu from %d to %d\n", dev->mtu, new_mtu); if (mgp->running) { /* if we change the mtu on an active device, we must * reset the device so the firmware sees the change */ myri10ge_close(dev); dev->mtu = new_mtu; myri10ge_open(dev); } else dev->mtu = new_mtu; return error; } /* * Enable ECRC to align PCI-E Completion packets on an 8-byte boundary. * Only do it if the bridge is a root port since we don't want to disturb * any other device, except if forced with myri10ge_ecrc_enable > 1. */ static void myri10ge_enable_ecrc(struct myri10ge_priv *mgp) { struct pci_dev *bridge = mgp->pdev->bus->self; struct device *dev = &mgp->pdev->dev; int cap; unsigned err_cap; u16 val; u8 ext_type; int ret; if (!myri10ge_ecrc_enable || !bridge) return; /* check that the bridge is a root port */ cap = pci_pcie_cap(bridge); pci_read_config_word(bridge, cap + PCI_CAP_FLAGS, &val); ext_type = (val & PCI_EXP_FLAGS_TYPE) >> 4; if (ext_type != PCI_EXP_TYPE_ROOT_PORT) { if (myri10ge_ecrc_enable > 1) { struct pci_dev *prev_bridge, *old_bridge = bridge; /* Walk the hierarchy up to the root port * where ECRC has to be enabled */ do { prev_bridge = bridge; bridge = bridge->bus->self; if (!bridge || prev_bridge == bridge) { dev_err(dev, "Failed to find root port" " to force ECRC\n"); return; } cap = pci_pcie_cap(bridge); pci_read_config_word(bridge, cap + PCI_CAP_FLAGS, &val); ext_type = (val & PCI_EXP_FLAGS_TYPE) >> 4; } while (ext_type != PCI_EXP_TYPE_ROOT_PORT); dev_info(dev, "Forcing ECRC on non-root port %s" " (enabling on root port %s)\n", pci_name(old_bridge), pci_name(bridge)); } else { dev_err(dev, "Not enabling ECRC on non-root port %s\n", pci_name(bridge)); return; } } cap = pci_find_ext_capability(bridge, PCI_EXT_CAP_ID_ERR); if (!cap) return; ret = pci_read_config_dword(bridge, cap + PCI_ERR_CAP, &err_cap); if (ret) { dev_err(dev, "failed reading ext-conf-space of %s\n", pci_name(bridge)); dev_err(dev, "\t pci=nommconf in use? " "or buggy/incomplete/absent ACPI MCFG attr?\n"); return; } if (!(err_cap & PCI_ERR_CAP_ECRC_GENC)) return; err_cap |= PCI_ERR_CAP_ECRC_GENE; pci_write_config_dword(bridge, cap + PCI_ERR_CAP, err_cap); dev_info(dev, "Enabled ECRC on upstream bridge %s\n", pci_name(bridge)); } /* * The Lanai Z8E PCI-E interface achieves higher Read-DMA throughput * when the PCI-E Completion packets are aligned on an 8-byte * boundary. Some PCI-E chip sets always align Completion packets; on * the ones that do not, the alignment can be enforced by enabling * ECRC generation (if supported). * * When PCI-E Completion packets are not aligned, it is actually more * efficient to limit Read-DMA transactions to 2KB, rather than 4KB. * * If the driver can neither enable ECRC nor verify that it has * already been enabled, then it must use a firmware image which works * around unaligned completion packets (myri10ge_rss_ethp_z8e.dat), and it * should also ensure that it never gives the device a Read-DMA which is * larger than 2KB by setting the tx_boundary to 2KB. If ECRC is * enabled, then the driver should use the aligned (myri10ge_rss_eth_z8e.dat) * firmware image, and set tx_boundary to 4KB. */ static void myri10ge_firmware_probe(struct myri10ge_priv *mgp) { struct pci_dev *pdev = mgp->pdev; struct device *dev = &pdev->dev; int status; mgp->tx_boundary = 4096; /* * Verify the max read request size was set to 4KB * before trying the test with 4KB. */ status = pcie_get_readrq(pdev); if (status < 0) { dev_err(dev, "Couldn't read max read req size: %d\n", status); goto abort; } if (status != 4096) { dev_warn(dev, "Max Read Request size != 4096 (%d)\n", status); mgp->tx_boundary = 2048; } /* * load the optimized firmware (which assumes aligned PCIe * completions) in order to see if it works on this host. */ set_fw_name(mgp, myri10ge_fw_aligned, false); status = myri10ge_load_firmware(mgp, 1); if (status != 0) { goto abort; } /* * Enable ECRC if possible */ myri10ge_enable_ecrc(mgp); /* * Run a DMA test which watches for unaligned completions and * aborts on the first one seen. */ status = myri10ge_dma_test(mgp, MXGEFW_CMD_UNALIGNED_TEST); if (status == 0) return; /* keep the aligned firmware */ if (status != -E2BIG) dev_warn(dev, "DMA test failed: %d\n", status); if (status == -ENOSYS) dev_warn(dev, "Falling back to ethp! " "Please install up to date fw\n"); abort: /* fall back to using the unaligned firmware */ mgp->tx_boundary = 2048; set_fw_name(mgp, myri10ge_fw_unaligned, false); } static void myri10ge_select_firmware(struct myri10ge_priv *mgp) { int overridden = 0; if (myri10ge_force_firmware == 0) { int link_width, exp_cap; u16 lnk; exp_cap = pci_pcie_cap(mgp->pdev); pci_read_config_word(mgp->pdev, exp_cap + PCI_EXP_LNKSTA, &lnk); link_width = (lnk >> 4) & 0x3f; /* Check to see if Link is less than 8 or if the * upstream bridge is known to provide aligned * completions */ if (link_width < 8) { dev_info(&mgp->pdev->dev, "PCIE x%d Link\n", link_width); mgp->tx_boundary = 4096; set_fw_name(mgp, myri10ge_fw_aligned, false); } else { myri10ge_firmware_probe(mgp); } } else { if (myri10ge_force_firmware == 1) { dev_info(&mgp->pdev->dev, "Assuming aligned completions (forced)\n"); mgp->tx_boundary = 4096; set_fw_name(mgp, myri10ge_fw_aligned, false); } else { dev_info(&mgp->pdev->dev, "Assuming unaligned completions (forced)\n"); mgp->tx_boundary = 2048; set_fw_name(mgp, myri10ge_fw_unaligned, false); } } kparam_block_sysfs_write(myri10ge_fw_name); if (myri10ge_fw_name != NULL) { char *fw_name = kstrdup(myri10ge_fw_name, GFP_KERNEL); if (fw_name) { overridden = 1; set_fw_name(mgp, fw_name, true); } } kparam_unblock_sysfs_write(myri10ge_fw_name); if (mgp->board_number < MYRI10GE_MAX_BOARDS && myri10ge_fw_names[mgp->board_number] != NULL && strlen(myri10ge_fw_names[mgp->board_number])) { set_fw_name(mgp, myri10ge_fw_names[mgp->board_number], false); overridden = 1; } if (overridden) dev_info(&mgp->pdev->dev, "overriding firmware to %s\n", mgp->fw_name); } static void myri10ge_mask_surprise_down(struct pci_dev *pdev) { struct pci_dev *bridge = pdev->bus->self; int cap; u32 mask; if (bridge == NULL) return; cap = pci_find_ext_capability(bridge, PCI_EXT_CAP_ID_ERR); if (cap) { /* a sram parity error can cause a surprise link * down; since we expect and can recover from sram * parity errors, mask surprise link down events */ pci_read_config_dword(bridge, cap + PCI_ERR_UNCOR_MASK, &mask); mask |= 0x20; pci_write_config_dword(bridge, cap + PCI_ERR_UNCOR_MASK, mask); } } #ifdef CONFIG_PM static int myri10ge_suspend(struct pci_dev *pdev, pm_message_t state) { struct myri10ge_priv *mgp; struct net_device *netdev; mgp = pci_get_drvdata(pdev); if (mgp == NULL) return -EINVAL; netdev = mgp->dev; netif_device_detach(netdev); if (netif_running(netdev)) { netdev_info(netdev, "closing\n"); rtnl_lock(); myri10ge_close(netdev); rtnl_unlock(); } myri10ge_dummy_rdma(mgp, 0); pci_save_state(pdev); pci_disable_device(pdev); return pci_set_power_state(pdev, pci_choose_state(pdev, state)); } static int myri10ge_resume(struct pci_dev *pdev) { struct myri10ge_priv *mgp; struct net_device *netdev; int status; u16 vendor; mgp = pci_get_drvdata(pdev); if (mgp == NULL) return -EINVAL; netdev = mgp->dev; pci_set_power_state(pdev, 0); /* zeros conf space as a side effect */ msleep(5); /* give card time to respond */ pci_read_config_word(mgp->pdev, PCI_VENDOR_ID, &vendor); if (vendor == 0xffff) { netdev_err(mgp->dev, "device disappeared!\n"); return -EIO; } pci_restore_state(pdev); status = pci_enable_device(pdev); if (status) { dev_err(&pdev->dev, "failed to enable device\n"); return status; } pci_set_master(pdev); myri10ge_reset(mgp); myri10ge_dummy_rdma(mgp, 1); /* Save configuration space to be restored if the * nic resets due to a parity error */ pci_save_state(pdev); if (netif_running(netdev)) { rtnl_lock(); status = myri10ge_open(netdev); rtnl_unlock(); if (status != 0) goto abort_with_enabled; } netif_device_attach(netdev); return 0; abort_with_enabled: pci_disable_device(pdev); return -EIO; } #endif /* CONFIG_PM */ static u32 myri10ge_read_reboot(struct myri10ge_priv *mgp) { struct pci_dev *pdev = mgp->pdev; int vs = mgp->vendor_specific_offset; u32 reboot; /*enter read32 mode */ pci_write_config_byte(pdev, vs + 0x10, 0x3); /*read REBOOT_STATUS (0xfffffff0) */ pci_write_config_dword(pdev, vs + 0x18, 0xfffffff0); pci_read_config_dword(pdev, vs + 0x14, &reboot); return reboot; } static void myri10ge_check_slice(struct myri10ge_slice_state *ss, int *reset_needed, int *busy_slice_cnt, u32 rx_pause_cnt) { struct myri10ge_priv *mgp = ss->mgp; int slice = ss - mgp->ss; if (ss->tx.req != ss->tx.done && ss->tx.done == ss->watchdog_tx_done && ss->watchdog_tx_req != ss->watchdog_tx_done) { /* nic seems like it might be stuck.. */ if (rx_pause_cnt != mgp->watchdog_pause) { if (net_ratelimit()) netdev_warn(mgp->dev, "slice %d: TX paused, " "check link partner\n", slice); } else { netdev_warn(mgp->dev, "slice %d: TX stuck %d %d %d %d %d %d\n", slice, ss->tx.queue_active, ss->tx.req, ss->tx.done, ss->tx.pkt_start, ss->tx.pkt_done, (int)ntohl(mgp->ss[slice].fw_stats-> send_done_count)); *reset_needed = 1; ss->stuck = 1; } } if (ss->watchdog_tx_done != ss->tx.done || ss->watchdog_rx_done != ss->rx_done.cnt) { *busy_slice_cnt += 1; } ss->watchdog_tx_done = ss->tx.done; ss->watchdog_tx_req = ss->tx.req; ss->watchdog_rx_done = ss->rx_done.cnt; } /* * This watchdog is used to check whether the board has suffered * from a parity error and needs to be recovered. */ static void myri10ge_watchdog(struct work_struct *work) { struct myri10ge_priv *mgp = container_of(work, struct myri10ge_priv, watchdog_work); struct myri10ge_slice_state *ss; u32 reboot, rx_pause_cnt; int status, rebooted; int i; int reset_needed = 0; int busy_slice_cnt = 0; u16 cmd, vendor; mgp->watchdog_resets++; pci_read_config_word(mgp->pdev, PCI_COMMAND, &cmd); rebooted = 0; if ((cmd & PCI_COMMAND_MASTER) == 0) { /* Bus master DMA disabled? Check to see * if the card rebooted due to a parity error * For now, just report it */ reboot = myri10ge_read_reboot(mgp); netdev_err(mgp->dev, "NIC rebooted (0x%x),%s resetting\n", reboot, myri10ge_reset_recover ? "" : " not"); if (myri10ge_reset_recover == 0) return; rtnl_lock(); mgp->rebooted = 1; rebooted = 1; myri10ge_close(mgp->dev); myri10ge_reset_recover--; mgp->rebooted = 0; /* * A rebooted nic will come back with config space as * it was after power was applied to PCIe bus. * Attempt to restore config space which was saved * when the driver was loaded, or the last time the * nic was resumed from power saving mode. */ pci_restore_state(mgp->pdev); /* save state again for accounting reasons */ pci_save_state(mgp->pdev); } else { /* if we get back -1's from our slot, perhaps somebody * powered off our card. Don't try to reset it in * this case */ if (cmd == 0xffff) { pci_read_config_word(mgp->pdev, PCI_VENDOR_ID, &vendor); if (vendor == 0xffff) { netdev_err(mgp->dev, "device disappeared!\n"); return; } } /* Perhaps it is a software error. See if stuck slice * has recovered, reset if not */ rx_pause_cnt = ntohl(mgp->ss[0].fw_stats->dropped_pause); for (i = 0; i < mgp->num_slices; i++) { ss = mgp->ss; if (ss->stuck) { myri10ge_check_slice(ss, &reset_needed, &busy_slice_cnt, rx_pause_cnt); ss->stuck = 0; } } if (!reset_needed) { netdev_dbg(mgp->dev, "not resetting\n"); return; } netdev_err(mgp->dev, "device timeout, resetting\n"); } if (!rebooted) { rtnl_lock(); myri10ge_close(mgp->dev); } status = myri10ge_load_firmware(mgp, 1); if (status != 0) netdev_err(mgp->dev, "failed to load firmware\n"); else myri10ge_open(mgp->dev); rtnl_unlock(); } /* * We use our own timer routine rather than relying upon * netdev->tx_timeout because we have a very large hardware transmit * queue. Due to the large queue, the netdev->tx_timeout function * cannot detect a NIC with a parity error in a timely fashion if the * NIC is lightly loaded. */ static void myri10ge_watchdog_timer(unsigned long arg) { struct myri10ge_priv *mgp; struct myri10ge_slice_state *ss; int i, reset_needed, busy_slice_cnt; u32 rx_pause_cnt; u16 cmd; mgp = (struct myri10ge_priv *)arg; rx_pause_cnt = ntohl(mgp->ss[0].fw_stats->dropped_pause); busy_slice_cnt = 0; for (i = 0, reset_needed = 0; i < mgp->num_slices && reset_needed == 0; ++i) { ss = &mgp->ss[i]; if (ss->rx_small.watchdog_needed) { myri10ge_alloc_rx_pages(mgp, &ss->rx_small, mgp->small_bytes + MXGEFW_PAD, 1); if (ss->rx_small.fill_cnt - ss->rx_small.cnt >= myri10ge_fill_thresh) ss->rx_small.watchdog_needed = 0; } if (ss->rx_big.watchdog_needed) { myri10ge_alloc_rx_pages(mgp, &ss->rx_big, mgp->big_bytes, 1); if (ss->rx_big.fill_cnt - ss->rx_big.cnt >= myri10ge_fill_thresh) ss->rx_big.watchdog_needed = 0; } myri10ge_check_slice(ss, &reset_needed, &busy_slice_cnt, rx_pause_cnt); } /* if we've sent or received no traffic, poll the NIC to * ensure it is still there. Otherwise, we risk not noticing * an error in a timely fashion */ if (busy_slice_cnt == 0) { pci_read_config_word(mgp->pdev, PCI_COMMAND, &cmd); if ((cmd & PCI_COMMAND_MASTER) == 0) { reset_needed = 1; } } mgp->watchdog_pause = rx_pause_cnt; if (reset_needed) { schedule_work(&mgp->watchdog_work); } else { /* rearm timer */ mod_timer(&mgp->watchdog_timer, jiffies + myri10ge_watchdog_timeout * HZ); } } static void myri10ge_free_slices(struct myri10ge_priv *mgp) { struct myri10ge_slice_state *ss; struct pci_dev *pdev = mgp->pdev; size_t bytes; int i; if (mgp->ss == NULL) return; for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; if (ss->rx_done.entry != NULL) { bytes = mgp->max_intr_slots * sizeof(*ss->rx_done.entry); dma_free_coherent(&pdev->dev, bytes, ss->rx_done.entry, ss->rx_done.bus); ss->rx_done.entry = NULL; } if (ss->fw_stats != NULL) { bytes = sizeof(*ss->fw_stats); dma_free_coherent(&pdev->dev, bytes, ss->fw_stats, ss->fw_stats_bus); ss->fw_stats = NULL; } netif_napi_del(&ss->napi); } kfree(mgp->ss); mgp->ss = NULL; } static int myri10ge_alloc_slices(struct myri10ge_priv *mgp) { struct myri10ge_slice_state *ss; struct pci_dev *pdev = mgp->pdev; size_t bytes; int i; bytes = sizeof(*mgp->ss) * mgp->num_slices; mgp->ss = kzalloc(bytes, GFP_KERNEL); if (mgp->ss == NULL) { return -ENOMEM; } for (i = 0; i < mgp->num_slices; i++) { ss = &mgp->ss[i]; bytes = mgp->max_intr_slots * sizeof(*ss->rx_done.entry); ss->rx_done.entry = dma_alloc_coherent(&pdev->dev, bytes, &ss->rx_done.bus, GFP_KERNEL); if (ss->rx_done.entry == NULL) goto abort; memset(ss->rx_done.entry, 0, bytes); bytes = sizeof(*ss->fw_stats); ss->fw_stats = dma_alloc_coherent(&pdev->dev, bytes, &ss->fw_stats_bus, GFP_KERNEL); if (ss->fw_stats == NULL) goto abort; ss->mgp = mgp; ss->dev = mgp->dev; netif_napi_add(ss->dev, &ss->napi, myri10ge_poll, myri10ge_napi_weight); } return 0; abort: myri10ge_free_slices(mgp); return -ENOMEM; } /* * This function determines the number of slices supported. * The number slices is the minimum of the number of CPUS, * the number of MSI-X irqs supported, the number of slices * supported by the firmware */ static void myri10ge_probe_slices(struct myri10ge_priv *mgp) { struct myri10ge_cmd cmd; struct pci_dev *pdev = mgp->pdev; char *old_fw; bool old_allocated; int i, status, ncpus, msix_cap; mgp->num_slices = 1; msix_cap = pci_find_capability(pdev, PCI_CAP_ID_MSIX); ncpus = num_online_cpus(); if (myri10ge_max_slices == 1 || msix_cap == 0 || (myri10ge_max_slices == -1 && ncpus < 2)) return; /* try to load the slice aware rss firmware */ old_fw = mgp->fw_name; old_allocated = mgp->fw_name_allocated; /* don't free old_fw if we override it. */ mgp->fw_name_allocated = false; if (myri10ge_fw_name != NULL) { dev_info(&mgp->pdev->dev, "overriding rss firmware to %s\n", myri10ge_fw_name); set_fw_name(mgp, myri10ge_fw_name, false); } else if (old_fw == myri10ge_fw_aligned) set_fw_name(mgp, myri10ge_fw_rss_aligned, false); else set_fw_name(mgp, myri10ge_fw_rss_unaligned, false); status = myri10ge_load_firmware(mgp, 0); if (status != 0) { dev_info(&pdev->dev, "Rss firmware not found\n"); if (old_allocated) kfree(old_fw); return; } /* hit the board with a reset to ensure it is alive */ memset(&cmd, 0, sizeof(cmd)); status = myri10ge_send_cmd(mgp, MXGEFW_CMD_RESET, &cmd, 0); if (status != 0) { dev_err(&mgp->pdev->dev, "failed reset\n"); goto abort_with_fw; } mgp->max_intr_slots = cmd.data0 / sizeof(struct mcp_slot); /* tell it the size of the interrupt queues */ cmd.data0 = mgp->max_intr_slots * sizeof(struct mcp_slot); status = myri10ge_send_cmd(mgp, MXGEFW_CMD_SET_INTRQ_SIZE, &cmd, 0); if (status != 0) { dev_err(&mgp->pdev->dev, "failed MXGEFW_CMD_SET_INTRQ_SIZE\n"); goto abort_with_fw; } /* ask the maximum number of slices it supports */ status = myri10ge_send_cmd(mgp, MXGEFW_CMD_GET_MAX_RSS_QUEUES, &cmd, 0); if (status != 0) goto abort_with_fw; else mgp->num_slices = cmd.data0; /* Only allow multiple slices if MSI-X is usable */ if (!myri10ge_msi) { goto abort_with_fw; } /* if the admin did not specify a limit to how many * slices we should use, cap it automatically to the * number of CPUs currently online */ if (myri10ge_max_slices == -1) myri10ge_max_slices = ncpus; if (mgp->num_slices > myri10ge_max_slices) mgp->num_slices = myri10ge_max_slices; /* Now try to allocate as many MSI-X vectors as we have * slices. We give up on MSI-X if we can only get a single * vector. */ mgp->msix_vectors = kcalloc(mgp->num_slices, sizeof(*mgp->msix_vectors), GFP_KERNEL); if (mgp->msix_vectors == NULL) goto disable_msix; for (i = 0; i < mgp->num_slices; i++) { mgp->msix_vectors[i].entry = i; } while (mgp->num_slices > 1) { /* make sure it is a power of two */ while (!is_power_of_2(mgp->num_slices)) mgp->num_slices--; if (mgp->num_slices == 1) goto disable_msix; status = pci_enable_msix(pdev, mgp->msix_vectors, mgp->num_slices); if (status == 0) { pci_disable_msix(pdev); if (old_allocated) kfree(old_fw); return; } if (status > 0) mgp->num_slices = status; else goto disable_msix; } disable_msix: if (mgp->msix_vectors != NULL) { kfree(mgp->msix_vectors); mgp->msix_vectors = NULL; } abort_with_fw: mgp->num_slices = 1; set_fw_name(mgp, old_fw, old_allocated); myri10ge_load_firmware(mgp, 0); } static const struct net_device_ops myri10ge_netdev_ops = { .ndo_open = myri10ge_open, .ndo_stop = myri10ge_close, .ndo_start_xmit = myri10ge_xmit, .ndo_get_stats64 = myri10ge_get_stats, .ndo_validate_addr = eth_validate_addr, .ndo_change_mtu = myri10ge_change_mtu, .ndo_fix_features = myri10ge_fix_features, .ndo_set_rx_mode = myri10ge_set_multicast_list, .ndo_set_mac_address = myri10ge_set_mac_address, }; static int myri10ge_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct myri10ge_priv *mgp; struct device *dev = &pdev->dev; int i; int status = -ENXIO; int dac_enabled; unsigned hdr_offset, ss_offset; static int board_number; netdev = alloc_etherdev_mq(sizeof(*mgp), MYRI10GE_MAX_SLICES); if (netdev == NULL) return -ENOMEM; SET_NETDEV_DEV(netdev, &pdev->dev); mgp = netdev_priv(netdev); mgp->dev = netdev; mgp->pdev = pdev; mgp->pause = myri10ge_flow_control; mgp->intr_coal_delay = myri10ge_intr_coal_delay; mgp->msg_enable = netif_msg_init(myri10ge_debug, MYRI10GE_MSG_DEFAULT); mgp->board_number = board_number; init_waitqueue_head(&mgp->down_wq); if (pci_enable_device(pdev)) { dev_err(&pdev->dev, "pci_enable_device call failed\n"); status = -ENODEV; goto abort_with_netdev; } /* Find the vendor-specific cap so we can check * the reboot register later on */ mgp->vendor_specific_offset = pci_find_capability(pdev, PCI_CAP_ID_VNDR); /* Set our max read request to 4KB */ status = pcie_set_readrq(pdev, 4096); if (status != 0) { dev_err(&pdev->dev, "Error %d writing PCI_EXP_DEVCTL\n", status); goto abort_with_enabled; } myri10ge_mask_surprise_down(pdev); pci_set_master(pdev); dac_enabled = 1; status = pci_set_dma_mask(pdev, DMA_BIT_MASK(64)); if (status != 0) { dac_enabled = 0; dev_err(&pdev->dev, "64-bit pci address mask was refused, " "trying 32-bit\n"); status = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); } if (status != 0) { dev_err(&pdev->dev, "Error %d setting DMA mask\n", status); goto abort_with_enabled; } (void)pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64)); mgp->cmd = dma_alloc_coherent(&pdev->dev, sizeof(*mgp->cmd), &mgp->cmd_bus, GFP_KERNEL); if (mgp->cmd == NULL) goto abort_with_enabled; mgp->board_span = pci_resource_len(pdev, 0); mgp->iomem_base = pci_resource_start(pdev, 0); mgp->mtrr = -1; mgp->wc_enabled = 0; #ifdef CONFIG_MTRR mgp->mtrr = mtrr_add(mgp->iomem_base, mgp->board_span, MTRR_TYPE_WRCOMB, 1); if (mgp->mtrr >= 0) mgp->wc_enabled = 1; #endif mgp->sram = ioremap_wc(mgp->iomem_base, mgp->board_span); if (mgp->sram == NULL) { dev_err(&pdev->dev, "ioremap failed for %ld bytes at 0x%lx\n", mgp->board_span, mgp->iomem_base); status = -ENXIO; goto abort_with_mtrr; } hdr_offset = ntohl(__raw_readl(mgp->sram + MCP_HEADER_PTR_OFFSET)) & 0xffffc; ss_offset = hdr_offset + offsetof(struct mcp_gen_header, string_specs); mgp->sram_size = ntohl(__raw_readl(mgp->sram + ss_offset)); if (mgp->sram_size > mgp->board_span || mgp->sram_size <= MYRI10GE_FW_OFFSET) { dev_err(&pdev->dev, "invalid sram_size %dB or board span %ldB\n", mgp->sram_size, mgp->board_span); goto abort_with_ioremap; } memcpy_fromio(mgp->eeprom_strings, mgp->sram + mgp->sram_size, MYRI10GE_EEPROM_STRINGS_SIZE); memset(mgp->eeprom_strings + MYRI10GE_EEPROM_STRINGS_SIZE - 2, 0, 2); status = myri10ge_read_mac_addr(mgp); if (status) goto abort_with_ioremap; for (i = 0; i < ETH_ALEN; i++) netdev->dev_addr[i] = mgp->mac_addr[i]; myri10ge_select_firmware(mgp); status = myri10ge_load_firmware(mgp, 1); if (status != 0) { dev_err(&pdev->dev, "failed to load firmware\n"); goto abort_with_ioremap; } myri10ge_probe_slices(mgp); status = myri10ge_alloc_slices(mgp); if (status != 0) { dev_err(&pdev->dev, "failed to alloc slice state\n"); goto abort_with_firmware; } netif_set_real_num_tx_queues(netdev, mgp->num_slices); netif_set_real_num_rx_queues(netdev, mgp->num_slices); status = myri10ge_reset(mgp); if (status != 0) { dev_err(&pdev->dev, "failed reset\n"); goto abort_with_slices; } #ifdef CONFIG_MYRI10GE_DCA myri10ge_setup_dca(mgp); #endif pci_set_drvdata(pdev, mgp); if ((myri10ge_initial_mtu + ETH_HLEN) > MYRI10GE_MAX_ETHER_MTU) myri10ge_initial_mtu = MYRI10GE_MAX_ETHER_MTU - ETH_HLEN; if ((myri10ge_initial_mtu + ETH_HLEN) < 68) myri10ge_initial_mtu = 68; netdev->netdev_ops = &myri10ge_netdev_ops; netdev->mtu = myri10ge_initial_mtu; netdev->base_addr = mgp->iomem_base; netdev->hw_features = mgp->features | NETIF_F_LRO | NETIF_F_RXCSUM; netdev->features = netdev->hw_features; if (dac_enabled) netdev->features |= NETIF_F_HIGHDMA; netdev->vlan_features |= mgp->features; if (mgp->fw_ver_tiny < 37) netdev->vlan_features &= ~NETIF_F_TSO6; if (mgp->fw_ver_tiny < 32) netdev->vlan_features &= ~NETIF_F_TSO; /* make sure we can get an irq, and that MSI can be * setup (if available). Also ensure netdev->irq * is set to correct value if MSI is enabled */ status = myri10ge_request_irq(mgp); if (status != 0) goto abort_with_firmware; netdev->irq = pdev->irq; myri10ge_free_irq(mgp); /* Save configuration space to be restored if the * nic resets due to a parity error */ pci_save_state(pdev); /* Setup the watchdog timer */ setup_timer(&mgp->watchdog_timer, myri10ge_watchdog_timer, (unsigned long)mgp); SET_ETHTOOL_OPS(netdev, &myri10ge_ethtool_ops); INIT_WORK(&mgp->watchdog_work, myri10ge_watchdog); status = register_netdev(netdev); if (status != 0) { dev_err(&pdev->dev, "register_netdev failed: %d\n", status); goto abort_with_state; } if (mgp->msix_enabled) dev_info(dev, "%d MSI-X IRQs, tx bndry %d, fw %s, WC %s\n", mgp->num_slices, mgp->tx_boundary, mgp->fw_name, (mgp->wc_enabled ? "Enabled" : "Disabled")); else dev_info(dev, "%s IRQ %d, tx bndry %d, fw %s, WC %s\n", mgp->msi_enabled ? "MSI" : "xPIC", netdev->irq, mgp->tx_boundary, mgp->fw_name, (mgp->wc_enabled ? "Enabled" : "Disabled")); board_number++; return 0; abort_with_state: pci_restore_state(pdev); abort_with_slices: myri10ge_free_slices(mgp); abort_with_firmware: myri10ge_dummy_rdma(mgp, 0); abort_with_ioremap: if (mgp->mac_addr_string != NULL) dev_err(&pdev->dev, "myri10ge_probe() failed: MAC=%s, SN=%ld\n", mgp->mac_addr_string, mgp->serial_number); iounmap(mgp->sram); abort_with_mtrr: #ifdef CONFIG_MTRR if (mgp->mtrr >= 0) mtrr_del(mgp->mtrr, mgp->iomem_base, mgp->board_span); #endif dma_free_coherent(&pdev->dev, sizeof(*mgp->cmd), mgp->cmd, mgp->cmd_bus); abort_with_enabled: pci_disable_device(pdev); abort_with_netdev: set_fw_name(mgp, NULL, false); free_netdev(netdev); return status; } /* * myri10ge_remove * * Does what is necessary to shutdown one Myrinet device. Called * once for each Myrinet card by the kernel when a module is * unloaded. */ static void myri10ge_remove(struct pci_dev *pdev) { struct myri10ge_priv *mgp; struct net_device *netdev; mgp = pci_get_drvdata(pdev); if (mgp == NULL) return; cancel_work_sync(&mgp->watchdog_work); netdev = mgp->dev; unregister_netdev(netdev); #ifdef CONFIG_MYRI10GE_DCA myri10ge_teardown_dca(mgp); #endif myri10ge_dummy_rdma(mgp, 0); /* avoid a memory leak */ pci_restore_state(pdev); iounmap(mgp->sram); #ifdef CONFIG_MTRR if (mgp->mtrr >= 0) mtrr_del(mgp->mtrr, mgp->iomem_base, mgp->board_span); #endif myri10ge_free_slices(mgp); if (mgp->msix_vectors != NULL) kfree(mgp->msix_vectors); dma_free_coherent(&pdev->dev, sizeof(*mgp->cmd), mgp->cmd, mgp->cmd_bus); set_fw_name(mgp, NULL, false); free_netdev(netdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } #define PCI_DEVICE_ID_MYRICOM_MYRI10GE_Z8E 0x0008 #define PCI_DEVICE_ID_MYRICOM_MYRI10GE_Z8E_9 0x0009 static DEFINE_PCI_DEVICE_TABLE(myri10ge_pci_tbl) = { {PCI_DEVICE(PCI_VENDOR_ID_MYRICOM, PCI_DEVICE_ID_MYRICOM_MYRI10GE_Z8E)}, {PCI_DEVICE (PCI_VENDOR_ID_MYRICOM, PCI_DEVICE_ID_MYRICOM_MYRI10GE_Z8E_9)}, {0}, }; MODULE_DEVICE_TABLE(pci, myri10ge_pci_tbl); static struct pci_driver myri10ge_driver = { .name = "myri10ge", .probe = myri10ge_probe, .remove = myri10ge_remove, .id_table = myri10ge_pci_tbl, #ifdef CONFIG_PM .suspend = myri10ge_suspend, .resume = myri10ge_resume, #endif }; #ifdef CONFIG_MYRI10GE_DCA static int myri10ge_notify_dca(struct notifier_block *nb, unsigned long event, void *p) { int err = driver_for_each_device(&myri10ge_driver.driver, NULL, &event, myri10ge_notify_dca_device); if (err) return NOTIFY_BAD; return NOTIFY_DONE; } static struct notifier_block myri10ge_dca_notifier = { .notifier_call = myri10ge_notify_dca, .next = NULL, .priority = 0, }; #endif /* CONFIG_MYRI10GE_DCA */ static __init int myri10ge_init_module(void) { pr_info("Version %s\n", MYRI10GE_VERSION_STR); if (myri10ge_rss_hash > MXGEFW_RSS_HASH_TYPE_MAX) { pr_err("Illegal rssh hash type %d, defaulting to source port\n", myri10ge_rss_hash); myri10ge_rss_hash = MXGEFW_RSS_HASH_TYPE_SRC_PORT; } #ifdef CONFIG_MYRI10GE_DCA dca_register_notify(&myri10ge_dca_notifier); #endif if (myri10ge_max_slices > MYRI10GE_MAX_SLICES) myri10ge_max_slices = MYRI10GE_MAX_SLICES; return pci_register_driver(&myri10ge_driver); } module_init(myri10ge_init_module); static __exit void myri10ge_cleanup_module(void) { #ifdef CONFIG_MYRI10GE_DCA dca_unregister_notify(&myri10ge_dca_notifier); #endif pci_unregister_driver(&myri10ge_driver); } module_exit(myri10ge_cleanup_module);
gpl-2.0
xwliu/Cubietruck_Plus-kernel-source
sound/pci/hda/hda_jack.c
4810
10079
/* * Jack-detection handling for HD-audio * * Copyright (c) 2011 Takashi Iwai <tiwai@suse.de> * * This driver 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/init.h> #include <linux/slab.h> #include <linux/export.h> #include <sound/core.h> #include <sound/control.h> #include <sound/jack.h> #include "hda_codec.h" #include "hda_local.h" #include "hda_jack.h" bool is_jack_detectable(struct hda_codec *codec, hda_nid_t nid) { if (codec->no_jack_detect) return false; if (!(snd_hda_query_pin_caps(codec, nid) & AC_PINCAP_PRES_DETECT)) return false; if (!codec->ignore_misc_bit && (get_defcfg_misc(snd_hda_codec_get_pincfg(codec, nid)) & AC_DEFCFG_MISC_NO_PRESENCE)) return false; if (!(get_wcaps(codec, nid) & AC_WCAP_UNSOL_CAP)) return false; return true; } EXPORT_SYMBOL_HDA(is_jack_detectable); /* execute pin sense measurement */ static u32 read_pin_sense(struct hda_codec *codec, hda_nid_t nid) { u32 pincap; if (!codec->no_trigger_sense) { pincap = snd_hda_query_pin_caps(codec, nid); if (pincap & AC_PINCAP_TRIG_REQ) /* need trigger? */ snd_hda_codec_read(codec, nid, 0, AC_VERB_SET_PIN_SENSE, 0); } return snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_SENSE, 0); } /** * snd_hda_jack_tbl_get - query the jack-table entry for the given NID */ struct hda_jack_tbl * snd_hda_jack_tbl_get(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; if (!nid || !jack) return NULL; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid == nid) return jack; return NULL; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_get); /** * snd_hda_jack_tbl_get_from_tag - query the jack-table entry for the given tag */ struct hda_jack_tbl * snd_hda_jack_tbl_get_from_tag(struct hda_codec *codec, unsigned char tag) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; if (!tag || !jack) return NULL; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->tag == tag) return jack; return NULL; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_get_from_tag); /** * snd_hda_jack_tbl_new - create a jack-table entry for the given NID */ struct hda_jack_tbl * snd_hda_jack_tbl_new(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_get(codec, nid); if (jack) return jack; snd_array_init(&codec->jacktbl, sizeof(*jack), 16); jack = snd_array_new(&codec->jacktbl); if (!jack) return NULL; jack->nid = nid; jack->jack_dirty = 1; jack->tag = codec->jacktbl.used; return jack; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_new); void snd_hda_jack_tbl_clear(struct hda_codec *codec) { #ifdef CONFIG_SND_HDA_INPUT_JACK /* free jack instances manually when clearing/reconfiguring */ if (!codec->bus->shutdown && codec->jacktbl.list) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; for (i = 0; i < codec->jacktbl.used; i++, jack++) { if (jack->jack) snd_device_free(codec->bus->card, jack->jack); } } #endif snd_array_free(&codec->jacktbl); } /* update the cached value and notification flag if needed */ static void jack_detect_update(struct hda_codec *codec, struct hda_jack_tbl *jack) { if (jack->jack_dirty || !jack->jack_detect) { jack->pin_sense = read_pin_sense(codec, jack->nid); jack->jack_dirty = 0; } } /** * snd_hda_set_dirty_all - Mark all the cached as dirty * * This function sets the dirty flag to all entries of jack table. * It's called from the resume path in hda_codec.c. */ void snd_hda_jack_set_dirty_all(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) jack->jack_dirty = 1; } EXPORT_SYMBOL_HDA(snd_hda_jack_set_dirty_all); /** * snd_hda_pin_sense - execute pin sense measurement * @codec: the CODEC to sense * @nid: the pin NID to sense * * Execute necessary pin sense measurement and return its Presence Detect, * Impedance, ELD Valid etc. status bits. */ u32 snd_hda_pin_sense(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_get(codec, nid); if (jack) { jack_detect_update(codec, jack); return jack->pin_sense; } return read_pin_sense(codec, nid); } EXPORT_SYMBOL_HDA(snd_hda_pin_sense); #define get_jack_plug_state(sense) !!(sense & AC_PINSENSE_PRESENCE) /** * snd_hda_jack_detect - query pin Presence Detect status * @codec: the CODEC to sense * @nid: the pin NID to sense * * Query and return the pin's Presence Detect status. */ int snd_hda_jack_detect(struct hda_codec *codec, hda_nid_t nid) { u32 sense = snd_hda_pin_sense(codec, nid); return get_jack_plug_state(sense); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect); /** * snd_hda_jack_detect_enable - enable the jack-detection */ int snd_hda_jack_detect_enable(struct hda_codec *codec, hda_nid_t nid, unsigned char action) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_new(codec, nid); if (!jack) return -ENOMEM; if (jack->jack_detect) return 0; /* already registered */ jack->jack_detect = 1; if (action) jack->action = action; return snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | jack->tag); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect_enable); /** * snd_hda_jack_report_sync - sync the states of all jacks and report if changed */ void snd_hda_jack_report_sync(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i, state; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) { jack_detect_update(codec, jack); if (!jack->kctl) continue; state = get_jack_plug_state(jack->pin_sense); snd_kctl_jack_report(codec->bus->card, jack->kctl, state); #ifdef CONFIG_SND_HDA_INPUT_JACK if (jack->jack) snd_jack_report(jack->jack, state ? jack->type : 0); #endif } } EXPORT_SYMBOL_HDA(snd_hda_jack_report_sync); #ifdef CONFIG_SND_HDA_INPUT_JACK /* guess the jack type from the pin-config */ static int get_input_jack_type(struct hda_codec *codec, hda_nid_t nid) { unsigned int def_conf = snd_hda_codec_get_pincfg(codec, nid); switch (get_defcfg_device(def_conf)) { case AC_JACK_LINE_OUT: case AC_JACK_SPEAKER: return SND_JACK_LINEOUT; case AC_JACK_HP_OUT: return SND_JACK_HEADPHONE; case AC_JACK_SPDIF_OUT: case AC_JACK_DIG_OTHER_OUT: return SND_JACK_AVOUT; case AC_JACK_MIC_IN: return SND_JACK_MICROPHONE; default: return SND_JACK_LINEIN; } } static void hda_free_jack_priv(struct snd_jack *jack) { struct hda_jack_tbl *jacks = jack->private_data; jacks->nid = 0; jacks->jack = NULL; } #endif /** * snd_hda_jack_add_kctl - Add a kctl for the given pin * * This assigns a jack-detection kctl to the given pin. The kcontrol * will have the given name and index. */ int snd_hda_jack_add_kctl(struct hda_codec *codec, hda_nid_t nid, const char *name, int idx) { struct hda_jack_tbl *jack; struct snd_kcontrol *kctl; int err, state; jack = snd_hda_jack_tbl_new(codec, nid); if (!jack) return 0; if (jack->kctl) return 0; /* already created */ kctl = snd_kctl_jack_new(name, idx, codec); if (!kctl) return -ENOMEM; err = snd_hda_ctl_add(codec, nid, kctl); if (err < 0) return err; jack->kctl = kctl; state = snd_hda_jack_detect(codec, nid); snd_kctl_jack_report(codec->bus->card, kctl, state); #ifdef CONFIG_SND_HDA_INPUT_JACK jack->type = get_input_jack_type(codec, nid); err = snd_jack_new(codec->bus->card, name, jack->type, &jack->jack); if (err < 0) return err; jack->jack->private_data = jack; jack->jack->private_free = hda_free_jack_priv; snd_jack_report(jack->jack, state ? jack->type : 0); #endif return 0; } EXPORT_SYMBOL_HDA(snd_hda_jack_add_kctl); static int add_jack_kctl(struct hda_codec *codec, hda_nid_t nid, const struct auto_pin_cfg *cfg, char *lastname, int *lastidx) { unsigned int def_conf, conn; char name[44]; int idx, err; if (!nid) return 0; if (!is_jack_detectable(codec, nid)) return 0; def_conf = snd_hda_codec_get_pincfg(codec, nid); conn = get_defcfg_connect(def_conf); if (conn != AC_JACK_PORT_COMPLEX) return 0; snd_hda_get_pin_label(codec, nid, cfg, name, sizeof(name), &idx); if (!strcmp(name, lastname) && idx == *lastidx) idx++; strncpy(lastname, name, 44); *lastidx = idx; err = snd_hda_jack_add_kctl(codec, nid, name, idx); if (err < 0) return err; return snd_hda_jack_detect_enable(codec, nid, 0); } /** * snd_hda_jack_add_kctls - Add kctls for all pins included in the given pincfg */ int snd_hda_jack_add_kctls(struct hda_codec *codec, const struct auto_pin_cfg *cfg) { const hda_nid_t *p; int i, err, lastidx = 0; char lastname[44] = ""; for (i = 0, p = cfg->line_out_pins; i < cfg->line_outs; i++, p++) { err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0, p = cfg->hp_pins; i < cfg->hp_outs; i++, p++) { if (*p == *cfg->line_out_pins) /* might be duplicated */ break; err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0, p = cfg->speaker_pins; i < cfg->speaker_outs; i++, p++) { if (*p == *cfg->line_out_pins) /* might be duplicated */ break; err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0; i < cfg->num_inputs; i++) { err = add_jack_kctl(codec, cfg->inputs[i].pin, cfg, lastname, &lastidx); if (err < 0) return err; } for (i = 0, p = cfg->dig_out_pins; i < cfg->dig_outs; i++, p++) { err = add_jack_kctl(codec, *p, cfg, lastname, &lastidx); if (err < 0) return err; } err = add_jack_kctl(codec, cfg->dig_in_pin, cfg, lastname, &lastidx); if (err < 0) return err; err = add_jack_kctl(codec, cfg->mono_out_pin, cfg, lastname, &lastidx); if (err < 0) return err; return 0; } EXPORT_SYMBOL_HDA(snd_hda_jack_add_kctls);
gpl-2.0
akw28888/n909
drivers/scsi/bnx2i/bnx2i_init.c
4810
15776
/* bnx2i.c: Broadcom NetXtreme II iSCSI driver. * * Copyright (c) 2006 - 2011 Broadcom Corporation * Copyright (c) 2007, 2008 Red Hat, Inc. All rights reserved. * Copyright (c) 2007, 2008 Mike Christie * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * Written by: Anil Veerabhadrappa (anilgv@broadcom.com) * Maintained by: Eddie Wai (eddie.wai@broadcom.com) */ #include "bnx2i.h" static struct list_head adapter_list = LIST_HEAD_INIT(adapter_list); static u32 adapter_count; #define DRV_MODULE_NAME "bnx2i" #define DRV_MODULE_VERSION "2.7.0.3" #define DRV_MODULE_RELDATE "Jun 15, 2011" static char version[] __devinitdata = "Broadcom NetXtreme II iSCSI Driver " DRV_MODULE_NAME \ " v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n"; MODULE_AUTHOR("Anil Veerabhadrappa <anilgv@broadcom.com> and " "Eddie Wai <eddie.wai@broadcom.com>"); MODULE_DESCRIPTION("Broadcom NetXtreme II BCM5706/5708/5709/57710/57711/57712" "/57800/57810/57840 iSCSI Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_MODULE_VERSION); static DEFINE_MUTEX(bnx2i_dev_lock); unsigned int event_coal_min = 24; module_param(event_coal_min, int, 0664); MODULE_PARM_DESC(event_coal_min, "Event Coalescing Minimum Commands"); unsigned int event_coal_div = 2; module_param(event_coal_div, int, 0664); MODULE_PARM_DESC(event_coal_div, "Event Coalescing Divide Factor"); unsigned int en_tcp_dack = 1; module_param(en_tcp_dack, int, 0664); MODULE_PARM_DESC(en_tcp_dack, "Enable TCP Delayed ACK"); unsigned int error_mask1 = 0x00; module_param(error_mask1, uint, 0664); MODULE_PARM_DESC(error_mask1, "Config FW iSCSI Error Mask #1"); unsigned int error_mask2 = 0x00; module_param(error_mask2, uint, 0664); MODULE_PARM_DESC(error_mask2, "Config FW iSCSI Error Mask #2"); unsigned int sq_size; module_param(sq_size, int, 0664); MODULE_PARM_DESC(sq_size, "Configure SQ size"); unsigned int rq_size = BNX2I_RQ_WQES_DEFAULT; module_param(rq_size, int, 0664); MODULE_PARM_DESC(rq_size, "Configure RQ size"); u64 iscsi_error_mask = 0x00; DEFINE_PER_CPU(struct bnx2i_percpu_s, bnx2i_percpu); static int bnx2i_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu); /* notification function for CPU hotplug events */ static struct notifier_block bnx2i_cpu_notifier = { .notifier_call = bnx2i_cpu_callback, }; /** * bnx2i_identify_device - identifies NetXtreme II device type * @hba: Adapter structure pointer * * This function identifies the NX2 device type and sets appropriate * queue mailbox register access method, 5709 requires driver to * access MBOX regs using *bin* mode */ void bnx2i_identify_device(struct bnx2i_hba *hba) { hba->cnic_dev_type = 0; if ((hba->pci_did == PCI_DEVICE_ID_NX2_5706) || (hba->pci_did == PCI_DEVICE_ID_NX2_5706S)) set_bit(BNX2I_NX2_DEV_5706, &hba->cnic_dev_type); else if ((hba->pci_did == PCI_DEVICE_ID_NX2_5708) || (hba->pci_did == PCI_DEVICE_ID_NX2_5708S)) set_bit(BNX2I_NX2_DEV_5708, &hba->cnic_dev_type); else if ((hba->pci_did == PCI_DEVICE_ID_NX2_5709) || (hba->pci_did == PCI_DEVICE_ID_NX2_5709S)) { set_bit(BNX2I_NX2_DEV_5709, &hba->cnic_dev_type); hba->mail_queue_access = BNX2I_MQ_BIN_MODE; } else if (hba->pci_did == PCI_DEVICE_ID_NX2_57710 || hba->pci_did == PCI_DEVICE_ID_NX2_57711 || hba->pci_did == PCI_DEVICE_ID_NX2_57711E || hba->pci_did == PCI_DEVICE_ID_NX2_57712 || hba->pci_did == PCI_DEVICE_ID_NX2_57712E || hba->pci_did == PCI_DEVICE_ID_NX2_57800 || hba->pci_did == PCI_DEVICE_ID_NX2_57800_MF || hba->pci_did == PCI_DEVICE_ID_NX2_57800_VF || hba->pci_did == PCI_DEVICE_ID_NX2_57810 || hba->pci_did == PCI_DEVICE_ID_NX2_57810_MF || hba->pci_did == PCI_DEVICE_ID_NX2_57810_VF || hba->pci_did == PCI_DEVICE_ID_NX2_57840 || hba->pci_did == PCI_DEVICE_ID_NX2_57840_MF || hba->pci_did == PCI_DEVICE_ID_NX2_57840_VF) set_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type); else printk(KERN_ALERT "bnx2i: unknown device, 0x%x\n", hba->pci_did); } /** * get_adapter_list_head - returns head of adapter list */ struct bnx2i_hba *get_adapter_list_head(void) { struct bnx2i_hba *hba = NULL; struct bnx2i_hba *tmp_hba; if (!adapter_count) goto hba_not_found; mutex_lock(&bnx2i_dev_lock); list_for_each_entry(tmp_hba, &adapter_list, link) { if (tmp_hba->cnic && tmp_hba->cnic->cm_select_dev) { hba = tmp_hba; break; } } mutex_unlock(&bnx2i_dev_lock); hba_not_found: return hba; } /** * bnx2i_find_hba_for_cnic - maps cnic device instance to bnx2i adapter instance * @cnic: pointer to cnic device instance * */ struct bnx2i_hba *bnx2i_find_hba_for_cnic(struct cnic_dev *cnic) { struct bnx2i_hba *hba, *temp; mutex_lock(&bnx2i_dev_lock); list_for_each_entry_safe(hba, temp, &adapter_list, link) { if (hba->cnic == cnic) { mutex_unlock(&bnx2i_dev_lock); return hba; } } mutex_unlock(&bnx2i_dev_lock); return NULL; } /** * bnx2i_start - cnic callback to initialize & start adapter instance * @handle: transparent handle pointing to adapter structure * * This function maps adapter structure to pcidev structure and initiates * firmware handshake to enable/initialize on chip iscsi components * This bnx2i - cnic interface api callback is issued after following * 2 conditions are met - * a) underlying network interface is up (marked by event 'NETDEV_UP' * from netdev * b) bnx2i adapter instance is registered */ void bnx2i_start(void *handle) { #define BNX2I_INIT_POLL_TIME (1000 / HZ) struct bnx2i_hba *hba = handle; int i = HZ; /* * We should never register devices that don't support iSCSI * (see bnx2i_init_one), so something is wrong if we try to * start a iSCSI adapter on hardware with 0 supported iSCSI * connections */ BUG_ON(!hba->cnic->max_iscsi_conn); bnx2i_send_fw_iscsi_init_msg(hba); while (!test_bit(ADAPTER_STATE_UP, &hba->adapter_state) && i--) msleep(BNX2I_INIT_POLL_TIME); } /** * bnx2i_chip_cleanup - local routine to handle chip cleanup * @hba: Adapter instance to register * * Driver checks if adapter still has any active connections before * executing the cleanup process */ static void bnx2i_chip_cleanup(struct bnx2i_hba *hba) { struct bnx2i_endpoint *bnx2i_ep; struct list_head *pos, *tmp; if (hba->ofld_conns_active) { /* Stage to force the disconnection * This is the case where the daemon is either slow or * not present */ printk(KERN_ALERT "bnx2i: (%s) chip cleanup for %d active " "connections\n", hba->netdev->name, hba->ofld_conns_active); mutex_lock(&hba->net_dev_lock); list_for_each_safe(pos, tmp, &hba->ep_active_list) { bnx2i_ep = list_entry(pos, struct bnx2i_endpoint, link); /* Clean up the chip only */ bnx2i_hw_ep_disconnect(bnx2i_ep); bnx2i_ep->cm_sk = NULL; } mutex_unlock(&hba->net_dev_lock); } } /** * bnx2i_stop - cnic callback to shutdown adapter instance * @handle: transparent handle pointing to adapter structure * * driver checks if adapter is already in shutdown mode, if not start * the shutdown process */ void bnx2i_stop(void *handle) { struct bnx2i_hba *hba = handle; int conns_active; int wait_delay = 1 * HZ; /* check if cleanup happened in GOING_DOWN context */ if (!test_and_set_bit(ADAPTER_STATE_GOING_DOWN, &hba->adapter_state)) { iscsi_host_for_each_session(hba->shost, bnx2i_drop_session); wait_delay = hba->hba_shutdown_tmo; } /* Wait for inflight offload connection tasks to complete before * proceeding. Forcefully terminate all connection recovery in * progress at the earliest, either in bind(), send_pdu(LOGIN), * or conn_start() */ wait_event_interruptible_timeout(hba->eh_wait, (list_empty(&hba->ep_ofld_list) && list_empty(&hba->ep_destroy_list)), 2 * HZ); /* Wait for all endpoints to be torn down, Chip will be reset once * control returns to network driver. So it is required to cleanup and * release all connection resources before returning from this routine. */ while (hba->ofld_conns_active) { conns_active = hba->ofld_conns_active; wait_event_interruptible_timeout(hba->eh_wait, (hba->ofld_conns_active != conns_active), wait_delay); if (hba->ofld_conns_active == conns_active) break; } bnx2i_chip_cleanup(hba); /* This flag should be cleared last so that ep_disconnect() gracefully * cleans up connection context */ clear_bit(ADAPTER_STATE_GOING_DOWN, &hba->adapter_state); clear_bit(ADAPTER_STATE_UP, &hba->adapter_state); } /** * bnx2i_init_one - initialize an adapter instance and allocate memory resources * @hba: bnx2i adapter instance * @cnic: cnic device handle * * Global resource lock is held during critical sections below. This routine is * called from either cnic_register_driver() or device hot plug context and * and does majority of device specific initialization */ static int bnx2i_init_one(struct bnx2i_hba *hba, struct cnic_dev *cnic) { int rc; mutex_lock(&bnx2i_dev_lock); if (!cnic->max_iscsi_conn) { printk(KERN_ALERT "bnx2i: dev %s does not support " "iSCSI\n", hba->netdev->name); rc = -EOPNOTSUPP; goto out; } hba->cnic = cnic; rc = cnic->register_device(cnic, CNIC_ULP_ISCSI, hba); if (!rc) { hba->age++; set_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic); list_add_tail(&hba->link, &adapter_list); adapter_count++; } else if (rc == -EBUSY) /* duplicate registration */ printk(KERN_ALERT "bnx2i, duplicate registration" "hba=%p, cnic=%p\n", hba, cnic); else if (rc == -EAGAIN) printk(KERN_ERR "bnx2i, driver not registered\n"); else if (rc == -EINVAL) printk(KERN_ERR "bnx2i, invalid type %d\n", CNIC_ULP_ISCSI); else printk(KERN_ERR "bnx2i dev reg, unknown error, %d\n", rc); out: mutex_unlock(&bnx2i_dev_lock); return rc; } /** * bnx2i_ulp_init - initialize an adapter instance * @dev: cnic device handle * * Called from cnic_register_driver() context to initialize all enumerated * cnic devices. This routine allocate adapter structure and other * device specific resources. */ void bnx2i_ulp_init(struct cnic_dev *dev) { struct bnx2i_hba *hba; /* Allocate a HBA structure for this device */ hba = bnx2i_alloc_hba(dev); if (!hba) { printk(KERN_ERR "bnx2i init: hba initialization failed\n"); return; } /* Get PCI related information and update hba struct members */ clear_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic); if (bnx2i_init_one(hba, dev)) { printk(KERN_ERR "bnx2i - hba %p init failed\n", hba); bnx2i_free_hba(hba); } } /** * bnx2i_ulp_exit - shuts down adapter instance and frees all resources * @dev: cnic device handle * */ void bnx2i_ulp_exit(struct cnic_dev *dev) { struct bnx2i_hba *hba; hba = bnx2i_find_hba_for_cnic(dev); if (!hba) { printk(KERN_INFO "bnx2i_ulp_exit: hba not " "found, dev 0x%p\n", dev); return; } mutex_lock(&bnx2i_dev_lock); list_del_init(&hba->link); adapter_count--; if (test_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic)) { hba->cnic->unregister_device(hba->cnic, CNIC_ULP_ISCSI); clear_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic); } mutex_unlock(&bnx2i_dev_lock); bnx2i_free_hba(hba); } /** * bnx2i_percpu_thread_create - Create a receive thread for an * online CPU * * @cpu: cpu index for the online cpu */ static void bnx2i_percpu_thread_create(unsigned int cpu) { struct bnx2i_percpu_s *p; struct task_struct *thread; p = &per_cpu(bnx2i_percpu, cpu); thread = kthread_create_on_node(bnx2i_percpu_io_thread, (void *)p, cpu_to_node(cpu), "bnx2i_thread/%d", cpu); /* bind thread to the cpu */ if (likely(!IS_ERR(thread))) { kthread_bind(thread, cpu); p->iothread = thread; wake_up_process(thread); } } static void bnx2i_percpu_thread_destroy(unsigned int cpu) { struct bnx2i_percpu_s *p; struct task_struct *thread; struct bnx2i_work *work, *tmp; /* Prevent any new work from being queued for this CPU */ p = &per_cpu(bnx2i_percpu, cpu); spin_lock_bh(&p->p_work_lock); thread = p->iothread; p->iothread = NULL; /* Free all work in the list */ list_for_each_entry_safe(work, tmp, &p->work_list, list) { list_del_init(&work->list); bnx2i_process_scsi_cmd_resp(work->session, work->bnx2i_conn, &work->cqe); kfree(work); } spin_unlock_bh(&p->p_work_lock); if (thread) kthread_stop(thread); } /** * bnx2i_cpu_callback - Handler for CPU hotplug events * * @nfb: The callback data block * @action: The event triggering the callback * @hcpu: The index of the CPU that the event is for * * This creates or destroys per-CPU data for iSCSI * * Returns NOTIFY_OK always. */ static int bnx2i_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned cpu = (unsigned long)hcpu; switch (action) { case CPU_ONLINE: case CPU_ONLINE_FROZEN: printk(KERN_INFO "bnx2i: CPU %x online: Create Rx thread\n", cpu); bnx2i_percpu_thread_create(cpu); break; case CPU_DEAD: case CPU_DEAD_FROZEN: printk(KERN_INFO "CPU %x offline: Remove Rx thread\n", cpu); bnx2i_percpu_thread_destroy(cpu); break; default: break; } return NOTIFY_OK; } /** * bnx2i_mod_init - module init entry point * * initialize any driver wide global data structures such as endpoint pool, * tcp port manager/queue, sysfs. finally driver will register itself * with the cnic module */ static int __init bnx2i_mod_init(void) { int err; unsigned cpu = 0; struct bnx2i_percpu_s *p; printk(KERN_INFO "%s", version); if (sq_size && !is_power_of_2(sq_size)) sq_size = roundup_pow_of_two(sq_size); mutex_init(&bnx2i_dev_lock); bnx2i_scsi_xport_template = iscsi_register_transport(&bnx2i_iscsi_transport); if (!bnx2i_scsi_xport_template) { printk(KERN_ERR "Could not register bnx2i transport.\n"); err = -ENOMEM; goto out; } err = cnic_register_driver(CNIC_ULP_ISCSI, &bnx2i_cnic_cb); if (err) { printk(KERN_ERR "Could not register bnx2i cnic driver.\n"); goto unreg_xport; } /* Create percpu kernel threads to handle iSCSI I/O completions */ for_each_possible_cpu(cpu) { p = &per_cpu(bnx2i_percpu, cpu); INIT_LIST_HEAD(&p->work_list); spin_lock_init(&p->p_work_lock); p->iothread = NULL; } for_each_online_cpu(cpu) bnx2i_percpu_thread_create(cpu); /* Initialize per CPU interrupt thread */ register_hotcpu_notifier(&bnx2i_cpu_notifier); return 0; unreg_xport: iscsi_unregister_transport(&bnx2i_iscsi_transport); out: return err; } /** * bnx2i_mod_exit - module cleanup/exit entry point * * Global resource lock and host adapter lock is held during critical sections * in this function. Driver will browse through the adapter list, cleans-up * each instance, unregisters iscsi transport name and finally driver will * unregister itself with the cnic module */ static void __exit bnx2i_mod_exit(void) { struct bnx2i_hba *hba; unsigned cpu = 0; mutex_lock(&bnx2i_dev_lock); while (!list_empty(&adapter_list)) { hba = list_entry(adapter_list.next, struct bnx2i_hba, link); list_del(&hba->link); adapter_count--; if (test_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic)) { bnx2i_chip_cleanup(hba); hba->cnic->unregister_device(hba->cnic, CNIC_ULP_ISCSI); clear_bit(BNX2I_CNIC_REGISTERED, &hba->reg_with_cnic); } bnx2i_free_hba(hba); } mutex_unlock(&bnx2i_dev_lock); unregister_hotcpu_notifier(&bnx2i_cpu_notifier); for_each_online_cpu(cpu) bnx2i_percpu_thread_destroy(cpu); iscsi_unregister_transport(&bnx2i_iscsi_transport); cnic_unregister_driver(CNIC_ULP_ISCSI); } module_init(bnx2i_mod_init); module_exit(bnx2i_mod_exit);
gpl-2.0
TaichiN/android_kernel_lge_hammerhead
drivers/input/misc/ad714x.c
5066
36413
/* * AD714X CapTouch Programmable Controller driver supporting AD7142/3/7/8/7A * * Copyright 2009-2011 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #include <linux/device.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/input/ad714x.h> #include <linux/module.h> #include "ad714x.h" #define AD714X_PWR_CTRL 0x0 #define AD714X_STG_CAL_EN_REG 0x1 #define AD714X_AMB_COMP_CTRL0_REG 0x2 #define AD714X_PARTID_REG 0x17 #define AD7142_PARTID 0xE620 #define AD7143_PARTID 0xE630 #define AD7147_PARTID 0x1470 #define AD7148_PARTID 0x1480 #define AD714X_STAGECFG_REG 0x80 #define AD714X_SYSCFG_REG 0x0 #define STG_LOW_INT_EN_REG 0x5 #define STG_HIGH_INT_EN_REG 0x6 #define STG_COM_INT_EN_REG 0x7 #define STG_LOW_INT_STA_REG 0x8 #define STG_HIGH_INT_STA_REG 0x9 #define STG_COM_INT_STA_REG 0xA #define CDC_RESULT_S0 0xB #define CDC_RESULT_S1 0xC #define CDC_RESULT_S2 0xD #define CDC_RESULT_S3 0xE #define CDC_RESULT_S4 0xF #define CDC_RESULT_S5 0x10 #define CDC_RESULT_S6 0x11 #define CDC_RESULT_S7 0x12 #define CDC_RESULT_S8 0x13 #define CDC_RESULT_S9 0x14 #define CDC_RESULT_S10 0x15 #define CDC_RESULT_S11 0x16 #define STAGE0_AMBIENT 0xF1 #define STAGE1_AMBIENT 0x115 #define STAGE2_AMBIENT 0x139 #define STAGE3_AMBIENT 0x15D #define STAGE4_AMBIENT 0x181 #define STAGE5_AMBIENT 0x1A5 #define STAGE6_AMBIENT 0x1C9 #define STAGE7_AMBIENT 0x1ED #define STAGE8_AMBIENT 0x211 #define STAGE9_AMBIENT 0x234 #define STAGE10_AMBIENT 0x259 #define STAGE11_AMBIENT 0x27D #define PER_STAGE_REG_NUM 36 #define STAGE_CFGREG_NUM 8 #define SYS_CFGREG_NUM 8 /* * driver information which will be used to maintain the software flow */ enum ad714x_device_state { IDLE, JITTER, ACTIVE, SPACE }; struct ad714x_slider_drv { int highest_stage; int abs_pos; int flt_pos; enum ad714x_device_state state; struct input_dev *input; }; struct ad714x_wheel_drv { int abs_pos; int flt_pos; int pre_highest_stage; int highest_stage; enum ad714x_device_state state; struct input_dev *input; }; struct ad714x_touchpad_drv { int x_highest_stage; int x_flt_pos; int x_abs_pos; int y_highest_stage; int y_flt_pos; int y_abs_pos; int left_ep; int left_ep_val; int right_ep; int right_ep_val; int top_ep; int top_ep_val; int bottom_ep; int bottom_ep_val; enum ad714x_device_state state; struct input_dev *input; }; struct ad714x_button_drv { enum ad714x_device_state state; /* * Unlike slider/wheel/touchpad, all buttons point to * same input_dev instance */ struct input_dev *input; }; struct ad714x_driver_data { struct ad714x_slider_drv *slider; struct ad714x_wheel_drv *wheel; struct ad714x_touchpad_drv *touchpad; struct ad714x_button_drv *button; }; /* * information to integrate all things which will be private data * of spi/i2c device */ static void ad714x_use_com_int(struct ad714x_chip *ad714x, int start_stage, int end_stage) { unsigned short data; unsigned short mask; mask = ((1 << (end_stage + 1)) - 1) - ((1 << start_stage) - 1); ad714x->read(ad714x, STG_COM_INT_EN_REG, &data, 1); data |= 1 << end_stage; ad714x->write(ad714x, STG_COM_INT_EN_REG, data); ad714x->read(ad714x, STG_HIGH_INT_EN_REG, &data, 1); data &= ~mask; ad714x->write(ad714x, STG_HIGH_INT_EN_REG, data); } static void ad714x_use_thr_int(struct ad714x_chip *ad714x, int start_stage, int end_stage) { unsigned short data; unsigned short mask; mask = ((1 << (end_stage + 1)) - 1) - ((1 << start_stage) - 1); ad714x->read(ad714x, STG_COM_INT_EN_REG, &data, 1); data &= ~(1 << end_stage); ad714x->write(ad714x, STG_COM_INT_EN_REG, data); ad714x->read(ad714x, STG_HIGH_INT_EN_REG, &data, 1); data |= mask; ad714x->write(ad714x, STG_HIGH_INT_EN_REG, data); } static int ad714x_cal_highest_stage(struct ad714x_chip *ad714x, int start_stage, int end_stage) { int max_res = 0; int max_idx = 0; int i; for (i = start_stage; i <= end_stage; i++) { if (ad714x->sensor_val[i] > max_res) { max_res = ad714x->sensor_val[i]; max_idx = i; } } return max_idx; } static int ad714x_cal_abs_pos(struct ad714x_chip *ad714x, int start_stage, int end_stage, int highest_stage, int max_coord) { int a_param, b_param; if (highest_stage == start_stage) { a_param = ad714x->sensor_val[start_stage + 1]; b_param = ad714x->sensor_val[start_stage] + ad714x->sensor_val[start_stage + 1]; } else if (highest_stage == end_stage) { a_param = ad714x->sensor_val[end_stage] * (end_stage - start_stage) + ad714x->sensor_val[end_stage - 1] * (end_stage - start_stage - 1); b_param = ad714x->sensor_val[end_stage] + ad714x->sensor_val[end_stage - 1]; } else { a_param = ad714x->sensor_val[highest_stage] * (highest_stage - start_stage) + ad714x->sensor_val[highest_stage - 1] * (highest_stage - start_stage - 1) + ad714x->sensor_val[highest_stage + 1] * (highest_stage - start_stage + 1); b_param = ad714x->sensor_val[highest_stage] + ad714x->sensor_val[highest_stage - 1] + ad714x->sensor_val[highest_stage + 1]; } return (max_coord / (end_stage - start_stage)) * a_param / b_param; } /* * One button can connect to multi positive and negative of CDCs * Multi-buttons can connect to same positive/negative of one CDC */ static void ad714x_button_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_button_plat *hw = &ad714x->hw->button[idx]; struct ad714x_button_drv *sw = &ad714x->sw->button[idx]; switch (sw->state) { case IDLE: if (((ad714x->h_state & hw->h_mask) == hw->h_mask) && ((ad714x->l_state & hw->l_mask) == hw->l_mask)) { dev_dbg(ad714x->dev, "button %d touched\n", idx); input_report_key(sw->input, hw->keycode, 1); input_sync(sw->input); sw->state = ACTIVE; } break; case ACTIVE: if (((ad714x->h_state & hw->h_mask) != hw->h_mask) || ((ad714x->l_state & hw->l_mask) != hw->l_mask)) { dev_dbg(ad714x->dev, "button %d released\n", idx); input_report_key(sw->input, hw->keycode, 0); input_sync(sw->input); sw->state = IDLE; } break; default: break; } } /* * The response of a sensor is defined by the absolute number of codes * between the current CDC value and the ambient value. */ static void ad714x_slider_cal_sensor_val(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; int i; ad714x->read(ad714x, CDC_RESULT_S0 + hw->start_stage, &ad714x->adc_reg[hw->start_stage], hw->end_stage - hw->start_stage + 1); for (i = hw->start_stage; i <= hw->end_stage; i++) { ad714x->read(ad714x, STAGE0_AMBIENT + i * PER_STAGE_REG_NUM, &ad714x->amb_reg[i], 1); ad714x->sensor_val[i] = abs(ad714x->adc_reg[i] - ad714x->amb_reg[i]); } } static void ad714x_slider_cal_highest_stage(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; sw->highest_stage = ad714x_cal_highest_stage(ad714x, hw->start_stage, hw->end_stage); dev_dbg(ad714x->dev, "slider %d highest_stage:%d\n", idx, sw->highest_stage); } /* * The formulae are very straight forward. It uses the sensor with the * highest response and the 2 adjacent ones. * When Sensor 0 has the highest response, only sensor 0 and sensor 1 * are used in the calculations. Similarly when the last sensor has the * highest response, only the last sensor and the second last sensors * are used in the calculations. * * For i= idx_of_peak_Sensor-1 to i= idx_of_peak_Sensor+1 * v += Sensor response(i)*i * w += Sensor response(i) * POS=(Number_of_Positions_Wanted/(Number_of_Sensors_Used-1)) *(v/w) */ static void ad714x_slider_cal_abs_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; sw->abs_pos = ad714x_cal_abs_pos(ad714x, hw->start_stage, hw->end_stage, sw->highest_stage, hw->max_coord); dev_dbg(ad714x->dev, "slider %d absolute position:%d\n", idx, sw->abs_pos); } /* * To minimise the Impact of the noise on the algorithm, ADI developed a * routine that filters the CDC results after they have been read by the * host processor. * The filter used is an Infinite Input Response(IIR) filter implemented * in firmware and attenuates the noise on the CDC results after they've * been read by the host processor. * Filtered_CDC_result = (Filtered_CDC_result * (10 - Coefficient) + * Latest_CDC_result * Coefficient)/10 */ static void ad714x_slider_cal_flt_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; sw->flt_pos = (sw->flt_pos * (10 - 4) + sw->abs_pos * 4)/10; dev_dbg(ad714x->dev, "slider %d filter position:%d\n", idx, sw->flt_pos); } static void ad714x_slider_use_com_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; ad714x_use_com_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_slider_use_thr_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; ad714x_use_thr_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_slider_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; unsigned short h_state, c_state; unsigned short mask; mask = ((1 << (hw->end_stage + 1)) - 1) - ((1 << hw->start_stage) - 1); h_state = ad714x->h_state & mask; c_state = ad714x->c_state & mask; switch (sw->state) { case IDLE: if (h_state) { sw->state = JITTER; /* In End of Conversion interrupt mode, the AD714X * continuously generates hardware interrupts. */ ad714x_slider_use_com_int(ad714x, idx); dev_dbg(ad714x->dev, "slider %d touched\n", idx); } break; case JITTER: if (c_state == mask) { ad714x_slider_cal_sensor_val(ad714x, idx); ad714x_slider_cal_highest_stage(ad714x, idx); ad714x_slider_cal_abs_pos(ad714x, idx); sw->flt_pos = sw->abs_pos; sw->state = ACTIVE; } break; case ACTIVE: if (c_state == mask) { if (h_state) { ad714x_slider_cal_sensor_val(ad714x, idx); ad714x_slider_cal_highest_stage(ad714x, idx); ad714x_slider_cal_abs_pos(ad714x, idx); ad714x_slider_cal_flt_pos(ad714x, idx); input_report_abs(sw->input, ABS_X, sw->flt_pos); input_report_key(sw->input, BTN_TOUCH, 1); } else { /* When the user lifts off the sensor, configure * the AD714X back to threshold interrupt mode. */ ad714x_slider_use_thr_int(ad714x, idx); sw->state = IDLE; input_report_key(sw->input, BTN_TOUCH, 0); dev_dbg(ad714x->dev, "slider %d released\n", idx); } input_sync(sw->input); } break; default: break; } } /* * When the scroll wheel is activated, we compute the absolute position based * on the sensor values. To calculate the position, we first determine the * sensor that has the greatest response among the 8 sensors that constitutes * the scrollwheel. Then we determined the 2 sensors on either sides of the * sensor with the highest response and we apply weights to these sensors. */ static void ad714x_wheel_cal_highest_stage(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; sw->pre_highest_stage = sw->highest_stage; sw->highest_stage = ad714x_cal_highest_stage(ad714x, hw->start_stage, hw->end_stage); dev_dbg(ad714x->dev, "wheel %d highest_stage:%d\n", idx, sw->highest_stage); } static void ad714x_wheel_cal_sensor_val(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; int i; ad714x->read(ad714x, CDC_RESULT_S0 + hw->start_stage, &ad714x->adc_reg[hw->start_stage], hw->end_stage - hw->start_stage + 1); for (i = hw->start_stage; i <= hw->end_stage; i++) { ad714x->read(ad714x, STAGE0_AMBIENT + i * PER_STAGE_REG_NUM, &ad714x->amb_reg[i], 1); if (ad714x->adc_reg[i] > ad714x->amb_reg[i]) ad714x->sensor_val[i] = ad714x->adc_reg[i] - ad714x->amb_reg[i]; else ad714x->sensor_val[i] = 0; } } /* * When the scroll wheel is activated, we compute the absolute position based * on the sensor values. To calculate the position, we first determine the * sensor that has the greatest response among the sensors that constitutes * the scrollwheel. Then we determined the sensors on either sides of the * sensor with the highest response and we apply weights to these sensors. The * result of this computation gives us the mean value. */ static void ad714x_wheel_cal_abs_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; int stage_num = hw->end_stage - hw->start_stage + 1; int first_before, highest, first_after; int a_param, b_param; first_before = (sw->highest_stage + stage_num - 1) % stage_num; highest = sw->highest_stage; first_after = (sw->highest_stage + stage_num + 1) % stage_num; a_param = ad714x->sensor_val[highest] * (highest - hw->start_stage) + ad714x->sensor_val[first_before] * (highest - hw->start_stage - 1) + ad714x->sensor_val[first_after] * (highest - hw->start_stage + 1); b_param = ad714x->sensor_val[highest] + ad714x->sensor_val[first_before] + ad714x->sensor_val[first_after]; sw->abs_pos = ((hw->max_coord / (hw->end_stage - hw->start_stage)) * a_param) / b_param; if (sw->abs_pos > hw->max_coord) sw->abs_pos = hw->max_coord; else if (sw->abs_pos < 0) sw->abs_pos = 0; } static void ad714x_wheel_cal_flt_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; if (((sw->pre_highest_stage == hw->end_stage) && (sw->highest_stage == hw->start_stage)) || ((sw->pre_highest_stage == hw->start_stage) && (sw->highest_stage == hw->end_stage))) sw->flt_pos = sw->abs_pos; else sw->flt_pos = ((sw->flt_pos * 30) + (sw->abs_pos * 71)) / 100; if (sw->flt_pos > hw->max_coord) sw->flt_pos = hw->max_coord; } static void ad714x_wheel_use_com_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; ad714x_use_com_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_wheel_use_thr_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; ad714x_use_thr_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_wheel_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; unsigned short h_state, c_state; unsigned short mask; mask = ((1 << (hw->end_stage + 1)) - 1) - ((1 << hw->start_stage) - 1); h_state = ad714x->h_state & mask; c_state = ad714x->c_state & mask; switch (sw->state) { case IDLE: if (h_state) { sw->state = JITTER; /* In End of Conversion interrupt mode, the AD714X * continuously generates hardware interrupts. */ ad714x_wheel_use_com_int(ad714x, idx); dev_dbg(ad714x->dev, "wheel %d touched\n", idx); } break; case JITTER: if (c_state == mask) { ad714x_wheel_cal_sensor_val(ad714x, idx); ad714x_wheel_cal_highest_stage(ad714x, idx); ad714x_wheel_cal_abs_pos(ad714x, idx); sw->flt_pos = sw->abs_pos; sw->state = ACTIVE; } break; case ACTIVE: if (c_state == mask) { if (h_state) { ad714x_wheel_cal_sensor_val(ad714x, idx); ad714x_wheel_cal_highest_stage(ad714x, idx); ad714x_wheel_cal_abs_pos(ad714x, idx); ad714x_wheel_cal_flt_pos(ad714x, idx); input_report_abs(sw->input, ABS_WHEEL, sw->flt_pos); input_report_key(sw->input, BTN_TOUCH, 1); } else { /* When the user lifts off the sensor, configure * the AD714X back to threshold interrupt mode. */ ad714x_wheel_use_thr_int(ad714x, idx); sw->state = IDLE; input_report_key(sw->input, BTN_TOUCH, 0); dev_dbg(ad714x->dev, "wheel %d released\n", idx); } input_sync(sw->input); } break; default: break; } } static void touchpad_cal_sensor_val(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; int i; ad714x->read(ad714x, CDC_RESULT_S0 + hw->x_start_stage, &ad714x->adc_reg[hw->x_start_stage], hw->x_end_stage - hw->x_start_stage + 1); for (i = hw->x_start_stage; i <= hw->x_end_stage; i++) { ad714x->read(ad714x, STAGE0_AMBIENT + i * PER_STAGE_REG_NUM, &ad714x->amb_reg[i], 1); if (ad714x->adc_reg[i] > ad714x->amb_reg[i]) ad714x->sensor_val[i] = ad714x->adc_reg[i] - ad714x->amb_reg[i]; else ad714x->sensor_val[i] = 0; } } static void touchpad_cal_highest_stage(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; sw->x_highest_stage = ad714x_cal_highest_stage(ad714x, hw->x_start_stage, hw->x_end_stage); sw->y_highest_stage = ad714x_cal_highest_stage(ad714x, hw->y_start_stage, hw->y_end_stage); dev_dbg(ad714x->dev, "touchpad %d x_highest_stage:%d, y_highest_stage:%d\n", idx, sw->x_highest_stage, sw->y_highest_stage); } /* * If 2 fingers are touching the sensor then 2 peaks can be observed in the * distribution. * The arithmetic doesn't support to get absolute coordinates for multi-touch * yet. */ static int touchpad_check_second_peak(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; int i; for (i = hw->x_start_stage; i < sw->x_highest_stage; i++) { if ((ad714x->sensor_val[i] - ad714x->sensor_val[i + 1]) > (ad714x->sensor_val[i + 1] / 10)) return 1; } for (i = sw->x_highest_stage; i < hw->x_end_stage; i++) { if ((ad714x->sensor_val[i + 1] - ad714x->sensor_val[i]) > (ad714x->sensor_val[i] / 10)) return 1; } for (i = hw->y_start_stage; i < sw->y_highest_stage; i++) { if ((ad714x->sensor_val[i] - ad714x->sensor_val[i + 1]) > (ad714x->sensor_val[i + 1] / 10)) return 1; } for (i = sw->y_highest_stage; i < hw->y_end_stage; i++) { if ((ad714x->sensor_val[i + 1] - ad714x->sensor_val[i]) > (ad714x->sensor_val[i] / 10)) return 1; } return 0; } /* * If only one finger is used to activate the touch pad then only 1 peak will be * registered in the distribution. This peak and the 2 adjacent sensors will be * used in the calculation of the absolute position. This will prevent hand * shadows to affect the absolute position calculation. */ static void touchpad_cal_abs_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; sw->x_abs_pos = ad714x_cal_abs_pos(ad714x, hw->x_start_stage, hw->x_end_stage, sw->x_highest_stage, hw->x_max_coord); sw->y_abs_pos = ad714x_cal_abs_pos(ad714x, hw->y_start_stage, hw->y_end_stage, sw->y_highest_stage, hw->y_max_coord); dev_dbg(ad714x->dev, "touchpad %d absolute position:(%d, %d)\n", idx, sw->x_abs_pos, sw->y_abs_pos); } static void touchpad_cal_flt_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; sw->x_flt_pos = (sw->x_flt_pos * (10 - 4) + sw->x_abs_pos * 4)/10; sw->y_flt_pos = (sw->y_flt_pos * (10 - 4) + sw->y_abs_pos * 4)/10; dev_dbg(ad714x->dev, "touchpad %d filter position:(%d, %d)\n", idx, sw->x_flt_pos, sw->y_flt_pos); } /* * To prevent distortion from showing in the absolute position, it is * necessary to detect the end points. When endpoints are detected, the * driver stops updating the status variables with absolute positions. * End points are detected on the 4 edges of the touchpad sensor. The * method to detect them is the same for all 4. * To detect the end points, the firmware computes the difference in * percent between the sensor on the edge and the adjacent one. The * difference is calculated in percent in order to make the end point * detection independent of the pressure. */ #define LEFT_END_POINT_DETECTION_LEVEL 550 #define RIGHT_END_POINT_DETECTION_LEVEL 750 #define LEFT_RIGHT_END_POINT_DEAVTIVALION_LEVEL 850 #define TOP_END_POINT_DETECTION_LEVEL 550 #define BOTTOM_END_POINT_DETECTION_LEVEL 950 #define TOP_BOTTOM_END_POINT_DEAVTIVALION_LEVEL 700 static int touchpad_check_endpoint(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; int percent_sensor_diff; /* left endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->x_start_stage] - ad714x->sensor_val[hw->x_start_stage + 1]) * 100 / ad714x->sensor_val[hw->x_start_stage + 1]; if (!sw->left_ep) { if (percent_sensor_diff >= LEFT_END_POINT_DETECTION_LEVEL) { sw->left_ep = 1; sw->left_ep_val = ad714x->sensor_val[hw->x_start_stage + 1]; } } else { if ((percent_sensor_diff < LEFT_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->x_start_stage + 1] > LEFT_RIGHT_END_POINT_DEAVTIVALION_LEVEL + sw->left_ep_val)) sw->left_ep = 0; } /* right endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->x_end_stage] - ad714x->sensor_val[hw->x_end_stage - 1]) * 100 / ad714x->sensor_val[hw->x_end_stage - 1]; if (!sw->right_ep) { if (percent_sensor_diff >= RIGHT_END_POINT_DETECTION_LEVEL) { sw->right_ep = 1; sw->right_ep_val = ad714x->sensor_val[hw->x_end_stage - 1]; } } else { if ((percent_sensor_diff < RIGHT_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->x_end_stage - 1] > LEFT_RIGHT_END_POINT_DEAVTIVALION_LEVEL + sw->right_ep_val)) sw->right_ep = 0; } /* top endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->y_start_stage] - ad714x->sensor_val[hw->y_start_stage + 1]) * 100 / ad714x->sensor_val[hw->y_start_stage + 1]; if (!sw->top_ep) { if (percent_sensor_diff >= TOP_END_POINT_DETECTION_LEVEL) { sw->top_ep = 1; sw->top_ep_val = ad714x->sensor_val[hw->y_start_stage + 1]; } } else { if ((percent_sensor_diff < TOP_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->y_start_stage + 1] > TOP_BOTTOM_END_POINT_DEAVTIVALION_LEVEL + sw->top_ep_val)) sw->top_ep = 0; } /* bottom endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->y_end_stage] - ad714x->sensor_val[hw->y_end_stage - 1]) * 100 / ad714x->sensor_val[hw->y_end_stage - 1]; if (!sw->bottom_ep) { if (percent_sensor_diff >= BOTTOM_END_POINT_DETECTION_LEVEL) { sw->bottom_ep = 1; sw->bottom_ep_val = ad714x->sensor_val[hw->y_end_stage - 1]; } } else { if ((percent_sensor_diff < BOTTOM_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->y_end_stage - 1] > TOP_BOTTOM_END_POINT_DEAVTIVALION_LEVEL + sw->bottom_ep_val)) sw->bottom_ep = 0; } return sw->left_ep || sw->right_ep || sw->top_ep || sw->bottom_ep; } static void touchpad_use_com_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; ad714x_use_com_int(ad714x, hw->x_start_stage, hw->x_end_stage); } static void touchpad_use_thr_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; ad714x_use_thr_int(ad714x, hw->x_start_stage, hw->x_end_stage); ad714x_use_thr_int(ad714x, hw->y_start_stage, hw->y_end_stage); } static void ad714x_touchpad_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; unsigned short h_state, c_state; unsigned short mask; mask = (((1 << (hw->x_end_stage + 1)) - 1) - ((1 << hw->x_start_stage) - 1)) + (((1 << (hw->y_end_stage + 1)) - 1) - ((1 << hw->y_start_stage) - 1)); h_state = ad714x->h_state & mask; c_state = ad714x->c_state & mask; switch (sw->state) { case IDLE: if (h_state) { sw->state = JITTER; /* In End of Conversion interrupt mode, the AD714X * continuously generates hardware interrupts. */ touchpad_use_com_int(ad714x, idx); dev_dbg(ad714x->dev, "touchpad %d touched\n", idx); } break; case JITTER: if (c_state == mask) { touchpad_cal_sensor_val(ad714x, idx); touchpad_cal_highest_stage(ad714x, idx); if ((!touchpad_check_second_peak(ad714x, idx)) && (!touchpad_check_endpoint(ad714x, idx))) { dev_dbg(ad714x->dev, "touchpad%d, 2 fingers or endpoint\n", idx); touchpad_cal_abs_pos(ad714x, idx); sw->x_flt_pos = sw->x_abs_pos; sw->y_flt_pos = sw->y_abs_pos; sw->state = ACTIVE; } } break; case ACTIVE: if (c_state == mask) { if (h_state) { touchpad_cal_sensor_val(ad714x, idx); touchpad_cal_highest_stage(ad714x, idx); if ((!touchpad_check_second_peak(ad714x, idx)) && (!touchpad_check_endpoint(ad714x, idx))) { touchpad_cal_abs_pos(ad714x, idx); touchpad_cal_flt_pos(ad714x, idx); input_report_abs(sw->input, ABS_X, sw->x_flt_pos); input_report_abs(sw->input, ABS_Y, sw->y_flt_pos); input_report_key(sw->input, BTN_TOUCH, 1); } } else { /* When the user lifts off the sensor, configure * the AD714X back to threshold interrupt mode. */ touchpad_use_thr_int(ad714x, idx); sw->state = IDLE; input_report_key(sw->input, BTN_TOUCH, 0); dev_dbg(ad714x->dev, "touchpad %d released\n", idx); } input_sync(sw->input); } break; default: break; } } static int ad714x_hw_detect(struct ad714x_chip *ad714x) { unsigned short data; ad714x->read(ad714x, AD714X_PARTID_REG, &data, 1); switch (data & 0xFFF0) { case AD7142_PARTID: ad714x->product = 0x7142; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7142 captouch, rev:%d\n", ad714x->version); return 0; case AD7143_PARTID: ad714x->product = 0x7143; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7143 captouch, rev:%d\n", ad714x->version); return 0; case AD7147_PARTID: ad714x->product = 0x7147; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7147(A) captouch, rev:%d\n", ad714x->version); return 0; case AD7148_PARTID: ad714x->product = 0x7148; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7148 captouch, rev:%d\n", ad714x->version); return 0; default: dev_err(ad714x->dev, "fail to detect AD714X captouch, read ID is %04x\n", data); return -ENODEV; } } static void ad714x_hw_init(struct ad714x_chip *ad714x) { int i, j; unsigned short reg_base; unsigned short data; /* configuration CDC and interrupts */ for (i = 0; i < STAGE_NUM; i++) { reg_base = AD714X_STAGECFG_REG + i * STAGE_CFGREG_NUM; for (j = 0; j < STAGE_CFGREG_NUM; j++) ad714x->write(ad714x, reg_base + j, ad714x->hw->stage_cfg_reg[i][j]); } for (i = 0; i < SYS_CFGREG_NUM; i++) ad714x->write(ad714x, AD714X_SYSCFG_REG + i, ad714x->hw->sys_cfg_reg[i]); for (i = 0; i < SYS_CFGREG_NUM; i++) ad714x->read(ad714x, AD714X_SYSCFG_REG + i, &data, 1); ad714x->write(ad714x, AD714X_STG_CAL_EN_REG, 0xFFF); /* clear all interrupts */ ad714x->read(ad714x, STG_LOW_INT_STA_REG, &ad714x->l_state, 3); } static irqreturn_t ad714x_interrupt_thread(int irq, void *data) { struct ad714x_chip *ad714x = data; int i; mutex_lock(&ad714x->mutex); ad714x->read(ad714x, STG_LOW_INT_STA_REG, &ad714x->l_state, 3); for (i = 0; i < ad714x->hw->button_num; i++) ad714x_button_state_machine(ad714x, i); for (i = 0; i < ad714x->hw->slider_num; i++) ad714x_slider_state_machine(ad714x, i); for (i = 0; i < ad714x->hw->wheel_num; i++) ad714x_wheel_state_machine(ad714x, i); for (i = 0; i < ad714x->hw->touchpad_num; i++) ad714x_touchpad_state_machine(ad714x, i); mutex_unlock(&ad714x->mutex); return IRQ_HANDLED; } #define MAX_DEVICE_NUM 8 struct ad714x_chip *ad714x_probe(struct device *dev, u16 bus_type, int irq, ad714x_read_t read, ad714x_write_t write) { int i, alloc_idx; int error; struct input_dev *input[MAX_DEVICE_NUM]; struct ad714x_platform_data *plat_data = dev->platform_data; struct ad714x_chip *ad714x; void *drv_mem; struct ad714x_button_drv *bt_drv; struct ad714x_slider_drv *sd_drv; struct ad714x_wheel_drv *wl_drv; struct ad714x_touchpad_drv *tp_drv; if (irq <= 0) { dev_err(dev, "IRQ not configured!\n"); error = -EINVAL; goto err_out; } if (dev->platform_data == NULL) { dev_err(dev, "platform data for ad714x doesn't exist\n"); error = -EINVAL; goto err_out; } ad714x = kzalloc(sizeof(*ad714x) + sizeof(*ad714x->sw) + sizeof(*sd_drv) * plat_data->slider_num + sizeof(*wl_drv) * plat_data->wheel_num + sizeof(*tp_drv) * plat_data->touchpad_num + sizeof(*bt_drv) * plat_data->button_num, GFP_KERNEL); if (!ad714x) { error = -ENOMEM; goto err_out; } ad714x->hw = plat_data; drv_mem = ad714x + 1; ad714x->sw = drv_mem; drv_mem += sizeof(*ad714x->sw); ad714x->sw->slider = sd_drv = drv_mem; drv_mem += sizeof(*sd_drv) * ad714x->hw->slider_num; ad714x->sw->wheel = wl_drv = drv_mem; drv_mem += sizeof(*wl_drv) * ad714x->hw->wheel_num; ad714x->sw->touchpad = tp_drv = drv_mem; drv_mem += sizeof(*tp_drv) * ad714x->hw->touchpad_num; ad714x->sw->button = bt_drv = drv_mem; drv_mem += sizeof(*bt_drv) * ad714x->hw->button_num; ad714x->read = read; ad714x->write = write; ad714x->irq = irq; ad714x->dev = dev; error = ad714x_hw_detect(ad714x); if (error) goto err_free_mem; /* initialize and request sw/hw resources */ ad714x_hw_init(ad714x); mutex_init(&ad714x->mutex); /* * Allocate and register AD714X input device */ alloc_idx = 0; /* a slider uses one input_dev instance */ if (ad714x->hw->slider_num > 0) { struct ad714x_slider_plat *sd_plat = ad714x->hw->slider; for (i = 0; i < ad714x->hw->slider_num; i++) { sd_drv[i].input = input[alloc_idx] = input_allocate_device(); if (!input[alloc_idx]) { error = -ENOMEM; goto err_free_dev; } __set_bit(EV_ABS, input[alloc_idx]->evbit); __set_bit(EV_KEY, input[alloc_idx]->evbit); __set_bit(ABS_X, input[alloc_idx]->absbit); __set_bit(BTN_TOUCH, input[alloc_idx]->keybit); input_set_abs_params(input[alloc_idx], ABS_X, 0, sd_plat->max_coord, 0, 0); input[alloc_idx]->id.bustype = bus_type; input[alloc_idx]->id.product = ad714x->product; input[alloc_idx]->id.version = ad714x->version; input[alloc_idx]->name = "ad714x_captouch_slider"; input[alloc_idx]->dev.parent = dev; error = input_register_device(input[alloc_idx]); if (error) goto err_free_dev; alloc_idx++; } } /* a wheel uses one input_dev instance */ if (ad714x->hw->wheel_num > 0) { struct ad714x_wheel_plat *wl_plat = ad714x->hw->wheel; for (i = 0; i < ad714x->hw->wheel_num; i++) { wl_drv[i].input = input[alloc_idx] = input_allocate_device(); if (!input[alloc_idx]) { error = -ENOMEM; goto err_free_dev; } __set_bit(EV_KEY, input[alloc_idx]->evbit); __set_bit(EV_ABS, input[alloc_idx]->evbit); __set_bit(ABS_WHEEL, input[alloc_idx]->absbit); __set_bit(BTN_TOUCH, input[alloc_idx]->keybit); input_set_abs_params(input[alloc_idx], ABS_WHEEL, 0, wl_plat->max_coord, 0, 0); input[alloc_idx]->id.bustype = bus_type; input[alloc_idx]->id.product = ad714x->product; input[alloc_idx]->id.version = ad714x->version; input[alloc_idx]->name = "ad714x_captouch_wheel"; input[alloc_idx]->dev.parent = dev; error = input_register_device(input[alloc_idx]); if (error) goto err_free_dev; alloc_idx++; } } /* a touchpad uses one input_dev instance */ if (ad714x->hw->touchpad_num > 0) { struct ad714x_touchpad_plat *tp_plat = ad714x->hw->touchpad; for (i = 0; i < ad714x->hw->touchpad_num; i++) { tp_drv[i].input = input[alloc_idx] = input_allocate_device(); if (!input[alloc_idx]) { error = -ENOMEM; goto err_free_dev; } __set_bit(EV_ABS, input[alloc_idx]->evbit); __set_bit(EV_KEY, input[alloc_idx]->evbit); __set_bit(ABS_X, input[alloc_idx]->absbit); __set_bit(ABS_Y, input[alloc_idx]->absbit); __set_bit(BTN_TOUCH, input[alloc_idx]->keybit); input_set_abs_params(input[alloc_idx], ABS_X, 0, tp_plat->x_max_coord, 0, 0); input_set_abs_params(input[alloc_idx], ABS_Y, 0, tp_plat->y_max_coord, 0, 0); input[alloc_idx]->id.bustype = bus_type; input[alloc_idx]->id.product = ad714x->product; input[alloc_idx]->id.version = ad714x->version; input[alloc_idx]->name = "ad714x_captouch_pad"; input[alloc_idx]->dev.parent = dev; error = input_register_device(input[alloc_idx]); if (error) goto err_free_dev; alloc_idx++; } } /* all buttons use one input node */ if (ad714x->hw->button_num > 0) { struct ad714x_button_plat *bt_plat = ad714x->hw->button; input[alloc_idx] = input_allocate_device(); if (!input[alloc_idx]) { error = -ENOMEM; goto err_free_dev; } __set_bit(EV_KEY, input[alloc_idx]->evbit); for (i = 0; i < ad714x->hw->button_num; i++) { bt_drv[i].input = input[alloc_idx]; __set_bit(bt_plat[i].keycode, input[alloc_idx]->keybit); } input[alloc_idx]->id.bustype = bus_type; input[alloc_idx]->id.product = ad714x->product; input[alloc_idx]->id.version = ad714x->version; input[alloc_idx]->name = "ad714x_captouch_button"; input[alloc_idx]->dev.parent = dev; error = input_register_device(input[alloc_idx]); if (error) goto err_free_dev; alloc_idx++; } error = request_threaded_irq(ad714x->irq, NULL, ad714x_interrupt_thread, plat_data->irqflags ? plat_data->irqflags : IRQF_TRIGGER_FALLING, "ad714x_captouch", ad714x); if (error) { dev_err(dev, "can't allocate irq %d\n", ad714x->irq); goto err_unreg_dev; } return ad714x; err_free_dev: dev_err(dev, "failed to setup AD714x input device %i\n", alloc_idx); input_free_device(input[alloc_idx]); err_unreg_dev: while (--alloc_idx >= 0) input_unregister_device(input[alloc_idx]); err_free_mem: kfree(ad714x); err_out: return ERR_PTR(error); } EXPORT_SYMBOL(ad714x_probe); void ad714x_remove(struct ad714x_chip *ad714x) { struct ad714x_platform_data *hw = ad714x->hw; struct ad714x_driver_data *sw = ad714x->sw; int i; free_irq(ad714x->irq, ad714x); /* unregister and free all input devices */ for (i = 0; i < hw->slider_num; i++) input_unregister_device(sw->slider[i].input); for (i = 0; i < hw->wheel_num; i++) input_unregister_device(sw->wheel[i].input); for (i = 0; i < hw->touchpad_num; i++) input_unregister_device(sw->touchpad[i].input); if (hw->button_num) input_unregister_device(sw->button[0].input); kfree(ad714x); } EXPORT_SYMBOL(ad714x_remove); #ifdef CONFIG_PM int ad714x_disable(struct ad714x_chip *ad714x) { unsigned short data; dev_dbg(ad714x->dev, "%s enter\n", __func__); mutex_lock(&ad714x->mutex); data = ad714x->hw->sys_cfg_reg[AD714X_PWR_CTRL] | 0x3; ad714x->write(ad714x, AD714X_PWR_CTRL, data); mutex_unlock(&ad714x->mutex); return 0; } EXPORT_SYMBOL(ad714x_disable); int ad714x_enable(struct ad714x_chip *ad714x) { dev_dbg(ad714x->dev, "%s enter\n", __func__); mutex_lock(&ad714x->mutex); /* resume to non-shutdown mode */ ad714x->write(ad714x, AD714X_PWR_CTRL, ad714x->hw->sys_cfg_reg[AD714X_PWR_CTRL]); /* make sure the interrupt output line is not low level after resume, * otherwise we will get no chance to enter falling-edge irq again */ ad714x->read(ad714x, STG_LOW_INT_STA_REG, &ad714x->l_state, 3); mutex_unlock(&ad714x->mutex); return 0; } EXPORT_SYMBOL(ad714x_enable); #endif MODULE_DESCRIPTION("Analog Devices AD714X Capacitance Touch Sensor Driver"); MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>"); MODULE_LICENSE("GPL");
gpl-2.0
thehelios/pm-linux-3.8.y
drivers/isdn/hardware/eicon/divasproc.c
5066
10556
/* $Id: divasproc.c,v 1.19.4.3 2005/01/31 12:22:20 armin Exp $ * * Low level driver for Eicon DIVA Server ISDN cards. * /proc functions * * Copyright 2000-2003 by Armin Schindler (mac@melware.de) * Copyright 2000-2003 Cytronics & Melware (info@melware.de) * * 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/kernel.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/list.h> #include <asm/uaccess.h> #include "platform.h" #include "debuglib.h" #undef ID_MASK #undef N_DATA #include "pc.h" #include "di_defs.h" #include "divasync.h" #include "di.h" #include "io.h" #include "xdi_msg.h" #include "xdi_adapter.h" #include "diva.h" #include "diva_pci.h" extern PISDN_ADAPTER IoAdapters[MAX_ADAPTER]; extern void divas_get_version(char *); extern void diva_get_vserial_number(PISDN_ADAPTER IoAdapter, char *buf); /********************************************************* ** Functions for /proc interface / File operations *********************************************************/ static char *divas_proc_name = "divas"; static char *adapter_dir_name = "adapter"; static char *info_proc_name = "info"; static char *grp_opt_proc_name = "group_optimization"; static char *d_l1_down_proc_name = "dynamic_l1_down"; /* ** "divas" entry */ extern struct proc_dir_entry *proc_net_eicon; static struct proc_dir_entry *divas_proc_entry = NULL; static ssize_t divas_read(struct file *file, char __user *buf, size_t count, loff_t *off) { int len = 0; int cadapter; char tmpbuf[80]; char tmpser[16]; if (*off) return 0; divas_get_version(tmpbuf); if (copy_to_user(buf + len, &tmpbuf, strlen(tmpbuf))) return -EFAULT; len += strlen(tmpbuf); for (cadapter = 0; cadapter < MAX_ADAPTER; cadapter++) { if (IoAdapters[cadapter]) { diva_get_vserial_number(IoAdapters[cadapter], tmpser); sprintf(tmpbuf, "%2d: %-30s Serial:%-10s IRQ:%2d\n", cadapter + 1, IoAdapters[cadapter]->Properties.Name, tmpser, IoAdapters[cadapter]->irq_info.irq_nr); if ((strlen(tmpbuf) + len) > count) break; if (copy_to_user (buf + len, &tmpbuf, strlen(tmpbuf))) return -EFAULT; len += strlen(tmpbuf); } } *off += len; return (len); } static ssize_t divas_write(struct file *file, const char __user *buf, size_t count, loff_t *off) { return (-ENODEV); } static unsigned int divas_poll(struct file *file, poll_table *wait) { return (POLLERR); } static int divas_open(struct inode *inode, struct file *file) { return nonseekable_open(inode, file); } static int divas_close(struct inode *inode, struct file *file) { return (0); } static const struct file_operations divas_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read = divas_read, .write = divas_write, .poll = divas_poll, .open = divas_open, .release = divas_close }; int create_divas_proc(void) { divas_proc_entry = proc_create(divas_proc_name, S_IFREG | S_IRUGO, proc_net_eicon, &divas_fops); if (!divas_proc_entry) return (0); return (1); } void remove_divas_proc(void) { if (divas_proc_entry) { remove_proc_entry(divas_proc_name, proc_net_eicon); divas_proc_entry = NULL; } } static ssize_t grp_opt_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { diva_os_xdi_adapter_t *a = PDE(file->f_path.dentry->d_inode)->data; PISDN_ADAPTER IoAdapter = IoAdapters[a->controller - 1]; if ((count == 1) || (count == 2)) { char c; if (get_user(c, buffer)) return -EFAULT; switch (c) { case '0': IoAdapter->capi_cfg.cfg_1 &= ~DIVA_XDI_CAPI_CFG_1_GROUP_POPTIMIZATION_ON; break; case '1': IoAdapter->capi_cfg.cfg_1 |= DIVA_XDI_CAPI_CFG_1_GROUP_POPTIMIZATION_ON; break; default: return (-EINVAL); } return (count); } return (-EINVAL); } static ssize_t d_l1_down_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { diva_os_xdi_adapter_t *a = PDE(file->f_path.dentry->d_inode)->data; PISDN_ADAPTER IoAdapter = IoAdapters[a->controller - 1]; if ((count == 1) || (count == 2)) { char c; if (get_user(c, buffer)) return -EFAULT; switch (c) { case '0': IoAdapter->capi_cfg.cfg_1 &= ~DIVA_XDI_CAPI_CFG_1_DYNAMIC_L1_ON; break; case '1': IoAdapter->capi_cfg.cfg_1 |= DIVA_XDI_CAPI_CFG_1_DYNAMIC_L1_ON; break; default: return (-EINVAL); } return (count); } return (-EINVAL); } static int d_l1_down_proc_show(struct seq_file *m, void *v) { diva_os_xdi_adapter_t *a = m->private; PISDN_ADAPTER IoAdapter = IoAdapters[a->controller - 1]; seq_printf(m, "%s\n", (IoAdapter->capi_cfg. cfg_1 & DIVA_XDI_CAPI_CFG_1_DYNAMIC_L1_ON) ? "1" : "0"); return 0; } static int d_l1_down_proc_open(struct inode *inode, struct file *file) { return single_open(file, d_l1_down_proc_show, PDE(inode)->data); } static const struct file_operations d_l1_down_proc_fops = { .owner = THIS_MODULE, .open = d_l1_down_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = d_l1_down_proc_write, }; static int grp_opt_proc_show(struct seq_file *m, void *v) { diva_os_xdi_adapter_t *a = m->private; PISDN_ADAPTER IoAdapter = IoAdapters[a->controller - 1]; seq_printf(m, "%s\n", (IoAdapter->capi_cfg. cfg_1 & DIVA_XDI_CAPI_CFG_1_GROUP_POPTIMIZATION_ON) ? "1" : "0"); return 0; } static int grp_opt_proc_open(struct inode *inode, struct file *file) { return single_open(file, grp_opt_proc_show, PDE(inode)->data); } static const struct file_operations grp_opt_proc_fops = { .owner = THIS_MODULE, .open = grp_opt_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = grp_opt_proc_write, }; static ssize_t info_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { diva_os_xdi_adapter_t *a = PDE(file->f_path.dentry->d_inode)->data; PISDN_ADAPTER IoAdapter = IoAdapters[a->controller - 1]; char c[4]; if (count <= 4) return -EINVAL; if (copy_from_user(c, buffer, 4)) return -EFAULT; /* this is for test purposes only */ if (!memcmp(c, "trap", 4)) { (*(IoAdapter->os_trap_nfy_Fnc)) (IoAdapter, IoAdapter->ANum); return (count); } return (-EINVAL); } static int info_proc_show(struct seq_file *m, void *v) { int i = 0; char *p; char tmpser[16]; diva_os_xdi_adapter_t *a = m->private; PISDN_ADAPTER IoAdapter = IoAdapters[a->controller - 1]; seq_printf(m, "Name : %s\n", IoAdapter->Properties.Name); seq_printf(m, "DSP state : %08x\n", a->dsp_mask); seq_printf(m, "Channels : %02d\n", IoAdapter->Properties.Channels); seq_printf(m, "E. max/used : %03d/%03d\n", IoAdapter->e_max, IoAdapter->e_count); diva_get_vserial_number(IoAdapter, tmpser); seq_printf(m, "Serial : %s\n", tmpser); seq_printf(m, "IRQ : %d\n", IoAdapter->irq_info.irq_nr); seq_printf(m, "CardIndex : %d\n", a->CardIndex); seq_printf(m, "CardOrdinal : %d\n", a->CardOrdinal); seq_printf(m, "Controller : %d\n", a->controller); seq_printf(m, "Bus-Type : %s\n", (a->Bus == DIVAS_XDI_ADAPTER_BUS_ISA) ? "ISA" : "PCI"); seq_printf(m, "Port-Name : %s\n", a->port_name); if (a->Bus == DIVAS_XDI_ADAPTER_BUS_PCI) { seq_printf(m, "PCI-bus : %d\n", a->resources.pci.bus); seq_printf(m, "PCI-func : %d\n", a->resources.pci.func); for (i = 0; i < 8; i++) { if (a->resources.pci.bar[i]) { seq_printf(m, "Mem / I/O %d : 0x%x / mapped : 0x%lx", i, a->resources.pci.bar[i], (unsigned long) a->resources. pci.addr[i]); if (a->resources.pci.length[i]) { seq_printf(m, " / length : %d", a->resources.pci. length[i]); } seq_putc(m, '\n'); } } } if ((!a->xdi_adapter.port) && ((!a->xdi_adapter.ram) || (!a->xdi_adapter.reset) || (!a->xdi_adapter.cfg))) { if (!IoAdapter->irq_info.irq_nr) { p = "slave"; } else { p = "out of service"; } } else if (a->xdi_adapter.trapped) { p = "trapped"; } else if (a->xdi_adapter.Initialized) { p = "active"; } else { p = "ready"; } seq_printf(m, "State : %s\n", p); return 0; } static int info_proc_open(struct inode *inode, struct file *file) { return single_open(file, info_proc_show, PDE(inode)->data); } static const struct file_operations info_proc_fops = { .owner = THIS_MODULE, .open = info_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = info_proc_write, }; /* ** adapter proc init/de-init */ /* -------------------------------------------------------------------------- Create adapter directory and files in proc file system -------------------------------------------------------------------------- */ int create_adapter_proc(diva_os_xdi_adapter_t *a) { struct proc_dir_entry *de, *pe; char tmp[16]; sprintf(tmp, "%s%d", adapter_dir_name, a->controller); if (!(de = proc_mkdir(tmp, proc_net_eicon))) return (0); a->proc_adapter_dir = (void *) de; pe = proc_create_data(info_proc_name, S_IRUGO | S_IWUSR, de, &info_proc_fops, a); if (!pe) return (0); a->proc_info = (void *) pe; pe = proc_create_data(grp_opt_proc_name, S_IRUGO | S_IWUSR, de, &grp_opt_proc_fops, a); if (pe) a->proc_grp_opt = (void *) pe; pe = proc_create_data(d_l1_down_proc_name, S_IRUGO | S_IWUSR, de, &d_l1_down_proc_fops, a); if (pe) a->proc_d_l1_down = (void *) pe; DBG_TRC(("proc entry %s created", tmp)); return (1); } /* -------------------------------------------------------------------------- Remove adapter directory and files in proc file system -------------------------------------------------------------------------- */ void remove_adapter_proc(diva_os_xdi_adapter_t *a) { char tmp[16]; if (a->proc_adapter_dir) { if (a->proc_d_l1_down) { remove_proc_entry(d_l1_down_proc_name, (struct proc_dir_entry *) a->proc_adapter_dir); } if (a->proc_grp_opt) { remove_proc_entry(grp_opt_proc_name, (struct proc_dir_entry *) a->proc_adapter_dir); } if (a->proc_info) { remove_proc_entry(info_proc_name, (struct proc_dir_entry *) a->proc_adapter_dir); } sprintf(tmp, "%s%d", adapter_dir_name, a->controller); remove_proc_entry(tmp, proc_net_eicon); DBG_TRC(("proc entry %s%d removed", adapter_dir_name, a->controller)); } }
gpl-2.0
arokux/linux
drivers/media/pci/zoran/zr36050.c
13002
27029
/* * Zoran ZR36050 basic configuration functions * * Copyright (C) 2001 Wolfgang Scherr <scherr@net4you.at> * * $Id: zr36050.c,v 1.1.2.11 2003/08/03 14:54:53 rbultje Exp $ * * ------------------------------------------------------------------------ * * 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 ZR050_VERSION "v0.7.1" #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/types.h> #include <linux/wait.h> /* I/O commands, error codes */ #include <asm/io.h> /* headerfile of this module */ #include "zr36050.h" /* codec io API */ #include "videocodec.h" /* it doesn't make sense to have more than 20 or so, just to prevent some unwanted loops */ #define MAX_CODECS 20 /* amount of chips attached via this driver */ static int zr36050_codecs; /* debugging is available via module parameter */ static int debug; module_param(debug, int, 0); MODULE_PARM_DESC(debug, "Debug level (0-4)"); #define dprintk(num, format, args...) \ do { \ if (debug >= num) \ printk(format, ##args); \ } while (0) /* ========================================================================= Local hardware I/O functions: read/write via codec layer (registers are located in the master device) ========================================================================= */ /* read and write functions */ static u8 zr36050_read (struct zr36050 *ptr, u16 reg) { u8 value = 0; // just in case something is wrong... if (ptr->codec->master_data->readreg) value = (ptr->codec->master_data->readreg(ptr->codec, reg)) & 0xFF; else dprintk(1, KERN_ERR "%s: invalid I/O setup, nothing read!\n", ptr->name); dprintk(4, "%s: reading from 0x%04x: %02x\n", ptr->name, reg, value); return value; } static void zr36050_write (struct zr36050 *ptr, u16 reg, u8 value) { dprintk(4, "%s: writing 0x%02x to 0x%04x\n", ptr->name, value, reg); // just in case something is wrong... if (ptr->codec->master_data->writereg) ptr->codec->master_data->writereg(ptr->codec, reg, value); else dprintk(1, KERN_ERR "%s: invalid I/O setup, nothing written!\n", ptr->name); } /* ========================================================================= Local helper function: status read ========================================================================= */ /* status is kept in datastructure */ static u8 zr36050_read_status1 (struct zr36050 *ptr) { ptr->status1 = zr36050_read(ptr, ZR050_STATUS_1); zr36050_read(ptr, 0); return ptr->status1; } /* ========================================================================= Local helper function: scale factor read ========================================================================= */ /* scale factor is kept in datastructure */ static u16 zr36050_read_scalefactor (struct zr36050 *ptr) { ptr->scalefact = (zr36050_read(ptr, ZR050_SF_HI) << 8) | (zr36050_read(ptr, ZR050_SF_LO) & 0xFF); /* leave 0 selected for an eventually GO from master */ zr36050_read(ptr, 0); return ptr->scalefact; } /* ========================================================================= Local helper function: wait if codec is ready to proceed (end of processing) or time is over ========================================================================= */ static void zr36050_wait_end (struct zr36050 *ptr) { int i = 0; while (!(zr36050_read_status1(ptr) & 0x4)) { udelay(1); if (i++ > 200000) { // 200ms, there is for sure something wrong!!! dprintk(1, "%s: timeout at wait_end (last status: 0x%02x)\n", ptr->name, ptr->status1); break; } } } /* ========================================================================= Local helper function: basic test of "connectivity", writes/reads to/from memory the SOF marker ========================================================================= */ static int zr36050_basic_test (struct zr36050 *ptr) { zr36050_write(ptr, ZR050_SOF_IDX, 0x00); zr36050_write(ptr, ZR050_SOF_IDX + 1, 0x00); if ((zr36050_read(ptr, ZR050_SOF_IDX) | zr36050_read(ptr, ZR050_SOF_IDX + 1)) != 0x0000) { dprintk(1, KERN_ERR "%s: attach failed, can't connect to jpeg processor!\n", ptr->name); return -ENXIO; } zr36050_write(ptr, ZR050_SOF_IDX, 0xff); zr36050_write(ptr, ZR050_SOF_IDX + 1, 0xc0); if (((zr36050_read(ptr, ZR050_SOF_IDX) << 8) | zr36050_read(ptr, ZR050_SOF_IDX + 1)) != 0xffc0) { dprintk(1, KERN_ERR "%s: attach failed, can't connect to jpeg processor!\n", ptr->name); return -ENXIO; } zr36050_wait_end(ptr); if ((ptr->status1 & 0x4) == 0) { dprintk(1, KERN_ERR "%s: attach failed, jpeg processor failed (end flag)!\n", ptr->name); return -EBUSY; } return 0; /* looks good! */ } /* ========================================================================= Local helper function: simple loop for pushing the init datasets ========================================================================= */ static int zr36050_pushit (struct zr36050 *ptr, u16 startreg, u16 len, const char *data) { int i = 0; dprintk(4, "%s: write data block to 0x%04x (len=%d)\n", ptr->name, startreg, len); while (i < len) { zr36050_write(ptr, startreg++, data[i++]); } return i; } /* ========================================================================= Basic datasets: jpeg baseline setup data (you find it on lots places in internet, or just extract it from any regular .jpg image...) Could be variable, but until it's not needed it they are just fixed to save memory. Otherwise expand zr36050 structure with arrays, push the values to it and initialize from there, as e.g. the linux zr36057/60 driver does it. ========================================================================= */ static const char zr36050_dqt[0x86] = { 0xff, 0xdb, //Marker: DQT 0x00, 0x84, //Length: 2*65+2 0x00, //Pq,Tq first table 0x10, 0x0b, 0x0c, 0x0e, 0x0c, 0x0a, 0x10, 0x0e, 0x0d, 0x0e, 0x12, 0x11, 0x10, 0x13, 0x18, 0x28, 0x1a, 0x18, 0x16, 0x16, 0x18, 0x31, 0x23, 0x25, 0x1d, 0x28, 0x3a, 0x33, 0x3d, 0x3c, 0x39, 0x33, 0x38, 0x37, 0x40, 0x48, 0x5c, 0x4e, 0x40, 0x44, 0x57, 0x45, 0x37, 0x38, 0x50, 0x6d, 0x51, 0x57, 0x5f, 0x62, 0x67, 0x68, 0x67, 0x3e, 0x4d, 0x71, 0x79, 0x70, 0x64, 0x78, 0x5c, 0x65, 0x67, 0x63, 0x01, //Pq,Tq second table 0x11, 0x12, 0x12, 0x18, 0x15, 0x18, 0x2f, 0x1a, 0x1a, 0x2f, 0x63, 0x42, 0x38, 0x42, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63 }; static const char zr36050_dht[0x1a4] = { 0xff, 0xc4, //Marker: DHT 0x01, 0xa2, //Length: 2*AC, 2*DC 0x00, //DC first table 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x01, //DC second table 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x10, //AC first table 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0x11, //AC second table 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA }; /* jpeg baseline setup, this is just fixed in this driver (YUV pictures) */ #define NO_OF_COMPONENTS 0x3 //Y,U,V #define BASELINE_PRECISION 0x8 //MCU size (?) static const char zr36050_tq[8] = { 0, 1, 1, 0, 0, 0, 0, 0 }; //table idx's QT static const char zr36050_td[8] = { 0, 1, 1, 0, 0, 0, 0, 0 }; //table idx's DC static const char zr36050_ta[8] = { 0, 1, 1, 0, 0, 0, 0, 0 }; //table idx's AC /* horizontal 422 decimation setup (maybe we support 411 or so later, too) */ static const char zr36050_decimation_h[8] = { 2, 1, 1, 0, 0, 0, 0, 0 }; static const char zr36050_decimation_v[8] = { 1, 1, 1, 0, 0, 0, 0, 0 }; /* ========================================================================= Local helper functions: calculation and setup of parameter-dependent JPEG baseline segments (needed for compression only) ========================================================================= */ /* ------------------------------------------------------------------------- */ /* SOF (start of frame) segment depends on width, height and sampling ratio of each color component */ static int zr36050_set_sof (struct zr36050 *ptr) { char sof_data[34]; // max. size of register set int i; dprintk(3, "%s: write SOF (%dx%d, %d components)\n", ptr->name, ptr->width, ptr->height, NO_OF_COMPONENTS); sof_data[0] = 0xff; sof_data[1] = 0xc0; sof_data[2] = 0x00; sof_data[3] = (3 * NO_OF_COMPONENTS) + 8; sof_data[4] = BASELINE_PRECISION; // only '8' possible with zr36050 sof_data[5] = (ptr->height) >> 8; sof_data[6] = (ptr->height) & 0xff; sof_data[7] = (ptr->width) >> 8; sof_data[8] = (ptr->width) & 0xff; sof_data[9] = NO_OF_COMPONENTS; for (i = 0; i < NO_OF_COMPONENTS; i++) { sof_data[10 + (i * 3)] = i; // index identifier sof_data[11 + (i * 3)] = (ptr->h_samp_ratio[i] << 4) | (ptr->v_samp_ratio[i]); // sampling ratios sof_data[12 + (i * 3)] = zr36050_tq[i]; // Q table selection } return zr36050_pushit(ptr, ZR050_SOF_IDX, (3 * NO_OF_COMPONENTS) + 10, sof_data); } /* ------------------------------------------------------------------------- */ /* SOS (start of scan) segment depends on the used scan components of each color component */ static int zr36050_set_sos (struct zr36050 *ptr) { char sos_data[16]; // max. size of register set int i; dprintk(3, "%s: write SOS\n", ptr->name); sos_data[0] = 0xff; sos_data[1] = 0xda; sos_data[2] = 0x00; sos_data[3] = 2 + 1 + (2 * NO_OF_COMPONENTS) + 3; sos_data[4] = NO_OF_COMPONENTS; for (i = 0; i < NO_OF_COMPONENTS; i++) { sos_data[5 + (i * 2)] = i; // index sos_data[6 + (i * 2)] = (zr36050_td[i] << 4) | zr36050_ta[i]; // AC/DC tbl.sel. } sos_data[2 + 1 + (2 * NO_OF_COMPONENTS) + 2] = 00; // scan start sos_data[2 + 1 + (2 * NO_OF_COMPONENTS) + 3] = 0x3F; sos_data[2 + 1 + (2 * NO_OF_COMPONENTS) + 4] = 00; return zr36050_pushit(ptr, ZR050_SOS1_IDX, 4 + 1 + (2 * NO_OF_COMPONENTS) + 3, sos_data); } /* ------------------------------------------------------------------------- */ /* DRI (define restart interval) */ static int zr36050_set_dri (struct zr36050 *ptr) { char dri_data[6]; // max. size of register set dprintk(3, "%s: write DRI\n", ptr->name); dri_data[0] = 0xff; dri_data[1] = 0xdd; dri_data[2] = 0x00; dri_data[3] = 0x04; dri_data[4] = ptr->dri >> 8; dri_data[5] = ptr->dri & 0xff; return zr36050_pushit(ptr, ZR050_DRI_IDX, 6, dri_data); } /* ========================================================================= Setup function: Setup compression/decompression of Zoran's JPEG processor ( see also zoran 36050 manual ) ... sorry for the spaghetti code ... ========================================================================= */ static void zr36050_init (struct zr36050 *ptr) { int sum = 0; long bitcnt, tmp; if (ptr->mode == CODEC_DO_COMPRESSION) { dprintk(2, "%s: COMPRESSION SETUP\n", ptr->name); /* 050 communicates with 057 in master mode */ zr36050_write(ptr, ZR050_HARDWARE, ZR050_HW_MSTR); /* encoding table preload for compression */ zr36050_write(ptr, ZR050_MODE, ZR050_MO_COMP | ZR050_MO_TLM); zr36050_write(ptr, ZR050_OPTIONS, 0); /* disable all IRQs */ zr36050_write(ptr, ZR050_INT_REQ_0, 0); zr36050_write(ptr, ZR050_INT_REQ_1, 3); // low 2 bits always 1 /* volume control settings */ /*zr36050_write(ptr, ZR050_MBCV, ptr->max_block_vol);*/ zr36050_write(ptr, ZR050_SF_HI, ptr->scalefact >> 8); zr36050_write(ptr, ZR050_SF_LO, ptr->scalefact & 0xff); zr36050_write(ptr, ZR050_AF_HI, 0xff); zr36050_write(ptr, ZR050_AF_M, 0xff); zr36050_write(ptr, ZR050_AF_LO, 0xff); /* setup the variable jpeg tables */ sum += zr36050_set_sof(ptr); sum += zr36050_set_sos(ptr); sum += zr36050_set_dri(ptr); /* setup the fixed jpeg tables - maybe variable, though - * (see table init section above) */ dprintk(3, "%s: write DQT, DHT, APP\n", ptr->name); sum += zr36050_pushit(ptr, ZR050_DQT_IDX, sizeof(zr36050_dqt), zr36050_dqt); sum += zr36050_pushit(ptr, ZR050_DHT_IDX, sizeof(zr36050_dht), zr36050_dht); zr36050_write(ptr, ZR050_APP_IDX, 0xff); zr36050_write(ptr, ZR050_APP_IDX + 1, 0xe0 + ptr->app.appn); zr36050_write(ptr, ZR050_APP_IDX + 2, 0x00); zr36050_write(ptr, ZR050_APP_IDX + 3, ptr->app.len + 2); sum += zr36050_pushit(ptr, ZR050_APP_IDX + 4, 60, ptr->app.data) + 4; zr36050_write(ptr, ZR050_COM_IDX, 0xff); zr36050_write(ptr, ZR050_COM_IDX + 1, 0xfe); zr36050_write(ptr, ZR050_COM_IDX + 2, 0x00); zr36050_write(ptr, ZR050_COM_IDX + 3, ptr->com.len + 2); sum += zr36050_pushit(ptr, ZR050_COM_IDX + 4, 60, ptr->com.data) + 4; /* do the internal huffman table preload */ zr36050_write(ptr, ZR050_MARKERS_EN, ZR050_ME_DHTI); zr36050_write(ptr, ZR050_GO, 1); // launch codec zr36050_wait_end(ptr); dprintk(2, "%s: Status after table preload: 0x%02x\n", ptr->name, ptr->status1); if ((ptr->status1 & 0x4) == 0) { dprintk(1, KERN_ERR "%s: init aborted!\n", ptr->name); return; // something is wrong, its timed out!!!! } /* setup misc. data for compression (target code sizes) */ /* size of compressed code to reach without header data */ sum = ptr->real_code_vol - sum; bitcnt = sum << 3; /* need the size in bits */ tmp = bitcnt >> 16; dprintk(3, "%s: code: csize=%d, tot=%d, bit=%ld, highbits=%ld\n", ptr->name, sum, ptr->real_code_vol, bitcnt, tmp); zr36050_write(ptr, ZR050_TCV_NET_HI, tmp >> 8); zr36050_write(ptr, ZR050_TCV_NET_MH, tmp & 0xff); tmp = bitcnt & 0xffff; zr36050_write(ptr, ZR050_TCV_NET_ML, tmp >> 8); zr36050_write(ptr, ZR050_TCV_NET_LO, tmp & 0xff); bitcnt -= bitcnt >> 7; // bits without stuffing bitcnt -= ((bitcnt * 5) >> 6); // bits without eob tmp = bitcnt >> 16; dprintk(3, "%s: code: nettobit=%ld, highnettobits=%ld\n", ptr->name, bitcnt, tmp); zr36050_write(ptr, ZR050_TCV_DATA_HI, tmp >> 8); zr36050_write(ptr, ZR050_TCV_DATA_MH, tmp & 0xff); tmp = bitcnt & 0xffff; zr36050_write(ptr, ZR050_TCV_DATA_ML, tmp >> 8); zr36050_write(ptr, ZR050_TCV_DATA_LO, tmp & 0xff); /* compression setup with or without bitrate control */ zr36050_write(ptr, ZR050_MODE, ZR050_MO_COMP | ZR050_MO_PASS2 | (ptr->bitrate_ctrl ? ZR050_MO_BRC : 0)); /* this headers seem to deliver "valid AVI" jpeg frames */ zr36050_write(ptr, ZR050_MARKERS_EN, ZR050_ME_DQT | ZR050_ME_DHT | ((ptr->app.len > 0) ? ZR050_ME_APP : 0) | ((ptr->com.len > 0) ? ZR050_ME_COM : 0)); } else { dprintk(2, "%s: EXPANSION SETUP\n", ptr->name); /* 050 communicates with 055 in master mode */ zr36050_write(ptr, ZR050_HARDWARE, ZR050_HW_MSTR | ZR050_HW_CFIS_2_CLK); /* encoding table preload */ zr36050_write(ptr, ZR050_MODE, ZR050_MO_TLM); /* disable all IRQs */ zr36050_write(ptr, ZR050_INT_REQ_0, 0); zr36050_write(ptr, ZR050_INT_REQ_1, 3); // low 2 bits always 1 dprintk(3, "%s: write DHT\n", ptr->name); zr36050_pushit(ptr, ZR050_DHT_IDX, sizeof(zr36050_dht), zr36050_dht); /* do the internal huffman table preload */ zr36050_write(ptr, ZR050_MARKERS_EN, ZR050_ME_DHTI); zr36050_write(ptr, ZR050_GO, 1); // launch codec zr36050_wait_end(ptr); dprintk(2, "%s: Status after table preload: 0x%02x\n", ptr->name, ptr->status1); if ((ptr->status1 & 0x4) == 0) { dprintk(1, KERN_ERR "%s: init aborted!\n", ptr->name); return; // something is wrong, its timed out!!!! } /* setup misc. data for expansion */ zr36050_write(ptr, ZR050_MODE, 0); zr36050_write(ptr, ZR050_MARKERS_EN, 0); } /* adr on selected, to allow GO from master */ zr36050_read(ptr, 0); } /* ========================================================================= CODEC API FUNCTIONS this functions are accessed by the master via the API structure ========================================================================= */ /* set compression/expansion mode and launches codec - this should be the last call from the master before starting processing */ static int zr36050_set_mode (struct videocodec *codec, int mode) { struct zr36050 *ptr = (struct zr36050 *) codec->data; dprintk(2, "%s: set_mode %d call\n", ptr->name, mode); if ((mode != CODEC_DO_EXPANSION) && (mode != CODEC_DO_COMPRESSION)) return -EINVAL; ptr->mode = mode; zr36050_init(ptr); return 0; } /* set picture size (norm is ignored as the codec doesn't know about it) */ static int zr36050_set_video (struct videocodec *codec, struct tvnorm *norm, struct vfe_settings *cap, struct vfe_polarity *pol) { struct zr36050 *ptr = (struct zr36050 *) codec->data; int size; dprintk(2, "%s: set_video %d.%d, %d/%d-%dx%d (0x%x) q%d call\n", ptr->name, norm->HStart, norm->VStart, cap->x, cap->y, cap->width, cap->height, cap->decimation, cap->quality); /* if () return -EINVAL; * trust the master driver that it knows what it does - so * we allow invalid startx/y and norm for now ... */ ptr->width = cap->width / (cap->decimation & 0xff); ptr->height = cap->height / ((cap->decimation >> 8) & 0xff); /* (KM) JPEG quality */ size = ptr->width * ptr->height; size *= 16; /* size in bits */ /* apply quality setting */ size = size * cap->quality / 200; /* Minimum: 1kb */ if (size < 8192) size = 8192; /* Maximum: 7/8 of code buffer */ if (size > ptr->total_code_vol * 7) size = ptr->total_code_vol * 7; ptr->real_code_vol = size >> 3; /* in bytes */ /* Set max_block_vol here (previously in zr36050_init, moved * here for consistency with zr36060 code */ zr36050_write(ptr, ZR050_MBCV, ptr->max_block_vol); return 0; } /* additional control functions */ static int zr36050_control (struct videocodec *codec, int type, int size, void *data) { struct zr36050 *ptr = (struct zr36050 *) codec->data; int *ival = (int *) data; dprintk(2, "%s: control %d call with %d byte\n", ptr->name, type, size); switch (type) { case CODEC_G_STATUS: /* get last status */ if (size != sizeof(int)) return -EFAULT; zr36050_read_status1(ptr); *ival = ptr->status1; break; case CODEC_G_CODEC_MODE: if (size != sizeof(int)) return -EFAULT; *ival = CODEC_MODE_BJPG; break; case CODEC_S_CODEC_MODE: if (size != sizeof(int)) return -EFAULT; if (*ival != CODEC_MODE_BJPG) return -EINVAL; /* not needed, do nothing */ return 0; case CODEC_G_VFE: case CODEC_S_VFE: /* not needed, do nothing */ return 0; case CODEC_S_MMAP: /* not available, give an error */ return -ENXIO; case CODEC_G_JPEG_TDS_BYTE: /* get target volume in byte */ if (size != sizeof(int)) return -EFAULT; *ival = ptr->total_code_vol; break; case CODEC_S_JPEG_TDS_BYTE: /* get target volume in byte */ if (size != sizeof(int)) return -EFAULT; ptr->total_code_vol = *ival; /* (Kieran Morrissey) * code copied from zr36060.c to ensure proper bitrate */ ptr->real_code_vol = (ptr->total_code_vol * 6) >> 3; break; case CODEC_G_JPEG_SCALE: /* get scaling factor */ if (size != sizeof(int)) return -EFAULT; *ival = zr36050_read_scalefactor(ptr); break; case CODEC_S_JPEG_SCALE: /* set scaling factor */ if (size != sizeof(int)) return -EFAULT; ptr->scalefact = *ival; break; case CODEC_G_JPEG_APP_DATA: { /* get appn marker data */ struct jpeg_app_marker *app = data; if (size != sizeof(struct jpeg_app_marker)) return -EFAULT; *app = ptr->app; break; } case CODEC_S_JPEG_APP_DATA: { /* set appn marker data */ struct jpeg_app_marker *app = data; if (size != sizeof(struct jpeg_app_marker)) return -EFAULT; ptr->app = *app; break; } case CODEC_G_JPEG_COM_DATA: { /* get comment marker data */ struct jpeg_com_marker *com = data; if (size != sizeof(struct jpeg_com_marker)) return -EFAULT; *com = ptr->com; break; } case CODEC_S_JPEG_COM_DATA: { /* set comment marker data */ struct jpeg_com_marker *com = data; if (size != sizeof(struct jpeg_com_marker)) return -EFAULT; ptr->com = *com; break; } default: return -EINVAL; } return size; } /* ========================================================================= Exit and unregister function: Deinitializes Zoran's JPEG processor ========================================================================= */ static int zr36050_unset (struct videocodec *codec) { struct zr36050 *ptr = codec->data; if (ptr) { /* do wee need some codec deinit here, too ???? */ dprintk(1, "%s: finished codec #%d\n", ptr->name, ptr->num); kfree(ptr); codec->data = NULL; zr36050_codecs--; return 0; } return -EFAULT; } /* ========================================================================= Setup and registry function: Initializes Zoran's JPEG processor Also sets pixel size, average code size, mode (compr./decompr.) (the given size is determined by the processor with the video interface) ========================================================================= */ static int zr36050_setup (struct videocodec *codec) { struct zr36050 *ptr; int res; dprintk(2, "zr36050: initializing MJPEG subsystem #%d.\n", zr36050_codecs); if (zr36050_codecs == MAX_CODECS) { dprintk(1, KERN_ERR "zr36050: Can't attach more codecs!\n"); return -ENOSPC; } //mem structure init codec->data = ptr = kzalloc(sizeof(struct zr36050), GFP_KERNEL); if (NULL == ptr) { dprintk(1, KERN_ERR "zr36050: Can't get enough memory!\n"); return -ENOMEM; } snprintf(ptr->name, sizeof(ptr->name), "zr36050[%d]", zr36050_codecs); ptr->num = zr36050_codecs++; ptr->codec = codec; //testing res = zr36050_basic_test(ptr); if (res < 0) { zr36050_unset(codec); return res; } //final setup memcpy(ptr->h_samp_ratio, zr36050_decimation_h, 8); memcpy(ptr->v_samp_ratio, zr36050_decimation_v, 8); ptr->bitrate_ctrl = 0; /* 0 or 1 - fixed file size flag * (what is the difference?) */ ptr->mode = CODEC_DO_COMPRESSION; ptr->width = 384; ptr->height = 288; ptr->total_code_vol = 16000; ptr->max_block_vol = 240; ptr->scalefact = 0x100; ptr->dri = 1; /* no app/com marker by default */ ptr->app.appn = 0; ptr->app.len = 0; ptr->com.len = 0; zr36050_init(ptr); dprintk(1, KERN_INFO "%s: codec attached and running\n", ptr->name); return 0; } static const struct videocodec zr36050_codec = { .owner = THIS_MODULE, .name = "zr36050", .magic = 0L, // magic not used .flags = CODEC_FLAG_JPEG | CODEC_FLAG_HARDWARE | CODEC_FLAG_ENCODER | CODEC_FLAG_DECODER, .type = CODEC_TYPE_ZR36050, .setup = zr36050_setup, // functionality .unset = zr36050_unset, .set_mode = zr36050_set_mode, .set_video = zr36050_set_video, .control = zr36050_control, // others are not used }; /* ========================================================================= HOOK IN DRIVER AS KERNEL MODULE ========================================================================= */ static int __init zr36050_init_module (void) { //dprintk(1, "ZR36050 driver %s\n",ZR050_VERSION); zr36050_codecs = 0; return videocodec_register(&zr36050_codec); } static void __exit zr36050_cleanup_module (void) { if (zr36050_codecs) { dprintk(1, "zr36050: something's wrong - %d codecs left somehow.\n", zr36050_codecs); } videocodec_unregister(&zr36050_codec); } module_init(zr36050_init_module); module_exit(zr36050_cleanup_module); MODULE_AUTHOR("Wolfgang Scherr <scherr@net4you.at>"); MODULE_DESCRIPTION("Driver module for ZR36050 jpeg processors " ZR050_VERSION); MODULE_LICENSE("GPL");
gpl-2.0
lyapota/n7_port2edge
drivers/md/persistent-data/dm-btree-spine.c
1227
5258
/* * Copyright (C) 2011 Red Hat, Inc. * * This file is released under the GPL. */ #include "dm-btree-internal.h" #include "dm-transaction-manager.h" #include <linux/device-mapper.h> #define DM_MSG_PREFIX "btree spine" /*----------------------------------------------------------------*/ #define BTREE_CSUM_XOR 121107 static int node_check(struct dm_block_validator *v, struct dm_block *b, size_t block_size); static void node_prepare_for_write(struct dm_block_validator *v, struct dm_block *b, size_t block_size) { struct btree_node *n = dm_block_data(b); struct node_header *h = &n->header; h->blocknr = cpu_to_le64(dm_block_location(b)); h->csum = cpu_to_le32(dm_bm_checksum(&h->flags, block_size - sizeof(__le32), BTREE_CSUM_XOR)); BUG_ON(node_check(v, b, 4096)); } static int node_check(struct dm_block_validator *v, struct dm_block *b, size_t block_size) { struct btree_node *n = dm_block_data(b); struct node_header *h = &n->header; size_t value_size; __le32 csum_disk; uint32_t flags; if (dm_block_location(b) != le64_to_cpu(h->blocknr)) { DMERR_LIMIT("node_check failed: blocknr %llu != wanted %llu", le64_to_cpu(h->blocknr), dm_block_location(b)); return -ENOTBLK; } csum_disk = cpu_to_le32(dm_bm_checksum(&h->flags, block_size - sizeof(__le32), BTREE_CSUM_XOR)); if (csum_disk != h->csum) { DMERR_LIMIT("node_check failed: csum %u != wanted %u", le32_to_cpu(csum_disk), le32_to_cpu(h->csum)); return -EILSEQ; } value_size = le32_to_cpu(h->value_size); if (sizeof(struct node_header) + (sizeof(__le64) + value_size) * le32_to_cpu(h->max_entries) > block_size) { DMERR_LIMIT("node_check failed: max_entries too large"); return -EILSEQ; } if (le32_to_cpu(h->nr_entries) > le32_to_cpu(h->max_entries)) { DMERR_LIMIT("node_check failed: too many entries"); return -EILSEQ; } /* * The node must be either INTERNAL or LEAF. */ flags = le32_to_cpu(h->flags); if (!(flags & INTERNAL_NODE) && !(flags & LEAF_NODE)) { DMERR_LIMIT("node_check failed: node is neither INTERNAL or LEAF"); return -EILSEQ; } return 0; } struct dm_block_validator btree_node_validator = { .name = "btree_node", .prepare_for_write = node_prepare_for_write, .check = node_check }; /*----------------------------------------------------------------*/ int bn_read_lock(struct dm_btree_info *info, dm_block_t b, struct dm_block **result) { return dm_tm_read_lock(info->tm, b, &btree_node_validator, result); } static int bn_shadow(struct dm_btree_info *info, dm_block_t orig, struct dm_btree_value_type *vt, struct dm_block **result) { int r, inc; r = dm_tm_shadow_block(info->tm, orig, &btree_node_validator, result, &inc); if (!r && inc) inc_children(info->tm, dm_block_data(*result), vt); return r; } int new_block(struct dm_btree_info *info, struct dm_block **result) { return dm_tm_new_block(info->tm, &btree_node_validator, result); } int unlock_block(struct dm_btree_info *info, struct dm_block *b) { return dm_tm_unlock(info->tm, b); } /*----------------------------------------------------------------*/ void init_ro_spine(struct ro_spine *s, struct dm_btree_info *info) { s->info = info; s->count = 0; s->nodes[0] = NULL; s->nodes[1] = NULL; } int exit_ro_spine(struct ro_spine *s) { int r = 0, i; for (i = 0; i < s->count; i++) { int r2 = unlock_block(s->info, s->nodes[i]); if (r2 < 0) r = r2; } return r; } int ro_step(struct ro_spine *s, dm_block_t new_child) { int r; if (s->count == 2) { r = unlock_block(s->info, s->nodes[0]); if (r < 0) return r; s->nodes[0] = s->nodes[1]; s->count--; } r = bn_read_lock(s->info, new_child, s->nodes + s->count); if (!r) s->count++; return r; } void ro_pop(struct ro_spine *s) { BUG_ON(!s->count); --s->count; unlock_block(s->info, s->nodes[s->count]); } struct btree_node *ro_node(struct ro_spine *s) { struct dm_block *block; BUG_ON(!s->count); block = s->nodes[s->count - 1]; return dm_block_data(block); } /*----------------------------------------------------------------*/ void init_shadow_spine(struct shadow_spine *s, struct dm_btree_info *info) { s->info = info; s->count = 0; } int exit_shadow_spine(struct shadow_spine *s) { int r = 0, i; for (i = 0; i < s->count; i++) { int r2 = unlock_block(s->info, s->nodes[i]); if (r2 < 0) r = r2; } return r; } int shadow_step(struct shadow_spine *s, dm_block_t b, struct dm_btree_value_type *vt) { int r; if (s->count == 2) { r = unlock_block(s->info, s->nodes[0]); if (r < 0) return r; s->nodes[0] = s->nodes[1]; s->count--; } r = bn_shadow(s->info, b, vt, s->nodes + s->count); if (!r) { if (!s->count) s->root = dm_block_location(s->nodes[0]); s->count++; } return r; } struct dm_block *shadow_current(struct shadow_spine *s) { BUG_ON(!s->count); return s->nodes[s->count - 1]; } struct dm_block *shadow_parent(struct shadow_spine *s) { BUG_ON(s->count != 2); return s->count == 2 ? s->nodes[0] : NULL; } int shadow_has_parent(struct shadow_spine *s) { return s->count >= 2; } int shadow_root(struct shadow_spine *s) { return s->root; }
gpl-2.0
CMNookTablet/acclaim_kernel
block/deadline-iosched.c
1483
11700
/* * Deadline i/o scheduler. * * Copyright (C) 2002 Jens Axboe <axboe@kernel.dk> */ #include <linux/kernel.h> #include <linux/fs.h> #include <linux/blkdev.h> #include <linux/elevator.h> #include <linux/bio.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/compiler.h> #include <linux/rbtree.h> /* * See Documentation/block/deadline-iosched.txt */ static const int read_expire = HZ / 2; /* max time before a read is submitted. */ static const int write_expire = 5 * HZ; /* ditto for writes, these limits are SOFT! */ static const int writes_starved = 2; /* max times reads can starve a write */ static const int fifo_batch = 16; /* # of sequential requests treated as one by the above parameters. For throughput. */ struct deadline_data { /* * run time data */ /* * requests (deadline_rq s) are present on both sort_list and fifo_list */ struct rb_root sort_list[2]; struct list_head fifo_list[2]; /* * next in sort order. read, write or both are NULL */ struct request *next_rq[2]; unsigned int batching; /* number of sequential requests made */ sector_t last_sector; /* head position */ unsigned int starved; /* times reads have starved writes */ /* * settings that change how the i/o scheduler behaves */ int fifo_expire[2]; int fifo_batch; int writes_starved; int front_merges; }; static void deadline_move_request(struct deadline_data *, struct request *); static inline struct rb_root * deadline_rb_root(struct deadline_data *dd, struct request *rq) { return &dd->sort_list[rq_data_dir(rq)]; } /* * get the request after `rq' in sector-sorted order */ static inline struct request * deadline_latter_request(struct request *rq) { struct rb_node *node = rb_next(&rq->rb_node); if (node) return rb_entry_rq(node); return NULL; } static void deadline_add_rq_rb(struct deadline_data *dd, struct request *rq) { struct rb_root *root = deadline_rb_root(dd, rq); struct request *__alias; while (unlikely(__alias = elv_rb_add(root, rq))) deadline_move_request(dd, __alias); } static inline void deadline_del_rq_rb(struct deadline_data *dd, struct request *rq) { const int data_dir = rq_data_dir(rq); if (dd->next_rq[data_dir] == rq) dd->next_rq[data_dir] = deadline_latter_request(rq); elv_rb_del(deadline_rb_root(dd, rq), rq); } /* * add rq to rbtree and fifo */ static void deadline_add_request(struct request_queue *q, struct request *rq) { struct deadline_data *dd = q->elevator->elevator_data; const int data_dir = rq_data_dir(rq); deadline_add_rq_rb(dd, rq); /* * set expire time and add to fifo list */ rq_set_fifo_time(rq, jiffies + dd->fifo_expire[data_dir]); list_add_tail(&rq->queuelist, &dd->fifo_list[data_dir]); } /* * remove rq from rbtree and fifo. */ static void deadline_remove_request(struct request_queue *q, struct request *rq) { struct deadline_data *dd = q->elevator->elevator_data; rq_fifo_clear(rq); deadline_del_rq_rb(dd, rq); } static int deadline_merge(struct request_queue *q, struct request **req, struct bio *bio) { struct deadline_data *dd = q->elevator->elevator_data; struct request *__rq; int ret; /* * check for front merge */ if (dd->front_merges) { sector_t sector = bio->bi_sector + bio_sectors(bio); __rq = elv_rb_find(&dd->sort_list[bio_data_dir(bio)], sector); if (__rq) { BUG_ON(sector != blk_rq_pos(__rq)); if (elv_rq_merge_ok(__rq, bio)) { ret = ELEVATOR_FRONT_MERGE; goto out; } } } return ELEVATOR_NO_MERGE; out: *req = __rq; return ret; } static void deadline_merged_request(struct request_queue *q, struct request *req, int type) { struct deadline_data *dd = q->elevator->elevator_data; /* * if the merge was a front merge, we need to reposition request */ if (type == ELEVATOR_FRONT_MERGE) { elv_rb_del(deadline_rb_root(dd, req), req); deadline_add_rq_rb(dd, req); } } static void deadline_merged_requests(struct request_queue *q, struct request *req, struct request *next) { /* * if next expires before rq, assign its expire time to rq * and move into next position (next will be deleted) in fifo */ if (!list_empty(&req->queuelist) && !list_empty(&next->queuelist)) { if (time_before(rq_fifo_time(next), rq_fifo_time(req))) { list_move(&req->queuelist, &next->queuelist); rq_set_fifo_time(req, rq_fifo_time(next)); } } /* * kill knowledge of next, this one is a goner */ deadline_remove_request(q, next); } /* * move request from sort list to dispatch queue. */ static inline void deadline_move_to_dispatch(struct deadline_data *dd, struct request *rq) { struct request_queue *q = rq->q; deadline_remove_request(q, rq); elv_dispatch_add_tail(q, rq); } /* * move an entry to dispatch queue */ static void deadline_move_request(struct deadline_data *dd, struct request *rq) { const int data_dir = rq_data_dir(rq); dd->next_rq[READ] = NULL; dd->next_rq[WRITE] = NULL; dd->next_rq[data_dir] = deadline_latter_request(rq); dd->last_sector = rq_end_sector(rq); /* * take it off the sort and fifo list, move * to dispatch queue */ deadline_move_to_dispatch(dd, rq); } /* * deadline_check_fifo returns 0 if there are no expired requests on the fifo, * 1 otherwise. Requires !list_empty(&dd->fifo_list[data_dir]) */ static inline int deadline_check_fifo(struct deadline_data *dd, int ddir) { struct request *rq = rq_entry_fifo(dd->fifo_list[ddir].next); /* * rq is expired! */ if (time_after(jiffies, rq_fifo_time(rq))) return 1; return 0; } /* * deadline_dispatch_requests selects the best request according to * read/write expire, fifo_batch, etc */ static int deadline_dispatch_requests(struct request_queue *q, int force) { struct deadline_data *dd = q->elevator->elevator_data; const int reads = !list_empty(&dd->fifo_list[READ]); const int writes = !list_empty(&dd->fifo_list[WRITE]); struct request *rq; int data_dir; /* * batches are currently reads XOR writes */ if (dd->next_rq[WRITE]) rq = dd->next_rq[WRITE]; else rq = dd->next_rq[READ]; if (rq && dd->batching < dd->fifo_batch) /* we have a next request are still entitled to batch */ goto dispatch_request; /* * at this point we are not running a batch. select the appropriate * data direction (read / write) */ if (reads) { BUG_ON(RB_EMPTY_ROOT(&dd->sort_list[READ])); if (writes && (dd->starved++ >= dd->writes_starved)) goto dispatch_writes; data_dir = READ; goto dispatch_find_request; } /* * there are either no reads or writes have been starved */ if (writes) { dispatch_writes: BUG_ON(RB_EMPTY_ROOT(&dd->sort_list[WRITE])); dd->starved = 0; data_dir = WRITE; goto dispatch_find_request; } return 0; dispatch_find_request: /* * we are not running a batch, find best request for selected data_dir */ if (deadline_check_fifo(dd, data_dir) || !dd->next_rq[data_dir]) { /* * A deadline has expired, the last request was in the other * direction, or we have run out of higher-sectored requests. * Start again from the request with the earliest expiry time. */ rq = rq_entry_fifo(dd->fifo_list[data_dir].next); } else { /* * The last req was the same dir and we have a next request in * sort order. No expired requests so continue on from here. */ rq = dd->next_rq[data_dir]; } dd->batching = 0; dispatch_request: /* * rq is the selected appropriate request. */ dd->batching++; deadline_move_request(dd, rq); return 1; } static int deadline_queue_empty(struct request_queue *q) { struct deadline_data *dd = q->elevator->elevator_data; return list_empty(&dd->fifo_list[WRITE]) && list_empty(&dd->fifo_list[READ]); } static void deadline_exit_queue(struct elevator_queue *e) { struct deadline_data *dd = e->elevator_data; BUG_ON(!list_empty(&dd->fifo_list[READ])); BUG_ON(!list_empty(&dd->fifo_list[WRITE])); kfree(dd); } /* * initialize elevator private data (deadline_data). */ static void *deadline_init_queue(struct request_queue *q) { struct deadline_data *dd; dd = kmalloc_node(sizeof(*dd), GFP_KERNEL | __GFP_ZERO, q->node); if (!dd) return NULL; INIT_LIST_HEAD(&dd->fifo_list[READ]); INIT_LIST_HEAD(&dd->fifo_list[WRITE]); dd->sort_list[READ] = RB_ROOT; dd->sort_list[WRITE] = RB_ROOT; dd->fifo_expire[READ] = read_expire; dd->fifo_expire[WRITE] = write_expire; dd->writes_starved = writes_starved; dd->front_merges = 1; dd->fifo_batch = fifo_batch; return dd; } /* * sysfs parts below */ static ssize_t deadline_var_show(int var, char *page) { return sprintf(page, "%d\n", var); } static ssize_t deadline_var_store(int *var, const char *page, size_t count) { char *p = (char *) page; *var = simple_strtol(p, &p, 10); return count; } #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \ static ssize_t __FUNC(struct elevator_queue *e, char *page) \ { \ struct deadline_data *dd = e->elevator_data; \ int __data = __VAR; \ if (__CONV) \ __data = jiffies_to_msecs(__data); \ return deadline_var_show(__data, (page)); \ } SHOW_FUNCTION(deadline_read_expire_show, dd->fifo_expire[READ], 1); SHOW_FUNCTION(deadline_write_expire_show, dd->fifo_expire[WRITE], 1); SHOW_FUNCTION(deadline_writes_starved_show, dd->writes_starved, 0); SHOW_FUNCTION(deadline_front_merges_show, dd->front_merges, 0); SHOW_FUNCTION(deadline_fifo_batch_show, dd->fifo_batch, 0); #undef SHOW_FUNCTION #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \ static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \ { \ struct deadline_data *dd = e->elevator_data; \ int __data; \ int ret = deadline_var_store(&__data, (page), count); \ if (__data < (MIN)) \ __data = (MIN); \ else if (__data > (MAX)) \ __data = (MAX); \ if (__CONV) \ *(__PTR) = msecs_to_jiffies(__data); \ else \ *(__PTR) = __data; \ return ret; \ } STORE_FUNCTION(deadline_read_expire_store, &dd->fifo_expire[READ], 0, INT_MAX, 1); STORE_FUNCTION(deadline_write_expire_store, &dd->fifo_expire[WRITE], 0, INT_MAX, 1); STORE_FUNCTION(deadline_writes_starved_store, &dd->writes_starved, INT_MIN, INT_MAX, 0); STORE_FUNCTION(deadline_front_merges_store, &dd->front_merges, 0, 1, 0); STORE_FUNCTION(deadline_fifo_batch_store, &dd->fifo_batch, 0, INT_MAX, 0); #undef STORE_FUNCTION #define DD_ATTR(name) \ __ATTR(name, S_IRUGO|S_IWUSR, deadline_##name##_show, \ deadline_##name##_store) static struct elv_fs_entry deadline_attrs[] = { DD_ATTR(read_expire), DD_ATTR(write_expire), DD_ATTR(writes_starved), DD_ATTR(front_merges), DD_ATTR(fifo_batch), __ATTR_NULL }; static struct elevator_type iosched_deadline = { .ops = { .elevator_merge_fn = deadline_merge, .elevator_merged_fn = deadline_merged_request, .elevator_merge_req_fn = deadline_merged_requests, .elevator_dispatch_fn = deadline_dispatch_requests, .elevator_add_req_fn = deadline_add_request, .elevator_queue_empty_fn = deadline_queue_empty, .elevator_former_req_fn = elv_rb_former_request, .elevator_latter_req_fn = elv_rb_latter_request, .elevator_init_fn = deadline_init_queue, .elevator_exit_fn = deadline_exit_queue, }, .elevator_attrs = deadline_attrs, .elevator_name = "deadline", .elevator_owner = THIS_MODULE, }; static int __init deadline_init(void) { elv_register(&iosched_deadline); return 0; } static void __exit deadline_exit(void) { elv_unregister(&iosched_deadline); } module_init(deadline_init); module_exit(deadline_exit); MODULE_AUTHOR("Jens Axboe"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("deadline IO scheduler");
gpl-2.0
dmore70/nexus7-kernel
sound/soc/codecs/wm8991.c
2763
44258
/* * wm8991.c -- WM8991 ALSA Soc Audio driver * * Copyright 2007-2010 Wolfson Microelectronics PLC. * Author: Graeme Gregory * linux@wolfsonmicro.com * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/initval.h> #include <sound/tlv.h> #include <asm/div64.h> #include "wm8991.h" struct wm8991_priv { enum snd_soc_control_type control_type; unsigned int pcmclk; }; static const u16 wm8991_reg_defs[] = { 0x8991, /* R0 - Reset */ 0x0000, /* R1 - Power Management (1) */ 0x6000, /* R2 - Power Management (2) */ 0x0000, /* R3 - Power Management (3) */ 0x4050, /* R4 - Audio Interface (1) */ 0x4000, /* R5 - Audio Interface (2) */ 0x01C8, /* R6 - Clocking (1) */ 0x0000, /* R7 - Clocking (2) */ 0x0040, /* R8 - Audio Interface (3) */ 0x0040, /* R9 - Audio Interface (4) */ 0x0004, /* R10 - DAC CTRL */ 0x00C0, /* R11 - Left DAC Digital Volume */ 0x00C0, /* R12 - Right DAC Digital Volume */ 0x0000, /* R13 - Digital Side Tone */ 0x0100, /* R14 - ADC CTRL */ 0x00C0, /* R15 - Left ADC Digital Volume */ 0x00C0, /* R16 - Right ADC Digital Volume */ 0x0000, /* R17 */ 0x0000, /* R18 - GPIO CTRL 1 */ 0x1000, /* R19 - GPIO1 & GPIO2 */ 0x1010, /* R20 - GPIO3 & GPIO4 */ 0x1010, /* R21 - GPIO5 & GPIO6 */ 0x8000, /* R22 - GPIOCTRL 2 */ 0x0800, /* R23 - GPIO_POL */ 0x008B, /* R24 - Left Line Input 1&2 Volume */ 0x008B, /* R25 - Left Line Input 3&4 Volume */ 0x008B, /* R26 - Right Line Input 1&2 Volume */ 0x008B, /* R27 - Right Line Input 3&4 Volume */ 0x0000, /* R28 - Left Output Volume */ 0x0000, /* R29 - Right Output Volume */ 0x0066, /* R30 - Line Outputs Volume */ 0x0022, /* R31 - Out3/4 Volume */ 0x0079, /* R32 - Left OPGA Volume */ 0x0079, /* R33 - Right OPGA Volume */ 0x0003, /* R34 - Speaker Volume */ 0x0003, /* R35 - ClassD1 */ 0x0000, /* R36 */ 0x0100, /* R37 - ClassD3 */ 0x0000, /* R38 */ 0x0000, /* R39 - Input Mixer1 */ 0x0000, /* R40 - Input Mixer2 */ 0x0000, /* R41 - Input Mixer3 */ 0x0000, /* R42 - Input Mixer4 */ 0x0000, /* R43 - Input Mixer5 */ 0x0000, /* R44 - Input Mixer6 */ 0x0000, /* R45 - Output Mixer1 */ 0x0000, /* R46 - Output Mixer2 */ 0x0000, /* R47 - Output Mixer3 */ 0x0000, /* R48 - Output Mixer4 */ 0x0000, /* R49 - Output Mixer5 */ 0x0000, /* R50 - Output Mixer6 */ 0x0180, /* R51 - Out3/4 Mixer */ 0x0000, /* R52 - Line Mixer1 */ 0x0000, /* R53 - Line Mixer2 */ 0x0000, /* R54 - Speaker Mixer */ 0x0000, /* R55 - Additional Control */ 0x0000, /* R56 - AntiPOP1 */ 0x0000, /* R57 - AntiPOP2 */ 0x0000, /* R58 - MICBIAS */ 0x0000, /* R59 */ 0x0008, /* R60 - PLL1 */ 0x0031, /* R61 - PLL2 */ 0x0026, /* R62 - PLL3 */ }; #define wm8991_reset(c) snd_soc_write(c, WM8991_RESET, 0) static const unsigned int rec_mix_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 7, TLV_DB_LINEAR_ITEM(-1500, 600), }; static const unsigned int in_pga_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 0x1F, TLV_DB_LINEAR_ITEM(-1650, 3000), }; static const unsigned int out_mix_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 7, TLV_DB_LINEAR_ITEM(0, -2100), }; static const unsigned int out_pga_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 127, TLV_DB_LINEAR_ITEM(-7300, 600), }; static const unsigned int out_omix_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 7, TLV_DB_LINEAR_ITEM(-600, 0), }; static const unsigned int out_dac_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 255, TLV_DB_LINEAR_ITEM(-7163, 0), }; static const unsigned int in_adc_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 255, TLV_DB_LINEAR_ITEM(-7163, 1763), }; static const unsigned int out_sidetone_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 31, TLV_DB_LINEAR_ITEM(-3600, 0), }; static int wm899x_outpga_put_volsw_vu(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value & 0xff; int ret; u16 val; ret = snd_soc_put_volsw(kcontrol, ucontrol); if (ret < 0) return ret; /* now hit the volume update bits (always bit 8) */ val = snd_soc_read(codec, reg); return snd_soc_write(codec, reg, val | 0x0100); } static const char *wm8991_digital_sidetone[] = {"None", "Left ADC", "Right ADC", "Reserved"}; static const struct soc_enum wm8991_left_digital_sidetone_enum = SOC_ENUM_SINGLE(WM8991_DIGITAL_SIDE_TONE, WM8991_ADC_TO_DACL_SHIFT, WM8991_ADC_TO_DACL_MASK, wm8991_digital_sidetone); static const struct soc_enum wm8991_right_digital_sidetone_enum = SOC_ENUM_SINGLE(WM8991_DIGITAL_SIDE_TONE, WM8991_ADC_TO_DACR_SHIFT, WM8991_ADC_TO_DACR_MASK, wm8991_digital_sidetone); static const char *wm8991_adcmode[] = {"Hi-fi mode", "Voice mode 1", "Voice mode 2", "Voice mode 3"}; static const struct soc_enum wm8991_right_adcmode_enum = SOC_ENUM_SINGLE(WM8991_ADC_CTRL, WM8991_ADC_HPF_CUT_SHIFT, WM8991_ADC_HPF_CUT_MASK, wm8991_adcmode); static const struct snd_kcontrol_new wm8991_snd_controls[] = { /* INMIXL */ SOC_SINGLE("LIN12 PGA Boost", WM8991_INPUT_MIXER3, WM8991_L12MNBST_BIT, 1, 0), SOC_SINGLE("LIN34 PGA Boost", WM8991_INPUT_MIXER3, WM8991_L34MNBST_BIT, 1, 0), /* INMIXR */ SOC_SINGLE("RIN12 PGA Boost", WM8991_INPUT_MIXER3, WM8991_R12MNBST_BIT, 1, 0), SOC_SINGLE("RIN34 PGA Boost", WM8991_INPUT_MIXER3, WM8991_R34MNBST_BIT, 1, 0), /* LOMIX */ SOC_SINGLE_TLV("LOMIX LIN3 Bypass Volume", WM8991_OUTPUT_MIXER3, WM8991_LLI3LOVOL_SHIFT, WM8991_LLI3LOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX RIN12 PGA Bypass Volume", WM8991_OUTPUT_MIXER3, WM8991_LR12LOVOL_SHIFT, WM8991_LR12LOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX LIN12 PGA Bypass Volume", WM8991_OUTPUT_MIXER3, WM8991_LL12LOVOL_SHIFT, WM8991_LL12LOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX RIN3 Bypass Volume", WM8991_OUTPUT_MIXER5, WM8991_LRI3LOVOL_SHIFT, WM8991_LRI3LOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX AINRMUX Bypass Volume", WM8991_OUTPUT_MIXER5, WM8991_LRBLOVOL_SHIFT, WM8991_LRBLOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX AINLMUX Bypass Volume", WM8991_OUTPUT_MIXER5, WM8991_LRBLOVOL_SHIFT, WM8991_LRBLOVOL_MASK, 1, out_mix_tlv), /* ROMIX */ SOC_SINGLE_TLV("ROMIX RIN3 Bypass Volume", WM8991_OUTPUT_MIXER4, WM8991_RRI3ROVOL_SHIFT, WM8991_RRI3ROVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("ROMIX LIN12 PGA Bypass Volume", WM8991_OUTPUT_MIXER4, WM8991_RL12ROVOL_SHIFT, WM8991_RL12ROVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("ROMIX RIN12 PGA Bypass Volume", WM8991_OUTPUT_MIXER4, WM8991_RR12ROVOL_SHIFT, WM8991_RR12ROVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("ROMIX LIN3 Bypass Volume", WM8991_OUTPUT_MIXER6, WM8991_RLI3ROVOL_SHIFT, WM8991_RLI3ROVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("ROMIX AINLMUX Bypass Volume", WM8991_OUTPUT_MIXER6, WM8991_RLBROVOL_SHIFT, WM8991_RLBROVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("ROMIX AINRMUX Bypass Volume", WM8991_OUTPUT_MIXER6, WM8991_RRBROVOL_SHIFT, WM8991_RRBROVOL_MASK, 1, out_mix_tlv), /* LOUT */ SOC_WM899X_OUTPGA_SINGLE_R_TLV("LOUT Volume", WM8991_LEFT_OUTPUT_VOLUME, WM8991_LOUTVOL_SHIFT, WM8991_LOUTVOL_MASK, 0, out_pga_tlv), SOC_SINGLE("LOUT ZC", WM8991_LEFT_OUTPUT_VOLUME, WM8991_LOZC_BIT, 1, 0), /* ROUT */ SOC_WM899X_OUTPGA_SINGLE_R_TLV("ROUT Volume", WM8991_RIGHT_OUTPUT_VOLUME, WM8991_ROUTVOL_SHIFT, WM8991_ROUTVOL_MASK, 0, out_pga_tlv), SOC_SINGLE("ROUT ZC", WM8991_RIGHT_OUTPUT_VOLUME, WM8991_ROZC_BIT, 1, 0), /* LOPGA */ SOC_WM899X_OUTPGA_SINGLE_R_TLV("LOPGA Volume", WM8991_LEFT_OPGA_VOLUME, WM8991_LOPGAVOL_SHIFT, WM8991_LOPGAVOL_MASK, 0, out_pga_tlv), SOC_SINGLE("LOPGA ZC Switch", WM8991_LEFT_OPGA_VOLUME, WM8991_LOPGAZC_BIT, 1, 0), /* ROPGA */ SOC_WM899X_OUTPGA_SINGLE_R_TLV("ROPGA Volume", WM8991_RIGHT_OPGA_VOLUME, WM8991_ROPGAVOL_SHIFT, WM8991_ROPGAVOL_MASK, 0, out_pga_tlv), SOC_SINGLE("ROPGA ZC Switch", WM8991_RIGHT_OPGA_VOLUME, WM8991_ROPGAZC_BIT, 1, 0), SOC_SINGLE("LON Mute Switch", WM8991_LINE_OUTPUTS_VOLUME, WM8991_LONMUTE_BIT, 1, 0), SOC_SINGLE("LOP Mute Switch", WM8991_LINE_OUTPUTS_VOLUME, WM8991_LOPMUTE_BIT, 1, 0), SOC_SINGLE("LOP Attenuation Switch", WM8991_LINE_OUTPUTS_VOLUME, WM8991_LOATTN_BIT, 1, 0), SOC_SINGLE("RON Mute Switch", WM8991_LINE_OUTPUTS_VOLUME, WM8991_RONMUTE_BIT, 1, 0), SOC_SINGLE("ROP Mute Switch", WM8991_LINE_OUTPUTS_VOLUME, WM8991_ROPMUTE_BIT, 1, 0), SOC_SINGLE("ROP Attenuation Switch", WM8991_LINE_OUTPUTS_VOLUME, WM8991_ROATTN_BIT, 1, 0), SOC_SINGLE("OUT3 Mute Switch", WM8991_OUT3_4_VOLUME, WM8991_OUT3MUTE_BIT, 1, 0), SOC_SINGLE("OUT3 Attenuation Switch", WM8991_OUT3_4_VOLUME, WM8991_OUT3ATTN_BIT, 1, 0), SOC_SINGLE("OUT4 Mute Switch", WM8991_OUT3_4_VOLUME, WM8991_OUT4MUTE_BIT, 1, 0), SOC_SINGLE("OUT4 Attenuation Switch", WM8991_OUT3_4_VOLUME, WM8991_OUT4ATTN_BIT, 1, 0), SOC_SINGLE("Speaker Mode Switch", WM8991_CLASSD1, WM8991_CDMODE_BIT, 1, 0), SOC_SINGLE("Speaker Output Attenuation Volume", WM8991_SPEAKER_VOLUME, WM8991_SPKVOL_SHIFT, WM8991_SPKVOL_MASK, 0), SOC_SINGLE("Speaker DC Boost Volume", WM8991_CLASSD3, WM8991_DCGAIN_SHIFT, WM8991_DCGAIN_MASK, 0), SOC_SINGLE("Speaker AC Boost Volume", WM8991_CLASSD3, WM8991_ACGAIN_SHIFT, WM8991_ACGAIN_MASK, 0), SOC_WM899X_OUTPGA_SINGLE_R_TLV("Left DAC Digital Volume", WM8991_LEFT_DAC_DIGITAL_VOLUME, WM8991_DACL_VOL_SHIFT, WM8991_DACL_VOL_MASK, 0, out_dac_tlv), SOC_WM899X_OUTPGA_SINGLE_R_TLV("Right DAC Digital Volume", WM8991_RIGHT_DAC_DIGITAL_VOLUME, WM8991_DACR_VOL_SHIFT, WM8991_DACR_VOL_MASK, 0, out_dac_tlv), SOC_ENUM("Left Digital Sidetone", wm8991_left_digital_sidetone_enum), SOC_ENUM("Right Digital Sidetone", wm8991_right_digital_sidetone_enum), SOC_SINGLE_TLV("Left Digital Sidetone Volume", WM8991_DIGITAL_SIDE_TONE, WM8991_ADCL_DAC_SVOL_SHIFT, WM8991_ADCL_DAC_SVOL_MASK, 0, out_sidetone_tlv), SOC_SINGLE_TLV("Right Digital Sidetone Volume", WM8991_DIGITAL_SIDE_TONE, WM8991_ADCR_DAC_SVOL_SHIFT, WM8991_ADCR_DAC_SVOL_MASK, 0, out_sidetone_tlv), SOC_SINGLE("ADC Digital High Pass Filter Switch", WM8991_ADC_CTRL, WM8991_ADC_HPF_ENA_BIT, 1, 0), SOC_ENUM("ADC HPF Mode", wm8991_right_adcmode_enum), SOC_WM899X_OUTPGA_SINGLE_R_TLV("Left ADC Digital Volume", WM8991_LEFT_ADC_DIGITAL_VOLUME, WM8991_ADCL_VOL_SHIFT, WM8991_ADCL_VOL_MASK, 0, in_adc_tlv), SOC_WM899X_OUTPGA_SINGLE_R_TLV("Right ADC Digital Volume", WM8991_RIGHT_ADC_DIGITAL_VOLUME, WM8991_ADCR_VOL_SHIFT, WM8991_ADCR_VOL_MASK, 0, in_adc_tlv), SOC_WM899X_OUTPGA_SINGLE_R_TLV("LIN12 Volume", WM8991_LEFT_LINE_INPUT_1_2_VOLUME, WM8991_LIN12VOL_SHIFT, WM8991_LIN12VOL_MASK, 0, in_pga_tlv), SOC_SINGLE("LIN12 ZC Switch", WM8991_LEFT_LINE_INPUT_1_2_VOLUME, WM8991_LI12ZC_BIT, 1, 0), SOC_SINGLE("LIN12 Mute Switch", WM8991_LEFT_LINE_INPUT_1_2_VOLUME, WM8991_LI12MUTE_BIT, 1, 0), SOC_WM899X_OUTPGA_SINGLE_R_TLV("LIN34 Volume", WM8991_LEFT_LINE_INPUT_3_4_VOLUME, WM8991_LIN34VOL_SHIFT, WM8991_LIN34VOL_MASK, 0, in_pga_tlv), SOC_SINGLE("LIN34 ZC Switch", WM8991_LEFT_LINE_INPUT_3_4_VOLUME, WM8991_LI34ZC_BIT, 1, 0), SOC_SINGLE("LIN34 Mute Switch", WM8991_LEFT_LINE_INPUT_3_4_VOLUME, WM8991_LI34MUTE_BIT, 1, 0), SOC_WM899X_OUTPGA_SINGLE_R_TLV("RIN12 Volume", WM8991_RIGHT_LINE_INPUT_1_2_VOLUME, WM8991_RIN12VOL_SHIFT, WM8991_RIN12VOL_MASK, 0, in_pga_tlv), SOC_SINGLE("RIN12 ZC Switch", WM8991_RIGHT_LINE_INPUT_1_2_VOLUME, WM8991_RI12ZC_BIT, 1, 0), SOC_SINGLE("RIN12 Mute Switch", WM8991_RIGHT_LINE_INPUT_1_2_VOLUME, WM8991_RI12MUTE_BIT, 1, 0), SOC_WM899X_OUTPGA_SINGLE_R_TLV("RIN34 Volume", WM8991_RIGHT_LINE_INPUT_3_4_VOLUME, WM8991_RIN34VOL_SHIFT, WM8991_RIN34VOL_MASK, 0, in_pga_tlv), SOC_SINGLE("RIN34 ZC Switch", WM8991_RIGHT_LINE_INPUT_3_4_VOLUME, WM8991_RI34ZC_BIT, 1, 0), SOC_SINGLE("RIN34 Mute Switch", WM8991_RIGHT_LINE_INPUT_3_4_VOLUME, WM8991_RI34MUTE_BIT, 1, 0), }; /* * _DAPM_ Controls */ static int inmixer_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { u16 reg, fakepower; reg = snd_soc_read(w->codec, WM8991_POWER_MANAGEMENT_2); fakepower = snd_soc_read(w->codec, WM8991_INTDRIVBITS); if (fakepower & ((1 << WM8991_INMIXL_PWR_BIT) | (1 << WM8991_AINLMUX_PWR_BIT))) reg |= WM8991_AINL_ENA; else reg &= ~WM8991_AINL_ENA; if (fakepower & ((1 << WM8991_INMIXR_PWR_BIT) | (1 << WM8991_AINRMUX_PWR_BIT))) reg |= WM8991_AINR_ENA; else reg &= ~WM8991_AINL_ENA; snd_soc_write(w->codec, WM8991_POWER_MANAGEMENT_2, reg); return 0; } static int outmixer_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { u32 reg_shift = kcontrol->private_value & 0xfff; int ret = 0; u16 reg; switch (reg_shift) { case WM8991_SPEAKER_MIXER | (WM8991_LDSPK_BIT << 8): reg = snd_soc_read(w->codec, WM8991_OUTPUT_MIXER1); if (reg & WM8991_LDLO) { printk(KERN_WARNING "Cannot set as Output Mixer 1 LDLO Set\n"); ret = -1; } break; case WM8991_SPEAKER_MIXER | (WM8991_RDSPK_BIT << 8): reg = snd_soc_read(w->codec, WM8991_OUTPUT_MIXER2); if (reg & WM8991_RDRO) { printk(KERN_WARNING "Cannot set as Output Mixer 2 RDRO Set\n"); ret = -1; } break; case WM8991_OUTPUT_MIXER1 | (WM8991_LDLO_BIT << 8): reg = snd_soc_read(w->codec, WM8991_SPEAKER_MIXER); if (reg & WM8991_LDSPK) { printk(KERN_WARNING "Cannot set as Speaker Mixer LDSPK Set\n"); ret = -1; } break; case WM8991_OUTPUT_MIXER2 | (WM8991_RDRO_BIT << 8): reg = snd_soc_read(w->codec, WM8991_SPEAKER_MIXER); if (reg & WM8991_RDSPK) { printk(KERN_WARNING "Cannot set as Speaker Mixer RDSPK Set\n"); ret = -1; } break; } return ret; } /* INMIX dB values */ static const unsigned int in_mix_tlv[] = { TLV_DB_RANGE_HEAD(1), 0, 7, TLV_DB_LINEAR_ITEM(-1200, 600), }; /* Left In PGA Connections */ static const struct snd_kcontrol_new wm8991_dapm_lin12_pga_controls[] = { SOC_DAPM_SINGLE("LIN1 Switch", WM8991_INPUT_MIXER2, WM8991_LMN1_BIT, 1, 0), SOC_DAPM_SINGLE("LIN2 Switch", WM8991_INPUT_MIXER2, WM8991_LMP2_BIT, 1, 0), }; static const struct snd_kcontrol_new wm8991_dapm_lin34_pga_controls[] = { SOC_DAPM_SINGLE("LIN3 Switch", WM8991_INPUT_MIXER2, WM8991_LMN3_BIT, 1, 0), SOC_DAPM_SINGLE("LIN4 Switch", WM8991_INPUT_MIXER2, WM8991_LMP4_BIT, 1, 0), }; /* Right In PGA Connections */ static const struct snd_kcontrol_new wm8991_dapm_rin12_pga_controls[] = { SOC_DAPM_SINGLE("RIN1 Switch", WM8991_INPUT_MIXER2, WM8991_RMN1_BIT, 1, 0), SOC_DAPM_SINGLE("RIN2 Switch", WM8991_INPUT_MIXER2, WM8991_RMP2_BIT, 1, 0), }; static const struct snd_kcontrol_new wm8991_dapm_rin34_pga_controls[] = { SOC_DAPM_SINGLE("RIN3 Switch", WM8991_INPUT_MIXER2, WM8991_RMN3_BIT, 1, 0), SOC_DAPM_SINGLE("RIN4 Switch", WM8991_INPUT_MIXER2, WM8991_RMP4_BIT, 1, 0), }; /* INMIXL */ static const struct snd_kcontrol_new wm8991_dapm_inmixl_controls[] = { SOC_DAPM_SINGLE_TLV("Record Left Volume", WM8991_INPUT_MIXER3, WM8991_LDBVOL_SHIFT, WM8991_LDBVOL_MASK, 0, in_mix_tlv), SOC_DAPM_SINGLE_TLV("LIN2 Volume", WM8991_INPUT_MIXER5, WM8991_LI2BVOL_SHIFT, 7, 0, in_mix_tlv), SOC_DAPM_SINGLE("LINPGA12 Switch", WM8991_INPUT_MIXER3, WM8991_L12MNB_BIT, 1, 0), SOC_DAPM_SINGLE("LINPGA34 Switch", WM8991_INPUT_MIXER3, WM8991_L34MNB_BIT, 1, 0), }; /* INMIXR */ static const struct snd_kcontrol_new wm8991_dapm_inmixr_controls[] = { SOC_DAPM_SINGLE_TLV("Record Right Volume", WM8991_INPUT_MIXER4, WM8991_RDBVOL_SHIFT, WM8991_RDBVOL_MASK, 0, in_mix_tlv), SOC_DAPM_SINGLE_TLV("RIN2 Volume", WM8991_INPUT_MIXER6, WM8991_RI2BVOL_SHIFT, 7, 0, in_mix_tlv), SOC_DAPM_SINGLE("RINPGA12 Switch", WM8991_INPUT_MIXER3, WM8991_L12MNB_BIT, 1, 0), SOC_DAPM_SINGLE("RINPGA34 Switch", WM8991_INPUT_MIXER3, WM8991_L34MNB_BIT, 1, 0), }; /* AINLMUX */ static const char *wm8991_ainlmux[] = {"INMIXL Mix", "RXVOICE Mix", "DIFFINL Mix"}; static const struct soc_enum wm8991_ainlmux_enum = SOC_ENUM_SINGLE(WM8991_INPUT_MIXER1, WM8991_AINLMODE_SHIFT, ARRAY_SIZE(wm8991_ainlmux), wm8991_ainlmux); static const struct snd_kcontrol_new wm8991_dapm_ainlmux_controls = SOC_DAPM_ENUM("Route", wm8991_ainlmux_enum); /* DIFFINL */ /* AINRMUX */ static const char *wm8991_ainrmux[] = {"INMIXR Mix", "RXVOICE Mix", "DIFFINR Mix"}; static const struct soc_enum wm8991_ainrmux_enum = SOC_ENUM_SINGLE(WM8991_INPUT_MIXER1, WM8991_AINRMODE_SHIFT, ARRAY_SIZE(wm8991_ainrmux), wm8991_ainrmux); static const struct snd_kcontrol_new wm8991_dapm_ainrmux_controls = SOC_DAPM_ENUM("Route", wm8991_ainrmux_enum); /* RXVOICE */ static const struct snd_kcontrol_new wm8991_dapm_rxvoice_controls[] = { SOC_DAPM_SINGLE_TLV("LIN4RXN", WM8991_INPUT_MIXER5, WM8991_LR4BVOL_SHIFT, WM8991_LR4BVOL_MASK, 0, in_mix_tlv), SOC_DAPM_SINGLE_TLV("RIN4RXP", WM8991_INPUT_MIXER6, WM8991_RL4BVOL_SHIFT, WM8991_RL4BVOL_MASK, 0, in_mix_tlv), }; /* LOMIX */ static const struct snd_kcontrol_new wm8991_dapm_lomix_controls[] = { SOC_DAPM_SINGLE("LOMIX Right ADC Bypass Switch", WM8991_OUTPUT_MIXER1, WM8991_LRBLO_BIT, 1, 0), SOC_DAPM_SINGLE("LOMIX Left ADC Bypass Switch", WM8991_OUTPUT_MIXER1, WM8991_LLBLO_BIT, 1, 0), SOC_DAPM_SINGLE("LOMIX RIN3 Bypass Switch", WM8991_OUTPUT_MIXER1, WM8991_LRI3LO_BIT, 1, 0), SOC_DAPM_SINGLE("LOMIX LIN3 Bypass Switch", WM8991_OUTPUT_MIXER1, WM8991_LLI3LO_BIT, 1, 0), SOC_DAPM_SINGLE("LOMIX RIN12 PGA Bypass Switch", WM8991_OUTPUT_MIXER1, WM8991_LR12LO_BIT, 1, 0), SOC_DAPM_SINGLE("LOMIX LIN12 PGA Bypass Switch", WM8991_OUTPUT_MIXER1, WM8991_LL12LO_BIT, 1, 0), SOC_DAPM_SINGLE("LOMIX Left DAC Switch", WM8991_OUTPUT_MIXER1, WM8991_LDLO_BIT, 1, 0), }; /* ROMIX */ static const struct snd_kcontrol_new wm8991_dapm_romix_controls[] = { SOC_DAPM_SINGLE("ROMIX Left ADC Bypass Switch", WM8991_OUTPUT_MIXER2, WM8991_RLBRO_BIT, 1, 0), SOC_DAPM_SINGLE("ROMIX Right ADC Bypass Switch", WM8991_OUTPUT_MIXER2, WM8991_RRBRO_BIT, 1, 0), SOC_DAPM_SINGLE("ROMIX LIN3 Bypass Switch", WM8991_OUTPUT_MIXER2, WM8991_RLI3RO_BIT, 1, 0), SOC_DAPM_SINGLE("ROMIX RIN3 Bypass Switch", WM8991_OUTPUT_MIXER2, WM8991_RRI3RO_BIT, 1, 0), SOC_DAPM_SINGLE("ROMIX LIN12 PGA Bypass Switch", WM8991_OUTPUT_MIXER2, WM8991_RL12RO_BIT, 1, 0), SOC_DAPM_SINGLE("ROMIX RIN12 PGA Bypass Switch", WM8991_OUTPUT_MIXER2, WM8991_RR12RO_BIT, 1, 0), SOC_DAPM_SINGLE("ROMIX Right DAC Switch", WM8991_OUTPUT_MIXER2, WM8991_RDRO_BIT, 1, 0), }; /* LONMIX */ static const struct snd_kcontrol_new wm8991_dapm_lonmix_controls[] = { SOC_DAPM_SINGLE("LONMIX Left Mixer PGA Switch", WM8991_LINE_MIXER1, WM8991_LLOPGALON_BIT, 1, 0), SOC_DAPM_SINGLE("LONMIX Right Mixer PGA Switch", WM8991_LINE_MIXER1, WM8991_LROPGALON_BIT, 1, 0), SOC_DAPM_SINGLE("LONMIX Inverted LOP Switch", WM8991_LINE_MIXER1, WM8991_LOPLON_BIT, 1, 0), }; /* LOPMIX */ static const struct snd_kcontrol_new wm8991_dapm_lopmix_controls[] = { SOC_DAPM_SINGLE("LOPMIX Right Mic Bypass Switch", WM8991_LINE_MIXER1, WM8991_LR12LOP_BIT, 1, 0), SOC_DAPM_SINGLE("LOPMIX Left Mic Bypass Switch", WM8991_LINE_MIXER1, WM8991_LL12LOP_BIT, 1, 0), SOC_DAPM_SINGLE("LOPMIX Left Mixer PGA Switch", WM8991_LINE_MIXER1, WM8991_LLOPGALOP_BIT, 1, 0), }; /* RONMIX */ static const struct snd_kcontrol_new wm8991_dapm_ronmix_controls[] = { SOC_DAPM_SINGLE("RONMIX Right Mixer PGA Switch", WM8991_LINE_MIXER2, WM8991_RROPGARON_BIT, 1, 0), SOC_DAPM_SINGLE("RONMIX Left Mixer PGA Switch", WM8991_LINE_MIXER2, WM8991_RLOPGARON_BIT, 1, 0), SOC_DAPM_SINGLE("RONMIX Inverted ROP Switch", WM8991_LINE_MIXER2, WM8991_ROPRON_BIT, 1, 0), }; /* ROPMIX */ static const struct snd_kcontrol_new wm8991_dapm_ropmix_controls[] = { SOC_DAPM_SINGLE("ROPMIX Left Mic Bypass Switch", WM8991_LINE_MIXER2, WM8991_RL12ROP_BIT, 1, 0), SOC_DAPM_SINGLE("ROPMIX Right Mic Bypass Switch", WM8991_LINE_MIXER2, WM8991_RR12ROP_BIT, 1, 0), SOC_DAPM_SINGLE("ROPMIX Right Mixer PGA Switch", WM8991_LINE_MIXER2, WM8991_RROPGAROP_BIT, 1, 0), }; /* OUT3MIX */ static const struct snd_kcontrol_new wm8991_dapm_out3mix_controls[] = { SOC_DAPM_SINGLE("OUT3MIX LIN4RXN Bypass Switch", WM8991_OUT3_4_MIXER, WM8991_LI4O3_BIT, 1, 0), SOC_DAPM_SINGLE("OUT3MIX Left Out PGA Switch", WM8991_OUT3_4_MIXER, WM8991_LPGAO3_BIT, 1, 0), }; /* OUT4MIX */ static const struct snd_kcontrol_new wm8991_dapm_out4mix_controls[] = { SOC_DAPM_SINGLE("OUT4MIX Right Out PGA Switch", WM8991_OUT3_4_MIXER, WM8991_RPGAO4_BIT, 1, 0), SOC_DAPM_SINGLE("OUT4MIX RIN4RXP Bypass Switch", WM8991_OUT3_4_MIXER, WM8991_RI4O4_BIT, 1, 0), }; /* SPKMIX */ static const struct snd_kcontrol_new wm8991_dapm_spkmix_controls[] = { SOC_DAPM_SINGLE("SPKMIX LIN2 Bypass Switch", WM8991_SPEAKER_MIXER, WM8991_LI2SPK_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX LADC Bypass Switch", WM8991_SPEAKER_MIXER, WM8991_LB2SPK_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX Left Mixer PGA Switch", WM8991_SPEAKER_MIXER, WM8991_LOPGASPK_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX Left DAC Switch", WM8991_SPEAKER_MIXER, WM8991_LDSPK_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX Right DAC Switch", WM8991_SPEAKER_MIXER, WM8991_RDSPK_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX Right Mixer PGA Switch", WM8991_SPEAKER_MIXER, WM8991_ROPGASPK_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX RADC Bypass Switch", WM8991_SPEAKER_MIXER, WM8991_RL12ROP_BIT, 1, 0), SOC_DAPM_SINGLE("SPKMIX RIN2 Bypass Switch", WM8991_SPEAKER_MIXER, WM8991_RI2SPK_BIT, 1, 0), }; static const struct snd_soc_dapm_widget wm8991_dapm_widgets[] = { /* Input Side */ /* Input Lines */ SND_SOC_DAPM_INPUT("LIN1"), SND_SOC_DAPM_INPUT("LIN2"), SND_SOC_DAPM_INPUT("LIN3"), SND_SOC_DAPM_INPUT("LIN4RXN"), SND_SOC_DAPM_INPUT("RIN3"), SND_SOC_DAPM_INPUT("RIN4RXP"), SND_SOC_DAPM_INPUT("RIN1"), SND_SOC_DAPM_INPUT("RIN2"), SND_SOC_DAPM_INPUT("Internal ADC Source"), /* DACs */ SND_SOC_DAPM_ADC("Left ADC", "Left Capture", WM8991_POWER_MANAGEMENT_2, WM8991_ADCL_ENA_BIT, 0), SND_SOC_DAPM_ADC("Right ADC", "Right Capture", WM8991_POWER_MANAGEMENT_2, WM8991_ADCR_ENA_BIT, 0), /* Input PGAs */ SND_SOC_DAPM_MIXER("LIN12 PGA", WM8991_POWER_MANAGEMENT_2, WM8991_LIN12_ENA_BIT, 0, &wm8991_dapm_lin12_pga_controls[0], ARRAY_SIZE(wm8991_dapm_lin12_pga_controls)), SND_SOC_DAPM_MIXER("LIN34 PGA", WM8991_POWER_MANAGEMENT_2, WM8991_LIN34_ENA_BIT, 0, &wm8991_dapm_lin34_pga_controls[0], ARRAY_SIZE(wm8991_dapm_lin34_pga_controls)), SND_SOC_DAPM_MIXER("RIN12 PGA", WM8991_POWER_MANAGEMENT_2, WM8991_RIN12_ENA_BIT, 0, &wm8991_dapm_rin12_pga_controls[0], ARRAY_SIZE(wm8991_dapm_rin12_pga_controls)), SND_SOC_DAPM_MIXER("RIN34 PGA", WM8991_POWER_MANAGEMENT_2, WM8991_RIN34_ENA_BIT, 0, &wm8991_dapm_rin34_pga_controls[0], ARRAY_SIZE(wm8991_dapm_rin34_pga_controls)), /* INMIXL */ SND_SOC_DAPM_MIXER_E("INMIXL", WM8991_INTDRIVBITS, WM8991_INMIXL_PWR_BIT, 0, &wm8991_dapm_inmixl_controls[0], ARRAY_SIZE(wm8991_dapm_inmixl_controls), inmixer_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* AINLMUX */ SND_SOC_DAPM_MUX_E("AINLMUX", WM8991_INTDRIVBITS, WM8991_AINLMUX_PWR_BIT, 0, &wm8991_dapm_ainlmux_controls, inmixer_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* INMIXR */ SND_SOC_DAPM_MIXER_E("INMIXR", WM8991_INTDRIVBITS, WM8991_INMIXR_PWR_BIT, 0, &wm8991_dapm_inmixr_controls[0], ARRAY_SIZE(wm8991_dapm_inmixr_controls), inmixer_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* AINRMUX */ SND_SOC_DAPM_MUX_E("AINRMUX", WM8991_INTDRIVBITS, WM8991_AINRMUX_PWR_BIT, 0, &wm8991_dapm_ainrmux_controls, inmixer_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), /* Output Side */ /* DACs */ SND_SOC_DAPM_DAC("Left DAC", "Left Playback", WM8991_POWER_MANAGEMENT_3, WM8991_DACL_ENA_BIT, 0), SND_SOC_DAPM_DAC("Right DAC", "Right Playback", WM8991_POWER_MANAGEMENT_3, WM8991_DACR_ENA_BIT, 0), /* LOMIX */ SND_SOC_DAPM_MIXER_E("LOMIX", WM8991_POWER_MANAGEMENT_3, WM8991_LOMIX_ENA_BIT, 0, &wm8991_dapm_lomix_controls[0], ARRAY_SIZE(wm8991_dapm_lomix_controls), outmixer_event, SND_SOC_DAPM_PRE_REG), /* LONMIX */ SND_SOC_DAPM_MIXER("LONMIX", WM8991_POWER_MANAGEMENT_3, WM8991_LON_ENA_BIT, 0, &wm8991_dapm_lonmix_controls[0], ARRAY_SIZE(wm8991_dapm_lonmix_controls)), /* LOPMIX */ SND_SOC_DAPM_MIXER("LOPMIX", WM8991_POWER_MANAGEMENT_3, WM8991_LOP_ENA_BIT, 0, &wm8991_dapm_lopmix_controls[0], ARRAY_SIZE(wm8991_dapm_lopmix_controls)), /* OUT3MIX */ SND_SOC_DAPM_MIXER("OUT3MIX", WM8991_POWER_MANAGEMENT_1, WM8991_OUT3_ENA_BIT, 0, &wm8991_dapm_out3mix_controls[0], ARRAY_SIZE(wm8991_dapm_out3mix_controls)), /* SPKMIX */ SND_SOC_DAPM_MIXER_E("SPKMIX", WM8991_POWER_MANAGEMENT_1, WM8991_SPK_ENA_BIT, 0, &wm8991_dapm_spkmix_controls[0], ARRAY_SIZE(wm8991_dapm_spkmix_controls), outmixer_event, SND_SOC_DAPM_PRE_REG), /* OUT4MIX */ SND_SOC_DAPM_MIXER("OUT4MIX", WM8991_POWER_MANAGEMENT_1, WM8991_OUT4_ENA_BIT, 0, &wm8991_dapm_out4mix_controls[0], ARRAY_SIZE(wm8991_dapm_out4mix_controls)), /* ROPMIX */ SND_SOC_DAPM_MIXER("ROPMIX", WM8991_POWER_MANAGEMENT_3, WM8991_ROP_ENA_BIT, 0, &wm8991_dapm_ropmix_controls[0], ARRAY_SIZE(wm8991_dapm_ropmix_controls)), /* RONMIX */ SND_SOC_DAPM_MIXER("RONMIX", WM8991_POWER_MANAGEMENT_3, WM8991_RON_ENA_BIT, 0, &wm8991_dapm_ronmix_controls[0], ARRAY_SIZE(wm8991_dapm_ronmix_controls)), /* ROMIX */ SND_SOC_DAPM_MIXER_E("ROMIX", WM8991_POWER_MANAGEMENT_3, WM8991_ROMIX_ENA_BIT, 0, &wm8991_dapm_romix_controls[0], ARRAY_SIZE(wm8991_dapm_romix_controls), outmixer_event, SND_SOC_DAPM_PRE_REG), /* LOUT PGA */ SND_SOC_DAPM_PGA("LOUT PGA", WM8991_POWER_MANAGEMENT_1, WM8991_LOUT_ENA_BIT, 0, NULL, 0), /* ROUT PGA */ SND_SOC_DAPM_PGA("ROUT PGA", WM8991_POWER_MANAGEMENT_1, WM8991_ROUT_ENA_BIT, 0, NULL, 0), /* LOPGA */ SND_SOC_DAPM_PGA("LOPGA", WM8991_POWER_MANAGEMENT_3, WM8991_LOPGA_ENA_BIT, 0, NULL, 0), /* ROPGA */ SND_SOC_DAPM_PGA("ROPGA", WM8991_POWER_MANAGEMENT_3, WM8991_ROPGA_ENA_BIT, 0, NULL, 0), /* MICBIAS */ SND_SOC_DAPM_MICBIAS("MICBIAS", WM8991_POWER_MANAGEMENT_1, WM8991_MICBIAS_ENA_BIT, 0), SND_SOC_DAPM_OUTPUT("LON"), SND_SOC_DAPM_OUTPUT("LOP"), SND_SOC_DAPM_OUTPUT("OUT3"), SND_SOC_DAPM_OUTPUT("LOUT"), SND_SOC_DAPM_OUTPUT("SPKN"), SND_SOC_DAPM_OUTPUT("SPKP"), SND_SOC_DAPM_OUTPUT("ROUT"), SND_SOC_DAPM_OUTPUT("OUT4"), SND_SOC_DAPM_OUTPUT("ROP"), SND_SOC_DAPM_OUTPUT("RON"), SND_SOC_DAPM_OUTPUT("OUT"), SND_SOC_DAPM_OUTPUT("Internal DAC Sink"), }; static const struct snd_soc_dapm_route audio_map[] = { /* Make DACs turn on when playing even if not mixed into any outputs */ {"Internal DAC Sink", NULL, "Left DAC"}, {"Internal DAC Sink", NULL, "Right DAC"}, /* Make ADCs turn on when recording even if not mixed from any inputs */ {"Left ADC", NULL, "Internal ADC Source"}, {"Right ADC", NULL, "Internal ADC Source"}, /* Input Side */ /* LIN12 PGA */ {"LIN12 PGA", "LIN1 Switch", "LIN1"}, {"LIN12 PGA", "LIN2 Switch", "LIN2"}, /* LIN34 PGA */ {"LIN34 PGA", "LIN3 Switch", "LIN3"}, {"LIN34 PGA", "LIN4 Switch", "LIN4RXN"}, /* INMIXL */ {"INMIXL", "Record Left Volume", "LOMIX"}, {"INMIXL", "LIN2 Volume", "LIN2"}, {"INMIXL", "LINPGA12 Switch", "LIN12 PGA"}, {"INMIXL", "LINPGA34 Switch", "LIN34 PGA"}, /* AINLMUX */ {"AINLMUX", "INMIXL Mix", "INMIXL"}, {"AINLMUX", "DIFFINL Mix", "LIN12 PGA"}, {"AINLMUX", "DIFFINL Mix", "LIN34 PGA"}, {"AINLMUX", "RXVOICE Mix", "LIN4RXN"}, {"AINLMUX", "RXVOICE Mix", "RIN4RXP"}, /* ADC */ {"Left ADC", NULL, "AINLMUX"}, /* RIN12 PGA */ {"RIN12 PGA", "RIN1 Switch", "RIN1"}, {"RIN12 PGA", "RIN2 Switch", "RIN2"}, /* RIN34 PGA */ {"RIN34 PGA", "RIN3 Switch", "RIN3"}, {"RIN34 PGA", "RIN4 Switch", "RIN4RXP"}, /* INMIXL */ {"INMIXR", "Record Right Volume", "ROMIX"}, {"INMIXR", "RIN2 Volume", "RIN2"}, {"INMIXR", "RINPGA12 Switch", "RIN12 PGA"}, {"INMIXR", "RINPGA34 Switch", "RIN34 PGA"}, /* AINRMUX */ {"AINRMUX", "INMIXR Mix", "INMIXR"}, {"AINRMUX", "DIFFINR Mix", "RIN12 PGA"}, {"AINRMUX", "DIFFINR Mix", "RIN34 PGA"}, {"AINRMUX", "RXVOICE Mix", "LIN4RXN"}, {"AINRMUX", "RXVOICE Mix", "RIN4RXP"}, /* ADC */ {"Right ADC", NULL, "AINRMUX"}, /* LOMIX */ {"LOMIX", "LOMIX RIN3 Bypass Switch", "RIN3"}, {"LOMIX", "LOMIX LIN3 Bypass Switch", "LIN3"}, {"LOMIX", "LOMIX LIN12 PGA Bypass Switch", "LIN12 PGA"}, {"LOMIX", "LOMIX RIN12 PGA Bypass Switch", "RIN12 PGA"}, {"LOMIX", "LOMIX Right ADC Bypass Switch", "AINRMUX"}, {"LOMIX", "LOMIX Left ADC Bypass Switch", "AINLMUX"}, {"LOMIX", "LOMIX Left DAC Switch", "Left DAC"}, /* ROMIX */ {"ROMIX", "ROMIX RIN3 Bypass Switch", "RIN3"}, {"ROMIX", "ROMIX LIN3 Bypass Switch", "LIN3"}, {"ROMIX", "ROMIX LIN12 PGA Bypass Switch", "LIN12 PGA"}, {"ROMIX", "ROMIX RIN12 PGA Bypass Switch", "RIN12 PGA"}, {"ROMIX", "ROMIX Right ADC Bypass Switch", "AINRMUX"}, {"ROMIX", "ROMIX Left ADC Bypass Switch", "AINLMUX"}, {"ROMIX", "ROMIX Right DAC Switch", "Right DAC"}, /* SPKMIX */ {"SPKMIX", "SPKMIX LIN2 Bypass Switch", "LIN2"}, {"SPKMIX", "SPKMIX RIN2 Bypass Switch", "RIN2"}, {"SPKMIX", "SPKMIX LADC Bypass Switch", "AINLMUX"}, {"SPKMIX", "SPKMIX RADC Bypass Switch", "AINRMUX"}, {"SPKMIX", "SPKMIX Left Mixer PGA Switch", "LOPGA"}, {"SPKMIX", "SPKMIX Right Mixer PGA Switch", "ROPGA"}, {"SPKMIX", "SPKMIX Right DAC Switch", "Right DAC"}, {"SPKMIX", "SPKMIX Left DAC Switch", "Right DAC"}, /* LONMIX */ {"LONMIX", "LONMIX Left Mixer PGA Switch", "LOPGA"}, {"LONMIX", "LONMIX Right Mixer PGA Switch", "ROPGA"}, {"LONMIX", "LONMIX Inverted LOP Switch", "LOPMIX"}, /* LOPMIX */ {"LOPMIX", "LOPMIX Right Mic Bypass Switch", "RIN12 PGA"}, {"LOPMIX", "LOPMIX Left Mic Bypass Switch", "LIN12 PGA"}, {"LOPMIX", "LOPMIX Left Mixer PGA Switch", "LOPGA"}, /* OUT3MIX */ {"OUT3MIX", "OUT3MIX LIN4RXN Bypass Switch", "LIN4RXN"}, {"OUT3MIX", "OUT3MIX Left Out PGA Switch", "LOPGA"}, /* OUT4MIX */ {"OUT4MIX", "OUT4MIX Right Out PGA Switch", "ROPGA"}, {"OUT4MIX", "OUT4MIX RIN4RXP Bypass Switch", "RIN4RXP"}, /* RONMIX */ {"RONMIX", "RONMIX Right Mixer PGA Switch", "ROPGA"}, {"RONMIX", "RONMIX Left Mixer PGA Switch", "LOPGA"}, {"RONMIX", "RONMIX Inverted ROP Switch", "ROPMIX"}, /* ROPMIX */ {"ROPMIX", "ROPMIX Left Mic Bypass Switch", "LIN12 PGA"}, {"ROPMIX", "ROPMIX Right Mic Bypass Switch", "RIN12 PGA"}, {"ROPMIX", "ROPMIX Right Mixer PGA Switch", "ROPGA"}, /* Out Mixer PGAs */ {"LOPGA", NULL, "LOMIX"}, {"ROPGA", NULL, "ROMIX"}, {"LOUT PGA", NULL, "LOMIX"}, {"ROUT PGA", NULL, "ROMIX"}, /* Output Pins */ {"LON", NULL, "LONMIX"}, {"LOP", NULL, "LOPMIX"}, {"OUT", NULL, "OUT3MIX"}, {"LOUT", NULL, "LOUT PGA"}, {"SPKN", NULL, "SPKMIX"}, {"ROUT", NULL, "ROUT PGA"}, {"OUT4", NULL, "OUT4MIX"}, {"ROP", NULL, "ROPMIX"}, {"RON", NULL, "RONMIX"}, }; /* PLL divisors */ struct _pll_div { u32 div2; u32 n; u32 k; }; /* The size in bits of the pll divide multiplied by 10 * to allow rounding later */ #define FIXED_PLL_SIZE ((1 << 16) * 10) static void pll_factors(struct _pll_div *pll_div, unsigned int target, unsigned int source) { u64 Kpart; unsigned int K, Ndiv, Nmod; Ndiv = target / source; if (Ndiv < 6) { source >>= 1; pll_div->div2 = 1; Ndiv = target / source; } else pll_div->div2 = 0; if ((Ndiv < 6) || (Ndiv > 12)) printk(KERN_WARNING "WM8991 N value outwith recommended range! N = %d\n", Ndiv); pll_div->n = Ndiv; Nmod = target % source; Kpart = FIXED_PLL_SIZE * (long long)Nmod; do_div(Kpart, source); K = Kpart & 0xFFFFFFFF; /* Check if we need to round */ if ((K % 10) >= 5) K += 5; /* Move down to proper range now rounding is done */ K /= 10; pll_div->k = K; } static int wm8991_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id, int src, unsigned int freq_in, unsigned int freq_out) { u16 reg; struct snd_soc_codec *codec = codec_dai->codec; struct _pll_div pll_div; if (freq_in && freq_out) { pll_factors(&pll_div, freq_out * 4, freq_in); /* Turn on PLL */ reg = snd_soc_read(codec, WM8991_POWER_MANAGEMENT_2); reg |= WM8991_PLL_ENA; snd_soc_write(codec, WM8991_POWER_MANAGEMENT_2, reg); /* sysclk comes from PLL */ reg = snd_soc_read(codec, WM8991_CLOCKING_2); snd_soc_write(codec, WM8991_CLOCKING_2, reg | WM8991_SYSCLK_SRC); /* set up N , fractional mode and pre-divisor if necessary */ snd_soc_write(codec, WM8991_PLL1, pll_div.n | WM8991_SDM | (pll_div.div2 ? WM8991_PRESCALE : 0)); snd_soc_write(codec, WM8991_PLL2, (u8)(pll_div.k>>8)); snd_soc_write(codec, WM8991_PLL3, (u8)(pll_div.k & 0xFF)); } else { /* Turn on PLL */ reg = snd_soc_read(codec, WM8991_POWER_MANAGEMENT_2); reg &= ~WM8991_PLL_ENA; snd_soc_write(codec, WM8991_POWER_MANAGEMENT_2, reg); } return 0; } /* * Set's ADC and Voice DAC format. */ static int wm8991_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; u16 audio1, audio3; audio1 = snd_soc_read(codec, WM8991_AUDIO_INTERFACE_1); audio3 = snd_soc_read(codec, WM8991_AUDIO_INTERFACE_3); /* set master/slave audio interface */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: audio3 &= ~WM8991_AIF_MSTR1; break; case SND_SOC_DAIFMT_CBM_CFM: audio3 |= WM8991_AIF_MSTR1; break; default: return -EINVAL; } audio1 &= ~WM8991_AIF_FMT_MASK; /* interface format */ switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: audio1 |= WM8991_AIF_TMF_I2S; audio1 &= ~WM8991_AIF_LRCLK_INV; break; case SND_SOC_DAIFMT_RIGHT_J: audio1 |= WM8991_AIF_TMF_RIGHTJ; audio1 &= ~WM8991_AIF_LRCLK_INV; break; case SND_SOC_DAIFMT_LEFT_J: audio1 |= WM8991_AIF_TMF_LEFTJ; audio1 &= ~WM8991_AIF_LRCLK_INV; break; case SND_SOC_DAIFMT_DSP_A: audio1 |= WM8991_AIF_TMF_DSP; audio1 &= ~WM8991_AIF_LRCLK_INV; break; case SND_SOC_DAIFMT_DSP_B: audio1 |= WM8991_AIF_TMF_DSP | WM8991_AIF_LRCLK_INV; break; default: return -EINVAL; } snd_soc_write(codec, WM8991_AUDIO_INTERFACE_1, audio1); snd_soc_write(codec, WM8991_AUDIO_INTERFACE_3, audio3); return 0; } static int wm8991_set_dai_clkdiv(struct snd_soc_dai *codec_dai, int div_id, int div) { struct snd_soc_codec *codec = codec_dai->codec; u16 reg; switch (div_id) { case WM8991_MCLK_DIV: reg = snd_soc_read(codec, WM8991_CLOCKING_2) & ~WM8991_MCLK_DIV_MASK; snd_soc_write(codec, WM8991_CLOCKING_2, reg | div); break; case WM8991_DACCLK_DIV: reg = snd_soc_read(codec, WM8991_CLOCKING_2) & ~WM8991_DAC_CLKDIV_MASK; snd_soc_write(codec, WM8991_CLOCKING_2, reg | div); break; case WM8991_ADCCLK_DIV: reg = snd_soc_read(codec, WM8991_CLOCKING_2) & ~WM8991_ADC_CLKDIV_MASK; snd_soc_write(codec, WM8991_CLOCKING_2, reg | div); break; case WM8991_BCLK_DIV: reg = snd_soc_read(codec, WM8991_CLOCKING_1) & ~WM8991_BCLK_DIV_MASK; snd_soc_write(codec, WM8991_CLOCKING_1, reg | div); break; default: return -EINVAL; } return 0; } /* * Set PCM DAI bit size and sample rate. */ static int wm8991_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; u16 audio1 = snd_soc_read(codec, WM8991_AUDIO_INTERFACE_1); audio1 &= ~WM8991_AIF_WL_MASK; /* bit size */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: break; case SNDRV_PCM_FORMAT_S20_3LE: audio1 |= WM8991_AIF_WL_20BITS; break; case SNDRV_PCM_FORMAT_S24_LE: audio1 |= WM8991_AIF_WL_24BITS; break; case SNDRV_PCM_FORMAT_S32_LE: audio1 |= WM8991_AIF_WL_32BITS; break; } snd_soc_write(codec, WM8991_AUDIO_INTERFACE_1, audio1); return 0; } static int wm8991_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = dai->codec; u16 val; val = snd_soc_read(codec, WM8991_DAC_CTRL) & ~WM8991_DAC_MUTE; if (mute) snd_soc_write(codec, WM8991_DAC_CTRL, val | WM8991_DAC_MUTE); else snd_soc_write(codec, WM8991_DAC_CTRL, val); return 0; } static int wm8991_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { u16 val; switch (level) { case SND_SOC_BIAS_ON: break; case SND_SOC_BIAS_PREPARE: /* VMID=2*50k */ val = snd_soc_read(codec, WM8991_POWER_MANAGEMENT_1) & ~WM8991_VMID_MODE_MASK; snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, val | 0x2); break; case SND_SOC_BIAS_STANDBY: if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) { snd_soc_cache_sync(codec); /* Enable all output discharge bits */ snd_soc_write(codec, WM8991_ANTIPOP1, WM8991_DIS_LLINE | WM8991_DIS_RLINE | WM8991_DIS_OUT3 | WM8991_DIS_OUT4 | WM8991_DIS_LOUT | WM8991_DIS_ROUT); /* Enable POBCTRL, SOFT_ST, VMIDTOG and BUFDCOPEN */ snd_soc_write(codec, WM8991_ANTIPOP2, WM8991_SOFTST | WM8991_BUFDCOPEN | WM8991_POBCTRL | WM8991_VMIDTOG); /* Delay to allow output caps to discharge */ msleep(300); /* Disable VMIDTOG */ snd_soc_write(codec, WM8991_ANTIPOP2, WM8991_SOFTST | WM8991_BUFDCOPEN | WM8991_POBCTRL); /* disable all output discharge bits */ snd_soc_write(codec, WM8991_ANTIPOP1, 0); /* Enable outputs */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x1b00); msleep(50); /* Enable VMID at 2x50k */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x1f02); msleep(100); /* Enable VREF */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x1f03); msleep(600); /* Enable BUFIOEN */ snd_soc_write(codec, WM8991_ANTIPOP2, WM8991_SOFTST | WM8991_BUFDCOPEN | WM8991_POBCTRL | WM8991_BUFIOEN); /* Disable outputs */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x3); /* disable POBCTRL, SOFT_ST and BUFDCOPEN */ snd_soc_write(codec, WM8991_ANTIPOP2, WM8991_BUFIOEN); } /* VMID=2*250k */ val = snd_soc_read(codec, WM8991_POWER_MANAGEMENT_1) & ~WM8991_VMID_MODE_MASK; snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, val | 0x4); break; case SND_SOC_BIAS_OFF: /* Enable POBCTRL and SOFT_ST */ snd_soc_write(codec, WM8991_ANTIPOP2, WM8991_SOFTST | WM8991_POBCTRL | WM8991_BUFIOEN); /* Enable POBCTRL, SOFT_ST and BUFDCOPEN */ snd_soc_write(codec, WM8991_ANTIPOP2, WM8991_SOFTST | WM8991_BUFDCOPEN | WM8991_POBCTRL | WM8991_BUFIOEN); /* mute DAC */ val = snd_soc_read(codec, WM8991_DAC_CTRL); snd_soc_write(codec, WM8991_DAC_CTRL, val | WM8991_DAC_MUTE); /* Enable any disabled outputs */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x1f03); /* Disable VMID */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x1f01); msleep(300); /* Enable all output discharge bits */ snd_soc_write(codec, WM8991_ANTIPOP1, WM8991_DIS_LLINE | WM8991_DIS_RLINE | WM8991_DIS_OUT3 | WM8991_DIS_OUT4 | WM8991_DIS_LOUT | WM8991_DIS_ROUT); /* Disable VREF */ snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, 0x0); /* disable POBCTRL, SOFT_ST and BUFDCOPEN */ snd_soc_write(codec, WM8991_ANTIPOP2, 0x0); codec->cache_sync = 1; break; } codec->dapm.bias_level = level; return 0; } static int wm8991_suspend(struct snd_soc_codec *codec, pm_message_t state) { wm8991_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int wm8991_resume(struct snd_soc_codec *codec) { wm8991_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } /* power down chip */ static int wm8991_remove(struct snd_soc_codec *codec) { wm8991_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int wm8991_probe(struct snd_soc_codec *codec) { struct wm8991_priv *wm8991; int ret; unsigned int reg; wm8991 = snd_soc_codec_get_drvdata(codec); ret = snd_soc_codec_set_cache_io(codec, 8, 16, wm8991->control_type); if (ret < 0) { dev_err(codec->dev, "Failed to set cache i/o: %d\n", ret); return ret; } ret = wm8991_reset(codec); if (ret < 0) { dev_err(codec->dev, "Failed to issue reset\n"); return ret; } wm8991_set_bias_level(codec, SND_SOC_BIAS_STANDBY); reg = snd_soc_read(codec, WM8991_AUDIO_INTERFACE_4); snd_soc_write(codec, WM8991_AUDIO_INTERFACE_4, reg | WM8991_ALRCGPIO1); reg = snd_soc_read(codec, WM8991_GPIO1_GPIO2) & ~WM8991_GPIO1_SEL_MASK; snd_soc_write(codec, WM8991_GPIO1_GPIO2, reg | 1); reg = snd_soc_read(codec, WM8991_POWER_MANAGEMENT_1); snd_soc_write(codec, WM8991_POWER_MANAGEMENT_1, reg | WM8991_VREF_ENA| WM8991_VMID_MODE_MASK); reg = snd_soc_read(codec, WM8991_POWER_MANAGEMENT_2); snd_soc_write(codec, WM8991_POWER_MANAGEMENT_2, reg | WM8991_OPCLK_ENA); snd_soc_write(codec, WM8991_DAC_CTRL, 0); snd_soc_write(codec, WM8991_LEFT_OUTPUT_VOLUME, 0x50 | (1<<8)); snd_soc_write(codec, WM8991_RIGHT_OUTPUT_VOLUME, 0x50 | (1<<8)); snd_soc_add_controls(codec, wm8991_snd_controls, ARRAY_SIZE(wm8991_snd_controls)); snd_soc_dapm_new_controls(&codec->dapm, wm8991_dapm_widgets, ARRAY_SIZE(wm8991_dapm_widgets)); snd_soc_dapm_add_routes(&codec->dapm, audio_map, ARRAY_SIZE(audio_map)); return 0; } #define WM8991_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\ SNDRV_PCM_FMTBIT_S24_LE) static struct snd_soc_dai_ops wm8991_ops = { .hw_params = wm8991_hw_params, .digital_mute = wm8991_mute, .set_fmt = wm8991_set_dai_fmt, .set_clkdiv = wm8991_set_dai_clkdiv, .set_pll = wm8991_set_dai_pll }; /* * The WM8991 supports 2 different and mutually exclusive DAI * configurations. * * 1. ADC/DAC on Primary Interface * 2. ADC on Primary Interface/DAC on secondary */ static struct snd_soc_dai_driver wm8991_dai = { /* ADC/DAC on primary */ .name = "wm8991", .id = 1, .playback = { .stream_name = "Playback", .channels_min = 1, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_96000, .formats = WM8991_FORMATS }, .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_96000, .formats = WM8991_FORMATS }, .ops = &wm8991_ops }; static struct snd_soc_codec_driver soc_codec_dev_wm8991 = { .probe = wm8991_probe, .remove = wm8991_remove, .suspend = wm8991_suspend, .resume = wm8991_resume, .set_bias_level = wm8991_set_bias_level, .reg_cache_size = WM8991_MAX_REGISTER + 1, .reg_word_size = sizeof(u16), .reg_cache_default = wm8991_reg_defs }; static __devinit int wm8991_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct wm8991_priv *wm8991; int ret; wm8991 = kzalloc(sizeof *wm8991, GFP_KERNEL); if (!wm8991) return -ENOMEM; wm8991->control_type = SND_SOC_I2C; i2c_set_clientdata(i2c, wm8991); ret = snd_soc_register_codec(&i2c->dev, &soc_codec_dev_wm8991, &wm8991_dai, 1); if (ret < 0) kfree(wm8991); return ret; } static __devexit int wm8991_i2c_remove(struct i2c_client *client) { snd_soc_unregister_codec(&client->dev); kfree(i2c_get_clientdata(client)); return 0; } static const struct i2c_device_id wm8991_i2c_id[] = { { "wm8991", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, wm8991_i2c_id); static struct i2c_driver wm8991_i2c_driver = { .driver = { .name = "wm8991", .owner = THIS_MODULE, }, .probe = wm8991_i2c_probe, .remove = __devexit_p(wm8991_i2c_remove), .id_table = wm8991_i2c_id, }; static int __init wm8991_modinit(void) { int ret; ret = i2c_add_driver(&wm8991_i2c_driver); if (ret != 0) { printk(KERN_ERR "Failed to register WM8991 I2C driver: %d\n", ret); } return 0; } module_init(wm8991_modinit); static void __exit wm8991_exit(void) { i2c_del_driver(&wm8991_i2c_driver); } module_exit(wm8991_exit); MODULE_DESCRIPTION("ASoC WM8991 driver"); MODULE_AUTHOR("Graeme Gregory"); MODULE_LICENSE("GPL");
gpl-2.0
TEAM-Gummy/android_kernel_samsung_d2
arch/arm/mach-ux500/id.c
4811
2324
/* * Copyright (C) ST-Ericsson SA 2010 * * Author: Rabin Vincent <rabin.vincent@stericsson.com> for ST-Ericsson * License terms: GNU General Public License (GPL) version 2 */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/io.h> #include <asm/cputype.h> #include <asm/tlbflush.h> #include <asm/cacheflush.h> #include <asm/mach/map.h> #include <mach/hardware.h> #include <mach/setup.h> struct dbx500_asic_id dbx500_id; static unsigned int ux500_read_asicid(phys_addr_t addr) { phys_addr_t base = addr & ~0xfff; struct map_desc desc = { .virtual = IO_ADDRESS(base), .pfn = __phys_to_pfn(base), .length = SZ_16K, .type = MT_DEVICE, }; iotable_init(&desc, 1); /* As in devicemaps_init() */ local_flush_tlb_all(); flush_cache_all(); return readl(__io_address(addr)); } static void ux500_print_soc_info(unsigned int asicid) { unsigned int rev = dbx500_revision(); pr_info("DB%4x ", dbx500_partnumber()); if (rev == 0x01) pr_cont("Early Drop"); else if (rev >= 0xA0) pr_cont("v%d.%d" , (rev >> 4) - 0xA + 1, rev & 0xf); else pr_cont("Unknown"); pr_cont(" [%#010x]\n", asicid); } static unsigned int partnumber(unsigned int asicid) { return (asicid >> 8) & 0xffff; } /* * SOC MIDR ASICID ADDRESS ASICID VALUE * DB8500ed 0x410fc090 0x9001FFF4 0x00850001 * DB8500v1 0x411fc091 0x9001FFF4 0x008500A0 * DB8500v1.1 0x411fc091 0x9001FFF4 0x008500A1 * DB8500v2 0x412fc091 0x9001DBF4 0x008500B0 * DB8520v2.2 0x412fc091 0x9001DBF4 0x008500B2 * DB5500v1 0x412fc091 0x9001FFF4 0x005500A0 */ void __init ux500_map_io(void) { unsigned int cpuid = read_cpuid_id(); unsigned int asicid = 0; phys_addr_t addr = 0; switch (cpuid) { case 0x410fc090: /* DB8500ed */ case 0x411fc091: /* DB8500v1 */ addr = 0x9001FFF4; break; case 0x412fc091: /* DB8520 / DB8500v2 / DB5500v1 */ asicid = ux500_read_asicid(0x9001DBF4); if (partnumber(asicid) == 0x8500 || partnumber(asicid) == 0x8520) /* DB8500v2 */ break; /* DB5500v1 */ addr = 0x9001FFF4; break; } if (addr) asicid = ux500_read_asicid(addr); if (!asicid) { pr_err("Unable to identify SoC\n"); ux500_unknown_soc(); } dbx500_id.process = asicid >> 24; dbx500_id.partnumber = partnumber(asicid); dbx500_id.revision = asicid & 0xff; ux500_print_soc_info(asicid); }
gpl-2.0
xXminiWHOOPERxX/dlxpul-kernel-final
drivers/staging/media/as102/as102_usb_drv.c
4811
12223
/* * Abilis Systems Single DVB-T Receiver * Copyright (C) 2008 Pierrick Hascoet <pierrick.hascoet@abilis.com> * Copyright (C) 2010 Devin Heitmueller <dheitmueller@kernellabs.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, 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/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/usb.h> #include "as102_drv.h" #include "as102_usb_drv.h" #include "as102_fw.h" static void as102_usb_disconnect(struct usb_interface *interface); static int as102_usb_probe(struct usb_interface *interface, const struct usb_device_id *id); static int as102_usb_start_stream(struct as102_dev_t *dev); static void as102_usb_stop_stream(struct as102_dev_t *dev); static int as102_open(struct inode *inode, struct file *file); static int as102_release(struct inode *inode, struct file *file); static struct usb_device_id as102_usb_id_table[] = { { USB_DEVICE(AS102_USB_DEVICE_VENDOR_ID, AS102_USB_DEVICE_PID_0001) }, { USB_DEVICE(PCTV_74E_USB_VID, PCTV_74E_USB_PID) }, { USB_DEVICE(ELGATO_EYETV_DTT_USB_VID, ELGATO_EYETV_DTT_USB_PID) }, { USB_DEVICE(NBOX_DVBT_DONGLE_USB_VID, NBOX_DVBT_DONGLE_USB_PID) }, { USB_DEVICE(SKY_IT_DIGITAL_KEY_USB_VID, SKY_IT_DIGITAL_KEY_USB_PID) }, { } /* Terminating entry */ }; /* Note that this table must always have the same number of entries as the as102_usb_id_table struct */ static const char * const as102_device_names[] = { AS102_REFERENCE_DESIGN, AS102_PCTV_74E, AS102_ELGATO_EYETV_DTT_NAME, AS102_NBOX_DVBT_DONGLE_NAME, AS102_SKY_IT_DIGITAL_KEY_NAME, NULL /* Terminating entry */ }; /* eLNA configuration: devices built on the reference design work best with 0xA0, while custom designs seem to require 0xC0 */ static uint8_t const as102_elna_cfg[] = { 0xA0, 0xC0, 0xC0, 0xA0, 0xA0, 0x00 /* Terminating entry */ }; struct usb_driver as102_usb_driver = { .name = DRIVER_FULL_NAME, .probe = as102_usb_probe, .disconnect = as102_usb_disconnect, .id_table = as102_usb_id_table }; static const struct file_operations as102_dev_fops = { .owner = THIS_MODULE, .open = as102_open, .release = as102_release, }; static struct usb_class_driver as102_usb_class_driver = { .name = "aton2-%d", .fops = &as102_dev_fops, .minor_base = AS102_DEVICE_MAJOR, }; static int as102_usb_xfer_cmd(struct as10x_bus_adapter_t *bus_adap, unsigned char *send_buf, int send_buf_len, unsigned char *recv_buf, int recv_buf_len) { int ret = 0; ENTER(); if (send_buf != NULL) { ret = usb_control_msg(bus_adap->usb_dev, usb_sndctrlpipe(bus_adap->usb_dev, 0), AS102_USB_DEVICE_TX_CTRL_CMD, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, bus_adap->cmd_xid, /* value */ 0, /* index */ send_buf, send_buf_len, USB_CTRL_SET_TIMEOUT /* 200 */); if (ret < 0) { dprintk(debug, "usb_control_msg(send) failed, err %i\n", ret); return ret; } if (ret != send_buf_len) { dprintk(debug, "only wrote %d of %d bytes\n", ret, send_buf_len); return -1; } } if (recv_buf != NULL) { #ifdef TRACE dprintk(debug, "want to read: %d bytes\n", recv_buf_len); #endif ret = usb_control_msg(bus_adap->usb_dev, usb_rcvctrlpipe(bus_adap->usb_dev, 0), AS102_USB_DEVICE_RX_CTRL_CMD, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, bus_adap->cmd_xid, /* value */ 0, /* index */ recv_buf, recv_buf_len, USB_CTRL_GET_TIMEOUT /* 200 */); if (ret < 0) { dprintk(debug, "usb_control_msg(recv) failed, err %i\n", ret); return ret; } #ifdef TRACE dprintk(debug, "read %d bytes\n", recv_buf_len); #endif } LEAVE(); return ret; } static int as102_send_ep1(struct as10x_bus_adapter_t *bus_adap, unsigned char *send_buf, int send_buf_len, int swap32) { int ret = 0, actual_len; ret = usb_bulk_msg(bus_adap->usb_dev, usb_sndbulkpipe(bus_adap->usb_dev, 1), send_buf, send_buf_len, &actual_len, 200); if (ret) { dprintk(debug, "usb_bulk_msg(send) failed, err %i\n", ret); return ret; } if (actual_len != send_buf_len) { dprintk(debug, "only wrote %d of %d bytes\n", actual_len, send_buf_len); return -1; } return ret ? ret : actual_len; } static int as102_read_ep2(struct as10x_bus_adapter_t *bus_adap, unsigned char *recv_buf, int recv_buf_len) { int ret = 0, actual_len; if (recv_buf == NULL) return -EINVAL; ret = usb_bulk_msg(bus_adap->usb_dev, usb_rcvbulkpipe(bus_adap->usb_dev, 2), recv_buf, recv_buf_len, &actual_len, 200); if (ret) { dprintk(debug, "usb_bulk_msg(recv) failed, err %i\n", ret); return ret; } if (actual_len != recv_buf_len) { dprintk(debug, "only read %d of %d bytes\n", actual_len, recv_buf_len); return -1; } return ret ? ret : actual_len; } struct as102_priv_ops_t as102_priv_ops = { .upload_fw_pkt = as102_send_ep1, .xfer_cmd = as102_usb_xfer_cmd, .as102_read_ep2 = as102_read_ep2, .start_stream = as102_usb_start_stream, .stop_stream = as102_usb_stop_stream, }; static int as102_submit_urb_stream(struct as102_dev_t *dev, struct urb *urb) { int err; usb_fill_bulk_urb(urb, dev->bus_adap.usb_dev, usb_rcvbulkpipe(dev->bus_adap.usb_dev, 0x2), urb->transfer_buffer, AS102_USB_BUF_SIZE, as102_urb_stream_irq, dev); err = usb_submit_urb(urb, GFP_ATOMIC); if (err) dprintk(debug, "%s: usb_submit_urb failed\n", __func__); return err; } void as102_urb_stream_irq(struct urb *urb) { struct as102_dev_t *as102_dev = urb->context; if (urb->actual_length > 0) { dvb_dmx_swfilter(&as102_dev->dvb_dmx, urb->transfer_buffer, urb->actual_length); } else { if (urb->actual_length == 0) memset(urb->transfer_buffer, 0, AS102_USB_BUF_SIZE); } /* is not stopped, re-submit urb */ if (as102_dev->streaming) as102_submit_urb_stream(as102_dev, urb); } static void as102_free_usb_stream_buffer(struct as102_dev_t *dev) { int i; ENTER(); for (i = 0; i < MAX_STREAM_URB; i++) usb_free_urb(dev->stream_urb[i]); usb_free_coherent(dev->bus_adap.usb_dev, MAX_STREAM_URB * AS102_USB_BUF_SIZE, dev->stream, dev->dma_addr); LEAVE(); } static int as102_alloc_usb_stream_buffer(struct as102_dev_t *dev) { int i, ret = 0; ENTER(); dev->stream = usb_alloc_coherent(dev->bus_adap.usb_dev, MAX_STREAM_URB * AS102_USB_BUF_SIZE, GFP_KERNEL, &dev->dma_addr); if (!dev->stream) { dprintk(debug, "%s: usb_buffer_alloc failed\n", __func__); return -ENOMEM; } memset(dev->stream, 0, MAX_STREAM_URB * AS102_USB_BUF_SIZE); /* init urb buffers */ for (i = 0; i < MAX_STREAM_URB; i++) { struct urb *urb; urb = usb_alloc_urb(0, GFP_ATOMIC); if (urb == NULL) { dprintk(debug, "%s: usb_alloc_urb failed\n", __func__); as102_free_usb_stream_buffer(dev); return -ENOMEM; } urb->transfer_buffer = dev->stream + (i * AS102_USB_BUF_SIZE); urb->transfer_dma = dev->dma_addr + (i * AS102_USB_BUF_SIZE); urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP; urb->transfer_buffer_length = AS102_USB_BUF_SIZE; dev->stream_urb[i] = urb; } LEAVE(); return ret; } static void as102_usb_stop_stream(struct as102_dev_t *dev) { int i; for (i = 0; i < MAX_STREAM_URB; i++) usb_kill_urb(dev->stream_urb[i]); } static int as102_usb_start_stream(struct as102_dev_t *dev) { int i, ret = 0; for (i = 0; i < MAX_STREAM_URB; i++) { ret = as102_submit_urb_stream(dev, dev->stream_urb[i]); if (ret) { as102_usb_stop_stream(dev); return ret; } } return 0; } static void as102_usb_release(struct kref *kref) { struct as102_dev_t *as102_dev; ENTER(); as102_dev = container_of(kref, struct as102_dev_t, kref); if (as102_dev != NULL) { usb_put_dev(as102_dev->bus_adap.usb_dev); kfree(as102_dev); } LEAVE(); } static void as102_usb_disconnect(struct usb_interface *intf) { struct as102_dev_t *as102_dev; ENTER(); /* extract as102_dev_t from usb_device private data */ as102_dev = usb_get_intfdata(intf); /* unregister dvb layer */ as102_dvb_unregister(as102_dev); /* free usb buffers */ as102_free_usb_stream_buffer(as102_dev); usb_set_intfdata(intf, NULL); /* usb unregister device */ usb_deregister_dev(intf, &as102_usb_class_driver); /* decrement usage counter */ kref_put(&as102_dev->kref, as102_usb_release); pr_info("%s: device has been disconnected\n", DRIVER_NAME); LEAVE(); } static int as102_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { int ret; struct as102_dev_t *as102_dev; int i; ENTER(); /* This should never actually happen */ if ((sizeof(as102_usb_id_table) / sizeof(struct usb_device_id)) != (sizeof(as102_device_names) / sizeof(const char *))) { pr_err("Device names table invalid size"); return -EINVAL; } as102_dev = kzalloc(sizeof(struct as102_dev_t), GFP_KERNEL); if (as102_dev == NULL) { err("%s: kzalloc failed", __func__); return -ENOMEM; } /* Assign the user-friendly device name */ for (i = 0; i < (sizeof(as102_usb_id_table) / sizeof(struct usb_device_id)); i++) { if (id == &as102_usb_id_table[i]) { as102_dev->name = as102_device_names[i]; as102_dev->elna_cfg = as102_elna_cfg[i]; } } if (as102_dev->name == NULL) as102_dev->name = "Unknown AS102 device"; /* set private callback functions */ as102_dev->bus_adap.ops = &as102_priv_ops; /* init cmd token for usb bus */ as102_dev->bus_adap.cmd = &as102_dev->bus_adap.token.usb.c; as102_dev->bus_adap.rsp = &as102_dev->bus_adap.token.usb.r; /* init kernel device reference */ kref_init(&as102_dev->kref); /* store as102 device to usb_device private data */ usb_set_intfdata(intf, (void *) as102_dev); /* store in as102 device the usb_device pointer */ as102_dev->bus_adap.usb_dev = usb_get_dev(interface_to_usbdev(intf)); /* we can register the device now, as it is ready */ ret = usb_register_dev(intf, &as102_usb_class_driver); if (ret < 0) { /* something prevented us from registering this driver */ err("%s: usb_register_dev() failed (errno = %d)", __func__, ret); goto failed; } pr_info("%s: device has been detected\n", DRIVER_NAME); /* request buffer allocation for streaming */ ret = as102_alloc_usb_stream_buffer(as102_dev); if (ret != 0) goto failed; /* register dvb layer */ ret = as102_dvb_register(as102_dev); LEAVE(); return ret; failed: usb_set_intfdata(intf, NULL); kfree(as102_dev); return ret; } static int as102_open(struct inode *inode, struct file *file) { int ret = 0, minor = 0; struct usb_interface *intf = NULL; struct as102_dev_t *dev = NULL; ENTER(); /* read minor from inode */ minor = iminor(inode); /* fetch device from usb interface */ intf = usb_find_interface(&as102_usb_driver, minor); if (intf == NULL) { pr_err("%s: can't find device for minor %d\n", __func__, minor); ret = -ENODEV; goto exit; } /* get our device */ dev = usb_get_intfdata(intf); if (dev == NULL) { ret = -EFAULT; goto exit; } /* save our device object in the file's private structure */ file->private_data = dev; /* increment our usage count for the device */ kref_get(&dev->kref); exit: LEAVE(); return ret; } static int as102_release(struct inode *inode, struct file *file) { int ret = 0; struct as102_dev_t *dev = NULL; ENTER(); dev = file->private_data; if (dev != NULL) { /* decrement the count on our device */ kref_put(&dev->kref, as102_usb_release); } LEAVE(); return ret; } MODULE_DEVICE_TABLE(usb, as102_usb_id_table);
gpl-2.0
Nothing-Dev/MaxiKernel_condor
sound/soc/codecs/wm8988.c
4811
27756
/* * wm8988.c -- WM8988 ALSA SoC audio driver * * Copyright 2009 Wolfson Microelectronics plc * Copyright 2005 Openedhand Ltd. * * Author: Mark Brown <broonie@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/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/spi/spi.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/tlv.h> #include <sound/soc.h> #include <sound/initval.h> #include "wm8988.h" /* * wm8988 register cache * We can't read the WM8988 register space when we * are using 2 wire for device control, so we cache them instead. */ static const struct reg_default wm8988_reg_defaults[] = { { 0, 0x0097 }, { 1, 0x0097 }, { 2, 0x0079 }, { 3, 0x0079 }, { 5, 0x0008 }, { 7, 0x000a }, { 8, 0x0000 }, { 10, 0x00ff }, { 11, 0x00ff }, { 12, 0x000f }, { 13, 0x000f }, { 16, 0x0000 }, { 17, 0x007b }, { 18, 0x0000 }, { 19, 0x0032 }, { 20, 0x0000 }, { 21, 0x00c3 }, { 22, 0x00c3 }, { 23, 0x00c0 }, { 24, 0x0000 }, { 25, 0x0000 }, { 26, 0x0000 }, { 27, 0x0000 }, { 31, 0x0000 }, { 32, 0x0000 }, { 33, 0x0000 }, { 34, 0x0050 }, { 35, 0x0050 }, { 36, 0x0050 }, { 37, 0x0050 }, { 40, 0x0079 }, { 41, 0x0079 }, { 42, 0x0079 }, }; static bool wm8988_writeable(struct device *dev, unsigned int reg) { switch (reg) { case WM8988_LINVOL: case WM8988_RINVOL: case WM8988_LOUT1V: case WM8988_ROUT1V: case WM8988_ADCDAC: case WM8988_IFACE: case WM8988_SRATE: case WM8988_LDAC: case WM8988_RDAC: case WM8988_BASS: case WM8988_TREBLE: case WM8988_RESET: case WM8988_3D: case WM8988_ALC1: case WM8988_ALC2: case WM8988_ALC3: case WM8988_NGATE: case WM8988_LADC: case WM8988_RADC: case WM8988_ADCTL1: case WM8988_ADCTL2: case WM8988_PWR1: case WM8988_PWR2: case WM8988_ADCTL3: case WM8988_ADCIN: case WM8988_LADCIN: case WM8988_RADCIN: case WM8988_LOUTM1: case WM8988_LOUTM2: case WM8988_ROUTM1: case WM8988_ROUTM2: case WM8988_LOUT2V: case WM8988_ROUT2V: case WM8988_LPPB: return true; default: return false; } } /* codec private data */ struct wm8988_priv { struct regmap *regmap; unsigned int sysclk; struct snd_pcm_hw_constraint_list *sysclk_constraints; }; #define wm8988_reset(c) snd_soc_write(c, WM8988_RESET, 0) /* * WM8988 Controls */ static const char *bass_boost_txt[] = {"Linear Control", "Adaptive Boost"}; static const struct soc_enum bass_boost = SOC_ENUM_SINGLE(WM8988_BASS, 7, 2, bass_boost_txt); static const char *bass_filter_txt[] = { "130Hz @ 48kHz", "200Hz @ 48kHz" }; static const struct soc_enum bass_filter = SOC_ENUM_SINGLE(WM8988_BASS, 6, 2, bass_filter_txt); static const char *treble_txt[] = {"8kHz", "4kHz"}; static const struct soc_enum treble = SOC_ENUM_SINGLE(WM8988_TREBLE, 6, 2, treble_txt); static const char *stereo_3d_lc_txt[] = {"200Hz", "500Hz"}; static const struct soc_enum stereo_3d_lc = SOC_ENUM_SINGLE(WM8988_3D, 5, 2, stereo_3d_lc_txt); static const char *stereo_3d_uc_txt[] = {"2.2kHz", "1.5kHz"}; static const struct soc_enum stereo_3d_uc = SOC_ENUM_SINGLE(WM8988_3D, 6, 2, stereo_3d_uc_txt); static const char *stereo_3d_func_txt[] = {"Capture", "Playback"}; static const struct soc_enum stereo_3d_func = SOC_ENUM_SINGLE(WM8988_3D, 7, 2, stereo_3d_func_txt); static const char *alc_func_txt[] = {"Off", "Right", "Left", "Stereo"}; static const struct soc_enum alc_func = SOC_ENUM_SINGLE(WM8988_ALC1, 7, 4, alc_func_txt); static const char *ng_type_txt[] = {"Constant PGA Gain", "Mute ADC Output"}; static const struct soc_enum ng_type = SOC_ENUM_SINGLE(WM8988_NGATE, 1, 2, ng_type_txt); static const char *deemph_txt[] = {"None", "32Khz", "44.1Khz", "48Khz"}; static const struct soc_enum deemph = SOC_ENUM_SINGLE(WM8988_ADCDAC, 1, 4, deemph_txt); static const char *adcpol_txt[] = {"Normal", "L Invert", "R Invert", "L + R Invert"}; static const struct soc_enum adcpol = SOC_ENUM_SINGLE(WM8988_ADCDAC, 5, 4, adcpol_txt); static const DECLARE_TLV_DB_SCALE(pga_tlv, -1725, 75, 0); static const DECLARE_TLV_DB_SCALE(adc_tlv, -9750, 50, 1); static const DECLARE_TLV_DB_SCALE(dac_tlv, -12750, 50, 1); static const DECLARE_TLV_DB_SCALE(out_tlv, -12100, 100, 1); static const DECLARE_TLV_DB_SCALE(bypass_tlv, -1500, 300, 0); static const struct snd_kcontrol_new wm8988_snd_controls[] = { SOC_ENUM("Bass Boost", bass_boost), SOC_ENUM("Bass Filter", bass_filter), SOC_SINGLE("Bass Volume", WM8988_BASS, 0, 15, 1), SOC_SINGLE("Treble Volume", WM8988_TREBLE, 0, 15, 0), SOC_ENUM("Treble Cut-off", treble), SOC_SINGLE("3D Switch", WM8988_3D, 0, 1, 0), SOC_SINGLE("3D Volume", WM8988_3D, 1, 15, 0), SOC_ENUM("3D Lower Cut-off", stereo_3d_lc), SOC_ENUM("3D Upper Cut-off", stereo_3d_uc), SOC_ENUM("3D Mode", stereo_3d_func), SOC_SINGLE("ALC Capture Target Volume", WM8988_ALC1, 0, 7, 0), SOC_SINGLE("ALC Capture Max Volume", WM8988_ALC1, 4, 7, 0), SOC_ENUM("ALC Capture Function", alc_func), SOC_SINGLE("ALC Capture ZC Switch", WM8988_ALC2, 7, 1, 0), SOC_SINGLE("ALC Capture Hold Time", WM8988_ALC2, 0, 15, 0), SOC_SINGLE("ALC Capture Decay Time", WM8988_ALC3, 4, 15, 0), SOC_SINGLE("ALC Capture Attack Time", WM8988_ALC3, 0, 15, 0), SOC_SINGLE("ALC Capture NG Threshold", WM8988_NGATE, 3, 31, 0), SOC_ENUM("ALC Capture NG Type", ng_type), SOC_SINGLE("ALC Capture NG Switch", WM8988_NGATE, 0, 1, 0), SOC_SINGLE("ZC Timeout Switch", WM8988_ADCTL1, 0, 1, 0), SOC_DOUBLE_R_TLV("Capture Digital Volume", WM8988_LADC, WM8988_RADC, 0, 255, 0, adc_tlv), SOC_DOUBLE_R_TLV("Capture Volume", WM8988_LINVOL, WM8988_RINVOL, 0, 63, 0, pga_tlv), SOC_DOUBLE_R("Capture ZC Switch", WM8988_LINVOL, WM8988_RINVOL, 6, 1, 0), SOC_DOUBLE_R("Capture Switch", WM8988_LINVOL, WM8988_RINVOL, 7, 1, 1), SOC_ENUM("Playback De-emphasis", deemph), SOC_ENUM("Capture Polarity", adcpol), SOC_SINGLE("Playback 6dB Attenuate", WM8988_ADCDAC, 7, 1, 0), SOC_SINGLE("Capture 6dB Attenuate", WM8988_ADCDAC, 8, 1, 0), SOC_DOUBLE_R_TLV("PCM Volume", WM8988_LDAC, WM8988_RDAC, 0, 255, 0, dac_tlv), SOC_SINGLE_TLV("Left Mixer Left Bypass Volume", WM8988_LOUTM1, 4, 7, 1, bypass_tlv), SOC_SINGLE_TLV("Left Mixer Right Bypass Volume", WM8988_LOUTM2, 4, 7, 1, bypass_tlv), SOC_SINGLE_TLV("Right Mixer Left Bypass Volume", WM8988_ROUTM1, 4, 7, 1, bypass_tlv), SOC_SINGLE_TLV("Right Mixer Right Bypass Volume", WM8988_ROUTM2, 4, 7, 1, bypass_tlv), SOC_DOUBLE_R("Output 1 Playback ZC Switch", WM8988_LOUT1V, WM8988_ROUT1V, 7, 1, 0), SOC_DOUBLE_R_TLV("Output 1 Playback Volume", WM8988_LOUT1V, WM8988_ROUT1V, 0, 127, 0, out_tlv), SOC_DOUBLE_R("Output 2 Playback ZC Switch", WM8988_LOUT2V, WM8988_ROUT2V, 7, 1, 0), SOC_DOUBLE_R_TLV("Output 2 Playback Volume", WM8988_LOUT2V, WM8988_ROUT2V, 0, 127, 0, out_tlv), }; /* * DAPM Controls */ static int wm8988_lrc_control(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; u16 adctl2 = snd_soc_read(codec, WM8988_ADCTL2); /* Use the DAC to gate LRC if active, otherwise use ADC */ if (snd_soc_read(codec, WM8988_PWR2) & 0x180) adctl2 &= ~0x4; else adctl2 |= 0x4; return snd_soc_write(codec, WM8988_ADCTL2, adctl2); } static const char *wm8988_line_texts[] = { "Line 1", "Line 2", "PGA", "Differential"}; static const unsigned int wm8988_line_values[] = { 0, 1, 3, 4}; static const struct soc_enum wm8988_lline_enum = SOC_VALUE_ENUM_SINGLE(WM8988_LOUTM1, 0, 7, ARRAY_SIZE(wm8988_line_texts), wm8988_line_texts, wm8988_line_values); static const struct snd_kcontrol_new wm8988_left_line_controls = SOC_DAPM_VALUE_ENUM("Route", wm8988_lline_enum); static const struct soc_enum wm8988_rline_enum = SOC_VALUE_ENUM_SINGLE(WM8988_ROUTM1, 0, 7, ARRAY_SIZE(wm8988_line_texts), wm8988_line_texts, wm8988_line_values); static const struct snd_kcontrol_new wm8988_right_line_controls = SOC_DAPM_VALUE_ENUM("Route", wm8988_lline_enum); /* Left Mixer */ static const struct snd_kcontrol_new wm8988_left_mixer_controls[] = { SOC_DAPM_SINGLE("Playback Switch", WM8988_LOUTM1, 8, 1, 0), SOC_DAPM_SINGLE("Left Bypass Switch", WM8988_LOUTM1, 7, 1, 0), SOC_DAPM_SINGLE("Right Playback Switch", WM8988_LOUTM2, 8, 1, 0), SOC_DAPM_SINGLE("Right Bypass Switch", WM8988_LOUTM2, 7, 1, 0), }; /* Right Mixer */ static const struct snd_kcontrol_new wm8988_right_mixer_controls[] = { SOC_DAPM_SINGLE("Left Playback Switch", WM8988_ROUTM1, 8, 1, 0), SOC_DAPM_SINGLE("Left Bypass Switch", WM8988_ROUTM1, 7, 1, 0), SOC_DAPM_SINGLE("Playback Switch", WM8988_ROUTM2, 8, 1, 0), SOC_DAPM_SINGLE("Right Bypass Switch", WM8988_ROUTM2, 7, 1, 0), }; static const char *wm8988_pga_sel[] = {"Line 1", "Line 2", "Differential"}; static const unsigned int wm8988_pga_val[] = { 0, 1, 3 }; /* Left PGA Mux */ static const struct soc_enum wm8988_lpga_enum = SOC_VALUE_ENUM_SINGLE(WM8988_LADCIN, 6, 3, ARRAY_SIZE(wm8988_pga_sel), wm8988_pga_sel, wm8988_pga_val); static const struct snd_kcontrol_new wm8988_left_pga_controls = SOC_DAPM_VALUE_ENUM("Route", wm8988_lpga_enum); /* Right PGA Mux */ static const struct soc_enum wm8988_rpga_enum = SOC_VALUE_ENUM_SINGLE(WM8988_RADCIN, 6, 3, ARRAY_SIZE(wm8988_pga_sel), wm8988_pga_sel, wm8988_pga_val); static const struct snd_kcontrol_new wm8988_right_pga_controls = SOC_DAPM_VALUE_ENUM("Route", wm8988_rpga_enum); /* Differential Mux */ static const char *wm8988_diff_sel[] = {"Line 1", "Line 2"}; static const struct soc_enum diffmux = SOC_ENUM_SINGLE(WM8988_ADCIN, 8, 2, wm8988_diff_sel); static const struct snd_kcontrol_new wm8988_diffmux_controls = SOC_DAPM_ENUM("Route", diffmux); /* Mono ADC Mux */ static const char *wm8988_mono_mux[] = {"Stereo", "Mono (Left)", "Mono (Right)", "Digital Mono"}; static const struct soc_enum monomux = SOC_ENUM_SINGLE(WM8988_ADCIN, 6, 4, wm8988_mono_mux); static const struct snd_kcontrol_new wm8988_monomux_controls = SOC_DAPM_ENUM("Route", monomux); static const struct snd_soc_dapm_widget wm8988_dapm_widgets[] = { SND_SOC_DAPM_SUPPLY("Mic Bias", WM8988_PWR1, 1, 0, NULL, 0), SND_SOC_DAPM_MUX("Differential Mux", SND_SOC_NOPM, 0, 0, &wm8988_diffmux_controls), SND_SOC_DAPM_MUX("Left ADC Mux", SND_SOC_NOPM, 0, 0, &wm8988_monomux_controls), SND_SOC_DAPM_MUX("Right ADC Mux", SND_SOC_NOPM, 0, 0, &wm8988_monomux_controls), SND_SOC_DAPM_MUX("Left PGA Mux", WM8988_PWR1, 5, 0, &wm8988_left_pga_controls), SND_SOC_DAPM_MUX("Right PGA Mux", WM8988_PWR1, 4, 0, &wm8988_right_pga_controls), SND_SOC_DAPM_MUX("Left Line Mux", SND_SOC_NOPM, 0, 0, &wm8988_left_line_controls), SND_SOC_DAPM_MUX("Right Line Mux", SND_SOC_NOPM, 0, 0, &wm8988_right_line_controls), SND_SOC_DAPM_ADC("Right ADC", "Right Capture", WM8988_PWR1, 2, 0), SND_SOC_DAPM_ADC("Left ADC", "Left Capture", WM8988_PWR1, 3, 0), SND_SOC_DAPM_DAC("Right DAC", "Right Playback", WM8988_PWR2, 7, 0), SND_SOC_DAPM_DAC("Left DAC", "Left Playback", WM8988_PWR2, 8, 0), SND_SOC_DAPM_MIXER("Left Mixer", SND_SOC_NOPM, 0, 0, &wm8988_left_mixer_controls[0], ARRAY_SIZE(wm8988_left_mixer_controls)), SND_SOC_DAPM_MIXER("Right Mixer", SND_SOC_NOPM, 0, 0, &wm8988_right_mixer_controls[0], ARRAY_SIZE(wm8988_right_mixer_controls)), SND_SOC_DAPM_PGA("Right Out 2", WM8988_PWR2, 3, 0, NULL, 0), SND_SOC_DAPM_PGA("Left Out 2", WM8988_PWR2, 4, 0, NULL, 0), SND_SOC_DAPM_PGA("Right Out 1", WM8988_PWR2, 5, 0, NULL, 0), SND_SOC_DAPM_PGA("Left Out 1", WM8988_PWR2, 6, 0, NULL, 0), SND_SOC_DAPM_POST("LRC control", wm8988_lrc_control), SND_SOC_DAPM_OUTPUT("LOUT1"), SND_SOC_DAPM_OUTPUT("ROUT1"), SND_SOC_DAPM_OUTPUT("LOUT2"), SND_SOC_DAPM_OUTPUT("ROUT2"), SND_SOC_DAPM_OUTPUT("VREF"), SND_SOC_DAPM_INPUT("LINPUT1"), SND_SOC_DAPM_INPUT("LINPUT2"), SND_SOC_DAPM_INPUT("RINPUT1"), SND_SOC_DAPM_INPUT("RINPUT2"), }; static const struct snd_soc_dapm_route wm8988_dapm_routes[] = { { "Left Line Mux", "Line 1", "LINPUT1" }, { "Left Line Mux", "Line 2", "LINPUT2" }, { "Left Line Mux", "PGA", "Left PGA Mux" }, { "Left Line Mux", "Differential", "Differential Mux" }, { "Right Line Mux", "Line 1", "RINPUT1" }, { "Right Line Mux", "Line 2", "RINPUT2" }, { "Right Line Mux", "PGA", "Right PGA Mux" }, { "Right Line Mux", "Differential", "Differential Mux" }, { "Left PGA Mux", "Line 1", "LINPUT1" }, { "Left PGA Mux", "Line 2", "LINPUT2" }, { "Left PGA Mux", "Differential", "Differential Mux" }, { "Right PGA Mux", "Line 1", "RINPUT1" }, { "Right PGA Mux", "Line 2", "RINPUT2" }, { "Right PGA Mux", "Differential", "Differential Mux" }, { "Differential Mux", "Line 1", "LINPUT1" }, { "Differential Mux", "Line 1", "RINPUT1" }, { "Differential Mux", "Line 2", "LINPUT2" }, { "Differential Mux", "Line 2", "RINPUT2" }, { "Left ADC Mux", "Stereo", "Left PGA Mux" }, { "Left ADC Mux", "Mono (Left)", "Left PGA Mux" }, { "Left ADC Mux", "Digital Mono", "Left PGA Mux" }, { "Right ADC Mux", "Stereo", "Right PGA Mux" }, { "Right ADC Mux", "Mono (Right)", "Right PGA Mux" }, { "Right ADC Mux", "Digital Mono", "Right PGA Mux" }, { "Left ADC", NULL, "Left ADC Mux" }, { "Right ADC", NULL, "Right ADC Mux" }, { "Left Line Mux", "Line 1", "LINPUT1" }, { "Left Line Mux", "Line 2", "LINPUT2" }, { "Left Line Mux", "PGA", "Left PGA Mux" }, { "Left Line Mux", "Differential", "Differential Mux" }, { "Right Line Mux", "Line 1", "RINPUT1" }, { "Right Line Mux", "Line 2", "RINPUT2" }, { "Right Line Mux", "PGA", "Right PGA Mux" }, { "Right Line Mux", "Differential", "Differential Mux" }, { "Left Mixer", "Playback Switch", "Left DAC" }, { "Left Mixer", "Left Bypass Switch", "Left Line Mux" }, { "Left Mixer", "Right Playback Switch", "Right DAC" }, { "Left Mixer", "Right Bypass Switch", "Right Line Mux" }, { "Right Mixer", "Left Playback Switch", "Left DAC" }, { "Right Mixer", "Left Bypass Switch", "Left Line Mux" }, { "Right Mixer", "Playback Switch", "Right DAC" }, { "Right Mixer", "Right Bypass Switch", "Right Line Mux" }, { "Left Out 1", NULL, "Left Mixer" }, { "LOUT1", NULL, "Left Out 1" }, { "Right Out 1", NULL, "Right Mixer" }, { "ROUT1", NULL, "Right Out 1" }, { "Left Out 2", NULL, "Left Mixer" }, { "LOUT2", NULL, "Left Out 2" }, { "Right Out 2", NULL, "Right Mixer" }, { "ROUT2", NULL, "Right Out 2" }, }; struct _coeff_div { u32 mclk; u32 rate; u16 fs; u8 sr:5; u8 usb:1; }; /* codec hifi mclk clock divider coefficients */ static const struct _coeff_div coeff_div[] = { /* 8k */ {12288000, 8000, 1536, 0x6, 0x0}, {11289600, 8000, 1408, 0x16, 0x0}, {18432000, 8000, 2304, 0x7, 0x0}, {16934400, 8000, 2112, 0x17, 0x0}, {12000000, 8000, 1500, 0x6, 0x1}, /* 11.025k */ {11289600, 11025, 1024, 0x18, 0x0}, {16934400, 11025, 1536, 0x19, 0x0}, {12000000, 11025, 1088, 0x19, 0x1}, /* 16k */ {12288000, 16000, 768, 0xa, 0x0}, {18432000, 16000, 1152, 0xb, 0x0}, {12000000, 16000, 750, 0xa, 0x1}, /* 22.05k */ {11289600, 22050, 512, 0x1a, 0x0}, {16934400, 22050, 768, 0x1b, 0x0}, {12000000, 22050, 544, 0x1b, 0x1}, /* 32k */ {12288000, 32000, 384, 0xc, 0x0}, {18432000, 32000, 576, 0xd, 0x0}, {12000000, 32000, 375, 0xa, 0x1}, /* 44.1k */ {11289600, 44100, 256, 0x10, 0x0}, {16934400, 44100, 384, 0x11, 0x0}, {12000000, 44100, 272, 0x11, 0x1}, /* 48k */ {12288000, 48000, 256, 0x0, 0x0}, {18432000, 48000, 384, 0x1, 0x0}, {12000000, 48000, 250, 0x0, 0x1}, /* 88.2k */ {11289600, 88200, 128, 0x1e, 0x0}, {16934400, 88200, 192, 0x1f, 0x0}, {12000000, 88200, 136, 0x1f, 0x1}, /* 96k */ {12288000, 96000, 128, 0xe, 0x0}, {18432000, 96000, 192, 0xf, 0x0}, {12000000, 96000, 125, 0xe, 0x1}, }; static inline int get_coeff(int mclk, int rate) { int i; for (i = 0; i < ARRAY_SIZE(coeff_div); i++) { if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) return i; } return -EINVAL; } /* The set of rates we can generate from the above for each SYSCLK */ static unsigned int rates_12288[] = { 8000, 12000, 16000, 24000, 24000, 32000, 48000, 96000, }; static struct snd_pcm_hw_constraint_list constraints_12288 = { .count = ARRAY_SIZE(rates_12288), .list = rates_12288, }; static unsigned int rates_112896[] = { 8000, 11025, 22050, 44100, }; static struct snd_pcm_hw_constraint_list constraints_112896 = { .count = ARRAY_SIZE(rates_112896), .list = rates_112896, }; static unsigned int rates_12[] = { 8000, 11025, 12000, 16000, 22050, 2400, 32000, 41100, 48000, 48000, 88235, 96000, }; static struct snd_pcm_hw_constraint_list constraints_12 = { .count = ARRAY_SIZE(rates_12), .list = rates_12, }; /* * Note that this should be called from init rather than from hw_params. */ static int wm8988_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct wm8988_priv *wm8988 = snd_soc_codec_get_drvdata(codec); switch (freq) { case 11289600: case 18432000: case 22579200: case 36864000: wm8988->sysclk_constraints = &constraints_112896; wm8988->sysclk = freq; return 0; case 12288000: case 16934400: case 24576000: case 33868800: wm8988->sysclk_constraints = &constraints_12288; wm8988->sysclk = freq; return 0; case 12000000: case 24000000: wm8988->sysclk_constraints = &constraints_12; wm8988->sysclk = freq; return 0; } return -EINVAL; } static int wm8988_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; u16 iface = 0; /* set master/slave audio interface */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: iface = 0x0040; break; case SND_SOC_DAIFMT_CBS_CFS: break; default: return -EINVAL; } /* interface format */ switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: iface |= 0x0002; break; case SND_SOC_DAIFMT_RIGHT_J: break; case SND_SOC_DAIFMT_LEFT_J: iface |= 0x0001; break; case SND_SOC_DAIFMT_DSP_A: iface |= 0x0003; break; case SND_SOC_DAIFMT_DSP_B: iface |= 0x0013; break; default: return -EINVAL; } /* clock inversion */ switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: break; case SND_SOC_DAIFMT_IB_IF: iface |= 0x0090; break; case SND_SOC_DAIFMT_IB_NF: iface |= 0x0080; break; case SND_SOC_DAIFMT_NB_IF: iface |= 0x0010; break; default: return -EINVAL; } snd_soc_write(codec, WM8988_IFACE, iface); return 0; } static int wm8988_pcm_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct wm8988_priv *wm8988 = snd_soc_codec_get_drvdata(codec); /* The set of sample rates that can be supported depends on the * MCLK supplied to the CODEC - enforce this. */ if (!wm8988->sysclk) { dev_err(codec->dev, "No MCLK configured, call set_sysclk() on init\n"); return -EINVAL; } snd_pcm_hw_constraint_list(substream->runtime, 0, SNDRV_PCM_HW_PARAM_RATE, wm8988->sysclk_constraints); return 0; } static int wm8988_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct wm8988_priv *wm8988 = snd_soc_codec_get_drvdata(codec); u16 iface = snd_soc_read(codec, WM8988_IFACE) & 0x1f3; u16 srate = snd_soc_read(codec, WM8988_SRATE) & 0x180; int coeff; coeff = get_coeff(wm8988->sysclk, params_rate(params)); if (coeff < 0) { coeff = get_coeff(wm8988->sysclk / 2, params_rate(params)); srate |= 0x40; } if (coeff < 0) { dev_err(codec->dev, "Unable to configure sample rate %dHz with %dHz MCLK\n", params_rate(params), wm8988->sysclk); return coeff; } /* bit size */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: break; case SNDRV_PCM_FORMAT_S20_3LE: iface |= 0x0004; break; case SNDRV_PCM_FORMAT_S24_LE: iface |= 0x0008; break; case SNDRV_PCM_FORMAT_S32_LE: iface |= 0x000c; break; } /* set iface & srate */ snd_soc_write(codec, WM8988_IFACE, iface); if (coeff >= 0) snd_soc_write(codec, WM8988_SRATE, srate | (coeff_div[coeff].sr << 1) | coeff_div[coeff].usb); return 0; } static int wm8988_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = dai->codec; u16 mute_reg = snd_soc_read(codec, WM8988_ADCDAC) & 0xfff7; if (mute) snd_soc_write(codec, WM8988_ADCDAC, mute_reg | 0x8); else snd_soc_write(codec, WM8988_ADCDAC, mute_reg); return 0; } static int wm8988_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { struct wm8988_priv *wm8988 = snd_soc_codec_get_drvdata(codec); u16 pwr_reg = snd_soc_read(codec, WM8988_PWR1) & ~0x1c1; switch (level) { case SND_SOC_BIAS_ON: break; case SND_SOC_BIAS_PREPARE: /* VREF, VMID=2x50k, digital enabled */ snd_soc_write(codec, WM8988_PWR1, pwr_reg | 0x00c0); break; case SND_SOC_BIAS_STANDBY: if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) { regcache_sync(wm8988->regmap); /* VREF, VMID=2x5k */ snd_soc_write(codec, WM8988_PWR1, pwr_reg | 0x1c1); /* Charge caps */ msleep(100); } /* VREF, VMID=2*500k, digital stopped */ snd_soc_write(codec, WM8988_PWR1, pwr_reg | 0x0141); break; case SND_SOC_BIAS_OFF: snd_soc_write(codec, WM8988_PWR1, 0x0000); break; } codec->dapm.bias_level = level; return 0; } #define WM8988_RATES SNDRV_PCM_RATE_8000_96000 #define WM8988_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\ SNDRV_PCM_FMTBIT_S24_LE) static const struct snd_soc_dai_ops wm8988_ops = { .startup = wm8988_pcm_startup, .hw_params = wm8988_pcm_hw_params, .set_fmt = wm8988_set_dai_fmt, .set_sysclk = wm8988_set_dai_sysclk, .digital_mute = wm8988_mute, }; static struct snd_soc_dai_driver wm8988_dai = { .name = "wm8988-hifi", .playback = { .stream_name = "Playback", .channels_min = 1, .channels_max = 2, .rates = WM8988_RATES, .formats = WM8988_FORMATS, }, .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 2, .rates = WM8988_RATES, .formats = WM8988_FORMATS, }, .ops = &wm8988_ops, .symmetric_rates = 1, }; static int wm8988_suspend(struct snd_soc_codec *codec) { struct wm8988_priv *wm8988 = snd_soc_codec_get_drvdata(codec); wm8988_set_bias_level(codec, SND_SOC_BIAS_OFF); regcache_mark_dirty(wm8988->regmap); return 0; } static int wm8988_resume(struct snd_soc_codec *codec) { wm8988_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static int wm8988_probe(struct snd_soc_codec *codec) { struct wm8988_priv *wm8988 = snd_soc_codec_get_drvdata(codec); int ret = 0; codec->control_data = wm8988->regmap; ret = snd_soc_codec_set_cache_io(codec, 7, 9, SND_SOC_REGMAP); if (ret < 0) { dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret); return ret; } ret = wm8988_reset(codec); if (ret < 0) { dev_err(codec->dev, "Failed to issue reset\n"); return ret; } /* set the update bits (we always update left then right) */ snd_soc_update_bits(codec, WM8988_RADC, 0x0100, 0x0100); snd_soc_update_bits(codec, WM8988_RDAC, 0x0100, 0x0100); snd_soc_update_bits(codec, WM8988_ROUT1V, 0x0100, 0x0100); snd_soc_update_bits(codec, WM8988_ROUT2V, 0x0100, 0x0100); snd_soc_update_bits(codec, WM8988_RINVOL, 0x0100, 0x0100); wm8988_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static int wm8988_remove(struct snd_soc_codec *codec) { wm8988_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static struct snd_soc_codec_driver soc_codec_dev_wm8988 = { .probe = wm8988_probe, .remove = wm8988_remove, .suspend = wm8988_suspend, .resume = wm8988_resume, .set_bias_level = wm8988_set_bias_level, .controls = wm8988_snd_controls, .num_controls = ARRAY_SIZE(wm8988_snd_controls), .dapm_widgets = wm8988_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(wm8988_dapm_widgets), .dapm_routes = wm8988_dapm_routes, .num_dapm_routes = ARRAY_SIZE(wm8988_dapm_routes), }; static struct regmap_config wm8988_regmap = { .reg_bits = 7, .val_bits = 9, .max_register = WM8988_LPPB, .writeable_reg = wm8988_writeable, .cache_type = REGCACHE_RBTREE, .reg_defaults = wm8988_reg_defaults, .num_reg_defaults = ARRAY_SIZE(wm8988_reg_defaults), }; #if defined(CONFIG_SPI_MASTER) static int __devinit wm8988_spi_probe(struct spi_device *spi) { struct wm8988_priv *wm8988; int ret; wm8988 = devm_kzalloc(&spi->dev, sizeof(struct wm8988_priv), GFP_KERNEL); if (wm8988 == NULL) return -ENOMEM; wm8988->regmap = regmap_init_spi(spi, &wm8988_regmap); if (IS_ERR(wm8988->regmap)) { ret = PTR_ERR(wm8988->regmap); dev_err(&spi->dev, "Failed to init regmap: %d\n", ret); return ret; } spi_set_drvdata(spi, wm8988); ret = snd_soc_register_codec(&spi->dev, &soc_codec_dev_wm8988, &wm8988_dai, 1); if (ret != 0) regmap_exit(wm8988->regmap); return ret; } static int __devexit wm8988_spi_remove(struct spi_device *spi) { struct wm8988_priv *wm8988 = spi_get_drvdata(spi); snd_soc_unregister_codec(&spi->dev); regmap_exit(wm8988->regmap); return 0; } static struct spi_driver wm8988_spi_driver = { .driver = { .name = "wm8988", .owner = THIS_MODULE, }, .probe = wm8988_spi_probe, .remove = __devexit_p(wm8988_spi_remove), }; #endif /* CONFIG_SPI_MASTER */ #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) static __devinit int wm8988_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct wm8988_priv *wm8988; int ret; wm8988 = devm_kzalloc(&i2c->dev, sizeof(struct wm8988_priv), GFP_KERNEL); if (wm8988 == NULL) return -ENOMEM; i2c_set_clientdata(i2c, wm8988); wm8988->regmap = regmap_init_i2c(i2c, &wm8988_regmap); if (IS_ERR(wm8988->regmap)) { ret = PTR_ERR(wm8988->regmap); dev_err(&i2c->dev, "Failed to init regmap: %d\n", ret); return ret; } ret = snd_soc_register_codec(&i2c->dev, &soc_codec_dev_wm8988, &wm8988_dai, 1); if (ret != 0) regmap_exit(wm8988->regmap); return ret; } static __devexit int wm8988_i2c_remove(struct i2c_client *client) { struct wm8988_priv *wm8988 = i2c_get_clientdata(client); snd_soc_unregister_codec(&client->dev); regmap_exit(wm8988->regmap); return 0; } static const struct i2c_device_id wm8988_i2c_id[] = { { "wm8988", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, wm8988_i2c_id); static struct i2c_driver wm8988_i2c_driver = { .driver = { .name = "wm8988", .owner = THIS_MODULE, }, .probe = wm8988_i2c_probe, .remove = __devexit_p(wm8988_i2c_remove), .id_table = wm8988_i2c_id, }; #endif static int __init wm8988_modinit(void) { int ret = 0; #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) ret = i2c_add_driver(&wm8988_i2c_driver); if (ret != 0) { printk(KERN_ERR "Failed to register WM8988 I2C driver: %d\n", ret); } #endif #if defined(CONFIG_SPI_MASTER) ret = spi_register_driver(&wm8988_spi_driver); if (ret != 0) { printk(KERN_ERR "Failed to register WM8988 SPI driver: %d\n", ret); } #endif return ret; } module_init(wm8988_modinit); static void __exit wm8988_exit(void) { #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) i2c_del_driver(&wm8988_i2c_driver); #endif #if defined(CONFIG_SPI_MASTER) spi_unregister_driver(&wm8988_spi_driver); #endif } module_exit(wm8988_exit); MODULE_DESCRIPTION("ASoC WM8988 driver"); MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>"); MODULE_LICENSE("GPL");
gpl-2.0
supersonicninja/CAF-Kernel
drivers/misc/bmp085.c
4811
13099
/* Copyright (c) 2010 Christoph Mair <christoph.mair@gmail.com> This driver supports the bmp085 digital barometric pressure and temperature sensor from Bosch Sensortec. The datasheet is available from their website: http://www.bosch-sensortec.com/content/language1/downloads/BST-BMP085-DS000-05.pdf A pressure measurement is issued by reading from pressure0_input. The return value ranges from 30000 to 110000 pascal with a resulution of 1 pascal (0.01 millibar) which enables measurements from 9000m above to 500m below sea level. The temperature can be read from temp0_input. Values range from -400 to 850 representing the ambient temperature in degree celsius multiplied by 10.The resolution is 0.1 celsius. Because ambient pressure is temperature dependent, a temperature measurement will be executed automatically even if the user is reading from pressure0_input. This happens if the last temperature measurement has been executed more then one second ago. To decrease RMS noise from pressure measurements, the bmp085 can autonomously calculate the average of up to eight samples. This is set up by writing to the oversampling sysfs file. Accepted values are 0, 1, 2 and 3. 2^x when x is the value written to this file specifies the number of samples used to calculate the ambient pressure. RMS noise is specified with six pascal (without averaging) and decreases down to 3 pascal when using an oversampling setting of 3. 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/init.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/delay.h> #define BMP085_I2C_ADDRESS 0x77 #define BMP085_CHIP_ID 0x55 #define BMP085_CALIBRATION_DATA_START 0xAA #define BMP085_CALIBRATION_DATA_LENGTH 11 /* 16 bit values */ #define BMP085_CHIP_ID_REG 0xD0 #define BMP085_VERSION_REG 0xD1 #define BMP085_CTRL_REG 0xF4 #define BMP085_TEMP_MEASUREMENT 0x2E #define BMP085_PRESSURE_MEASUREMENT 0x34 #define BMP085_CONVERSION_REGISTER_MSB 0xF6 #define BMP085_CONVERSION_REGISTER_LSB 0xF7 #define BMP085_CONVERSION_REGISTER_XLSB 0xF8 #define BMP085_TEMP_CONVERSION_TIME 5 #define BMP085_CLIENT_NAME "bmp085" static const unsigned short normal_i2c[] = { BMP085_I2C_ADDRESS, I2C_CLIENT_END }; struct bmp085_calibration_data { s16 AC1, AC2, AC3; u16 AC4, AC5, AC6; s16 B1, B2; s16 MB, MC, MD; }; /* Each client has this additional data */ struct bmp085_data { struct i2c_client *client; struct mutex lock; struct bmp085_calibration_data calibration; u32 raw_temperature; u32 raw_pressure; unsigned char oversampling_setting; unsigned long last_temp_measurement; s32 b6; /* calculated temperature correction coefficient */ }; static s32 bmp085_read_calibration_data(struct i2c_client *client) { u16 tmp[BMP085_CALIBRATION_DATA_LENGTH]; struct bmp085_data *data = i2c_get_clientdata(client); struct bmp085_calibration_data *cali = &(data->calibration); s32 status = i2c_smbus_read_i2c_block_data(client, BMP085_CALIBRATION_DATA_START, BMP085_CALIBRATION_DATA_LENGTH*sizeof(u16), (u8 *)tmp); if (status < 0) return status; if (status != BMP085_CALIBRATION_DATA_LENGTH*sizeof(u16)) return -EIO; cali->AC1 = be16_to_cpu(tmp[0]); cali->AC2 = be16_to_cpu(tmp[1]); cali->AC3 = be16_to_cpu(tmp[2]); cali->AC4 = be16_to_cpu(tmp[3]); cali->AC5 = be16_to_cpu(tmp[4]); cali->AC6 = be16_to_cpu(tmp[5]); cali->B1 = be16_to_cpu(tmp[6]); cali->B2 = be16_to_cpu(tmp[7]); cali->MB = be16_to_cpu(tmp[8]); cali->MC = be16_to_cpu(tmp[9]); cali->MD = be16_to_cpu(tmp[10]); return 0; } static s32 bmp085_update_raw_temperature(struct bmp085_data *data) { u16 tmp; s32 status; mutex_lock(&data->lock); status = i2c_smbus_write_byte_data(data->client, BMP085_CTRL_REG, BMP085_TEMP_MEASUREMENT); if (status != 0) { dev_err(&data->client->dev, "Error while requesting temperature measurement.\n"); goto exit; } msleep(BMP085_TEMP_CONVERSION_TIME); status = i2c_smbus_read_i2c_block_data(data->client, BMP085_CONVERSION_REGISTER_MSB, sizeof(tmp), (u8 *)&tmp); if (status < 0) goto exit; if (status != sizeof(tmp)) { dev_err(&data->client->dev, "Error while reading temperature measurement result\n"); status = -EIO; goto exit; } data->raw_temperature = be16_to_cpu(tmp); data->last_temp_measurement = jiffies; status = 0; /* everything ok, return 0 */ exit: mutex_unlock(&data->lock); return status; } static s32 bmp085_update_raw_pressure(struct bmp085_data *data) { u32 tmp = 0; s32 status; mutex_lock(&data->lock); status = i2c_smbus_write_byte_data(data->client, BMP085_CTRL_REG, BMP085_PRESSURE_MEASUREMENT + (data->oversampling_setting<<6)); if (status != 0) { dev_err(&data->client->dev, "Error while requesting pressure measurement.\n"); goto exit; } /* wait for the end of conversion */ msleep(2+(3 << data->oversampling_setting)); /* copy data into a u32 (4 bytes), but skip the first byte. */ status = i2c_smbus_read_i2c_block_data(data->client, BMP085_CONVERSION_REGISTER_MSB, 3, ((u8 *)&tmp)+1); if (status < 0) goto exit; if (status != 3) { dev_err(&data->client->dev, "Error while reading pressure measurement results\n"); status = -EIO; goto exit; } data->raw_pressure = be32_to_cpu((tmp)); data->raw_pressure >>= (8-data->oversampling_setting); status = 0; /* everything ok, return 0 */ exit: mutex_unlock(&data->lock); return status; } /* * This function starts the temperature measurement and returns the value * in tenth of a degree celsius. */ static s32 bmp085_get_temperature(struct bmp085_data *data, int *temperature) { struct bmp085_calibration_data *cali = &data->calibration; long x1, x2; int status; status = bmp085_update_raw_temperature(data); if (status != 0) goto exit; x1 = ((data->raw_temperature - cali->AC6) * cali->AC5) >> 15; x2 = (cali->MC << 11) / (x1 + cali->MD); data->b6 = x1 + x2 - 4000; /* if NULL just update b6. Used for pressure only measurements */ if (temperature != NULL) *temperature = (x1+x2+8) >> 4; exit: return status; } /* * This function starts the pressure measurement and returns the value * in millibar. Since the pressure depends on the ambient temperature, * a temperature measurement is executed if the last known value is older * than one second. */ static s32 bmp085_get_pressure(struct bmp085_data *data, int *pressure) { struct bmp085_calibration_data *cali = &data->calibration; s32 x1, x2, x3, b3; u32 b4, b7; s32 p; int status; /* alt least every second force an update of the ambient temperature */ if (data->last_temp_measurement == 0 || time_is_before_jiffies(data->last_temp_measurement + 1*HZ)) { status = bmp085_get_temperature(data, NULL); if (status != 0) goto exit; } status = bmp085_update_raw_pressure(data); if (status != 0) goto exit; x1 = (data->b6 * data->b6) >> 12; x1 *= cali->B2; x1 >>= 11; x2 = cali->AC2 * data->b6; x2 >>= 11; x3 = x1 + x2; b3 = (((((s32)cali->AC1) * 4 + x3) << data->oversampling_setting) + 2); b3 >>= 2; x1 = (cali->AC3 * data->b6) >> 13; x2 = (cali->B1 * ((data->b6 * data->b6) >> 12)) >> 16; x3 = (x1 + x2 + 2) >> 2; b4 = (cali->AC4 * (u32)(x3 + 32768)) >> 15; b7 = ((u32)data->raw_pressure - b3) * (50000 >> data->oversampling_setting); p = ((b7 < 0x80000000) ? ((b7 << 1) / b4) : ((b7 / b4) * 2)); x1 = p >> 8; x1 *= x1; x1 = (x1 * 3038) >> 16; x2 = (-7357 * p) >> 16; p += (x1 + x2 + 3791) >> 4; *pressure = p; exit: return status; } /* * This function sets the chip-internal oversampling. Valid values are 0..3. * The chip will use 2^oversampling samples for internal averaging. * This influences the measurement time and the accuracy; larger values * increase both. The datasheet gives on overview on how measurement time, * accuracy and noise correlate. */ static void bmp085_set_oversampling(struct bmp085_data *data, unsigned char oversampling) { if (oversampling > 3) oversampling = 3; data->oversampling_setting = oversampling; } /* * Returns the currently selected oversampling. Range: 0..3 */ static unsigned char bmp085_get_oversampling(struct bmp085_data *data) { return data->oversampling_setting; } /* sysfs callbacks */ static ssize_t set_oversampling(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct bmp085_data *data = i2c_get_clientdata(client); unsigned long oversampling; int success = strict_strtoul(buf, 10, &oversampling); if (success == 0) { bmp085_set_oversampling(data, oversampling); return count; } return success; } static ssize_t show_oversampling(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct bmp085_data *data = i2c_get_clientdata(client); return sprintf(buf, "%u\n", bmp085_get_oversampling(data)); } static DEVICE_ATTR(oversampling, S_IWUSR | S_IRUGO, show_oversampling, set_oversampling); static ssize_t show_temperature(struct device *dev, struct device_attribute *attr, char *buf) { int temperature; int status; struct i2c_client *client = to_i2c_client(dev); struct bmp085_data *data = i2c_get_clientdata(client); status = bmp085_get_temperature(data, &temperature); if (status != 0) return status; else return sprintf(buf, "%d\n", temperature); } static DEVICE_ATTR(temp0_input, S_IRUGO, show_temperature, NULL); static ssize_t show_pressure(struct device *dev, struct device_attribute *attr, char *buf) { int pressure; int status; struct i2c_client *client = to_i2c_client(dev); struct bmp085_data *data = i2c_get_clientdata(client); status = bmp085_get_pressure(data, &pressure); if (status != 0) return status; else return sprintf(buf, "%d\n", pressure); } static DEVICE_ATTR(pressure0_input, S_IRUGO, show_pressure, NULL); static struct attribute *bmp085_attributes[] = { &dev_attr_temp0_input.attr, &dev_attr_pressure0_input.attr, &dev_attr_oversampling.attr, NULL }; static const struct attribute_group bmp085_attr_group = { .attrs = bmp085_attributes, }; static int bmp085_detect(struct i2c_client *client, struct i2c_board_info *info) { if (client->addr != BMP085_I2C_ADDRESS) return -ENODEV; if (i2c_smbus_read_byte_data(client, BMP085_CHIP_ID_REG) != BMP085_CHIP_ID) return -ENODEV; return 0; } static int bmp085_init_client(struct i2c_client *client) { unsigned char version; int status; struct bmp085_data *data = i2c_get_clientdata(client); data->client = client; status = bmp085_read_calibration_data(client); if (status != 0) goto exit; version = i2c_smbus_read_byte_data(client, BMP085_VERSION_REG); data->last_temp_measurement = 0; data->oversampling_setting = 3; mutex_init(&data->lock); dev_info(&data->client->dev, "BMP085 ver. %d.%d found.\n", (version & 0x0F), (version & 0xF0) >> 4); exit: return status; } static int __devinit bmp085_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct bmp085_data *data; int err = 0; data = kzalloc(sizeof(struct bmp085_data), GFP_KERNEL); if (!data) { err = -ENOMEM; goto exit; } /* default settings after POR */ data->oversampling_setting = 0x00; i2c_set_clientdata(client, data); /* Initialize the BMP085 chip */ err = bmp085_init_client(client); if (err != 0) goto exit_free; /* Register sysfs hooks */ err = sysfs_create_group(&client->dev.kobj, &bmp085_attr_group); if (err) goto exit_free; dev_info(&data->client->dev, "Successfully initialized bmp085!\n"); goto exit; exit_free: kfree(data); exit: return err; } static int __devexit bmp085_remove(struct i2c_client *client) { sysfs_remove_group(&client->dev.kobj, &bmp085_attr_group); kfree(i2c_get_clientdata(client)); return 0; } static const struct i2c_device_id bmp085_id[] = { { "bmp085", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, bmp085_id); static struct i2c_driver bmp085_driver = { .driver = { .owner = THIS_MODULE, .name = "bmp085" }, .id_table = bmp085_id, .probe = bmp085_probe, .remove = __devexit_p(bmp085_remove), .detect = bmp085_detect, .address_list = normal_i2c }; module_i2c_driver(bmp085_driver); MODULE_AUTHOR("Christoph Mair <christoph.mair@gmail.com"); MODULE_DESCRIPTION("BMP085 driver"); MODULE_LICENSE("GPL");
gpl-2.0
aosp-lb-nozomi/android_kernel_sony_msm8660
net/batman-adv/icmp_socket.c
4811
8669
/* * Copyright (C) 2007-2012 B.A.T.M.A.N. contributors: * * Marek Lindner * * 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-1301, USA * */ #include "main.h" #include <linux/debugfs.h> #include <linux/slab.h> #include "icmp_socket.h" #include "send.h" #include "hash.h" #include "originator.h" #include "hard-interface.h" static struct socket_client *socket_client_hash[256]; static void bat_socket_add_packet(struct socket_client *socket_client, struct icmp_packet_rr *icmp_packet, size_t icmp_len); void bat_socket_init(void) { memset(socket_client_hash, 0, sizeof(socket_client_hash)); } static int bat_socket_open(struct inode *inode, struct file *file) { unsigned int i; struct socket_client *socket_client; nonseekable_open(inode, file); socket_client = kmalloc(sizeof(*socket_client), GFP_KERNEL); if (!socket_client) return -ENOMEM; for (i = 0; i < ARRAY_SIZE(socket_client_hash); i++) { if (!socket_client_hash[i]) { socket_client_hash[i] = socket_client; break; } } if (i == ARRAY_SIZE(socket_client_hash)) { pr_err("Error - can't add another packet client: maximum number of clients reached\n"); kfree(socket_client); return -EXFULL; } INIT_LIST_HEAD(&socket_client->queue_list); socket_client->queue_len = 0; socket_client->index = i; socket_client->bat_priv = inode->i_private; spin_lock_init(&socket_client->lock); init_waitqueue_head(&socket_client->queue_wait); file->private_data = socket_client; inc_module_count(); return 0; } static int bat_socket_release(struct inode *inode, struct file *file) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; struct list_head *list_pos, *list_pos_tmp; spin_lock_bh(&socket_client->lock); /* for all packets in the queue ... */ list_for_each_safe(list_pos, list_pos_tmp, &socket_client->queue_list) { socket_packet = list_entry(list_pos, struct socket_packet, list); list_del(list_pos); kfree(socket_packet); } socket_client_hash[socket_client->index] = NULL; spin_unlock_bh(&socket_client->lock); kfree(socket_client); dec_module_count(); return 0; } static ssize_t bat_socket_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; size_t packet_len; int error; if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0)) return -EAGAIN; if ((!buf) || (count < sizeof(struct icmp_packet))) return -EINVAL; if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; error = wait_event_interruptible(socket_client->queue_wait, socket_client->queue_len); if (error) return error; spin_lock_bh(&socket_client->lock); socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); socket_client->queue_len--; spin_unlock_bh(&socket_client->lock); packet_len = min(count, socket_packet->icmp_len); error = copy_to_user(buf, &socket_packet->icmp_packet, packet_len); kfree(socket_packet); if (error) return -EFAULT; return packet_len; } static ssize_t bat_socket_write(struct file *file, const char __user *buff, size_t len, loff_t *off) { struct socket_client *socket_client = file->private_data; struct bat_priv *bat_priv = socket_client->bat_priv; struct hard_iface *primary_if = NULL; struct sk_buff *skb; struct icmp_packet_rr *icmp_packet; struct orig_node *orig_node = NULL; struct neigh_node *neigh_node = NULL; size_t packet_len = sizeof(struct icmp_packet); if (len < sizeof(struct icmp_packet)) { bat_dbg(DBG_BATMAN, bat_priv, "Error - can't send packet from char device: invalid packet size\n"); return -EINVAL; } primary_if = primary_if_get_selected(bat_priv); if (!primary_if) { len = -EFAULT; goto out; } if (len >= sizeof(struct icmp_packet_rr)) packet_len = sizeof(struct icmp_packet_rr); skb = dev_alloc_skb(packet_len + sizeof(struct ethhdr)); if (!skb) { len = -ENOMEM; goto out; } skb_reserve(skb, sizeof(struct ethhdr)); icmp_packet = (struct icmp_packet_rr *)skb_put(skb, packet_len); if (copy_from_user(icmp_packet, buff, packet_len)) { len = -EFAULT; goto free_skb; } if (icmp_packet->header.packet_type != BAT_ICMP) { bat_dbg(DBG_BATMAN, bat_priv, "Error - can't send packet from char device: got bogus packet type (expected: BAT_ICMP)\n"); len = -EINVAL; goto free_skb; } if (icmp_packet->msg_type != ECHO_REQUEST) { bat_dbg(DBG_BATMAN, bat_priv, "Error - can't send packet from char device: got bogus message type (expected: ECHO_REQUEST)\n"); len = -EINVAL; goto free_skb; } icmp_packet->uid = socket_client->index; if (icmp_packet->header.version != COMPAT_VERSION) { icmp_packet->msg_type = PARAMETER_PROBLEM; icmp_packet->header.version = COMPAT_VERSION; bat_socket_add_packet(socket_client, icmp_packet, packet_len); goto free_skb; } if (atomic_read(&bat_priv->mesh_state) != MESH_ACTIVE) goto dst_unreach; orig_node = orig_hash_find(bat_priv, icmp_packet->dst); if (!orig_node) goto dst_unreach; neigh_node = orig_node_get_router(orig_node); if (!neigh_node) goto dst_unreach; if (!neigh_node->if_incoming) goto dst_unreach; if (neigh_node->if_incoming->if_status != IF_ACTIVE) goto dst_unreach; memcpy(icmp_packet->orig, primary_if->net_dev->dev_addr, ETH_ALEN); if (packet_len == sizeof(struct icmp_packet_rr)) memcpy(icmp_packet->rr, neigh_node->if_incoming->net_dev->dev_addr, ETH_ALEN); send_skb_packet(skb, neigh_node->if_incoming, neigh_node->addr); goto out; dst_unreach: icmp_packet->msg_type = DESTINATION_UNREACHABLE; bat_socket_add_packet(socket_client, icmp_packet, packet_len); free_skb: kfree_skb(skb); out: if (primary_if) hardif_free_ref(primary_if); if (neigh_node) neigh_node_free_ref(neigh_node); if (orig_node) orig_node_free_ref(orig_node); return len; } static unsigned int bat_socket_poll(struct file *file, poll_table *wait) { struct socket_client *socket_client = file->private_data; poll_wait(file, &socket_client->queue_wait, wait); if (socket_client->queue_len > 0) return POLLIN | POLLRDNORM; return 0; } static const struct file_operations fops = { .owner = THIS_MODULE, .open = bat_socket_open, .release = bat_socket_release, .read = bat_socket_read, .write = bat_socket_write, .poll = bat_socket_poll, .llseek = no_llseek, }; int bat_socket_setup(struct bat_priv *bat_priv) { struct dentry *d; if (!bat_priv->debug_dir) goto err; d = debugfs_create_file(ICMP_SOCKET, S_IFREG | S_IWUSR | S_IRUSR, bat_priv->debug_dir, bat_priv, &fops); if (d) goto err; return 0; err: return 1; } static void bat_socket_add_packet(struct socket_client *socket_client, struct icmp_packet_rr *icmp_packet, size_t icmp_len) { struct socket_packet *socket_packet; socket_packet = kmalloc(sizeof(*socket_packet), GFP_ATOMIC); if (!socket_packet) return; INIT_LIST_HEAD(&socket_packet->list); memcpy(&socket_packet->icmp_packet, icmp_packet, icmp_len); socket_packet->icmp_len = icmp_len; spin_lock_bh(&socket_client->lock); /* while waiting for the lock the socket_client could have been * deleted */ if (!socket_client_hash[icmp_packet->uid]) { spin_unlock_bh(&socket_client->lock); kfree(socket_packet); return; } list_add_tail(&socket_packet->list, &socket_client->queue_list); socket_client->queue_len++; if (socket_client->queue_len > 100) { socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); kfree(socket_packet); socket_client->queue_len--; } spin_unlock_bh(&socket_client->lock); wake_up(&socket_client->queue_wait); } void bat_socket_receive_packet(struct icmp_packet_rr *icmp_packet, size_t icmp_len) { struct socket_client *hash = socket_client_hash[icmp_packet->uid]; if (hash) bat_socket_add_packet(hash, icmp_packet, icmp_len); }
gpl-2.0
tweez/kernel-msm
drivers/net/ethernet/mellanox/mlx4/mr.c
4811
21895
/* * Copyright (c) 2004 Topspin Communications. All rights reserved. * Copyright (c) 2005, 2006, 2007, 2008 Mellanox Technologies. All rights reserved. * Copyright (c) 2006, 2007 Cisco Systems, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/init.h> #include <linux/errno.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/mlx4/cmd.h> #include "mlx4.h" #include "icm.h" #define MLX4_MPT_FLAG_SW_OWNS (0xfUL << 28) #define MLX4_MPT_FLAG_FREE (0x3UL << 28) #define MLX4_MPT_FLAG_MIO (1 << 17) #define MLX4_MPT_FLAG_BIND_ENABLE (1 << 15) #define MLX4_MPT_FLAG_PHYSICAL (1 << 9) #define MLX4_MPT_FLAG_REGION (1 << 8) #define MLX4_MPT_PD_FLAG_FAST_REG (1 << 27) #define MLX4_MPT_PD_FLAG_RAE (1 << 28) #define MLX4_MPT_PD_FLAG_EN_INV (3 << 24) #define MLX4_MPT_STATUS_SW 0xF0 #define MLX4_MPT_STATUS_HW 0x00 static u32 mlx4_buddy_alloc(struct mlx4_buddy *buddy, int order) { int o; int m; u32 seg; spin_lock(&buddy->lock); for (o = order; o <= buddy->max_order; ++o) if (buddy->num_free[o]) { m = 1 << (buddy->max_order - o); seg = find_first_bit(buddy->bits[o], m); if (seg < m) goto found; } spin_unlock(&buddy->lock); return -1; found: clear_bit(seg, buddy->bits[o]); --buddy->num_free[o]; while (o > order) { --o; seg <<= 1; set_bit(seg ^ 1, buddy->bits[o]); ++buddy->num_free[o]; } spin_unlock(&buddy->lock); seg <<= order; return seg; } static void mlx4_buddy_free(struct mlx4_buddy *buddy, u32 seg, int order) { seg >>= order; spin_lock(&buddy->lock); while (test_bit(seg ^ 1, buddy->bits[order])) { clear_bit(seg ^ 1, buddy->bits[order]); --buddy->num_free[order]; seg >>= 1; ++order; } set_bit(seg, buddy->bits[order]); ++buddy->num_free[order]; spin_unlock(&buddy->lock); } static int mlx4_buddy_init(struct mlx4_buddy *buddy, int max_order) { int i, s; buddy->max_order = max_order; spin_lock_init(&buddy->lock); buddy->bits = kzalloc((buddy->max_order + 1) * sizeof (long *), GFP_KERNEL); buddy->num_free = kcalloc((buddy->max_order + 1), sizeof *buddy->num_free, GFP_KERNEL); if (!buddy->bits || !buddy->num_free) goto err_out; for (i = 0; i <= buddy->max_order; ++i) { s = BITS_TO_LONGS(1 << (buddy->max_order - i)); buddy->bits[i] = kmalloc(s * sizeof (long), GFP_KERNEL); if (!buddy->bits[i]) goto err_out_free; bitmap_zero(buddy->bits[i], 1 << (buddy->max_order - i)); } set_bit(0, buddy->bits[buddy->max_order]); buddy->num_free[buddy->max_order] = 1; return 0; err_out_free: for (i = 0; i <= buddy->max_order; ++i) kfree(buddy->bits[i]); err_out: kfree(buddy->bits); kfree(buddy->num_free); return -ENOMEM; } static void mlx4_buddy_cleanup(struct mlx4_buddy *buddy) { int i; for (i = 0; i <= buddy->max_order; ++i) kfree(buddy->bits[i]); kfree(buddy->bits); kfree(buddy->num_free); } u32 __mlx4_alloc_mtt_range(struct mlx4_dev *dev, int order) { struct mlx4_mr_table *mr_table = &mlx4_priv(dev)->mr_table; u32 seg; int seg_order; u32 offset; seg_order = max_t(int, order - log_mtts_per_seg, 0); seg = mlx4_buddy_alloc(&mr_table->mtt_buddy, seg_order); if (seg == -1) return -1; offset = seg * (1 << log_mtts_per_seg); if (mlx4_table_get_range(dev, &mr_table->mtt_table, offset, offset + (1 << order) - 1)) { mlx4_buddy_free(&mr_table->mtt_buddy, seg, seg_order); return -1; } return offset; } static u32 mlx4_alloc_mtt_range(struct mlx4_dev *dev, int order) { u64 in_param; u64 out_param; int err; if (mlx4_is_mfunc(dev)) { set_param_l(&in_param, order); err = mlx4_cmd_imm(dev, in_param, &out_param, RES_MTT, RES_OP_RESERVE_AND_MAP, MLX4_CMD_ALLOC_RES, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); if (err) return -1; return get_param_l(&out_param); } return __mlx4_alloc_mtt_range(dev, order); } int mlx4_mtt_init(struct mlx4_dev *dev, int npages, int page_shift, struct mlx4_mtt *mtt) { int i; if (!npages) { mtt->order = -1; mtt->page_shift = MLX4_ICM_PAGE_SHIFT; return 0; } else mtt->page_shift = page_shift; for (mtt->order = 0, i = 1; i < npages; i <<= 1) ++mtt->order; mtt->offset = mlx4_alloc_mtt_range(dev, mtt->order); if (mtt->offset == -1) return -ENOMEM; return 0; } EXPORT_SYMBOL_GPL(mlx4_mtt_init); void __mlx4_free_mtt_range(struct mlx4_dev *dev, u32 offset, int order) { u32 first_seg; int seg_order; struct mlx4_mr_table *mr_table = &mlx4_priv(dev)->mr_table; seg_order = max_t(int, order - log_mtts_per_seg, 0); first_seg = offset / (1 << log_mtts_per_seg); mlx4_buddy_free(&mr_table->mtt_buddy, first_seg, seg_order); mlx4_table_put_range(dev, &mr_table->mtt_table, offset, offset + (1 << order) - 1); } static void mlx4_free_mtt_range(struct mlx4_dev *dev, u32 offset, int order) { u64 in_param; int err; if (mlx4_is_mfunc(dev)) { set_param_l(&in_param, offset); set_param_h(&in_param, order); err = mlx4_cmd(dev, in_param, RES_MTT, RES_OP_RESERVE_AND_MAP, MLX4_CMD_FREE_RES, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); if (err) mlx4_warn(dev, "Failed to free mtt range at:" "%d order:%d\n", offset, order); return; } __mlx4_free_mtt_range(dev, offset, order); } void mlx4_mtt_cleanup(struct mlx4_dev *dev, struct mlx4_mtt *mtt) { if (mtt->order < 0) return; mlx4_free_mtt_range(dev, mtt->offset, mtt->order); } EXPORT_SYMBOL_GPL(mlx4_mtt_cleanup); u64 mlx4_mtt_addr(struct mlx4_dev *dev, struct mlx4_mtt *mtt) { return (u64) mtt->offset * dev->caps.mtt_entry_sz; } EXPORT_SYMBOL_GPL(mlx4_mtt_addr); static u32 hw_index_to_key(u32 ind) { return (ind >> 24) | (ind << 8); } static u32 key_to_hw_index(u32 key) { return (key << 24) | (key >> 8); } static int mlx4_SW2HW_MPT(struct mlx4_dev *dev, struct mlx4_cmd_mailbox *mailbox, int mpt_index) { return mlx4_cmd(dev, mailbox->dma, mpt_index, 0, MLX4_CMD_SW2HW_MPT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_WRAPPED); } static int mlx4_HW2SW_MPT(struct mlx4_dev *dev, struct mlx4_cmd_mailbox *mailbox, int mpt_index) { return mlx4_cmd_box(dev, 0, mailbox ? mailbox->dma : 0, mpt_index, !mailbox, MLX4_CMD_HW2SW_MPT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_WRAPPED); } static int mlx4_mr_alloc_reserved(struct mlx4_dev *dev, u32 mridx, u32 pd, u64 iova, u64 size, u32 access, int npages, int page_shift, struct mlx4_mr *mr) { mr->iova = iova; mr->size = size; mr->pd = pd; mr->access = access; mr->enabled = MLX4_MR_DISABLED; mr->key = hw_index_to_key(mridx); return mlx4_mtt_init(dev, npages, page_shift, &mr->mtt); } static int mlx4_WRITE_MTT(struct mlx4_dev *dev, struct mlx4_cmd_mailbox *mailbox, int num_entries) { return mlx4_cmd(dev, mailbox->dma, num_entries, 0, MLX4_CMD_WRITE_MTT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); } int __mlx4_mr_reserve(struct mlx4_dev *dev) { struct mlx4_priv *priv = mlx4_priv(dev); return mlx4_bitmap_alloc(&priv->mr_table.mpt_bitmap); } static int mlx4_mr_reserve(struct mlx4_dev *dev) { u64 out_param; if (mlx4_is_mfunc(dev)) { if (mlx4_cmd_imm(dev, 0, &out_param, RES_MPT, RES_OP_RESERVE, MLX4_CMD_ALLOC_RES, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED)) return -1; return get_param_l(&out_param); } return __mlx4_mr_reserve(dev); } void __mlx4_mr_release(struct mlx4_dev *dev, u32 index) { struct mlx4_priv *priv = mlx4_priv(dev); mlx4_bitmap_free(&priv->mr_table.mpt_bitmap, index); } static void mlx4_mr_release(struct mlx4_dev *dev, u32 index) { u64 in_param; if (mlx4_is_mfunc(dev)) { set_param_l(&in_param, index); if (mlx4_cmd(dev, in_param, RES_MPT, RES_OP_RESERVE, MLX4_CMD_FREE_RES, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED)) mlx4_warn(dev, "Failed to release mr index:%d\n", index); return; } __mlx4_mr_release(dev, index); } int __mlx4_mr_alloc_icm(struct mlx4_dev *dev, u32 index) { struct mlx4_mr_table *mr_table = &mlx4_priv(dev)->mr_table; return mlx4_table_get(dev, &mr_table->dmpt_table, index); } static int mlx4_mr_alloc_icm(struct mlx4_dev *dev, u32 index) { u64 param; if (mlx4_is_mfunc(dev)) { set_param_l(&param, index); return mlx4_cmd_imm(dev, param, &param, RES_MPT, RES_OP_MAP_ICM, MLX4_CMD_ALLOC_RES, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); } return __mlx4_mr_alloc_icm(dev, index); } void __mlx4_mr_free_icm(struct mlx4_dev *dev, u32 index) { struct mlx4_mr_table *mr_table = &mlx4_priv(dev)->mr_table; mlx4_table_put(dev, &mr_table->dmpt_table, index); } static void mlx4_mr_free_icm(struct mlx4_dev *dev, u32 index) { u64 in_param; if (mlx4_is_mfunc(dev)) { set_param_l(&in_param, index); if (mlx4_cmd(dev, in_param, RES_MPT, RES_OP_MAP_ICM, MLX4_CMD_FREE_RES, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED)) mlx4_warn(dev, "Failed to free icm of mr index:%d\n", index); return; } return __mlx4_mr_free_icm(dev, index); } int mlx4_mr_alloc(struct mlx4_dev *dev, u32 pd, u64 iova, u64 size, u32 access, int npages, int page_shift, struct mlx4_mr *mr) { u32 index; int err; index = mlx4_mr_reserve(dev); if (index == -1) return -ENOMEM; err = mlx4_mr_alloc_reserved(dev, index, pd, iova, size, access, npages, page_shift, mr); if (err) mlx4_mr_release(dev, index); return err; } EXPORT_SYMBOL_GPL(mlx4_mr_alloc); static void mlx4_mr_free_reserved(struct mlx4_dev *dev, struct mlx4_mr *mr) { int err; if (mr->enabled == MLX4_MR_EN_HW) { err = mlx4_HW2SW_MPT(dev, NULL, key_to_hw_index(mr->key) & (dev->caps.num_mpts - 1)); if (err) mlx4_warn(dev, "xxx HW2SW_MPT failed (%d)\n", err); mr->enabled = MLX4_MR_EN_SW; } mlx4_mtt_cleanup(dev, &mr->mtt); } void mlx4_mr_free(struct mlx4_dev *dev, struct mlx4_mr *mr) { mlx4_mr_free_reserved(dev, mr); if (mr->enabled) mlx4_mr_free_icm(dev, key_to_hw_index(mr->key)); mlx4_mr_release(dev, key_to_hw_index(mr->key)); } EXPORT_SYMBOL_GPL(mlx4_mr_free); int mlx4_mr_enable(struct mlx4_dev *dev, struct mlx4_mr *mr) { struct mlx4_cmd_mailbox *mailbox; struct mlx4_mpt_entry *mpt_entry; int err; err = mlx4_mr_alloc_icm(dev, key_to_hw_index(mr->key)); if (err) return err; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) { err = PTR_ERR(mailbox); goto err_table; } mpt_entry = mailbox->buf; memset(mpt_entry, 0, sizeof *mpt_entry); mpt_entry->flags = cpu_to_be32(MLX4_MPT_FLAG_MIO | MLX4_MPT_FLAG_REGION | mr->access); mpt_entry->key = cpu_to_be32(key_to_hw_index(mr->key)); mpt_entry->pd_flags = cpu_to_be32(mr->pd | MLX4_MPT_PD_FLAG_EN_INV); mpt_entry->start = cpu_to_be64(mr->iova); mpt_entry->length = cpu_to_be64(mr->size); mpt_entry->entity_size = cpu_to_be32(mr->mtt.page_shift); if (mr->mtt.order < 0) { mpt_entry->flags |= cpu_to_be32(MLX4_MPT_FLAG_PHYSICAL); mpt_entry->mtt_addr = 0; } else { mpt_entry->mtt_addr = cpu_to_be64(mlx4_mtt_addr(dev, &mr->mtt)); } if (mr->mtt.order >= 0 && mr->mtt.page_shift == 0) { /* fast register MR in free state */ mpt_entry->flags |= cpu_to_be32(MLX4_MPT_FLAG_FREE); mpt_entry->pd_flags |= cpu_to_be32(MLX4_MPT_PD_FLAG_FAST_REG | MLX4_MPT_PD_FLAG_RAE); mpt_entry->mtt_sz = cpu_to_be32(1 << mr->mtt.order); } else { mpt_entry->flags |= cpu_to_be32(MLX4_MPT_FLAG_SW_OWNS); } err = mlx4_SW2HW_MPT(dev, mailbox, key_to_hw_index(mr->key) & (dev->caps.num_mpts - 1)); if (err) { mlx4_warn(dev, "SW2HW_MPT failed (%d)\n", err); goto err_cmd; } mr->enabled = MLX4_MR_EN_HW; mlx4_free_cmd_mailbox(dev, mailbox); return 0; err_cmd: mlx4_free_cmd_mailbox(dev, mailbox); err_table: mlx4_mr_free_icm(dev, key_to_hw_index(mr->key)); return err; } EXPORT_SYMBOL_GPL(mlx4_mr_enable); static int mlx4_write_mtt_chunk(struct mlx4_dev *dev, struct mlx4_mtt *mtt, int start_index, int npages, u64 *page_list) { struct mlx4_priv *priv = mlx4_priv(dev); __be64 *mtts; dma_addr_t dma_handle; int i; mtts = mlx4_table_find(&priv->mr_table.mtt_table, mtt->offset + start_index, &dma_handle); if (!mtts) return -ENOMEM; dma_sync_single_for_cpu(&dev->pdev->dev, dma_handle, npages * sizeof (u64), DMA_TO_DEVICE); for (i = 0; i < npages; ++i) mtts[i] = cpu_to_be64(page_list[i] | MLX4_MTT_FLAG_PRESENT); dma_sync_single_for_device(&dev->pdev->dev, dma_handle, npages * sizeof (u64), DMA_TO_DEVICE); return 0; } int __mlx4_write_mtt(struct mlx4_dev *dev, struct mlx4_mtt *mtt, int start_index, int npages, u64 *page_list) { int err = 0; int chunk; int mtts_per_page; int max_mtts_first_page; /* compute how may mtts fit in the first page */ mtts_per_page = PAGE_SIZE / sizeof(u64); max_mtts_first_page = mtts_per_page - (mtt->offset + start_index) % mtts_per_page; chunk = min_t(int, max_mtts_first_page, npages); while (npages > 0) { err = mlx4_write_mtt_chunk(dev, mtt, start_index, chunk, page_list); if (err) return err; npages -= chunk; start_index += chunk; page_list += chunk; chunk = min_t(int, mtts_per_page, npages); } return err; } int mlx4_write_mtt(struct mlx4_dev *dev, struct mlx4_mtt *mtt, int start_index, int npages, u64 *page_list) { struct mlx4_cmd_mailbox *mailbox = NULL; __be64 *inbox = NULL; int chunk; int err = 0; int i; if (mtt->order < 0) return -EINVAL; if (mlx4_is_mfunc(dev)) { mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; while (npages > 0) { chunk = min_t(int, MLX4_MAILBOX_SIZE / sizeof(u64) - 2, npages); inbox[0] = cpu_to_be64(mtt->offset + start_index); inbox[1] = 0; for (i = 0; i < chunk; ++i) inbox[i + 2] = cpu_to_be64(page_list[i] | MLX4_MTT_FLAG_PRESENT); err = mlx4_WRITE_MTT(dev, mailbox, chunk); if (err) { mlx4_free_cmd_mailbox(dev, mailbox); return err; } npages -= chunk; start_index += chunk; page_list += chunk; } mlx4_free_cmd_mailbox(dev, mailbox); return err; } return __mlx4_write_mtt(dev, mtt, start_index, npages, page_list); } EXPORT_SYMBOL_GPL(mlx4_write_mtt); int mlx4_buf_write_mtt(struct mlx4_dev *dev, struct mlx4_mtt *mtt, struct mlx4_buf *buf) { u64 *page_list; int err; int i; page_list = kmalloc(buf->npages * sizeof *page_list, GFP_KERNEL); if (!page_list) return -ENOMEM; for (i = 0; i < buf->npages; ++i) if (buf->nbufs == 1) page_list[i] = buf->direct.map + (i << buf->page_shift); else page_list[i] = buf->page_list[i].map; err = mlx4_write_mtt(dev, mtt, 0, buf->npages, page_list); kfree(page_list); return err; } EXPORT_SYMBOL_GPL(mlx4_buf_write_mtt); int mlx4_init_mr_table(struct mlx4_dev *dev) { struct mlx4_priv *priv = mlx4_priv(dev); struct mlx4_mr_table *mr_table = &priv->mr_table; int err; if (!is_power_of_2(dev->caps.num_mpts)) return -EINVAL; /* Nothing to do for slaves - all MR handling is forwarded * to the master */ if (mlx4_is_slave(dev)) return 0; err = mlx4_bitmap_init(&mr_table->mpt_bitmap, dev->caps.num_mpts, ~0, dev->caps.reserved_mrws, 0); if (err) return err; err = mlx4_buddy_init(&mr_table->mtt_buddy, ilog2(dev->caps.num_mtts / (1 << log_mtts_per_seg))); if (err) goto err_buddy; if (dev->caps.reserved_mtts) { priv->reserved_mtts = mlx4_alloc_mtt_range(dev, fls(dev->caps.reserved_mtts - 1)); if (priv->reserved_mtts < 0) { mlx4_warn(dev, "MTT table of order %d is too small.\n", mr_table->mtt_buddy.max_order); err = -ENOMEM; goto err_reserve_mtts; } } return 0; err_reserve_mtts: mlx4_buddy_cleanup(&mr_table->mtt_buddy); err_buddy: mlx4_bitmap_cleanup(&mr_table->mpt_bitmap); return err; } void mlx4_cleanup_mr_table(struct mlx4_dev *dev) { struct mlx4_priv *priv = mlx4_priv(dev); struct mlx4_mr_table *mr_table = &priv->mr_table; if (mlx4_is_slave(dev)) return; if (priv->reserved_mtts >= 0) mlx4_free_mtt_range(dev, priv->reserved_mtts, fls(dev->caps.reserved_mtts - 1)); mlx4_buddy_cleanup(&mr_table->mtt_buddy); mlx4_bitmap_cleanup(&mr_table->mpt_bitmap); } static inline int mlx4_check_fmr(struct mlx4_fmr *fmr, u64 *page_list, int npages, u64 iova) { int i, page_mask; if (npages > fmr->max_pages) return -EINVAL; page_mask = (1 << fmr->page_shift) - 1; /* We are getting page lists, so va must be page aligned. */ if (iova & page_mask) return -EINVAL; /* Trust the user not to pass misaligned data in page_list */ if (0) for (i = 0; i < npages; ++i) { if (page_list[i] & ~page_mask) return -EINVAL; } if (fmr->maps >= fmr->max_maps) return -EINVAL; return 0; } int mlx4_map_phys_fmr(struct mlx4_dev *dev, struct mlx4_fmr *fmr, u64 *page_list, int npages, u64 iova, u32 *lkey, u32 *rkey) { u32 key; int i, err; err = mlx4_check_fmr(fmr, page_list, npages, iova); if (err) return err; ++fmr->maps; key = key_to_hw_index(fmr->mr.key); key += dev->caps.num_mpts; *lkey = *rkey = fmr->mr.key = hw_index_to_key(key); *(u8 *) fmr->mpt = MLX4_MPT_STATUS_SW; /* Make sure MPT status is visible before writing MTT entries */ wmb(); dma_sync_single_for_cpu(&dev->pdev->dev, fmr->dma_handle, npages * sizeof(u64), DMA_TO_DEVICE); for (i = 0; i < npages; ++i) fmr->mtts[i] = cpu_to_be64(page_list[i] | MLX4_MTT_FLAG_PRESENT); dma_sync_single_for_device(&dev->pdev->dev, fmr->dma_handle, npages * sizeof(u64), DMA_TO_DEVICE); fmr->mpt->key = cpu_to_be32(key); fmr->mpt->lkey = cpu_to_be32(key); fmr->mpt->length = cpu_to_be64(npages * (1ull << fmr->page_shift)); fmr->mpt->start = cpu_to_be64(iova); /* Make MTT entries are visible before setting MPT status */ wmb(); *(u8 *) fmr->mpt = MLX4_MPT_STATUS_HW; /* Make sure MPT status is visible before consumer can use FMR */ wmb(); return 0; } EXPORT_SYMBOL_GPL(mlx4_map_phys_fmr); int mlx4_fmr_alloc(struct mlx4_dev *dev, u32 pd, u32 access, int max_pages, int max_maps, u8 page_shift, struct mlx4_fmr *fmr) { struct mlx4_priv *priv = mlx4_priv(dev); u64 mtt_offset; int err = -ENOMEM; if (max_maps > dev->caps.max_fmr_maps) return -EINVAL; if (page_shift < (ffs(dev->caps.page_size_cap) - 1) || page_shift >= 32) return -EINVAL; /* All MTTs must fit in the same page */ if (max_pages * sizeof *fmr->mtts > PAGE_SIZE) return -EINVAL; fmr->page_shift = page_shift; fmr->max_pages = max_pages; fmr->max_maps = max_maps; fmr->maps = 0; err = mlx4_mr_alloc(dev, pd, 0, 0, access, max_pages, page_shift, &fmr->mr); if (err) return err; mtt_offset = fmr->mr.mtt.offset * dev->caps.mtt_entry_sz; fmr->mtts = mlx4_table_find(&priv->mr_table.mtt_table, fmr->mr.mtt.offset, &fmr->dma_handle); if (!fmr->mtts) { err = -ENOMEM; goto err_free; } return 0; err_free: mlx4_mr_free(dev, &fmr->mr); return err; } EXPORT_SYMBOL_GPL(mlx4_fmr_alloc); int mlx4_fmr_enable(struct mlx4_dev *dev, struct mlx4_fmr *fmr) { struct mlx4_priv *priv = mlx4_priv(dev); int err; err = mlx4_mr_enable(dev, &fmr->mr); if (err) return err; fmr->mpt = mlx4_table_find(&priv->mr_table.dmpt_table, key_to_hw_index(fmr->mr.key), NULL); if (!fmr->mpt) return -ENOMEM; return 0; } EXPORT_SYMBOL_GPL(mlx4_fmr_enable); void mlx4_fmr_unmap(struct mlx4_dev *dev, struct mlx4_fmr *fmr, u32 *lkey, u32 *rkey) { struct mlx4_cmd_mailbox *mailbox; int err; if (!fmr->maps) return; fmr->maps = 0; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) { err = PTR_ERR(mailbox); printk(KERN_WARNING "mlx4_ib: mlx4_alloc_cmd_mailbox" " failed (%d)\n", err); return; } err = mlx4_HW2SW_MPT(dev, NULL, key_to_hw_index(fmr->mr.key) & (dev->caps.num_mpts - 1)); mlx4_free_cmd_mailbox(dev, mailbox); if (err) { printk(KERN_WARNING "mlx4_ib: mlx4_HW2SW_MPT failed (%d)\n", err); return; } fmr->mr.enabled = MLX4_MR_EN_SW; } EXPORT_SYMBOL_GPL(mlx4_fmr_unmap); int mlx4_fmr_free(struct mlx4_dev *dev, struct mlx4_fmr *fmr) { if (fmr->maps) return -EBUSY; mlx4_mr_free(dev, &fmr->mr); fmr->mr.enabled = MLX4_MR_DISABLED; return 0; } EXPORT_SYMBOL_GPL(mlx4_fmr_free); int mlx4_SYNC_TPT(struct mlx4_dev *dev) { return mlx4_cmd(dev, 0, 0, 0, MLX4_CMD_SYNC_TPT, 1000, MLX4_CMD_WRAPPED); } EXPORT_SYMBOL_GPL(mlx4_SYNC_TPT);
gpl-2.0
ElectryDev/android_kernel_kingdom_row
net/batman-adv/gateway_client.c
4811
17411
/* * Copyright (C) 2009-2012 B.A.T.M.A.N. contributors: * * Marek Lindner * * 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-1301, USA * */ #include "main.h" #include "bat_sysfs.h" #include "gateway_client.h" #include "gateway_common.h" #include "hard-interface.h" #include "originator.h" #include "translation-table.h" #include "routing.h" #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/udp.h> #include <linux/if_vlan.h> /* This is the offset of the options field in a dhcp packet starting at * the beginning of the dhcp header */ #define DHCP_OPTIONS_OFFSET 240 #define DHCP_REQUEST 3 static void gw_node_free_ref(struct gw_node *gw_node) { if (atomic_dec_and_test(&gw_node->refcount)) kfree_rcu(gw_node, rcu); } static struct gw_node *gw_get_selected_gw_node(struct bat_priv *bat_priv) { struct gw_node *gw_node; rcu_read_lock(); gw_node = rcu_dereference(bat_priv->curr_gw); if (!gw_node) goto out; if (!atomic_inc_not_zero(&gw_node->refcount)) gw_node = NULL; out: rcu_read_unlock(); return gw_node; } struct orig_node *gw_get_selected_orig(struct bat_priv *bat_priv) { struct gw_node *gw_node; struct orig_node *orig_node = NULL; gw_node = gw_get_selected_gw_node(bat_priv); if (!gw_node) goto out; rcu_read_lock(); orig_node = gw_node->orig_node; if (!orig_node) goto unlock; if (!atomic_inc_not_zero(&orig_node->refcount)) orig_node = NULL; unlock: rcu_read_unlock(); out: if (gw_node) gw_node_free_ref(gw_node); return orig_node; } static void gw_select(struct bat_priv *bat_priv, struct gw_node *new_gw_node) { struct gw_node *curr_gw_node; spin_lock_bh(&bat_priv->gw_list_lock); if (new_gw_node && !atomic_inc_not_zero(&new_gw_node->refcount)) new_gw_node = NULL; curr_gw_node = rcu_dereference_protected(bat_priv->curr_gw, 1); rcu_assign_pointer(bat_priv->curr_gw, new_gw_node); if (curr_gw_node) gw_node_free_ref(curr_gw_node); spin_unlock_bh(&bat_priv->gw_list_lock); } void gw_deselect(struct bat_priv *bat_priv) { atomic_set(&bat_priv->gw_reselect, 1); } static struct gw_node *gw_get_best_gw_node(struct bat_priv *bat_priv) { struct neigh_node *router; struct hlist_node *node; struct gw_node *gw_node, *curr_gw = NULL; uint32_t max_gw_factor = 0, tmp_gw_factor = 0; uint8_t max_tq = 0; int down, up; rcu_read_lock(); hlist_for_each_entry_rcu(gw_node, node, &bat_priv->gw_list, list) { if (gw_node->deleted) continue; router = orig_node_get_router(gw_node->orig_node); if (!router) continue; if (!atomic_inc_not_zero(&gw_node->refcount)) goto next; switch (atomic_read(&bat_priv->gw_sel_class)) { case 1: /* fast connection */ gw_bandwidth_to_kbit(gw_node->orig_node->gw_flags, &down, &up); tmp_gw_factor = (router->tq_avg * router->tq_avg * down * 100 * 100) / (TQ_LOCAL_WINDOW_SIZE * TQ_LOCAL_WINDOW_SIZE * 64); if ((tmp_gw_factor > max_gw_factor) || ((tmp_gw_factor == max_gw_factor) && (router->tq_avg > max_tq))) { if (curr_gw) gw_node_free_ref(curr_gw); curr_gw = gw_node; atomic_inc(&curr_gw->refcount); } break; default: /** * 2: stable connection (use best statistic) * 3: fast-switch (use best statistic but change as * soon as a better gateway appears) * XX: late-switch (use best statistic but change as * soon as a better gateway appears which has * $routing_class more tq points) **/ if (router->tq_avg > max_tq) { if (curr_gw) gw_node_free_ref(curr_gw); curr_gw = gw_node; atomic_inc(&curr_gw->refcount); } break; } if (router->tq_avg > max_tq) max_tq = router->tq_avg; if (tmp_gw_factor > max_gw_factor) max_gw_factor = tmp_gw_factor; gw_node_free_ref(gw_node); next: neigh_node_free_ref(router); } rcu_read_unlock(); return curr_gw; } void gw_election(struct bat_priv *bat_priv) { struct gw_node *curr_gw = NULL, *next_gw = NULL; struct neigh_node *router = NULL; char gw_addr[18] = { '\0' }; /** * The batman daemon checks here if we already passed a full originator * cycle in order to make sure we don't choose the first gateway we * hear about. This check is based on the daemon's uptime which we * don't have. **/ if (atomic_read(&bat_priv->gw_mode) != GW_MODE_CLIENT) goto out; if (!atomic_dec_not_zero(&bat_priv->gw_reselect)) goto out; curr_gw = gw_get_selected_gw_node(bat_priv); next_gw = gw_get_best_gw_node(bat_priv); if (curr_gw == next_gw) goto out; if (next_gw) { sprintf(gw_addr, "%pM", next_gw->orig_node->orig); router = orig_node_get_router(next_gw->orig_node); if (!router) { gw_deselect(bat_priv); goto out; } } if ((curr_gw) && (!next_gw)) { bat_dbg(DBG_BATMAN, bat_priv, "Removing selected gateway - no gateway in range\n"); throw_uevent(bat_priv, UEV_GW, UEV_DEL, NULL); } else if ((!curr_gw) && (next_gw)) { bat_dbg(DBG_BATMAN, bat_priv, "Adding route to gateway %pM (gw_flags: %i, tq: %i)\n", next_gw->orig_node->orig, next_gw->orig_node->gw_flags, router->tq_avg); throw_uevent(bat_priv, UEV_GW, UEV_ADD, gw_addr); } else { bat_dbg(DBG_BATMAN, bat_priv, "Changing route to gateway %pM (gw_flags: %i, tq: %i)\n", next_gw->orig_node->orig, next_gw->orig_node->gw_flags, router->tq_avg); throw_uevent(bat_priv, UEV_GW, UEV_CHANGE, gw_addr); } gw_select(bat_priv, next_gw); out: if (curr_gw) gw_node_free_ref(curr_gw); if (next_gw) gw_node_free_ref(next_gw); if (router) neigh_node_free_ref(router); } void gw_check_election(struct bat_priv *bat_priv, struct orig_node *orig_node) { struct orig_node *curr_gw_orig; struct neigh_node *router_gw = NULL, *router_orig = NULL; uint8_t gw_tq_avg, orig_tq_avg; curr_gw_orig = gw_get_selected_orig(bat_priv); if (!curr_gw_orig) goto deselect; router_gw = orig_node_get_router(curr_gw_orig); if (!router_gw) goto deselect; /* this node already is the gateway */ if (curr_gw_orig == orig_node) goto out; router_orig = orig_node_get_router(orig_node); if (!router_orig) goto out; gw_tq_avg = router_gw->tq_avg; orig_tq_avg = router_orig->tq_avg; /* the TQ value has to be better */ if (orig_tq_avg < gw_tq_avg) goto out; /** * if the routing class is greater than 3 the value tells us how much * greater the TQ value of the new gateway must be **/ if ((atomic_read(&bat_priv->gw_sel_class) > 3) && (orig_tq_avg - gw_tq_avg < atomic_read(&bat_priv->gw_sel_class))) goto out; bat_dbg(DBG_BATMAN, bat_priv, "Restarting gateway selection: better gateway found (tq curr: %i, tq new: %i)\n", gw_tq_avg, orig_tq_avg); deselect: gw_deselect(bat_priv); out: if (curr_gw_orig) orig_node_free_ref(curr_gw_orig); if (router_gw) neigh_node_free_ref(router_gw); if (router_orig) neigh_node_free_ref(router_orig); return; } static void gw_node_add(struct bat_priv *bat_priv, struct orig_node *orig_node, uint8_t new_gwflags) { struct gw_node *gw_node; int down, up; gw_node = kzalloc(sizeof(*gw_node), GFP_ATOMIC); if (!gw_node) return; INIT_HLIST_NODE(&gw_node->list); gw_node->orig_node = orig_node; atomic_set(&gw_node->refcount, 1); spin_lock_bh(&bat_priv->gw_list_lock); hlist_add_head_rcu(&gw_node->list, &bat_priv->gw_list); spin_unlock_bh(&bat_priv->gw_list_lock); gw_bandwidth_to_kbit(new_gwflags, &down, &up); bat_dbg(DBG_BATMAN, bat_priv, "Found new gateway %pM -> gw_class: %i - %i%s/%i%s\n", orig_node->orig, new_gwflags, (down > 2048 ? down / 1024 : down), (down > 2048 ? "MBit" : "KBit"), (up > 2048 ? up / 1024 : up), (up > 2048 ? "MBit" : "KBit")); } void gw_node_update(struct bat_priv *bat_priv, struct orig_node *orig_node, uint8_t new_gwflags) { struct hlist_node *node; struct gw_node *gw_node, *curr_gw; /** * Note: We don't need a NULL check here, since curr_gw never gets * dereferenced. If curr_gw is NULL we also should not exit as we may * have this gateway in our list (duplication check!) even though we * have no currently selected gateway. */ curr_gw = gw_get_selected_gw_node(bat_priv); rcu_read_lock(); hlist_for_each_entry_rcu(gw_node, node, &bat_priv->gw_list, list) { if (gw_node->orig_node != orig_node) continue; bat_dbg(DBG_BATMAN, bat_priv, "Gateway class of originator %pM changed from %i to %i\n", orig_node->orig, gw_node->orig_node->gw_flags, new_gwflags); gw_node->deleted = 0; if (new_gwflags == NO_FLAGS) { gw_node->deleted = jiffies; bat_dbg(DBG_BATMAN, bat_priv, "Gateway %pM removed from gateway list\n", orig_node->orig); if (gw_node == curr_gw) goto deselect; } goto unlock; } if (new_gwflags == NO_FLAGS) goto unlock; gw_node_add(bat_priv, orig_node, new_gwflags); goto unlock; deselect: gw_deselect(bat_priv); unlock: rcu_read_unlock(); if (curr_gw) gw_node_free_ref(curr_gw); } void gw_node_delete(struct bat_priv *bat_priv, struct orig_node *orig_node) { gw_node_update(bat_priv, orig_node, 0); } void gw_node_purge(struct bat_priv *bat_priv) { struct gw_node *gw_node, *curr_gw; struct hlist_node *node, *node_tmp; unsigned long timeout = msecs_to_jiffies(2 * PURGE_TIMEOUT); int do_deselect = 0; curr_gw = gw_get_selected_gw_node(bat_priv); spin_lock_bh(&bat_priv->gw_list_lock); hlist_for_each_entry_safe(gw_node, node, node_tmp, &bat_priv->gw_list, list) { if (((!gw_node->deleted) || (time_before(jiffies, gw_node->deleted + timeout))) && atomic_read(&bat_priv->mesh_state) == MESH_ACTIVE) continue; if (curr_gw == gw_node) do_deselect = 1; hlist_del_rcu(&gw_node->list); gw_node_free_ref(gw_node); } spin_unlock_bh(&bat_priv->gw_list_lock); /* gw_deselect() needs to acquire the gw_list_lock */ if (do_deselect) gw_deselect(bat_priv); if (curr_gw) gw_node_free_ref(curr_gw); } /** * fails if orig_node has no router */ static int _write_buffer_text(struct bat_priv *bat_priv, struct seq_file *seq, const struct gw_node *gw_node) { struct gw_node *curr_gw; struct neigh_node *router; int down, up, ret = -1; gw_bandwidth_to_kbit(gw_node->orig_node->gw_flags, &down, &up); router = orig_node_get_router(gw_node->orig_node); if (!router) goto out; curr_gw = gw_get_selected_gw_node(bat_priv); ret = seq_printf(seq, "%s %pM (%3i) %pM [%10s]: %3i - %i%s/%i%s\n", (curr_gw == gw_node ? "=>" : " "), gw_node->orig_node->orig, router->tq_avg, router->addr, router->if_incoming->net_dev->name, gw_node->orig_node->gw_flags, (down > 2048 ? down / 1024 : down), (down > 2048 ? "MBit" : "KBit"), (up > 2048 ? up / 1024 : up), (up > 2048 ? "MBit" : "KBit")); neigh_node_free_ref(router); if (curr_gw) gw_node_free_ref(curr_gw); out: return ret; } int gw_client_seq_print_text(struct seq_file *seq, void *offset) { struct net_device *net_dev = (struct net_device *)seq->private; struct bat_priv *bat_priv = netdev_priv(net_dev); struct hard_iface *primary_if; struct gw_node *gw_node; struct hlist_node *node; int gw_count = 0, ret = 0; primary_if = primary_if_get_selected(bat_priv); if (!primary_if) { ret = seq_printf(seq, "BATMAN mesh %s disabled - please specify interfaces to enable it\n", net_dev->name); goto out; } if (primary_if->if_status != IF_ACTIVE) { ret = seq_printf(seq, "BATMAN mesh %s disabled - primary interface not active\n", net_dev->name); goto out; } seq_printf(seq, " %-12s (%s/%i) %17s [%10s]: gw_class ... [B.A.T.M.A.N. adv %s, MainIF/MAC: %s/%pM (%s)]\n", "Gateway", "#", TQ_MAX_VALUE, "Nexthop", "outgoingIF", SOURCE_VERSION, primary_if->net_dev->name, primary_if->net_dev->dev_addr, net_dev->name); rcu_read_lock(); hlist_for_each_entry_rcu(gw_node, node, &bat_priv->gw_list, list) { if (gw_node->deleted) continue; /* fails if orig_node has no router */ if (_write_buffer_text(bat_priv, seq, gw_node) < 0) continue; gw_count++; } rcu_read_unlock(); if (gw_count == 0) seq_printf(seq, "No gateways in range ...\n"); out: if (primary_if) hardif_free_ref(primary_if); return ret; } static bool is_type_dhcprequest(struct sk_buff *skb, int header_len) { int ret = false; unsigned char *p; int pkt_len; if (skb_linearize(skb) < 0) goto out; pkt_len = skb_headlen(skb); if (pkt_len < header_len + DHCP_OPTIONS_OFFSET + 1) goto out; p = skb->data + header_len + DHCP_OPTIONS_OFFSET; pkt_len -= header_len + DHCP_OPTIONS_OFFSET + 1; /* Access the dhcp option lists. Each entry is made up by: * - octet 1: option type * - octet 2: option data len (only if type != 255 and 0) * - octet 3: option data */ while (*p != 255 && !ret) { /* p now points to the first octet: option type */ if (*p == 53) { /* type 53 is the message type option. * Jump the len octet and go to the data octet */ if (pkt_len < 2) goto out; p += 2; /* check if the message type is what we need */ if (*p == DHCP_REQUEST) ret = true; break; } else if (*p == 0) { /* option type 0 (padding), just go forward */ if (pkt_len < 1) goto out; pkt_len--; p++; } else { /* This is any other option. So we get the length... */ if (pkt_len < 1) goto out; pkt_len--; p++; /* ...and then we jump over the data */ if (pkt_len < *p) goto out; pkt_len -= *p; p += (*p); } } out: return ret; } bool gw_is_dhcp_target(struct sk_buff *skb, unsigned int *header_len) { struct ethhdr *ethhdr; struct iphdr *iphdr; struct ipv6hdr *ipv6hdr; struct udphdr *udphdr; /* check for ethernet header */ if (!pskb_may_pull(skb, *header_len + ETH_HLEN)) return false; ethhdr = (struct ethhdr *)skb->data; *header_len += ETH_HLEN; /* check for initial vlan header */ if (ntohs(ethhdr->h_proto) == ETH_P_8021Q) { if (!pskb_may_pull(skb, *header_len + VLAN_HLEN)) return false; ethhdr = (struct ethhdr *)(skb->data + VLAN_HLEN); *header_len += VLAN_HLEN; } /* check for ip header */ switch (ntohs(ethhdr->h_proto)) { case ETH_P_IP: if (!pskb_may_pull(skb, *header_len + sizeof(*iphdr))) return false; iphdr = (struct iphdr *)(skb->data + *header_len); *header_len += iphdr->ihl * 4; /* check for udp header */ if (iphdr->protocol != IPPROTO_UDP) return false; break; case ETH_P_IPV6: if (!pskb_may_pull(skb, *header_len + sizeof(*ipv6hdr))) return false; ipv6hdr = (struct ipv6hdr *)(skb->data + *header_len); *header_len += sizeof(*ipv6hdr); /* check for udp header */ if (ipv6hdr->nexthdr != IPPROTO_UDP) return false; break; default: return false; } if (!pskb_may_pull(skb, *header_len + sizeof(*udphdr))) return false; udphdr = (struct udphdr *)(skb->data + *header_len); *header_len += sizeof(*udphdr); /* check for bootp port */ if ((ntohs(ethhdr->h_proto) == ETH_P_IP) && (ntohs(udphdr->dest) != 67)) return false; if ((ntohs(ethhdr->h_proto) == ETH_P_IPV6) && (ntohs(udphdr->dest) != 547)) return false; return true; } bool gw_out_of_range(struct bat_priv *bat_priv, struct sk_buff *skb, struct ethhdr *ethhdr) { struct neigh_node *neigh_curr = NULL, *neigh_old = NULL; struct orig_node *orig_dst_node = NULL; struct gw_node *curr_gw = NULL; bool ret, out_of_range = false; unsigned int header_len = 0; uint8_t curr_tq_avg; ret = gw_is_dhcp_target(skb, &header_len); if (!ret) goto out; orig_dst_node = transtable_search(bat_priv, ethhdr->h_source, ethhdr->h_dest); if (!orig_dst_node) goto out; if (!orig_dst_node->gw_flags) goto out; ret = is_type_dhcprequest(skb, header_len); if (!ret) goto out; switch (atomic_read(&bat_priv->gw_mode)) { case GW_MODE_SERVER: /* If we are a GW then we are our best GW. We can artificially * set the tq towards ourself as the maximum value */ curr_tq_avg = TQ_MAX_VALUE; break; case GW_MODE_CLIENT: curr_gw = gw_get_selected_gw_node(bat_priv); if (!curr_gw) goto out; /* packet is going to our gateway */ if (curr_gw->orig_node == orig_dst_node) goto out; /* If the dhcp packet has been sent to a different gw, * we have to evaluate whether the old gw is still * reliable enough */ neigh_curr = find_router(bat_priv, curr_gw->orig_node, NULL); if (!neigh_curr) goto out; curr_tq_avg = neigh_curr->tq_avg; break; case GW_MODE_OFF: default: goto out; } neigh_old = find_router(bat_priv, orig_dst_node, NULL); if (!neigh_old) goto out; if (curr_tq_avg - neigh_old->tq_avg > GW_THRESHOLD) out_of_range = true; out: if (orig_dst_node) orig_node_free_ref(orig_dst_node); if (curr_gw) gw_node_free_ref(curr_gw); if (neigh_old) neigh_node_free_ref(neigh_old); if (neigh_curr) neigh_node_free_ref(neigh_curr); return out_of_range; }
gpl-2.0
ujwalp15/android_kernel_motorola_msm8226
drivers/staging/rtl8712/rtl8712_cmd.c
5067
14019
/****************************************************************************** * rtl8712_cmd.c * * Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved. * Linux device driver for RTL8192SU * * 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 * * Modifications for inclusion into the Linux staging tree are * Copyright(c) 2010 Larry Finger. All rights reserved. * * Contact information: * WLAN FAE <wlanfae@realtek.com>. * Larry Finger <Larry.Finger@lwfinger.net> * ******************************************************************************/ #define _RTL8712_CMD_C_ #include <linux/compiler.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/kref.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/usb.h> #include <linux/usb/ch9.h> #include <linux/circ_buf.h> #include <linux/uaccess.h> #include <asm/byteorder.h> #include <linux/atomic.h> #include <linux/semaphore.h> #include <linux/rtnetlink.h> #include "osdep_service.h" #include "drv_types.h" #include "recv_osdep.h" #include "mlme_osdep.h" #include "rtl871x_byteorder.h" #include "rtl871x_ioctl_set.h" static void check_hw_pbc(struct _adapter *padapter) { u8 tmp1byte; r8712_write8(padapter, MAC_PINMUX_CTRL, (GPIOMUX_EN | GPIOSEL_GPIO)); tmp1byte = r8712_read8(padapter, GPIO_IO_SEL); tmp1byte &= ~(HAL_8192S_HW_GPIO_WPS_BIT); r8712_write8(padapter, GPIO_IO_SEL, tmp1byte); tmp1byte = r8712_read8(padapter, GPIO_CTRL); if (tmp1byte == 0xff) return ; if (tmp1byte&HAL_8192S_HW_GPIO_WPS_BIT) { /* Here we only set bPbcPressed to true * After trigger PBC, the variable will be set to false */ DBG_8712("CheckPbcGPIO - PBC is pressed !!!!\n"); /* 0 is the default value and it means the application monitors * the HW PBC doesn't privde its pid to driver. */ if (padapter->pid == 0) return; kill_pid(find_vpid(padapter->pid), SIGUSR1, 1); } } /* query rx phy status from fw. * Adhoc mode: beacon. * Infrastructure mode: beacon , data. */ static void query_fw_rx_phy_status(struct _adapter *padapter) { u32 val32 = 0; int pollingcnts = 50; if (check_fwstate(&padapter->mlmepriv, _FW_LINKED) == true) { r8712_write32(padapter, IOCMD_CTRL_REG, 0xf4000001); msleep(100); /* Wait FW complete IO Cmd */ while ((r8712_read32(padapter, IOCMD_CTRL_REG)) && (pollingcnts > 0)) { pollingcnts--; msleep(20); } if (pollingcnts != 0) val32 = r8712_read32(padapter, IOCMD_DATA_REG); else /* time out */ val32 = 0; val32 = val32 >> 4; padapter->recvpriv.fw_rssi = (u8)r8712_signal_scale_mapping(val32); } } /* check mlme, hw, phy, or dynamic algorithm status. */ static void StatusWatchdogCallback(struct _adapter *padapter) { check_hw_pbc(padapter); query_fw_rx_phy_status(padapter); } static void r871x_internal_cmd_hdl(struct _adapter *padapter, u8 *pbuf) { struct drvint_cmd_parm *pdrvcmd; if (!pbuf) return; pdrvcmd = (struct drvint_cmd_parm *)pbuf; switch (pdrvcmd->i_cid) { case WDG_WK_CID: StatusWatchdogCallback(padapter); break; default: break; } kfree(pdrvcmd->pbuf); } static u8 read_macreg_hdl(struct _adapter *padapter, u8 *pbuf) { void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; /* invoke cmd->callback function */ pcmd_callback = cmd_callback[pcmd->cmdcode].callback; if (pcmd_callback == NULL) r8712_free_cmd_obj(pcmd); else pcmd_callback(padapter, pcmd); return H2C_SUCCESS; } static u8 write_macreg_hdl(struct _adapter *padapter, u8 *pbuf) { void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; /* invoke cmd->callback function */ pcmd_callback = cmd_callback[pcmd->cmdcode].callback; if (pcmd_callback == NULL) r8712_free_cmd_obj(pcmd); else pcmd_callback(padapter, pcmd); return H2C_SUCCESS; } static u8 read_bbreg_hdl(struct _adapter *padapter, u8 *pbuf) { u32 val; void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct readBB_parm *prdbbparm; struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; prdbbparm = (struct readBB_parm *)pcmd->parmbuf; if (pcmd->rsp && pcmd->rspsz > 0) memcpy(pcmd->rsp, (u8 *)&val, pcmd->rspsz); pcmd_callback = cmd_callback[pcmd->cmdcode].callback; if (pcmd_callback == NULL) r8712_free_cmd_obj(pcmd); else pcmd_callback(padapter, pcmd); return H2C_SUCCESS; } static u8 write_bbreg_hdl(struct _adapter *padapter, u8 *pbuf) { void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct writeBB_parm *pwritebbparm; struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; pwritebbparm = (struct writeBB_parm *)pcmd->parmbuf; pcmd_callback = cmd_callback[pcmd->cmdcode].callback; if (pcmd_callback == NULL) r8712_free_cmd_obj(pcmd); else pcmd_callback(padapter, pcmd); return H2C_SUCCESS; } static u8 read_rfreg_hdl(struct _adapter *padapter, u8 *pbuf) { u32 val; void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct readRF_parm *prdrfparm; struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; prdrfparm = (struct readRF_parm *)pcmd->parmbuf; if (pcmd->rsp && pcmd->rspsz > 0) memcpy(pcmd->rsp, (u8 *)&val, pcmd->rspsz); pcmd_callback = cmd_callback[pcmd->cmdcode].callback; if (pcmd_callback == NULL) r8712_free_cmd_obj(pcmd); else pcmd_callback(padapter, pcmd); return H2C_SUCCESS; } static u8 write_rfreg_hdl(struct _adapter *padapter, u8 *pbuf) { void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct writeRF_parm *pwriterfparm; struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; pwriterfparm = (struct writeRF_parm *)pcmd->parmbuf; pcmd_callback = cmd_callback[pcmd->cmdcode].callback; if (pcmd_callback == NULL) r8712_free_cmd_obj(pcmd); else pcmd_callback(padapter, pcmd); return H2C_SUCCESS; } static u8 sys_suspend_hdl(struct _adapter *padapter, u8 *pbuf) { struct cmd_obj *pcmd = (struct cmd_obj *)pbuf; struct usb_suspend_parm *psetusbsuspend; psetusbsuspend = (struct usb_suspend_parm *)pcmd->parmbuf; r8712_free_cmd_obj(pcmd); return H2C_SUCCESS; } static struct cmd_obj *cmd_hdl_filter(struct _adapter *padapter, struct cmd_obj *pcmd) { struct cmd_obj *pcmd_r; if (pcmd == NULL) return pcmd; pcmd_r = NULL; switch (pcmd->cmdcode) { case GEN_CMD_CODE(_Read_MACREG): read_macreg_hdl(padapter, (u8 *)pcmd); pcmd_r = pcmd; break; case GEN_CMD_CODE(_Write_MACREG): write_macreg_hdl(padapter, (u8 *)pcmd); pcmd_r = pcmd; break; case GEN_CMD_CODE(_Read_BBREG): read_bbreg_hdl(padapter, (u8 *)pcmd); break; case GEN_CMD_CODE(_Write_BBREG): write_bbreg_hdl(padapter, (u8 *)pcmd); break; case GEN_CMD_CODE(_Read_RFREG): read_rfreg_hdl(padapter, (u8 *)pcmd); break; case GEN_CMD_CODE(_Write_RFREG): write_rfreg_hdl(padapter, (u8 *)pcmd); break; case GEN_CMD_CODE(_SetUsbSuspend): sys_suspend_hdl(padapter, (u8 *)pcmd); break; case GEN_CMD_CODE(_JoinBss): r8712_joinbss_reset(padapter); /* Before set JoinBss_CMD to FW, driver must ensure FW is in * PS_MODE_ACTIVE. Directly write rpwm to radio on and assign * new pwr_mode to Driver, instead of use workitem to change * state. */ if (padapter->pwrctrlpriv.pwr_mode > PS_MODE_ACTIVE) { padapter->pwrctrlpriv.pwr_mode = PS_MODE_ACTIVE; _enter_pwrlock(&(padapter->pwrctrlpriv.lock)); r8712_set_rpwm(padapter, PS_STATE_S4); up(&(padapter->pwrctrlpriv.lock)); } pcmd_r = pcmd; break; case _DRV_INT_CMD_: r871x_internal_cmd_hdl(padapter, pcmd->parmbuf); r8712_free_cmd_obj(pcmd); pcmd_r = NULL; break; default: pcmd_r = pcmd; break; } return pcmd_r; /* if returning pcmd_r == NULL, pcmd must be free. */ } static u8 check_cmd_fifo(struct _adapter *padapter, uint sz) { u8 res = _SUCCESS; return res; } u8 r8712_fw_cmd(struct _adapter *pAdapter, u32 cmd) { int pollingcnts = 50; r8712_write32(pAdapter, IOCMD_CTRL_REG, cmd); msleep(100); while ((0 != r8712_read32(pAdapter, IOCMD_CTRL_REG)) && (pollingcnts > 0)) { pollingcnts--; msleep(20); } if (pollingcnts == 0) return false; return true; } void r8712_fw_cmd_data(struct _adapter *pAdapter, u32 *value, u8 flag) { if (flag == 0) /* set */ r8712_write32(pAdapter, IOCMD_DATA_REG, *value); else /* query */ *value = r8712_read32(pAdapter, IOCMD_DATA_REG); } int r8712_cmd_thread(void *context) { struct cmd_obj *pcmd; unsigned int cmdsz, wr_sz, *pcmdbuf, *prspbuf; struct tx_desc *pdesc; void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd); struct _adapter *padapter = (struct _adapter *)context; struct cmd_priv *pcmdpriv = &(padapter->cmdpriv); thread_enter(padapter); while (1) { if ((_down_sema(&(pcmdpriv->cmd_queue_sema))) == _FAIL) break; if ((padapter->bDriverStopped == true) || (padapter->bSurpriseRemoved == true)) break; if (r8712_register_cmd_alive(padapter) != _SUCCESS) continue; _next: pcmd = r8712_dequeue_cmd(&(pcmdpriv->cmd_queue)); if (!(pcmd)) { r8712_unregister_cmd_alive(padapter); continue; } pcmdbuf = (unsigned int *)pcmdpriv->cmd_buf; prspbuf = (unsigned int *)pcmdpriv->rsp_buf; pdesc = (struct tx_desc *)pcmdbuf; memset(pdesc, 0, TXDESC_SIZE); pcmd = cmd_hdl_filter(padapter, pcmd); if (pcmd) { /* if pcmd != NULL, cmd will be handled by f/w */ struct dvobj_priv *pdvobj = (struct dvobj_priv *) &padapter->dvobjpriv; u8 blnPending = 0; pcmdpriv->cmd_issued_cnt++; cmdsz = _RND8((pcmd->cmdsz)); /* _RND8 */ wr_sz = TXDESC_SIZE + 8 + cmdsz; pdesc->txdw0 |= cpu_to_le32((wr_sz-TXDESC_SIZE) & 0x0000ffff); if (pdvobj->ishighspeed) { if ((wr_sz % 512) == 0) blnPending = 1; } else { if ((wr_sz % 64) == 0) blnPending = 1; } if (blnPending) /* 32 bytes for TX Desc - 8 offset */ pdesc->txdw0 |= cpu_to_le32(((TXDESC_SIZE + OFFSET_SZ + 8) << OFFSET_SHT) & 0x00ff0000); else { pdesc->txdw0 |= cpu_to_le32(((TXDESC_SIZE + OFFSET_SZ) << OFFSET_SHT) & 0x00ff0000); } pdesc->txdw0 |= cpu_to_le32(OWN | FSG | LSG); pdesc->txdw1 |= cpu_to_le32((0x13 << QSEL_SHT) & 0x00001f00); pcmdbuf += (TXDESC_SIZE >> 2); *pcmdbuf = cpu_to_le32((cmdsz & 0x0000ffff) | (pcmd->cmdcode << 16) | (pcmdpriv->cmd_seq << 24)); pcmdbuf += 2 ; /* 8 bytes aligment */ memcpy((u8 *)pcmdbuf, pcmd->parmbuf, pcmd->cmdsz); while (check_cmd_fifo(padapter, wr_sz) == _FAIL) { if ((padapter->bDriverStopped == true) || (padapter->bSurpriseRemoved == true)) break; msleep(100); continue; } if (blnPending) wr_sz += 8; /* Append 8 bytes */ r8712_write_mem(padapter, RTL8712_DMA_H2CCMD, wr_sz, (u8 *)pdesc); pcmdpriv->cmd_seq++; if (pcmd->cmdcode == GEN_CMD_CODE(_CreateBss)) { pcmd->res = H2C_SUCCESS; pcmd_callback = cmd_callback[pcmd-> cmdcode].callback; if (pcmd_callback) pcmd_callback(padapter, pcmd); continue; } if (pcmd->cmdcode == GEN_CMD_CODE(_SetPwrMode)) { if (padapter->pwrctrlpriv.bSleep) { _enter_pwrlock(&(padapter-> pwrctrlpriv.lock)); r8712_set_rpwm(padapter, PS_STATE_S2); up(&padapter->pwrctrlpriv.lock); } } r8712_free_cmd_obj(pcmd); if (_queue_empty(&(pcmdpriv->cmd_queue))) { r8712_unregister_cmd_alive(padapter); continue; } else goto _next; } else goto _next; flush_signals_thread(); } /* free all cmd_obj resources */ do { pcmd = r8712_dequeue_cmd(&(pcmdpriv->cmd_queue)); if (pcmd == NULL) break; r8712_free_cmd_obj(pcmd); } while (1); up(&pcmdpriv->terminate_cmdthread_sema); thread_exit(); } void r8712_event_handle(struct _adapter *padapter, uint *peventbuf) { u8 evt_code, evt_seq; u16 evt_sz; void (*event_callback)(struct _adapter *dev, u8 *pbuf); struct evt_priv *pevt_priv = &(padapter->evtpriv); if (peventbuf == NULL) goto _abort_event_; evt_sz = (u16)(le32_to_cpu(*peventbuf) & 0xffff); evt_seq = (u8)((le32_to_cpu(*peventbuf) >> 24) & 0x7f); evt_code = (u8)((le32_to_cpu(*peventbuf) >> 16) & 0xff); /* checking event sequence... */ if ((evt_seq & 0x7f) != pevt_priv->event_seq) { pevt_priv->event_seq = ((evt_seq + 1) & 0x7f); goto _abort_event_; } /* checking if event code is valid */ if (evt_code >= MAX_C2HEVT) { pevt_priv->event_seq = ((evt_seq+1) & 0x7f); goto _abort_event_; } else if ((evt_code == GEN_EVT_CODE(_Survey)) && (evt_sz > sizeof(struct wlan_bssid_ex))) { pevt_priv->event_seq = ((evt_seq+1)&0x7f); goto _abort_event_; } /* checking if event size match the event parm size */ if ((wlanevents[evt_code].parmsize) && (wlanevents[evt_code].parmsize != evt_sz)) { pevt_priv->event_seq = ((evt_seq+1)&0x7f); goto _abort_event_; } else if ((evt_sz == 0) && (evt_code != GEN_EVT_CODE(_WPS_PBC))) { pevt_priv->event_seq = ((evt_seq+1)&0x7f); goto _abort_event_; } pevt_priv->event_seq++; /* update evt_seq */ if (pevt_priv->event_seq > 127) pevt_priv->event_seq = 0; peventbuf = peventbuf + 2; /* move to event content, 8 bytes aligment */ if (peventbuf) { event_callback = wlanevents[evt_code].event_callback; if (event_callback) event_callback(padapter, (u8 *)peventbuf); } pevt_priv->evt_done_cnt++; _abort_event_: return; }
gpl-2.0
ffosilva/android_kernel_sony_msm8974
net/netfilter/ipvs/ip_vs_wrr.c
5067
5594
/* * IPVS: Weighted Round-Robin Scheduling module * * Authors: Wensong Zhang <wensong@linuxvirtualserver.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. * * Changes: * Wensong Zhang : changed the ip_vs_wrr_schedule to return dest * Wensong Zhang : changed some comestics things for debugging * Wensong Zhang : changed for the d-linked destination list * Wensong Zhang : added the ip_vs_wrr_update_svc * Julian Anastasov : fixed the bug of returning destination * with weight 0 when all weights are zero * */ #define KMSG_COMPONENT "IPVS" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/net.h> #include <linux/gcd.h> #include <net/ip_vs.h> /* * current destination pointer for weighted round-robin scheduling */ struct ip_vs_wrr_mark { struct list_head *cl; /* current list head */ int cw; /* current weight */ int mw; /* maximum weight */ int di; /* decreasing interval */ }; static int ip_vs_wrr_gcd_weight(struct ip_vs_service *svc) { struct ip_vs_dest *dest; int weight; int g = 0; list_for_each_entry(dest, &svc->destinations, n_list) { weight = atomic_read(&dest->weight); if (weight > 0) { if (g > 0) g = gcd(weight, g); else g = weight; } } return g ? g : 1; } /* * Get the maximum weight of the service destinations. */ static int ip_vs_wrr_max_weight(struct ip_vs_service *svc) { struct ip_vs_dest *dest; int new_weight, weight = 0; list_for_each_entry(dest, &svc->destinations, n_list) { new_weight = atomic_read(&dest->weight); if (new_weight > weight) weight = new_weight; } return weight; } static int ip_vs_wrr_init_svc(struct ip_vs_service *svc) { struct ip_vs_wrr_mark *mark; /* * Allocate the mark variable for WRR scheduling */ mark = kmalloc(sizeof(struct ip_vs_wrr_mark), GFP_ATOMIC); if (mark == NULL) return -ENOMEM; mark->cl = &svc->destinations; mark->cw = 0; mark->mw = ip_vs_wrr_max_weight(svc); mark->di = ip_vs_wrr_gcd_weight(svc); svc->sched_data = mark; return 0; } static int ip_vs_wrr_done_svc(struct ip_vs_service *svc) { /* * Release the mark variable */ kfree(svc->sched_data); return 0; } static int ip_vs_wrr_update_svc(struct ip_vs_service *svc) { struct ip_vs_wrr_mark *mark = svc->sched_data; mark->cl = &svc->destinations; mark->mw = ip_vs_wrr_max_weight(svc); mark->di = ip_vs_wrr_gcd_weight(svc); if (mark->cw > mark->mw) mark->cw = 0; return 0; } /* * Weighted Round-Robin Scheduling */ static struct ip_vs_dest * ip_vs_wrr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb) { struct ip_vs_dest *dest; struct ip_vs_wrr_mark *mark = svc->sched_data; struct list_head *p; IP_VS_DBG(6, "%s(): Scheduling...\n", __func__); /* * This loop will always terminate, because mark->cw in (0, max_weight] * and at least one server has its weight equal to max_weight. */ write_lock(&svc->sched_lock); p = mark->cl; while (1) { if (mark->cl == &svc->destinations) { /* it is at the head of the destination list */ if (mark->cl == mark->cl->next) { /* no dest entry */ ip_vs_scheduler_err(svc, "no destination available: " "no destinations present"); dest = NULL; goto out; } mark->cl = svc->destinations.next; mark->cw -= mark->di; if (mark->cw <= 0) { mark->cw = mark->mw; /* * Still zero, which means no available servers. */ if (mark->cw == 0) { mark->cl = &svc->destinations; ip_vs_scheduler_err(svc, "no destination available"); dest = NULL; goto out; } } } else mark->cl = mark->cl->next; if (mark->cl != &svc->destinations) { /* not at the head of the list */ dest = list_entry(mark->cl, struct ip_vs_dest, n_list); if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && atomic_read(&dest->weight) >= mark->cw) { /* got it */ break; } } if (mark->cl == p && mark->cw == mark->di) { /* back to the start, and no dest is found. It is only possible when all dests are OVERLOADED */ dest = NULL; ip_vs_scheduler_err(svc, "no destination available: " "all destinations are overloaded"); goto out; } } IP_VS_DBG_BUF(6, "WRR: server %s:%u " "activeconns %d refcnt %d weight %d\n", IP_VS_DBG_ADDR(svc->af, &dest->addr), ntohs(dest->port), atomic_read(&dest->activeconns), atomic_read(&dest->refcnt), atomic_read(&dest->weight)); out: write_unlock(&svc->sched_lock); return dest; } static struct ip_vs_scheduler ip_vs_wrr_scheduler = { .name = "wrr", .refcnt = ATOMIC_INIT(0), .module = THIS_MODULE, .n_list = LIST_HEAD_INIT(ip_vs_wrr_scheduler.n_list), .init_service = ip_vs_wrr_init_svc, .done_service = ip_vs_wrr_done_svc, .update_service = ip_vs_wrr_update_svc, .schedule = ip_vs_wrr_schedule, }; static int __init ip_vs_wrr_init(void) { return register_ip_vs_scheduler(&ip_vs_wrr_scheduler) ; } static void __exit ip_vs_wrr_cleanup(void) { unregister_ip_vs_scheduler(&ip_vs_wrr_scheduler); } module_init(ip_vs_wrr_init); module_exit(ip_vs_wrr_cleanup); MODULE_LICENSE("GPL");
gpl-2.0