repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
cornedor/android_kernel_htc_enrc2b | drivers/video/tegra/host/nvhost_acm.c | 21 | 16747 | /*
* drivers/video/tegra/host/nvhost_acm.c
*
* Tegra Graphics Host Automatic Clock Management
*
* Copyright (c) 2010-2012, NVIDIA Corporation. All rights reserved.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "nvhost_acm.h"
#include "dev.h"
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/sched.h>
#include <linux/err.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <mach/powergate.h>
#include <mach/clk.h>
#include <mach/hardware.h>
#define ACM_SUSPEND_WAIT_FOR_IDLE_TIMEOUT (2 * HZ)
#define POWERGATE_DELAY 10
#define MAX_DEVID_LENGTH 16
DEFINE_MUTEX(client_list_lock);
struct nvhost_module_client {
struct list_head node;
unsigned long rate[NVHOST_MODULE_MAX_CLOCKS];
void *priv;
};
static void do_powergate_locked(int id)
{
if (id != -1 && tegra_powergate_is_powered(id))
tegra_powergate_partition(id);
}
static void do_unpowergate_locked(int id)
{
if (id != -1)
tegra_unpowergate_partition(id);
}
static void do_module_reset_locked(struct nvhost_device *dev)
{
/* assert module and mc client reset */
if (dev->powergate_ids[0] != -1) {
tegra_powergate_mc_disable(dev->powergate_ids[0]);
tegra_periph_reset_assert(dev->clk[0]);
tegra_powergate_mc_flush(dev->powergate_ids[0]);
}
if (dev->powergate_ids[1] != -1) {
tegra_powergate_mc_disable(dev->powergate_ids[1]);
tegra_periph_reset_assert(dev->clk[1]);
tegra_powergate_mc_flush(dev->powergate_ids[1]);
}
udelay(POWERGATE_DELAY);
/* deassert reset */
if (dev->powergate_ids[0] != -1) {
tegra_powergate_mc_flush_done(dev->powergate_ids[0]);
tegra_periph_reset_deassert(dev->clk[0]);
tegra_powergate_mc_enable(dev->powergate_ids[0]);
}
if (dev->powergate_ids[1] != -1) {
tegra_powergate_mc_flush_done(dev->powergate_ids[1]);
tegra_periph_reset_deassert(dev->clk[1]);
tegra_powergate_mc_enable(dev->powergate_ids[1]);
}
}
void nvhost_module_reset(struct nvhost_device *dev)
{
dev_dbg(&dev->dev,
"%s: asserting %s module reset (id %d, id2 %d)\n",
__func__, dev->name,
dev->powergate_ids[0], dev->powergate_ids[1]);
mutex_lock(&dev->lock);
do_module_reset_locked(dev);
mutex_unlock(&dev->lock);
dev_dbg(&dev->dev, "%s: module %s out of reset\n",
__func__, dev->name);
}
static void to_state_clockgated_locked(struct nvhost_device *dev)
{
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
if (dev->powerstate == NVHOST_POWER_STATE_RUNNING) {
int i, err;
if (drv->prepare_clockoff) {
err = drv->prepare_clockoff(dev);
if (err) {
dev_err(&dev->dev, "error clock gating");
return;
}
}
for (i = 0; i < dev->num_clks; i++)
clk_disable(dev->clk[i]);
if (dev->dev.parent)
nvhost_module_idle(to_nvhost_device(dev->dev.parent));
} else if (dev->powerstate == NVHOST_POWER_STATE_POWERGATED
&& dev->can_powergate) {
do_unpowergate_locked(dev->powergate_ids[0]);
do_unpowergate_locked(dev->powergate_ids[1]);
if (dev->powerup_reset)
do_module_reset_locked(dev);
}
dev->powerstate = NVHOST_POWER_STATE_CLOCKGATED;
}
static void to_state_running_locked(struct nvhost_device *dev)
{
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
int prev_state = dev->powerstate;
if (dev->powerstate == NVHOST_POWER_STATE_POWERGATED)
to_state_clockgated_locked(dev);
if (dev->powerstate == NVHOST_POWER_STATE_CLOCKGATED) {
int i;
if (dev->dev.parent)
nvhost_module_busy(to_nvhost_device(dev->dev.parent));
for (i = 0; i < dev->num_clks; i++) {
int err = clk_enable(dev->clk[i]);
if (err) {
dev_err(&dev->dev, "Cannot turn on clock %s",
dev->clocks[i].name);
return;
}
}
/* Invoke callback after enabling clock. This is used for
* re-enabling host1x interrupts. */
if (prev_state == NVHOST_POWER_STATE_CLOCKGATED
&& drv->finalize_clockon)
drv->finalize_clockon(dev);
/* Invoke callback after power un-gating. This is used for
* restoring context. */
if (prev_state == NVHOST_POWER_STATE_POWERGATED
&& drv->finalize_poweron)
drv->finalize_poweron(dev);
}
dev->powerstate = NVHOST_POWER_STATE_RUNNING;
}
/* This gets called from powergate_handler() and from module suspend.
* Module suspend is done for all modules, runtime power gating only
* for modules with can_powergate set.
*/
static int to_state_powergated_locked(struct nvhost_device *dev)
{
int err = 0;
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
if (drv->prepare_poweroff
&& dev->powerstate != NVHOST_POWER_STATE_POWERGATED) {
/* Clock needs to be on in prepare_poweroff */
to_state_running_locked(dev);
err = drv->prepare_poweroff(dev);
if (err)
return err;
}
if (dev->powerstate == NVHOST_POWER_STATE_RUNNING)
to_state_clockgated_locked(dev);
if (dev->can_powergate) {
do_powergate_locked(dev->powergate_ids[0]);
do_powergate_locked(dev->powergate_ids[1]);
}
dev->powerstate = NVHOST_POWER_STATE_POWERGATED;
return 0;
}
static void schedule_powergating_locked(struct nvhost_device *dev)
{
if (dev->can_powergate)
schedule_delayed_work(&dev->powerstate_down,
msecs_to_jiffies(dev->powergate_delay));
}
static void schedule_clockgating_locked(struct nvhost_device *dev)
{
schedule_delayed_work(&dev->powerstate_down,
msecs_to_jiffies(dev->clockgate_delay));
}
void nvhost_module_busy(struct nvhost_device *dev)
{
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
if (drv->busy)
drv->busy(dev);
mutex_lock(&dev->lock);
cancel_delayed_work(&dev->powerstate_down);
dev->refcount++;
if (dev->refcount > 0 && !nvhost_module_powered(dev))
to_state_running_locked(dev);
mutex_unlock(&dev->lock);
}
static void powerstate_down_handler(struct work_struct *work)
{
struct nvhost_device *dev;
dev = container_of(to_delayed_work(work),
struct nvhost_device,
powerstate_down);
mutex_lock(&dev->lock);
if (dev->refcount == 0) {
switch (dev->powerstate) {
case NVHOST_POWER_STATE_RUNNING:
to_state_clockgated_locked(dev);
schedule_powergating_locked(dev);
break;
case NVHOST_POWER_STATE_CLOCKGATED:
if (to_state_powergated_locked(dev))
schedule_powergating_locked(dev);
break;
default:
break;
}
}
mutex_unlock(&dev->lock);
}
void nvhost_module_idle_mult(struct nvhost_device *dev, int refs)
{
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
bool kick = false;
mutex_lock(&dev->lock);
dev->refcount -= refs;
if (dev->refcount == 0) {
if (nvhost_module_powered(dev))
schedule_clockgating_locked(dev);
kick = true;
}
mutex_unlock(&dev->lock);
if (kick) {
wake_up(&dev->idle_wq);
if (drv->idle)
drv->idle(dev);
}
}
int nvhost_module_get_rate(struct nvhost_device *dev, unsigned long *rate,
int index)
{
struct clk *c;
c = dev->clk[index];
if (IS_ERR_OR_NULL(c))
return -EINVAL;
/* Need to enable client to get correct rate */
nvhost_module_busy(dev);
*rate = clk_get_rate(c);
nvhost_module_idle(dev);
return 0;
}
static int nvhost_module_update_rate(struct nvhost_device *dev, int index)
{
unsigned long rate = 0;
struct nvhost_module_client *m;
if (!dev->clk[index])
return -EINVAL;
list_for_each_entry(m, &dev->client_list, node) {
rate = max(m->rate[index], rate);
}
if (!rate)
rate = clk_round_rate(dev->clk[index],
dev->clocks[index].default_rate);
return clk_set_rate(dev->clk[index], rate);
}
int nvhost_module_set_rate(struct nvhost_device *dev, void *priv,
unsigned long rate, int index)
{
struct nvhost_module_client *m;
int i, ret = 0;
mutex_lock(&client_list_lock);
list_for_each_entry(m, &dev->client_list, node) {
if (m->priv == priv) {
for (i = 0; i < dev->num_clks; i++)
m->rate[i] = clk_round_rate(dev->clk[i], rate);
break;
}
}
for (i = 0; i < dev->num_clks; i++) {
ret = nvhost_module_update_rate(dev, i);
if (ret < 0)
break;
}
mutex_unlock(&client_list_lock);
return ret;
}
int nvhost_module_add_client(struct nvhost_device *dev, void *priv)
{
int i;
unsigned long rate;
struct nvhost_module_client *client;
client = kzalloc(sizeof(*client), GFP_KERNEL);
if (!client)
return -ENOMEM;
INIT_LIST_HEAD(&client->node);
client->priv = priv;
for (i = 0; i < dev->num_clks; i++) {
rate = clk_round_rate(dev->clk[i],
dev->clocks[i].default_rate);
client->rate[i] = rate;
}
mutex_lock(&client_list_lock);
list_add_tail(&client->node, &dev->client_list);
mutex_unlock(&client_list_lock);
return 0;
}
void nvhost_module_remove_client(struct nvhost_device *dev, void *priv)
{
int i;
struct nvhost_module_client *m;
int found = 0;
mutex_lock(&client_list_lock);
list_for_each_entry(m, &dev->client_list, node) {
if (priv == m->priv) {
list_del(&m->node);
found = 1;
break;
}
}
if (found) {
kfree(m);
for (i = 0; i < dev->num_clks; i++)
nvhost_module_update_rate(dev, i);
}
mutex_unlock(&client_list_lock);
}
static ssize_t refcount_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
int ret;
struct nvhost_device_power_attr *power_attribute =
container_of(attr, struct nvhost_device_power_attr, \
power_attr[NVHOST_POWER_SYSFS_ATTRIB_REFCOUNT]);
struct nvhost_device *dev = power_attribute->ndev;
mutex_lock(&dev->lock);
ret = sprintf(buf, "%d\n", dev->refcount);
mutex_unlock(&dev->lock);
return ret;
}
static ssize_t powergate_delay_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
int powergate_delay = 0, ret = 0;
struct nvhost_device_power_attr *power_attribute =
container_of(attr, struct nvhost_device_power_attr, \
power_attr[NVHOST_POWER_SYSFS_ATTRIB_POWERGATE_DELAY]);
struct nvhost_device *dev = power_attribute->ndev;
if (!dev->can_powergate) {
dev_info(&dev->dev, "does not support power-gating\n");
return count;
}
mutex_lock(&dev->lock);
ret = sscanf(buf, "%d", &powergate_delay);
if (ret == 1 && powergate_delay >= 0)
dev->powergate_delay = powergate_delay;
else
dev_err(&dev->dev, "Invalid powergate delay\n");
mutex_unlock(&dev->lock);
return count;
}
static ssize_t powergate_delay_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
int ret;
struct nvhost_device_power_attr *power_attribute =
container_of(attr, struct nvhost_device_power_attr, \
power_attr[NVHOST_POWER_SYSFS_ATTRIB_POWERGATE_DELAY]);
struct nvhost_device *dev = power_attribute->ndev;
mutex_lock(&dev->lock);
ret = sprintf(buf, "%d\n", dev->powergate_delay);
mutex_unlock(&dev->lock);
return ret;
}
static ssize_t clockgate_delay_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
int clockgate_delay = 0, ret = 0;
struct nvhost_device_power_attr *power_attribute =
container_of(attr, struct nvhost_device_power_attr, \
power_attr[NVHOST_POWER_SYSFS_ATTRIB_CLOCKGATE_DELAY]);
struct nvhost_device *dev = power_attribute->ndev;
mutex_lock(&dev->lock);
ret = sscanf(buf, "%d", &clockgate_delay);
if (ret == 1 && clockgate_delay >= 0)
dev->clockgate_delay = clockgate_delay;
else
dev_err(&dev->dev, "Invalid clockgate delay\n");
mutex_unlock(&dev->lock);
return count;
}
static ssize_t clockgate_delay_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
int ret;
struct nvhost_device_power_attr *power_attribute =
container_of(attr, struct nvhost_device_power_attr, \
power_attr[NVHOST_POWER_SYSFS_ATTRIB_CLOCKGATE_DELAY]);
struct nvhost_device *dev = power_attribute->ndev;
mutex_lock(&dev->lock);
ret = sprintf(buf, "%d\n", dev->clockgate_delay);
mutex_unlock(&dev->lock);
return ret;
}
int nvhost_module_init(struct nvhost_device *dev)
{
int i = 0, err = 0;
struct kobj_attribute *attr = NULL;
/* initialize clocks to known state */
INIT_LIST_HEAD(&dev->client_list);
while (dev->clocks[i].name && i < NVHOST_MODULE_MAX_CLOCKS) {
char devname[MAX_DEVID_LENGTH];
long rate = dev->clocks[i].default_rate;
struct clk *c;
snprintf(devname, MAX_DEVID_LENGTH, "tegra_%s", dev->name);
c = clk_get_sys(devname, dev->clocks[i].name);
if (IS_ERR_OR_NULL(c)) {
dev_err(&dev->dev, "Cannot get clock %s\n",
dev->clocks[i].name);
continue;
}
rate = clk_round_rate(c, rate);
clk_enable(c);
clk_set_rate(c, rate);
clk_disable(c);
dev->clk[i] = c;
i++;
}
dev->num_clks = i;
mutex_init(&dev->lock);
init_waitqueue_head(&dev->idle_wq);
INIT_DELAYED_WORK(&dev->powerstate_down, powerstate_down_handler);
/* power gate units that we can power gate */
if (dev->can_powergate) {
do_powergate_locked(dev->powergate_ids[0]);
do_powergate_locked(dev->powergate_ids[1]);
dev->powerstate = NVHOST_POWER_STATE_POWERGATED;
} else {
do_unpowergate_locked(dev->powergate_ids[0]);
do_unpowergate_locked(dev->powergate_ids[1]);
dev->powerstate = NVHOST_POWER_STATE_CLOCKGATED;
}
/* Init the power sysfs attributes for this device */
dev->power_attrib = kzalloc(sizeof(struct nvhost_device_power_attr),
GFP_KERNEL);
if (!dev->power_attrib) {
dev_err(&dev->dev, "Unable to allocate sysfs attributes\n");
return -ENOMEM;
}
dev->power_attrib->ndev = dev;
dev->power_kobj = kobject_create_and_add("acm", &dev->dev.kobj);
if (!dev->power_kobj) {
dev_err(&dev->dev, "Could not add dir 'power'\n");
err = -EIO;
goto fail_attrib_alloc;
}
attr = &dev->power_attrib->power_attr[NVHOST_POWER_SYSFS_ATTRIB_CLOCKGATE_DELAY];
attr->attr.name = "clockgate_delay";
attr->attr.mode = S_IWUSR | S_IRUGO;
attr->show = clockgate_delay_show;
attr->store = clockgate_delay_store;
if (sysfs_create_file(dev->power_kobj, &attr->attr)) {
dev_err(&dev->dev, "Could not create sysfs attribute clockgate_delay\n");
err = -EIO;
goto fail_clockdelay;
}
attr = &dev->power_attrib->power_attr[NVHOST_POWER_SYSFS_ATTRIB_POWERGATE_DELAY];
attr->attr.name = "powergate_delay";
attr->attr.mode = S_IWUSR | S_IRUGO;
attr->show = powergate_delay_show;
attr->store = powergate_delay_store;
if (sysfs_create_file(dev->power_kobj, &attr->attr)) {
dev_err(&dev->dev, "Could not create sysfs attribute powergate_delay\n");
err = -EIO;
goto fail_powergatedelay;
}
attr = &dev->power_attrib->power_attr[NVHOST_POWER_SYSFS_ATTRIB_REFCOUNT];
attr->attr.name = "refcount";
attr->attr.mode = S_IRUGO;
attr->show = refcount_show;
if (sysfs_create_file(dev->power_kobj, &attr->attr)) {
dev_err(&dev->dev, "Could not create sysfs attribute refcount\n");
err = -EIO;
goto fail_refcount;
}
return 0;
fail_refcount:
attr = &dev->power_attrib->power_attr[NVHOST_POWER_SYSFS_ATTRIB_POWERGATE_DELAY];
sysfs_remove_file(dev->power_kobj, &attr->attr);
fail_powergatedelay:
attr = &dev->power_attrib->power_attr[NVHOST_POWER_SYSFS_ATTRIB_CLOCKGATE_DELAY];
sysfs_remove_file(dev->power_kobj, &attr->attr);
fail_clockdelay:
kobject_put(dev->power_kobj);
fail_attrib_alloc:
kfree(dev->power_attrib);
return err;
}
static int is_module_idle(struct nvhost_device *dev)
{
int count;
mutex_lock(&dev->lock);
count = dev->refcount;
mutex_unlock(&dev->lock);
return (count == 0);
}
int nvhost_module_suspend(struct nvhost_device *dev)
{
int ret;
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
ret = wait_event_timeout(dev->idle_wq, is_module_idle(dev),
ACM_SUSPEND_WAIT_FOR_IDLE_TIMEOUT);
if (ret == 0) {
dev_info(&dev->dev, "%s prevented suspend\n",
dev->name);
return -EBUSY;
}
mutex_lock(&dev->lock);
cancel_delayed_work(&dev->powerstate_down);
to_state_powergated_locked(dev);
mutex_unlock(&dev->lock);
if (drv->suspend_ndev)
drv->suspend_ndev(dev);
return 0;
}
void nvhost_module_deinit(struct nvhost_device *dev)
{
int i;
struct nvhost_driver *drv = to_nvhost_driver(dev->dev.driver);
if (drv->deinit)
drv->deinit(dev);
nvhost_module_suspend(dev);
for (i = 0; i < dev->num_clks; i++)
clk_put(dev->clk[i]);
dev->powerstate = NVHOST_POWER_STATE_DEINIT;
}
/* public host1x power management APIs */
bool nvhost_module_powered_ext(struct nvhost_device *dev)
{
return nvhost_module_powered(dev);
}
void nvhost_module_busy_ext(struct nvhost_device *dev)
{
nvhost_module_busy(dev);
}
void nvhost_module_idle_ext(struct nvhost_device *dev)
{
nvhost_module_idle(dev);
}
| gpl-2.0 |
foomango/linux-3.7.1 | arch/sparc/kernel/leon_smp.c | 277 | 12376 | /* leon_smp.c: Sparc-Leon SMP support.
*
* based on sun4m_smp.c
* Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 2009 Daniel Hellstrom (daniel@gaisler.com) Aeroflex Gaisler AB
* Copyright (C) 2009 Konrad Eisele (konrad@gaisler.com) Aeroflex Gaisler AB
*/
#include <asm/head.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/threads.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/of.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/profile.h>
#include <linux/pm.h>
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/cpu.h>
#include <linux/clockchips.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/ptrace.h>
#include <linux/atomic.h>
#include <asm/irq_regs.h>
#include <asm/traps.h>
#include <asm/delay.h>
#include <asm/irq.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/oplib.h>
#include <asm/cpudata.h>
#include <asm/asi.h>
#include <asm/leon.h>
#include <asm/leon_amba.h>
#include <asm/timer.h>
#include "kernel.h"
#include "irq.h"
extern ctxd_t *srmmu_ctx_table_phys;
static int smp_processors_ready;
extern volatile unsigned long cpu_callin_map[NR_CPUS];
extern cpumask_t smp_commenced_mask;
void __cpuinit leon_configure_cache_smp(void);
static void leon_ipi_init(void);
/* IRQ number of LEON IPIs */
int leon_ipi_irq = LEON3_IRQ_IPI_DEFAULT;
static inline unsigned long do_swap(volatile unsigned long *ptr,
unsigned long val)
{
__asm__ __volatile__("swapa [%2] %3, %0\n\t" : "=&r"(val)
: "0"(val), "r"(ptr), "i"(ASI_LEON_DCACHE_MISS)
: "memory");
return val;
}
void __cpuinit leon_callin(void)
{
int cpuid = hard_smp_processor_id();
local_ops->cache_all();
local_ops->tlb_all();
leon_configure_cache_smp();
notify_cpu_starting(cpuid);
/* Get our local ticker going. */
register_percpu_ce(cpuid);
calibrate_delay();
smp_store_cpu_info(cpuid);
local_ops->cache_all();
local_ops->tlb_all();
/*
* Unblock the master CPU _only_ when the scheduler state
* of all secondary CPUs will be up-to-date, so after
* the SMP initialization the master will be just allowed
* to call the scheduler code.
* Allow master to continue.
*/
do_swap(&cpu_callin_map[cpuid], 1);
local_ops->cache_all();
local_ops->tlb_all();
/* Fix idle thread fields. */
__asm__ __volatile__("ld [%0], %%g6\n\t" : : "r"(¤t_set[cpuid])
: "memory" /* paranoid */);
/* Attach to the address space of init_task. */
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
while (!cpumask_test_cpu(cpuid, &smp_commenced_mask))
mb();
local_irq_enable();
set_cpu_online(cpuid, true);
}
/*
* Cycle through the processors asking the PROM to start each one.
*/
extern struct linux_prom_registers smp_penguin_ctable;
void __cpuinit leon_configure_cache_smp(void)
{
unsigned long cfg = sparc_leon3_get_dcachecfg();
int me = smp_processor_id();
if (ASI_LEON3_SYSCTRL_CFG_SSIZE(cfg) > 4) {
printk(KERN_INFO "Note: SMP with snooping only works on 4k cache, found %dk(0x%x) on cpu %d, disabling caches\n",
(unsigned int)ASI_LEON3_SYSCTRL_CFG_SSIZE(cfg),
(unsigned int)cfg, (unsigned int)me);
sparc_leon3_disable_cache();
} else {
if (cfg & ASI_LEON3_SYSCTRL_CFG_SNOOPING) {
sparc_leon3_enable_snooping();
} else {
printk(KERN_INFO "Note: You have to enable snooping in the vhdl model cpu %d, disabling caches\n",
me);
sparc_leon3_disable_cache();
}
}
local_ops->cache_all();
local_ops->tlb_all();
}
void leon_smp_setbroadcast(unsigned int mask)
{
int broadcast =
((LEON3_BYPASS_LOAD_PA(&(leon3_irqctrl_regs->mpstatus)) >>
LEON3_IRQMPSTATUS_BROADCAST) & 1);
if (!broadcast) {
prom_printf("######## !!!! The irqmp-ctrl must have broadcast enabled, smp wont work !!!!! ####### nr cpus: %d\n",
leon_smp_nrcpus());
if (leon_smp_nrcpus() > 1) {
BUG();
} else {
prom_printf("continue anyway\n");
return;
}
}
LEON_BYPASS_STORE_PA(&(leon3_irqctrl_regs->mpbroadcast), mask);
}
unsigned int leon_smp_getbroadcast(void)
{
unsigned int mask;
mask = LEON_BYPASS_LOAD_PA(&(leon3_irqctrl_regs->mpbroadcast));
return mask;
}
int leon_smp_nrcpus(void)
{
int nrcpu =
((LEON3_BYPASS_LOAD_PA(&(leon3_irqctrl_regs->mpstatus)) >>
LEON3_IRQMPSTATUS_CPUNR) & 0xf) + 1;
return nrcpu;
}
void __init leon_boot_cpus(void)
{
int nrcpu = leon_smp_nrcpus();
int me = smp_processor_id();
/* Setup IPI */
leon_ipi_init();
printk(KERN_INFO "%d:(%d:%d) cpus mpirq at 0x%x\n", (unsigned int)me,
(unsigned int)nrcpu, (unsigned int)NR_CPUS,
(unsigned int)&(leon3_irqctrl_regs->mpstatus));
leon_enable_irq_cpu(LEON3_IRQ_CROSS_CALL, me);
leon_enable_irq_cpu(LEON3_IRQ_TICKER, me);
leon_enable_irq_cpu(leon_ipi_irq, me);
leon_smp_setbroadcast(1 << LEON3_IRQ_TICKER);
leon_configure_cache_smp();
local_ops->cache_all();
}
int __cpuinit leon_boot_one_cpu(int i, struct task_struct *idle)
{
int timeout;
current_set[i] = task_thread_info(idle);
/* See trampoline.S:leon_smp_cpu_startup for details...
* Initialize the contexts table
* Since the call to prom_startcpu() trashes the structure,
* we need to re-initialize it for each cpu
*/
smp_penguin_ctable.which_io = 0;
smp_penguin_ctable.phys_addr = (unsigned int)srmmu_ctx_table_phys;
smp_penguin_ctable.reg_size = 0;
/* whirrr, whirrr, whirrrrrrrrr... */
printk(KERN_INFO "Starting CPU %d : (irqmp: 0x%x)\n", (unsigned int)i,
(unsigned int)&leon3_irqctrl_regs->mpstatus);
local_ops->cache_all();
/* Make sure all IRQs are of from the start for this new CPU */
LEON_BYPASS_STORE_PA(&leon3_irqctrl_regs->mask[i], 0);
/* Wake one CPU */
LEON_BYPASS_STORE_PA(&(leon3_irqctrl_regs->mpstatus), 1 << i);
/* wheee... it's going... */
for (timeout = 0; timeout < 10000; timeout++) {
if (cpu_callin_map[i])
break;
udelay(200);
}
printk(KERN_INFO "Started CPU %d\n", (unsigned int)i);
if (!(cpu_callin_map[i])) {
printk(KERN_ERR "Processor %d is stuck.\n", i);
return -ENODEV;
} else {
leon_enable_irq_cpu(LEON3_IRQ_CROSS_CALL, i);
leon_enable_irq_cpu(LEON3_IRQ_TICKER, i);
leon_enable_irq_cpu(leon_ipi_irq, i);
}
local_ops->cache_all();
return 0;
}
void __init leon_smp_done(void)
{
int i, first;
int *prev;
/* setup cpu list for irq rotation */
first = 0;
prev = &first;
for (i = 0; i < NR_CPUS; i++) {
if (cpu_online(i)) {
*prev = i;
prev = &cpu_data(i).next;
}
}
*prev = first;
local_ops->cache_all();
/* Free unneeded trap tables */
if (!cpu_present(1)) {
ClearPageReserved(virt_to_page(&trapbase_cpu1));
init_page_count(virt_to_page(&trapbase_cpu1));
free_page((unsigned long)&trapbase_cpu1);
totalram_pages++;
num_physpages++;
}
if (!cpu_present(2)) {
ClearPageReserved(virt_to_page(&trapbase_cpu2));
init_page_count(virt_to_page(&trapbase_cpu2));
free_page((unsigned long)&trapbase_cpu2);
totalram_pages++;
num_physpages++;
}
if (!cpu_present(3)) {
ClearPageReserved(virt_to_page(&trapbase_cpu3));
init_page_count(virt_to_page(&trapbase_cpu3));
free_page((unsigned long)&trapbase_cpu3);
totalram_pages++;
num_physpages++;
}
/* Ok, they are spinning and ready to go. */
smp_processors_ready = 1;
}
void leon_irq_rotate(int cpu)
{
}
struct leon_ipi_work {
int single;
int msk;
int resched;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct leon_ipi_work, leon_ipi_work);
/* Initialize IPIs on the LEON, in order to save IRQ resources only one IRQ
* is used for all three types of IPIs.
*/
static void __init leon_ipi_init(void)
{
int cpu, len;
struct leon_ipi_work *work;
struct property *pp;
struct device_node *rootnp;
struct tt_entry *trap_table;
unsigned long flags;
/* Find IPI IRQ or stick with default value */
rootnp = of_find_node_by_path("/ambapp0");
if (rootnp) {
pp = of_find_property(rootnp, "ipi_num", &len);
if (pp && (*(int *)pp->value))
leon_ipi_irq = *(int *)pp->value;
}
printk(KERN_INFO "leon: SMP IPIs at IRQ %d\n", leon_ipi_irq);
/* Adjust so that we jump directly to smpleon_ipi */
local_irq_save(flags);
trap_table = &sparc_ttable[SP_TRAP_IRQ1 + (leon_ipi_irq - 1)];
trap_table->inst_three += smpleon_ipi - real_irq_entry;
local_ops->cache_all();
local_irq_restore(flags);
for_each_possible_cpu(cpu) {
work = &per_cpu(leon_ipi_work, cpu);
work->single = work->msk = work->resched = 0;
}
}
static void leon_send_ipi(int cpu, int level)
{
unsigned long mask;
mask = leon_get_irqmask(level);
LEON3_BYPASS_STORE_PA(&leon3_irqctrl_regs->force[cpu], mask);
}
static void leon_ipi_single(int cpu)
{
struct leon_ipi_work *work = &per_cpu(leon_ipi_work, cpu);
/* Mark work */
work->single = 1;
/* Generate IRQ on the CPU */
leon_send_ipi(cpu, leon_ipi_irq);
}
static void leon_ipi_mask_one(int cpu)
{
struct leon_ipi_work *work = &per_cpu(leon_ipi_work, cpu);
/* Mark work */
work->msk = 1;
/* Generate IRQ on the CPU */
leon_send_ipi(cpu, leon_ipi_irq);
}
static void leon_ipi_resched(int cpu)
{
struct leon_ipi_work *work = &per_cpu(leon_ipi_work, cpu);
/* Mark work */
work->resched = 1;
/* Generate IRQ on the CPU (any IRQ will cause resched) */
leon_send_ipi(cpu, leon_ipi_irq);
}
void leonsmp_ipi_interrupt(void)
{
struct leon_ipi_work *work = &__get_cpu_var(leon_ipi_work);
if (work->single) {
work->single = 0;
smp_call_function_single_interrupt();
}
if (work->msk) {
work->msk = 0;
smp_call_function_interrupt();
}
if (work->resched) {
work->resched = 0;
smp_resched_interrupt();
}
}
static struct smp_funcall {
smpfunc_t func;
unsigned long arg1;
unsigned long arg2;
unsigned long arg3;
unsigned long arg4;
unsigned long arg5;
unsigned long processors_in[NR_CPUS]; /* Set when ipi entered. */
unsigned long processors_out[NR_CPUS]; /* Set when ipi exited. */
} ccall_info;
static DEFINE_SPINLOCK(cross_call_lock);
/* Cross calls must be serialized, at least currently. */
static void leon_cross_call(smpfunc_t func, cpumask_t mask, unsigned long arg1,
unsigned long arg2, unsigned long arg3,
unsigned long arg4)
{
if (smp_processors_ready) {
register int high = NR_CPUS - 1;
unsigned long flags;
spin_lock_irqsave(&cross_call_lock, flags);
{
/* If you make changes here, make sure gcc generates proper code... */
register smpfunc_t f asm("i0") = func;
register unsigned long a1 asm("i1") = arg1;
register unsigned long a2 asm("i2") = arg2;
register unsigned long a3 asm("i3") = arg3;
register unsigned long a4 asm("i4") = arg4;
register unsigned long a5 asm("i5") = 0;
__asm__ __volatile__("std %0, [%6]\n\t"
"std %2, [%6 + 8]\n\t"
"std %4, [%6 + 16]\n\t" : :
"r"(f), "r"(a1), "r"(a2), "r"(a3),
"r"(a4), "r"(a5),
"r"(&ccall_info.func));
}
/* Init receive/complete mapping, plus fire the IPI's off. */
{
register int i;
cpumask_clear_cpu(smp_processor_id(), &mask);
cpumask_and(&mask, cpu_online_mask, &mask);
for (i = 0; i <= high; i++) {
if (cpumask_test_cpu(i, &mask)) {
ccall_info.processors_in[i] = 0;
ccall_info.processors_out[i] = 0;
leon_send_ipi(i, LEON3_IRQ_CROSS_CALL);
}
}
}
{
register int i;
i = 0;
do {
if (!cpumask_test_cpu(i, &mask))
continue;
while (!ccall_info.processors_in[i])
barrier();
} while (++i <= high);
i = 0;
do {
if (!cpumask_test_cpu(i, &mask))
continue;
while (!ccall_info.processors_out[i])
barrier();
} while (++i <= high);
}
spin_unlock_irqrestore(&cross_call_lock, flags);
}
}
/* Running cross calls. */
void leon_cross_call_irq(void)
{
int i = smp_processor_id();
ccall_info.processors_in[i] = 1;
ccall_info.func(ccall_info.arg1, ccall_info.arg2, ccall_info.arg3,
ccall_info.arg4, ccall_info.arg5);
ccall_info.processors_out[i] = 1;
}
static const struct sparc32_ipi_ops leon_ipi_ops = {
.cross_call = leon_cross_call,
.resched = leon_ipi_resched,
.single = leon_ipi_single,
.mask_one = leon_ipi_mask_one,
};
void __init leon_init_smp(void)
{
/* Patch ipi15 trap table */
t_nmi[1] = t_nmi[1] + (linux_trap_ipi15_leon - linux_trap_ipi15_sun4m);
sparc32_ipi_ops = &leon_ipi_ops;
}
| gpl-2.0 |
janarthananfit/android_kernel_beni_jana | drivers/dma/mv_xor.c | 533 | 36337 | /*
* offload engine driver for the Marvell XOR engine
* Copyright (C) 2007, 2008, Marvell International Ltd.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/memory.h>
#include <plat/mv_xor.h>
#include "mv_xor.h"
static void mv_xor_issue_pending(struct dma_chan *chan);
#define to_mv_xor_chan(chan) \
container_of(chan, struct mv_xor_chan, common)
#define to_mv_xor_device(dev) \
container_of(dev, struct mv_xor_device, common)
#define to_mv_xor_slot(tx) \
container_of(tx, struct mv_xor_desc_slot, async_tx)
static void mv_desc_init(struct mv_xor_desc_slot *desc, unsigned long flags)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
hw_desc->status = (1 << 31);
hw_desc->phy_next_desc = 0;
hw_desc->desc_command = (1 << 31);
}
static u32 mv_desc_get_dest_addr(struct mv_xor_desc_slot *desc)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
return hw_desc->phy_dest_addr;
}
static u32 mv_desc_get_src_addr(struct mv_xor_desc_slot *desc,
int src_idx)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
return hw_desc->phy_src_addr[src_idx];
}
static void mv_desc_set_byte_count(struct mv_xor_desc_slot *desc,
u32 byte_count)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
hw_desc->byte_count = byte_count;
}
static void mv_desc_set_next_desc(struct mv_xor_desc_slot *desc,
u32 next_desc_addr)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
BUG_ON(hw_desc->phy_next_desc);
hw_desc->phy_next_desc = next_desc_addr;
}
static void mv_desc_clear_next_desc(struct mv_xor_desc_slot *desc)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
hw_desc->phy_next_desc = 0;
}
static void mv_desc_set_block_fill_val(struct mv_xor_desc_slot *desc, u32 val)
{
desc->value = val;
}
static void mv_desc_set_dest_addr(struct mv_xor_desc_slot *desc,
dma_addr_t addr)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
hw_desc->phy_dest_addr = addr;
}
static int mv_chan_memset_slot_count(size_t len)
{
return 1;
}
#define mv_chan_memcpy_slot_count(c) mv_chan_memset_slot_count(c)
static void mv_desc_set_src_addr(struct mv_xor_desc_slot *desc,
int index, dma_addr_t addr)
{
struct mv_xor_desc *hw_desc = desc->hw_desc;
hw_desc->phy_src_addr[index] = addr;
if (desc->type == DMA_XOR)
hw_desc->desc_command |= (1 << index);
}
static u32 mv_chan_get_current_desc(struct mv_xor_chan *chan)
{
return __raw_readl(XOR_CURR_DESC(chan));
}
static void mv_chan_set_next_descriptor(struct mv_xor_chan *chan,
u32 next_desc_addr)
{
__raw_writel(next_desc_addr, XOR_NEXT_DESC(chan));
}
static void mv_chan_set_dest_pointer(struct mv_xor_chan *chan, u32 desc_addr)
{
__raw_writel(desc_addr, XOR_DEST_POINTER(chan));
}
static void mv_chan_set_block_size(struct mv_xor_chan *chan, u32 block_size)
{
__raw_writel(block_size, XOR_BLOCK_SIZE(chan));
}
static void mv_chan_set_value(struct mv_xor_chan *chan, u32 value)
{
__raw_writel(value, XOR_INIT_VALUE_LOW(chan));
__raw_writel(value, XOR_INIT_VALUE_HIGH(chan));
}
static void mv_chan_unmask_interrupts(struct mv_xor_chan *chan)
{
u32 val = __raw_readl(XOR_INTR_MASK(chan));
val |= XOR_INTR_MASK_VALUE << (chan->idx * 16);
__raw_writel(val, XOR_INTR_MASK(chan));
}
static u32 mv_chan_get_intr_cause(struct mv_xor_chan *chan)
{
u32 intr_cause = __raw_readl(XOR_INTR_CAUSE(chan));
intr_cause = (intr_cause >> (chan->idx * 16)) & 0xFFFF;
return intr_cause;
}
static int mv_is_err_intr(u32 intr_cause)
{
if (intr_cause & ((1<<4)|(1<<5)|(1<<6)|(1<<7)|(1<<8)|(1<<9)))
return 1;
return 0;
}
static void mv_xor_device_clear_eoc_cause(struct mv_xor_chan *chan)
{
u32 val = ~(1 << (chan->idx * 16));
dev_dbg(chan->device->common.dev, "%s, val 0x%08x\n", __func__, val);
__raw_writel(val, XOR_INTR_CAUSE(chan));
}
static void mv_xor_device_clear_err_status(struct mv_xor_chan *chan)
{
u32 val = 0xFFFF0000 >> (chan->idx * 16);
__raw_writel(val, XOR_INTR_CAUSE(chan));
}
static int mv_can_chain(struct mv_xor_desc_slot *desc)
{
struct mv_xor_desc_slot *chain_old_tail = list_entry(
desc->chain_node.prev, struct mv_xor_desc_slot, chain_node);
if (chain_old_tail->type != desc->type)
return 0;
if (desc->type == DMA_MEMSET)
return 0;
return 1;
}
static void mv_set_mode(struct mv_xor_chan *chan,
enum dma_transaction_type type)
{
u32 op_mode;
u32 config = __raw_readl(XOR_CONFIG(chan));
switch (type) {
case DMA_XOR:
op_mode = XOR_OPERATION_MODE_XOR;
break;
case DMA_MEMCPY:
op_mode = XOR_OPERATION_MODE_MEMCPY;
break;
case DMA_MEMSET:
op_mode = XOR_OPERATION_MODE_MEMSET;
break;
default:
dev_printk(KERN_ERR, chan->device->common.dev,
"error: unsupported operation %d.\n",
type);
BUG();
return;
}
config &= ~0x7;
config |= op_mode;
__raw_writel(config, XOR_CONFIG(chan));
chan->current_type = type;
}
static void mv_chan_activate(struct mv_xor_chan *chan)
{
u32 activation;
dev_dbg(chan->device->common.dev, " activate chan.\n");
activation = __raw_readl(XOR_ACTIVATION(chan));
activation |= 0x1;
__raw_writel(activation, XOR_ACTIVATION(chan));
}
static char mv_chan_is_busy(struct mv_xor_chan *chan)
{
u32 state = __raw_readl(XOR_ACTIVATION(chan));
state = (state >> 4) & 0x3;
return (state == 1) ? 1 : 0;
}
static int mv_chan_xor_slot_count(size_t len, int src_cnt)
{
return 1;
}
/**
* mv_xor_free_slots - flags descriptor slots for reuse
* @slot: Slot to free
* Caller must hold &mv_chan->lock while calling this function
*/
static void mv_xor_free_slots(struct mv_xor_chan *mv_chan,
struct mv_xor_desc_slot *slot)
{
dev_dbg(mv_chan->device->common.dev, "%s %d slot %p\n",
__func__, __LINE__, slot);
slot->slots_per_op = 0;
}
/*
* mv_xor_start_new_chain - program the engine to operate on new chain headed by
* sw_desc
* Caller must hold &mv_chan->lock while calling this function
*/
static void mv_xor_start_new_chain(struct mv_xor_chan *mv_chan,
struct mv_xor_desc_slot *sw_desc)
{
dev_dbg(mv_chan->device->common.dev, "%s %d: sw_desc %p\n",
__func__, __LINE__, sw_desc);
if (sw_desc->type != mv_chan->current_type)
mv_set_mode(mv_chan, sw_desc->type);
if (sw_desc->type == DMA_MEMSET) {
/* for memset requests we need to program the engine, no
* descriptors used.
*/
struct mv_xor_desc *hw_desc = sw_desc->hw_desc;
mv_chan_set_dest_pointer(mv_chan, hw_desc->phy_dest_addr);
mv_chan_set_block_size(mv_chan, sw_desc->unmap_len);
mv_chan_set_value(mv_chan, sw_desc->value);
} else {
/* set the hardware chain */
mv_chan_set_next_descriptor(mv_chan, sw_desc->async_tx.phys);
}
mv_chan->pending += sw_desc->slot_cnt;
mv_xor_issue_pending(&mv_chan->common);
}
static dma_cookie_t
mv_xor_run_tx_complete_actions(struct mv_xor_desc_slot *desc,
struct mv_xor_chan *mv_chan, dma_cookie_t cookie)
{
BUG_ON(desc->async_tx.cookie < 0);
if (desc->async_tx.cookie > 0) {
cookie = desc->async_tx.cookie;
/* call the callback (must not sleep or submit new
* operations to this channel)
*/
if (desc->async_tx.callback)
desc->async_tx.callback(
desc->async_tx.callback_param);
/* unmap dma addresses
* (unmap_single vs unmap_page?)
*/
if (desc->group_head && desc->unmap_len) {
struct mv_xor_desc_slot *unmap = desc->group_head;
struct device *dev =
&mv_chan->device->pdev->dev;
u32 len = unmap->unmap_len;
enum dma_ctrl_flags flags = desc->async_tx.flags;
u32 src_cnt;
dma_addr_t addr;
dma_addr_t dest;
src_cnt = unmap->unmap_src_cnt;
dest = mv_desc_get_dest_addr(unmap);
if (!(flags & DMA_COMPL_SKIP_DEST_UNMAP)) {
enum dma_data_direction dir;
if (src_cnt > 1) /* is xor ? */
dir = DMA_BIDIRECTIONAL;
else
dir = DMA_FROM_DEVICE;
dma_unmap_page(dev, dest, len, dir);
}
if (!(flags & DMA_COMPL_SKIP_SRC_UNMAP)) {
while (src_cnt--) {
addr = mv_desc_get_src_addr(unmap,
src_cnt);
if (addr == dest)
continue;
dma_unmap_page(dev, addr, len,
DMA_TO_DEVICE);
}
}
desc->group_head = NULL;
}
}
/* run dependent operations */
dma_run_dependencies(&desc->async_tx);
return cookie;
}
static int
mv_xor_clean_completed_slots(struct mv_xor_chan *mv_chan)
{
struct mv_xor_desc_slot *iter, *_iter;
dev_dbg(mv_chan->device->common.dev, "%s %d\n", __func__, __LINE__);
list_for_each_entry_safe(iter, _iter, &mv_chan->completed_slots,
completed_node) {
if (async_tx_test_ack(&iter->async_tx)) {
list_del(&iter->completed_node);
mv_xor_free_slots(mv_chan, iter);
}
}
return 0;
}
static int
mv_xor_clean_slot(struct mv_xor_desc_slot *desc,
struct mv_xor_chan *mv_chan)
{
dev_dbg(mv_chan->device->common.dev, "%s %d: desc %p flags %d\n",
__func__, __LINE__, desc, desc->async_tx.flags);
list_del(&desc->chain_node);
/* the client is allowed to attach dependent operations
* until 'ack' is set
*/
if (!async_tx_test_ack(&desc->async_tx)) {
/* move this slot to the completed_slots */
list_add_tail(&desc->completed_node, &mv_chan->completed_slots);
return 0;
}
mv_xor_free_slots(mv_chan, desc);
return 0;
}
static void __mv_xor_slot_cleanup(struct mv_xor_chan *mv_chan)
{
struct mv_xor_desc_slot *iter, *_iter;
dma_cookie_t cookie = 0;
int busy = mv_chan_is_busy(mv_chan);
u32 current_desc = mv_chan_get_current_desc(mv_chan);
int seen_current = 0;
dev_dbg(mv_chan->device->common.dev, "%s %d\n", __func__, __LINE__);
dev_dbg(mv_chan->device->common.dev, "current_desc %x\n", current_desc);
mv_xor_clean_completed_slots(mv_chan);
/* free completed slots from the chain starting with
* the oldest descriptor
*/
list_for_each_entry_safe(iter, _iter, &mv_chan->chain,
chain_node) {
prefetch(_iter);
prefetch(&_iter->async_tx);
/* do not advance past the current descriptor loaded into the
* hardware channel, subsequent descriptors are either in
* process or have not been submitted
*/
if (seen_current)
break;
/* stop the search if we reach the current descriptor and the
* channel is busy
*/
if (iter->async_tx.phys == current_desc) {
seen_current = 1;
if (busy)
break;
}
cookie = mv_xor_run_tx_complete_actions(iter, mv_chan, cookie);
if (mv_xor_clean_slot(iter, mv_chan))
break;
}
if ((busy == 0) && !list_empty(&mv_chan->chain)) {
struct mv_xor_desc_slot *chain_head;
chain_head = list_entry(mv_chan->chain.next,
struct mv_xor_desc_slot,
chain_node);
mv_xor_start_new_chain(mv_chan, chain_head);
}
if (cookie > 0)
mv_chan->completed_cookie = cookie;
}
static void
mv_xor_slot_cleanup(struct mv_xor_chan *mv_chan)
{
spin_lock_bh(&mv_chan->lock);
__mv_xor_slot_cleanup(mv_chan);
spin_unlock_bh(&mv_chan->lock);
}
static void mv_xor_tasklet(unsigned long data)
{
struct mv_xor_chan *chan = (struct mv_xor_chan *) data;
mv_xor_slot_cleanup(chan);
}
static struct mv_xor_desc_slot *
mv_xor_alloc_slots(struct mv_xor_chan *mv_chan, int num_slots,
int slots_per_op)
{
struct mv_xor_desc_slot *iter, *_iter, *alloc_start = NULL;
LIST_HEAD(chain);
int slots_found, retry = 0;
/* start search from the last allocated descrtiptor
* if a contiguous allocation can not be found start searching
* from the beginning of the list
*/
retry:
slots_found = 0;
if (retry == 0)
iter = mv_chan->last_used;
else
iter = list_entry(&mv_chan->all_slots,
struct mv_xor_desc_slot,
slot_node);
list_for_each_entry_safe_continue(
iter, _iter, &mv_chan->all_slots, slot_node) {
prefetch(_iter);
prefetch(&_iter->async_tx);
if (iter->slots_per_op) {
/* give up after finding the first busy slot
* on the second pass through the list
*/
if (retry)
break;
slots_found = 0;
continue;
}
/* start the allocation if the slot is correctly aligned */
if (!slots_found++)
alloc_start = iter;
if (slots_found == num_slots) {
struct mv_xor_desc_slot *alloc_tail = NULL;
struct mv_xor_desc_slot *last_used = NULL;
iter = alloc_start;
while (num_slots) {
int i;
/* pre-ack all but the last descriptor */
async_tx_ack(&iter->async_tx);
list_add_tail(&iter->chain_node, &chain);
alloc_tail = iter;
iter->async_tx.cookie = 0;
iter->slot_cnt = num_slots;
iter->xor_check_result = NULL;
for (i = 0; i < slots_per_op; i++) {
iter->slots_per_op = slots_per_op - i;
last_used = iter;
iter = list_entry(iter->slot_node.next,
struct mv_xor_desc_slot,
slot_node);
}
num_slots -= slots_per_op;
}
alloc_tail->group_head = alloc_start;
alloc_tail->async_tx.cookie = -EBUSY;
list_splice(&chain, &alloc_tail->tx_list);
mv_chan->last_used = last_used;
mv_desc_clear_next_desc(alloc_start);
mv_desc_clear_next_desc(alloc_tail);
return alloc_tail;
}
}
if (!retry++)
goto retry;
/* try to free some slots if the allocation fails */
tasklet_schedule(&mv_chan->irq_tasklet);
return NULL;
}
static dma_cookie_t
mv_desc_assign_cookie(struct mv_xor_chan *mv_chan,
struct mv_xor_desc_slot *desc)
{
dma_cookie_t cookie = mv_chan->common.cookie;
if (++cookie < 0)
cookie = 1;
mv_chan->common.cookie = desc->async_tx.cookie = cookie;
return cookie;
}
/************************ DMA engine API functions ****************************/
static dma_cookie_t
mv_xor_tx_submit(struct dma_async_tx_descriptor *tx)
{
struct mv_xor_desc_slot *sw_desc = to_mv_xor_slot(tx);
struct mv_xor_chan *mv_chan = to_mv_xor_chan(tx->chan);
struct mv_xor_desc_slot *grp_start, *old_chain_tail;
dma_cookie_t cookie;
int new_hw_chain = 1;
dev_dbg(mv_chan->device->common.dev,
"%s sw_desc %p: async_tx %p\n",
__func__, sw_desc, &sw_desc->async_tx);
grp_start = sw_desc->group_head;
spin_lock_bh(&mv_chan->lock);
cookie = mv_desc_assign_cookie(mv_chan, sw_desc);
if (list_empty(&mv_chan->chain))
list_splice_init(&sw_desc->tx_list, &mv_chan->chain);
else {
new_hw_chain = 0;
old_chain_tail = list_entry(mv_chan->chain.prev,
struct mv_xor_desc_slot,
chain_node);
list_splice_init(&grp_start->tx_list,
&old_chain_tail->chain_node);
if (!mv_can_chain(grp_start))
goto submit_done;
dev_dbg(mv_chan->device->common.dev, "Append to last desc %x\n",
old_chain_tail->async_tx.phys);
/* fix up the hardware chain */
mv_desc_set_next_desc(old_chain_tail, grp_start->async_tx.phys);
/* if the channel is not busy */
if (!mv_chan_is_busy(mv_chan)) {
u32 current_desc = mv_chan_get_current_desc(mv_chan);
/*
* and the curren desc is the end of the chain before
* the append, then we need to start the channel
*/
if (current_desc == old_chain_tail->async_tx.phys)
new_hw_chain = 1;
}
}
if (new_hw_chain)
mv_xor_start_new_chain(mv_chan, grp_start);
submit_done:
spin_unlock_bh(&mv_chan->lock);
return cookie;
}
/* returns the number of allocated descriptors */
static int mv_xor_alloc_chan_resources(struct dma_chan *chan)
{
char *hw_desc;
int idx;
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
struct mv_xor_desc_slot *slot = NULL;
struct mv_xor_platform_data *plat_data =
mv_chan->device->pdev->dev.platform_data;
int num_descs_in_pool = plat_data->pool_size/MV_XOR_SLOT_SIZE;
/* Allocate descriptor slots */
idx = mv_chan->slots_allocated;
while (idx < num_descs_in_pool) {
slot = kzalloc(sizeof(*slot), GFP_KERNEL);
if (!slot) {
printk(KERN_INFO "MV XOR Channel only initialized"
" %d descriptor slots", idx);
break;
}
hw_desc = (char *) mv_chan->device->dma_desc_pool_virt;
slot->hw_desc = (void *) &hw_desc[idx * MV_XOR_SLOT_SIZE];
dma_async_tx_descriptor_init(&slot->async_tx, chan);
slot->async_tx.tx_submit = mv_xor_tx_submit;
INIT_LIST_HEAD(&slot->chain_node);
INIT_LIST_HEAD(&slot->slot_node);
INIT_LIST_HEAD(&slot->tx_list);
hw_desc = (char *) mv_chan->device->dma_desc_pool;
slot->async_tx.phys =
(dma_addr_t) &hw_desc[idx * MV_XOR_SLOT_SIZE];
slot->idx = idx++;
spin_lock_bh(&mv_chan->lock);
mv_chan->slots_allocated = idx;
list_add_tail(&slot->slot_node, &mv_chan->all_slots);
spin_unlock_bh(&mv_chan->lock);
}
if (mv_chan->slots_allocated && !mv_chan->last_used)
mv_chan->last_used = list_entry(mv_chan->all_slots.next,
struct mv_xor_desc_slot,
slot_node);
dev_dbg(mv_chan->device->common.dev,
"allocated %d descriptor slots last_used: %p\n",
mv_chan->slots_allocated, mv_chan->last_used);
return mv_chan->slots_allocated ? : -ENOMEM;
}
static struct dma_async_tx_descriptor *
mv_xor_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dest, dma_addr_t src,
size_t len, unsigned long flags)
{
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
struct mv_xor_desc_slot *sw_desc, *grp_start;
int slot_cnt;
dev_dbg(mv_chan->device->common.dev,
"%s dest: %x src %x len: %u flags: %ld\n",
__func__, dest, src, len, flags);
if (unlikely(len < MV_XOR_MIN_BYTE_COUNT))
return NULL;
BUG_ON(unlikely(len > MV_XOR_MAX_BYTE_COUNT));
spin_lock_bh(&mv_chan->lock);
slot_cnt = mv_chan_memcpy_slot_count(len);
sw_desc = mv_xor_alloc_slots(mv_chan, slot_cnt, 1);
if (sw_desc) {
sw_desc->type = DMA_MEMCPY;
sw_desc->async_tx.flags = flags;
grp_start = sw_desc->group_head;
mv_desc_init(grp_start, flags);
mv_desc_set_byte_count(grp_start, len);
mv_desc_set_dest_addr(sw_desc->group_head, dest);
mv_desc_set_src_addr(grp_start, 0, src);
sw_desc->unmap_src_cnt = 1;
sw_desc->unmap_len = len;
}
spin_unlock_bh(&mv_chan->lock);
dev_dbg(mv_chan->device->common.dev,
"%s sw_desc %p async_tx %p\n",
__func__, sw_desc, sw_desc ? &sw_desc->async_tx : 0);
return sw_desc ? &sw_desc->async_tx : NULL;
}
static struct dma_async_tx_descriptor *
mv_xor_prep_dma_memset(struct dma_chan *chan, dma_addr_t dest, int value,
size_t len, unsigned long flags)
{
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
struct mv_xor_desc_slot *sw_desc, *grp_start;
int slot_cnt;
dev_dbg(mv_chan->device->common.dev,
"%s dest: %x len: %u flags: %ld\n",
__func__, dest, len, flags);
if (unlikely(len < MV_XOR_MIN_BYTE_COUNT))
return NULL;
BUG_ON(unlikely(len > MV_XOR_MAX_BYTE_COUNT));
spin_lock_bh(&mv_chan->lock);
slot_cnt = mv_chan_memset_slot_count(len);
sw_desc = mv_xor_alloc_slots(mv_chan, slot_cnt, 1);
if (sw_desc) {
sw_desc->type = DMA_MEMSET;
sw_desc->async_tx.flags = flags;
grp_start = sw_desc->group_head;
mv_desc_init(grp_start, flags);
mv_desc_set_byte_count(grp_start, len);
mv_desc_set_dest_addr(sw_desc->group_head, dest);
mv_desc_set_block_fill_val(grp_start, value);
sw_desc->unmap_src_cnt = 1;
sw_desc->unmap_len = len;
}
spin_unlock_bh(&mv_chan->lock);
dev_dbg(mv_chan->device->common.dev,
"%s sw_desc %p async_tx %p \n",
__func__, sw_desc, &sw_desc->async_tx);
return sw_desc ? &sw_desc->async_tx : NULL;
}
static struct dma_async_tx_descriptor *
mv_xor_prep_dma_xor(struct dma_chan *chan, dma_addr_t dest, dma_addr_t *src,
unsigned int src_cnt, size_t len, unsigned long flags)
{
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
struct mv_xor_desc_slot *sw_desc, *grp_start;
int slot_cnt;
if (unlikely(len < MV_XOR_MIN_BYTE_COUNT))
return NULL;
BUG_ON(unlikely(len > MV_XOR_MAX_BYTE_COUNT));
dev_dbg(mv_chan->device->common.dev,
"%s src_cnt: %d len: dest %x %u flags: %ld\n",
__func__, src_cnt, len, dest, flags);
spin_lock_bh(&mv_chan->lock);
slot_cnt = mv_chan_xor_slot_count(len, src_cnt);
sw_desc = mv_xor_alloc_slots(mv_chan, slot_cnt, 1);
if (sw_desc) {
sw_desc->type = DMA_XOR;
sw_desc->async_tx.flags = flags;
grp_start = sw_desc->group_head;
mv_desc_init(grp_start, flags);
/* the byte count field is the same as in memcpy desc*/
mv_desc_set_byte_count(grp_start, len);
mv_desc_set_dest_addr(sw_desc->group_head, dest);
sw_desc->unmap_src_cnt = src_cnt;
sw_desc->unmap_len = len;
while (src_cnt--)
mv_desc_set_src_addr(grp_start, src_cnt, src[src_cnt]);
}
spin_unlock_bh(&mv_chan->lock);
dev_dbg(mv_chan->device->common.dev,
"%s sw_desc %p async_tx %p \n",
__func__, sw_desc, &sw_desc->async_tx);
return sw_desc ? &sw_desc->async_tx : NULL;
}
static void mv_xor_free_chan_resources(struct dma_chan *chan)
{
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
struct mv_xor_desc_slot *iter, *_iter;
int in_use_descs = 0;
mv_xor_slot_cleanup(mv_chan);
spin_lock_bh(&mv_chan->lock);
list_for_each_entry_safe(iter, _iter, &mv_chan->chain,
chain_node) {
in_use_descs++;
list_del(&iter->chain_node);
}
list_for_each_entry_safe(iter, _iter, &mv_chan->completed_slots,
completed_node) {
in_use_descs++;
list_del(&iter->completed_node);
}
list_for_each_entry_safe_reverse(
iter, _iter, &mv_chan->all_slots, slot_node) {
list_del(&iter->slot_node);
kfree(iter);
mv_chan->slots_allocated--;
}
mv_chan->last_used = NULL;
dev_dbg(mv_chan->device->common.dev, "%s slots_allocated %d\n",
__func__, mv_chan->slots_allocated);
spin_unlock_bh(&mv_chan->lock);
if (in_use_descs)
dev_err(mv_chan->device->common.dev,
"freeing %d in use descriptors!\n", in_use_descs);
}
/**
* mv_xor_status - poll the status of an XOR transaction
* @chan: XOR channel handle
* @cookie: XOR transaction identifier
* @txstate: XOR transactions state holder (or NULL)
*/
static enum dma_status mv_xor_status(struct dma_chan *chan,
dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
dma_cookie_t last_used;
dma_cookie_t last_complete;
enum dma_status ret;
last_used = chan->cookie;
last_complete = mv_chan->completed_cookie;
mv_chan->is_complete_cookie = cookie;
dma_set_tx_state(txstate, last_complete, last_used, 0);
ret = dma_async_is_complete(cookie, last_complete, last_used);
if (ret == DMA_SUCCESS) {
mv_xor_clean_completed_slots(mv_chan);
return ret;
}
mv_xor_slot_cleanup(mv_chan);
last_used = chan->cookie;
last_complete = mv_chan->completed_cookie;
dma_set_tx_state(txstate, last_complete, last_used, 0);
return dma_async_is_complete(cookie, last_complete, last_used);
}
static void mv_dump_xor_regs(struct mv_xor_chan *chan)
{
u32 val;
val = __raw_readl(XOR_CONFIG(chan));
dev_printk(KERN_ERR, chan->device->common.dev,
"config 0x%08x.\n", val);
val = __raw_readl(XOR_ACTIVATION(chan));
dev_printk(KERN_ERR, chan->device->common.dev,
"activation 0x%08x.\n", val);
val = __raw_readl(XOR_INTR_CAUSE(chan));
dev_printk(KERN_ERR, chan->device->common.dev,
"intr cause 0x%08x.\n", val);
val = __raw_readl(XOR_INTR_MASK(chan));
dev_printk(KERN_ERR, chan->device->common.dev,
"intr mask 0x%08x.\n", val);
val = __raw_readl(XOR_ERROR_CAUSE(chan));
dev_printk(KERN_ERR, chan->device->common.dev,
"error cause 0x%08x.\n", val);
val = __raw_readl(XOR_ERROR_ADDR(chan));
dev_printk(KERN_ERR, chan->device->common.dev,
"error addr 0x%08x.\n", val);
}
static void mv_xor_err_interrupt_handler(struct mv_xor_chan *chan,
u32 intr_cause)
{
if (intr_cause & (1 << 4)) {
dev_dbg(chan->device->common.dev,
"ignore this error\n");
return;
}
dev_printk(KERN_ERR, chan->device->common.dev,
"error on chan %d. intr cause 0x%08x.\n",
chan->idx, intr_cause);
mv_dump_xor_regs(chan);
BUG();
}
static irqreturn_t mv_xor_interrupt_handler(int irq, void *data)
{
struct mv_xor_chan *chan = data;
u32 intr_cause = mv_chan_get_intr_cause(chan);
dev_dbg(chan->device->common.dev, "intr cause %x\n", intr_cause);
if (mv_is_err_intr(intr_cause))
mv_xor_err_interrupt_handler(chan, intr_cause);
tasklet_schedule(&chan->irq_tasklet);
mv_xor_device_clear_eoc_cause(chan);
return IRQ_HANDLED;
}
static void mv_xor_issue_pending(struct dma_chan *chan)
{
struct mv_xor_chan *mv_chan = to_mv_xor_chan(chan);
if (mv_chan->pending >= MV_XOR_THRESHOLD) {
mv_chan->pending = 0;
mv_chan_activate(mv_chan);
}
}
/*
* Perform a transaction to verify the HW works.
*/
#define MV_XOR_TEST_SIZE 2000
static int __devinit mv_xor_memcpy_self_test(struct mv_xor_device *device)
{
int i;
void *src, *dest;
dma_addr_t src_dma, dest_dma;
struct dma_chan *dma_chan;
dma_cookie_t cookie;
struct dma_async_tx_descriptor *tx;
int err = 0;
struct mv_xor_chan *mv_chan;
src = kmalloc(sizeof(u8) * MV_XOR_TEST_SIZE, GFP_KERNEL);
if (!src)
return -ENOMEM;
dest = kzalloc(sizeof(u8) * MV_XOR_TEST_SIZE, GFP_KERNEL);
if (!dest) {
kfree(src);
return -ENOMEM;
}
/* Fill in src buffer */
for (i = 0; i < MV_XOR_TEST_SIZE; i++)
((u8 *) src)[i] = (u8)i;
/* Start copy, using first DMA channel */
dma_chan = container_of(device->common.channels.next,
struct dma_chan,
device_node);
if (mv_xor_alloc_chan_resources(dma_chan) < 1) {
err = -ENODEV;
goto out;
}
dest_dma = dma_map_single(dma_chan->device->dev, dest,
MV_XOR_TEST_SIZE, DMA_FROM_DEVICE);
src_dma = dma_map_single(dma_chan->device->dev, src,
MV_XOR_TEST_SIZE, DMA_TO_DEVICE);
tx = mv_xor_prep_dma_memcpy(dma_chan, dest_dma, src_dma,
MV_XOR_TEST_SIZE, 0);
cookie = mv_xor_tx_submit(tx);
mv_xor_issue_pending(dma_chan);
async_tx_ack(tx);
msleep(1);
if (mv_xor_status(dma_chan, cookie, NULL) !=
DMA_SUCCESS) {
dev_printk(KERN_ERR, dma_chan->device->dev,
"Self-test copy timed out, disabling\n");
err = -ENODEV;
goto free_resources;
}
mv_chan = to_mv_xor_chan(dma_chan);
dma_sync_single_for_cpu(&mv_chan->device->pdev->dev, dest_dma,
MV_XOR_TEST_SIZE, DMA_FROM_DEVICE);
if (memcmp(src, dest, MV_XOR_TEST_SIZE)) {
dev_printk(KERN_ERR, dma_chan->device->dev,
"Self-test copy failed compare, disabling\n");
err = -ENODEV;
goto free_resources;
}
free_resources:
mv_xor_free_chan_resources(dma_chan);
out:
kfree(src);
kfree(dest);
return err;
}
#define MV_XOR_NUM_SRC_TEST 4 /* must be <= 15 */
static int __devinit
mv_xor_xor_self_test(struct mv_xor_device *device)
{
int i, src_idx;
struct page *dest;
struct page *xor_srcs[MV_XOR_NUM_SRC_TEST];
dma_addr_t dma_srcs[MV_XOR_NUM_SRC_TEST];
dma_addr_t dest_dma;
struct dma_async_tx_descriptor *tx;
struct dma_chan *dma_chan;
dma_cookie_t cookie;
u8 cmp_byte = 0;
u32 cmp_word;
int err = 0;
struct mv_xor_chan *mv_chan;
for (src_idx = 0; src_idx < MV_XOR_NUM_SRC_TEST; src_idx++) {
xor_srcs[src_idx] = alloc_page(GFP_KERNEL);
if (!xor_srcs[src_idx]) {
while (src_idx--)
__free_page(xor_srcs[src_idx]);
return -ENOMEM;
}
}
dest = alloc_page(GFP_KERNEL);
if (!dest) {
while (src_idx--)
__free_page(xor_srcs[src_idx]);
return -ENOMEM;
}
/* Fill in src buffers */
for (src_idx = 0; src_idx < MV_XOR_NUM_SRC_TEST; src_idx++) {
u8 *ptr = page_address(xor_srcs[src_idx]);
for (i = 0; i < PAGE_SIZE; i++)
ptr[i] = (1 << src_idx);
}
for (src_idx = 0; src_idx < MV_XOR_NUM_SRC_TEST; src_idx++)
cmp_byte ^= (u8) (1 << src_idx);
cmp_word = (cmp_byte << 24) | (cmp_byte << 16) |
(cmp_byte << 8) | cmp_byte;
memset(page_address(dest), 0, PAGE_SIZE);
dma_chan = container_of(device->common.channels.next,
struct dma_chan,
device_node);
if (mv_xor_alloc_chan_resources(dma_chan) < 1) {
err = -ENODEV;
goto out;
}
/* test xor */
dest_dma = dma_map_page(dma_chan->device->dev, dest, 0, PAGE_SIZE,
DMA_FROM_DEVICE);
for (i = 0; i < MV_XOR_NUM_SRC_TEST; i++)
dma_srcs[i] = dma_map_page(dma_chan->device->dev, xor_srcs[i],
0, PAGE_SIZE, DMA_TO_DEVICE);
tx = mv_xor_prep_dma_xor(dma_chan, dest_dma, dma_srcs,
MV_XOR_NUM_SRC_TEST, PAGE_SIZE, 0);
cookie = mv_xor_tx_submit(tx);
mv_xor_issue_pending(dma_chan);
async_tx_ack(tx);
msleep(8);
if (mv_xor_status(dma_chan, cookie, NULL) !=
DMA_SUCCESS) {
dev_printk(KERN_ERR, dma_chan->device->dev,
"Self-test xor timed out, disabling\n");
err = -ENODEV;
goto free_resources;
}
mv_chan = to_mv_xor_chan(dma_chan);
dma_sync_single_for_cpu(&mv_chan->device->pdev->dev, dest_dma,
PAGE_SIZE, DMA_FROM_DEVICE);
for (i = 0; i < (PAGE_SIZE / sizeof(u32)); i++) {
u32 *ptr = page_address(dest);
if (ptr[i] != cmp_word) {
dev_printk(KERN_ERR, dma_chan->device->dev,
"Self-test xor failed compare, disabling."
" index %d, data %x, expected %x\n", i,
ptr[i], cmp_word);
err = -ENODEV;
goto free_resources;
}
}
free_resources:
mv_xor_free_chan_resources(dma_chan);
out:
src_idx = MV_XOR_NUM_SRC_TEST;
while (src_idx--)
__free_page(xor_srcs[src_idx]);
__free_page(dest);
return err;
}
static int __devexit mv_xor_remove(struct platform_device *dev)
{
struct mv_xor_device *device = platform_get_drvdata(dev);
struct dma_chan *chan, *_chan;
struct mv_xor_chan *mv_chan;
struct mv_xor_platform_data *plat_data = dev->dev.platform_data;
dma_async_device_unregister(&device->common);
dma_free_coherent(&dev->dev, plat_data->pool_size,
device->dma_desc_pool_virt, device->dma_desc_pool);
list_for_each_entry_safe(chan, _chan, &device->common.channels,
device_node) {
mv_chan = to_mv_xor_chan(chan);
list_del(&chan->device_node);
}
return 0;
}
static int __devinit mv_xor_probe(struct platform_device *pdev)
{
int ret = 0;
int irq;
struct mv_xor_device *adev;
struct mv_xor_chan *mv_chan;
struct dma_device *dma_dev;
struct mv_xor_platform_data *plat_data = pdev->dev.platform_data;
adev = devm_kzalloc(&pdev->dev, sizeof(*adev), GFP_KERNEL);
if (!adev)
return -ENOMEM;
dma_dev = &adev->common;
/* allocate coherent memory for hardware descriptors
* note: writecombine gives slightly better performance, but
* requires that we explicitly flush the writes
*/
adev->dma_desc_pool_virt = dma_alloc_writecombine(&pdev->dev,
plat_data->pool_size,
&adev->dma_desc_pool,
GFP_KERNEL);
if (!adev->dma_desc_pool_virt)
return -ENOMEM;
adev->id = plat_data->hw_id;
/* discover transaction capabilites from the platform data */
dma_dev->cap_mask = plat_data->cap_mask;
adev->pdev = pdev;
platform_set_drvdata(pdev, adev);
adev->shared = platform_get_drvdata(plat_data->shared);
INIT_LIST_HEAD(&dma_dev->channels);
/* set base routines */
dma_dev->device_alloc_chan_resources = mv_xor_alloc_chan_resources;
dma_dev->device_free_chan_resources = mv_xor_free_chan_resources;
dma_dev->device_tx_status = mv_xor_status;
dma_dev->device_issue_pending = mv_xor_issue_pending;
dma_dev->dev = &pdev->dev;
/* set prep routines based on capability */
if (dma_has_cap(DMA_MEMCPY, dma_dev->cap_mask))
dma_dev->device_prep_dma_memcpy = mv_xor_prep_dma_memcpy;
if (dma_has_cap(DMA_MEMSET, dma_dev->cap_mask))
dma_dev->device_prep_dma_memset = mv_xor_prep_dma_memset;
if (dma_has_cap(DMA_XOR, dma_dev->cap_mask)) {
dma_dev->max_xor = 8;
dma_dev->device_prep_dma_xor = mv_xor_prep_dma_xor;
}
mv_chan = devm_kzalloc(&pdev->dev, sizeof(*mv_chan), GFP_KERNEL);
if (!mv_chan) {
ret = -ENOMEM;
goto err_free_dma;
}
mv_chan->device = adev;
mv_chan->idx = plat_data->hw_id;
mv_chan->mmr_base = adev->shared->xor_base;
if (!mv_chan->mmr_base) {
ret = -ENOMEM;
goto err_free_dma;
}
tasklet_init(&mv_chan->irq_tasklet, mv_xor_tasklet, (unsigned long)
mv_chan);
/* clear errors before enabling interrupts */
mv_xor_device_clear_err_status(mv_chan);
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
ret = irq;
goto err_free_dma;
}
ret = devm_request_irq(&pdev->dev, irq,
mv_xor_interrupt_handler,
0, dev_name(&pdev->dev), mv_chan);
if (ret)
goto err_free_dma;
mv_chan_unmask_interrupts(mv_chan);
mv_set_mode(mv_chan, DMA_MEMCPY);
spin_lock_init(&mv_chan->lock);
INIT_LIST_HEAD(&mv_chan->chain);
INIT_LIST_HEAD(&mv_chan->completed_slots);
INIT_LIST_HEAD(&mv_chan->all_slots);
mv_chan->common.device = dma_dev;
list_add_tail(&mv_chan->common.device_node, &dma_dev->channels);
if (dma_has_cap(DMA_MEMCPY, dma_dev->cap_mask)) {
ret = mv_xor_memcpy_self_test(adev);
dev_dbg(&pdev->dev, "memcpy self test returned %d\n", ret);
if (ret)
goto err_free_dma;
}
if (dma_has_cap(DMA_XOR, dma_dev->cap_mask)) {
ret = mv_xor_xor_self_test(adev);
dev_dbg(&pdev->dev, "xor self test returned %d\n", ret);
if (ret)
goto err_free_dma;
}
dev_printk(KERN_INFO, &pdev->dev, "Marvell XOR: "
"( %s%s%s%s)\n",
dma_has_cap(DMA_XOR, dma_dev->cap_mask) ? "xor " : "",
dma_has_cap(DMA_MEMSET, dma_dev->cap_mask) ? "fill " : "",
dma_has_cap(DMA_MEMCPY, dma_dev->cap_mask) ? "cpy " : "",
dma_has_cap(DMA_INTERRUPT, dma_dev->cap_mask) ? "intr " : "");
dma_async_device_register(dma_dev);
goto out;
err_free_dma:
dma_free_coherent(&adev->pdev->dev, plat_data->pool_size,
adev->dma_desc_pool_virt, adev->dma_desc_pool);
out:
return ret;
}
static void
mv_xor_conf_mbus_windows(struct mv_xor_shared_private *msp,
struct mbus_dram_target_info *dram)
{
void __iomem *base = msp->xor_base;
u32 win_enable = 0;
int i;
for (i = 0; i < 8; i++) {
writel(0, base + WINDOW_BASE(i));
writel(0, base + WINDOW_SIZE(i));
if (i < 4)
writel(0, base + WINDOW_REMAP_HIGH(i));
}
for (i = 0; i < dram->num_cs; i++) {
struct mbus_dram_window *cs = dram->cs + i;
writel((cs->base & 0xffff0000) |
(cs->mbus_attr << 8) |
dram->mbus_dram_target_id, base + WINDOW_BASE(i));
writel((cs->size - 1) & 0xffff0000, base + WINDOW_SIZE(i));
win_enable |= (1 << i);
win_enable |= 3 << (16 + (2 * i));
}
writel(win_enable, base + WINDOW_BAR_ENABLE(0));
writel(win_enable, base + WINDOW_BAR_ENABLE(1));
}
static struct platform_driver mv_xor_driver = {
.probe = mv_xor_probe,
.remove = __devexit_p(mv_xor_remove),
.driver = {
.owner = THIS_MODULE,
.name = MV_XOR_NAME,
},
};
static int mv_xor_shared_probe(struct platform_device *pdev)
{
struct mv_xor_platform_shared_data *msd = pdev->dev.platform_data;
struct mv_xor_shared_private *msp;
struct resource *res;
dev_printk(KERN_NOTICE, &pdev->dev, "Marvell shared XOR driver\n");
msp = devm_kzalloc(&pdev->dev, sizeof(*msp), GFP_KERNEL);
if (!msp)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
msp->xor_base = devm_ioremap(&pdev->dev, res->start,
res->end - res->start + 1);
if (!msp->xor_base)
return -EBUSY;
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res)
return -ENODEV;
msp->xor_high_base = devm_ioremap(&pdev->dev, res->start,
res->end - res->start + 1);
if (!msp->xor_high_base)
return -EBUSY;
platform_set_drvdata(pdev, msp);
/*
* (Re-)program MBUS remapping windows if we are asked to.
*/
if (msd != NULL && msd->dram != NULL)
mv_xor_conf_mbus_windows(msp, msd->dram);
return 0;
}
static int mv_xor_shared_remove(struct platform_device *pdev)
{
return 0;
}
static struct platform_driver mv_xor_shared_driver = {
.probe = mv_xor_shared_probe,
.remove = mv_xor_shared_remove,
.driver = {
.owner = THIS_MODULE,
.name = MV_XOR_SHARED_NAME,
},
};
static int __init mv_xor_init(void)
{
int rc;
rc = platform_driver_register(&mv_xor_shared_driver);
if (!rc) {
rc = platform_driver_register(&mv_xor_driver);
if (rc)
platform_driver_unregister(&mv_xor_shared_driver);
}
return rc;
}
module_init(mv_xor_init);
/* it's currently unsafe to unload this module */
#if 0
static void __exit mv_xor_exit(void)
{
platform_driver_unregister(&mv_xor_driver);
platform_driver_unregister(&mv_xor_shared_driver);
return;
}
module_exit(mv_xor_exit);
#endif
MODULE_AUTHOR("Saeed Bishara <saeed@marvell.com>");
MODULE_DESCRIPTION("DMA engine driver for Marvell's XOR engine");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jianpingye/linux | arch/arm/mach-rpc/time.c | 2069 | 2133 | /*
* linux/arch/arm/common/time-acorn.c
*
* Copyright (c) 1996-2000 Russell King.
*
* 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.
*
* Changelog:
* 24-Sep-1996 RMK Created
* 10-Oct-1996 RMK Brought up to date with arch-sa110eval
* 04-Dec-1997 RMK Updated for new arch/arm/time.c
* 13=Jun-2004 DS Moved to arch/arm/common b/c shared w/CLPS7500
*/
#include <linux/timex.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/hardware/ioc.h>
#include <asm/mach/time.h>
#define RPC_CLOCK_FREQ 2000000
#define RPC_LATCH DIV_ROUND_CLOSEST(RPC_CLOCK_FREQ, HZ)
static u32 ioc_timer_gettimeoffset(void)
{
unsigned int count1, count2, status;
long offset;
ioc_writeb (0, IOC_T0LATCH);
barrier ();
count1 = ioc_readb(IOC_T0CNTL) | (ioc_readb(IOC_T0CNTH) << 8);
barrier ();
status = ioc_readb(IOC_IRQREQA);
barrier ();
ioc_writeb (0, IOC_T0LATCH);
barrier ();
count2 = ioc_readb(IOC_T0CNTL) | (ioc_readb(IOC_T0CNTH) << 8);
offset = count2;
if (count2 < count1) {
/*
* We have not had an interrupt between reading count1
* and count2.
*/
if (status & (1 << 5))
offset -= RPC_LATCH;
} else if (count2 > count1) {
/*
* We have just had another interrupt between reading
* count1 and count2.
*/
offset -= RPC_LATCH;
}
offset = (RPC_LATCH - offset) * (tick_nsec / 1000);
return DIV_ROUND_CLOSEST(offset, RPC_LATCH) * 1000;
}
void __init ioctime_init(void)
{
ioc_writeb(RPC_LATCH & 255, IOC_T0LTCHL);
ioc_writeb(RPC_LATCH >> 8, IOC_T0LTCHH);
ioc_writeb(0, IOC_T0GO);
}
static irqreturn_t
ioc_timer_interrupt(int irq, void *dev_id)
{
timer_tick();
return IRQ_HANDLED;
}
static struct irqaction ioc_timer_irq = {
.name = "timer",
.handler = ioc_timer_interrupt
};
/*
* Set up timer interrupt.
*/
void __init ioc_timer_init(void)
{
arch_gettimeoffset = ioc_timer_gettimeoffset;
ioctime_init();
setup_irq(IRQ_TIMER0, &ioc_timer_irq);
}
| gpl-2.0 |
jrspruitt/FriendlyARM_210_Kernel | drivers/net/wireless/ath/ath9k/ar9002_phy.c | 2325 | 17159 | /*
* Copyright (c) 2008-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* DOC: Programming Atheros 802.11n analog front end radios
*
* AR5416 MAC based PCI devices and AR518 MAC based PCI-Express
* devices have either an external AR2133 analog front end radio for single
* band 2.4 GHz communication or an AR5133 analog front end radio for dual
* band 2.4 GHz / 5 GHz communication.
*
* All devices after the AR5416 and AR5418 family starting with the AR9280
* have their analog front radios, MAC/BB and host PCIe/USB interface embedded
* into a single-chip and require less programming.
*
* The following single-chips exist with a respective embedded radio:
*
* AR9280 - 11n dual-band 2x2 MIMO for PCIe
* AR9281 - 11n single-band 1x2 MIMO for PCIe
* AR9285 - 11n single-band 1x1 for PCIe
* AR9287 - 11n single-band 2x2 MIMO for PCIe
*
* AR9220 - 11n dual-band 2x2 MIMO for PCI
* AR9223 - 11n single-band 2x2 MIMO for PCI
*
* AR9287 - 11n single-band 1x1 MIMO for USB
*/
#include "hw.h"
#include "ar9002_phy.h"
/**
* ar9002_hw_set_channel - set channel on single-chip device
* @ah: atheros hardware structure
* @chan:
*
* This is the function to change channel on single-chip devices, that is
* all devices after ar9280.
*
* This function takes the channel value in MHz and sets
* hardware channel value. Assumes writes have been enabled to analog bus.
*
* Actual Expression,
*
* For 2GHz channel,
* Channel Frequency = (3/4) * freq_ref * (chansel[8:0] + chanfrac[16:0]/2^17)
* (freq_ref = 40MHz)
*
* For 5GHz channel,
* Channel Frequency = (3/2) * freq_ref * (chansel[8:0] + chanfrac[16:0]/2^10)
* (freq_ref = 40MHz/(24>>amodeRefSel))
*/
static int ar9002_hw_set_channel(struct ath_hw *ah, struct ath9k_channel *chan)
{
u16 bMode, fracMode, aModeRefSel = 0;
u32 freq, ndiv, channelSel = 0, channelFrac = 0, reg32 = 0;
struct chan_centers centers;
u32 refDivA = 24;
ath9k_hw_get_channel_centers(ah, chan, ¢ers);
freq = centers.synth_center;
reg32 = REG_READ(ah, AR_PHY_SYNTH_CONTROL);
reg32 &= 0xc0000000;
if (freq < 4800) { /* 2 GHz, fractional mode */
u32 txctl;
int regWrites = 0;
bMode = 1;
fracMode = 1;
aModeRefSel = 0;
channelSel = CHANSEL_2G(freq);
if (AR_SREV_9287_11_OR_LATER(ah)) {
if (freq == 2484) {
/* Enable channel spreading for channel 14 */
REG_WRITE_ARRAY(&ah->iniCckfirJapan2484,
1, regWrites);
} else {
REG_WRITE_ARRAY(&ah->iniCckfirNormal,
1, regWrites);
}
} else {
txctl = REG_READ(ah, AR_PHY_CCK_TX_CTRL);
if (freq == 2484) {
/* Enable channel spreading for channel 14 */
REG_WRITE(ah, AR_PHY_CCK_TX_CTRL,
txctl | AR_PHY_CCK_TX_CTRL_JAPAN);
} else {
REG_WRITE(ah, AR_PHY_CCK_TX_CTRL,
txctl & ~AR_PHY_CCK_TX_CTRL_JAPAN);
}
}
} else {
bMode = 0;
fracMode = 0;
switch (ah->eep_ops->get_eeprom(ah, EEP_FRAC_N_5G)) {
case 0:
if ((freq % 20) == 0)
aModeRefSel = 3;
else if ((freq % 10) == 0)
aModeRefSel = 2;
if (aModeRefSel)
break;
case 1:
default:
aModeRefSel = 0;
/*
* Enable 2G (fractional) mode for channels
* which are 5MHz spaced.
*/
fracMode = 1;
refDivA = 1;
channelSel = CHANSEL_5G(freq);
/* RefDivA setting */
REG_RMW_FIELD(ah, AR_AN_SYNTH9,
AR_AN_SYNTH9_REFDIVA, refDivA);
}
if (!fracMode) {
ndiv = (freq * (refDivA >> aModeRefSel)) / 60;
channelSel = ndiv & 0x1ff;
channelFrac = (ndiv & 0xfffffe00) * 2;
channelSel = (channelSel << 17) | channelFrac;
}
}
reg32 = reg32 |
(bMode << 29) |
(fracMode << 28) | (aModeRefSel << 26) | (channelSel);
REG_WRITE(ah, AR_PHY_SYNTH_CONTROL, reg32);
ah->curchan = chan;
ah->curchan_rad_index = -1;
return 0;
}
/**
* ar9002_hw_spur_mitigate - convert baseband spur frequency
* @ah: atheros hardware structure
* @chan:
*
* For single-chip solutions. Converts to baseband spur frequency given the
* input channel frequency and compute register settings below.
*/
static void ar9002_hw_spur_mitigate(struct ath_hw *ah,
struct ath9k_channel *chan)
{
int bb_spur = AR_NO_SPUR;
int freq;
int bin, cur_bin;
int bb_spur_off, spur_subchannel_sd;
int spur_freq_sd;
int spur_delta_phase;
int denominator;
int upper, lower, cur_vit_mask;
int tmp, newVal;
int i;
static const int pilot_mask_reg[4] = {
AR_PHY_TIMING7, AR_PHY_TIMING8,
AR_PHY_PILOT_MASK_01_30, AR_PHY_PILOT_MASK_31_60
};
static const int chan_mask_reg[4] = {
AR_PHY_TIMING9, AR_PHY_TIMING10,
AR_PHY_CHANNEL_MASK_01_30, AR_PHY_CHANNEL_MASK_31_60
};
static const int inc[4] = { 0, 100, 0, 0 };
struct chan_centers centers;
int8_t mask_m[123];
int8_t mask_p[123];
int8_t mask_amt;
int tmp_mask;
int cur_bb_spur;
bool is2GHz = IS_CHAN_2GHZ(chan);
memset(&mask_m, 0, sizeof(int8_t) * 123);
memset(&mask_p, 0, sizeof(int8_t) * 123);
ath9k_hw_get_channel_centers(ah, chan, ¢ers);
freq = centers.synth_center;
ah->config.spurmode = SPUR_ENABLE_EEPROM;
for (i = 0; i < AR_EEPROM_MODAL_SPURS; i++) {
cur_bb_spur = ah->eep_ops->get_spur_channel(ah, i, is2GHz);
if (AR_NO_SPUR == cur_bb_spur)
break;
if (is2GHz)
cur_bb_spur = (cur_bb_spur / 10) + AR_BASE_FREQ_2GHZ;
else
cur_bb_spur = (cur_bb_spur / 10) + AR_BASE_FREQ_5GHZ;
cur_bb_spur = cur_bb_spur - freq;
if (IS_CHAN_HT40(chan)) {
if ((cur_bb_spur > -AR_SPUR_FEEQ_BOUND_HT40) &&
(cur_bb_spur < AR_SPUR_FEEQ_BOUND_HT40)) {
bb_spur = cur_bb_spur;
break;
}
} else if ((cur_bb_spur > -AR_SPUR_FEEQ_BOUND_HT20) &&
(cur_bb_spur < AR_SPUR_FEEQ_BOUND_HT20)) {
bb_spur = cur_bb_spur;
break;
}
}
if (AR_NO_SPUR == bb_spur) {
REG_CLR_BIT(ah, AR_PHY_FORCE_CLKEN_CCK,
AR_PHY_FORCE_CLKEN_CCK_MRC_MUX);
return;
} else {
REG_CLR_BIT(ah, AR_PHY_FORCE_CLKEN_CCK,
AR_PHY_FORCE_CLKEN_CCK_MRC_MUX);
}
bin = bb_spur * 320;
tmp = REG_READ(ah, AR_PHY_TIMING_CTRL4(0));
ENABLE_REGWRITE_BUFFER(ah);
newVal = tmp | (AR_PHY_TIMING_CTRL4_ENABLE_SPUR_RSSI |
AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK |
AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
REG_WRITE(ah, AR_PHY_TIMING_CTRL4(0), newVal);
newVal = (AR_PHY_SPUR_REG_MASK_RATE_CNTL |
AR_PHY_SPUR_REG_ENABLE_MASK_PPM |
AR_PHY_SPUR_REG_MASK_RATE_SELECT |
AR_PHY_SPUR_REG_ENABLE_VIT_SPUR_RSSI |
SM(SPUR_RSSI_THRESH, AR_PHY_SPUR_REG_SPUR_RSSI_THRESH));
REG_WRITE(ah, AR_PHY_SPUR_REG, newVal);
if (IS_CHAN_HT40(chan)) {
if (bb_spur < 0) {
spur_subchannel_sd = 1;
bb_spur_off = bb_spur + 10;
} else {
spur_subchannel_sd = 0;
bb_spur_off = bb_spur - 10;
}
} else {
spur_subchannel_sd = 0;
bb_spur_off = bb_spur;
}
if (IS_CHAN_HT40(chan))
spur_delta_phase =
((bb_spur * 262144) /
10) & AR_PHY_TIMING11_SPUR_DELTA_PHASE;
else
spur_delta_phase =
((bb_spur * 524288) /
10) & AR_PHY_TIMING11_SPUR_DELTA_PHASE;
denominator = IS_CHAN_2GHZ(chan) ? 44 : 40;
spur_freq_sd = ((bb_spur_off * 2048) / denominator) & 0x3ff;
newVal = (AR_PHY_TIMING11_USE_SPUR_IN_AGC |
SM(spur_freq_sd, AR_PHY_TIMING11_SPUR_FREQ_SD) |
SM(spur_delta_phase, AR_PHY_TIMING11_SPUR_DELTA_PHASE));
REG_WRITE(ah, AR_PHY_TIMING11, newVal);
newVal = spur_subchannel_sd << AR_PHY_SFCORR_SPUR_SUBCHNL_SD_S;
REG_WRITE(ah, AR_PHY_SFCORR_EXT, newVal);
cur_bin = -6000;
upper = bin + 100;
lower = bin - 100;
for (i = 0; i < 4; i++) {
int pilot_mask = 0;
int chan_mask = 0;
int bp = 0;
for (bp = 0; bp < 30; bp++) {
if ((cur_bin > lower) && (cur_bin < upper)) {
pilot_mask = pilot_mask | 0x1 << bp;
chan_mask = chan_mask | 0x1 << bp;
}
cur_bin += 100;
}
cur_bin += inc[i];
REG_WRITE(ah, pilot_mask_reg[i], pilot_mask);
REG_WRITE(ah, chan_mask_reg[i], chan_mask);
}
cur_vit_mask = 6100;
upper = bin + 120;
lower = bin - 120;
for (i = 0; i < 123; i++) {
if ((cur_vit_mask > lower) && (cur_vit_mask < upper)) {
/* workaround for gcc bug #37014 */
volatile int tmp_v = abs(cur_vit_mask - bin);
if (tmp_v < 75)
mask_amt = 1;
else
mask_amt = 0;
if (cur_vit_mask < 0)
mask_m[abs(cur_vit_mask / 100)] = mask_amt;
else
mask_p[cur_vit_mask / 100] = mask_amt;
}
cur_vit_mask -= 100;
}
tmp_mask = (mask_m[46] << 30) | (mask_m[47] << 28)
| (mask_m[48] << 26) | (mask_m[49] << 24)
| (mask_m[50] << 22) | (mask_m[51] << 20)
| (mask_m[52] << 18) | (mask_m[53] << 16)
| (mask_m[54] << 14) | (mask_m[55] << 12)
| (mask_m[56] << 10) | (mask_m[57] << 8)
| (mask_m[58] << 6) | (mask_m[59] << 4)
| (mask_m[60] << 2) | (mask_m[61] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK_1, tmp_mask);
REG_WRITE(ah, AR_PHY_VIT_MASK2_M_46_61, tmp_mask);
tmp_mask = (mask_m[31] << 28)
| (mask_m[32] << 26) | (mask_m[33] << 24)
| (mask_m[34] << 22) | (mask_m[35] << 20)
| (mask_m[36] << 18) | (mask_m[37] << 16)
| (mask_m[48] << 14) | (mask_m[39] << 12)
| (mask_m[40] << 10) | (mask_m[41] << 8)
| (mask_m[42] << 6) | (mask_m[43] << 4)
| (mask_m[44] << 2) | (mask_m[45] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK_2, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_M_31_45, tmp_mask);
tmp_mask = (mask_m[16] << 30) | (mask_m[16] << 28)
| (mask_m[18] << 26) | (mask_m[18] << 24)
| (mask_m[20] << 22) | (mask_m[20] << 20)
| (mask_m[22] << 18) | (mask_m[22] << 16)
| (mask_m[24] << 14) | (mask_m[24] << 12)
| (mask_m[25] << 10) | (mask_m[26] << 8)
| (mask_m[27] << 6) | (mask_m[28] << 4)
| (mask_m[29] << 2) | (mask_m[30] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK_3, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_M_16_30, tmp_mask);
tmp_mask = (mask_m[0] << 30) | (mask_m[1] << 28)
| (mask_m[2] << 26) | (mask_m[3] << 24)
| (mask_m[4] << 22) | (mask_m[5] << 20)
| (mask_m[6] << 18) | (mask_m[7] << 16)
| (mask_m[8] << 14) | (mask_m[9] << 12)
| (mask_m[10] << 10) | (mask_m[11] << 8)
| (mask_m[12] << 6) | (mask_m[13] << 4)
| (mask_m[14] << 2) | (mask_m[15] << 0);
REG_WRITE(ah, AR_PHY_MASK_CTL, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_M_00_15, tmp_mask);
tmp_mask = (mask_p[15] << 28)
| (mask_p[14] << 26) | (mask_p[13] << 24)
| (mask_p[12] << 22) | (mask_p[11] << 20)
| (mask_p[10] << 18) | (mask_p[9] << 16)
| (mask_p[8] << 14) | (mask_p[7] << 12)
| (mask_p[6] << 10) | (mask_p[5] << 8)
| (mask_p[4] << 6) | (mask_p[3] << 4)
| (mask_p[2] << 2) | (mask_p[1] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK2_1, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_P_15_01, tmp_mask);
tmp_mask = (mask_p[30] << 28)
| (mask_p[29] << 26) | (mask_p[28] << 24)
| (mask_p[27] << 22) | (mask_p[26] << 20)
| (mask_p[25] << 18) | (mask_p[24] << 16)
| (mask_p[23] << 14) | (mask_p[22] << 12)
| (mask_p[21] << 10) | (mask_p[20] << 8)
| (mask_p[19] << 6) | (mask_p[18] << 4)
| (mask_p[17] << 2) | (mask_p[16] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK2_2, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_P_30_16, tmp_mask);
tmp_mask = (mask_p[45] << 28)
| (mask_p[44] << 26) | (mask_p[43] << 24)
| (mask_p[42] << 22) | (mask_p[41] << 20)
| (mask_p[40] << 18) | (mask_p[39] << 16)
| (mask_p[38] << 14) | (mask_p[37] << 12)
| (mask_p[36] << 10) | (mask_p[35] << 8)
| (mask_p[34] << 6) | (mask_p[33] << 4)
| (mask_p[32] << 2) | (mask_p[31] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK2_3, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_P_45_31, tmp_mask);
tmp_mask = (mask_p[61] << 30) | (mask_p[60] << 28)
| (mask_p[59] << 26) | (mask_p[58] << 24)
| (mask_p[57] << 22) | (mask_p[56] << 20)
| (mask_p[55] << 18) | (mask_p[54] << 16)
| (mask_p[53] << 14) | (mask_p[52] << 12)
| (mask_p[51] << 10) | (mask_p[50] << 8)
| (mask_p[49] << 6) | (mask_p[48] << 4)
| (mask_p[47] << 2) | (mask_p[46] << 0);
REG_WRITE(ah, AR_PHY_BIN_MASK2_4, tmp_mask);
REG_WRITE(ah, AR_PHY_MASK2_P_61_45, tmp_mask);
REGWRITE_BUFFER_FLUSH(ah);
}
static void ar9002_olc_init(struct ath_hw *ah)
{
u32 i;
if (!OLC_FOR_AR9280_20_LATER)
return;
if (OLC_FOR_AR9287_10_LATER) {
REG_SET_BIT(ah, AR_PHY_TX_PWRCTRL9,
AR_PHY_TX_PWRCTRL9_RES_DC_REMOVAL);
ath9k_hw_analog_shift_rmw(ah, AR9287_AN_TXPC0,
AR9287_AN_TXPC0_TXPCMODE,
AR9287_AN_TXPC0_TXPCMODE_S,
AR9287_AN_TXPC0_TXPCMODE_TEMPSENSE);
udelay(100);
} else {
for (i = 0; i < AR9280_TX_GAIN_TABLE_SIZE; i++)
ah->originalGain[i] =
MS(REG_READ(ah, AR_PHY_TX_GAIN_TBL1 + i * 4),
AR_PHY_TX_GAIN);
ah->PDADCdelta = 0;
}
}
static u32 ar9002_hw_compute_pll_control(struct ath_hw *ah,
struct ath9k_channel *chan)
{
u32 pll;
pll = SM(0x5, AR_RTC_9160_PLL_REFDIV);
if (chan && IS_CHAN_HALF_RATE(chan))
pll |= SM(0x1, AR_RTC_9160_PLL_CLKSEL);
else if (chan && IS_CHAN_QUARTER_RATE(chan))
pll |= SM(0x2, AR_RTC_9160_PLL_CLKSEL);
if (chan && IS_CHAN_5GHZ(chan)) {
if (IS_CHAN_A_FAST_CLOCK(ah, chan))
pll = 0x142c;
else if (AR_SREV_9280_20(ah))
pll = 0x2850;
else
pll |= SM(0x28, AR_RTC_9160_PLL_DIV);
} else {
pll |= SM(0x2c, AR_RTC_9160_PLL_DIV);
}
return pll;
}
static void ar9002_hw_do_getnf(struct ath_hw *ah,
int16_t nfarray[NUM_NF_READINGS])
{
int16_t nf;
nf = MS(REG_READ(ah, AR_PHY_CCA), AR9280_PHY_MINCCA_PWR);
nfarray[0] = sign_extend32(nf, 8);
nf = MS(REG_READ(ah, AR_PHY_EXT_CCA), AR9280_PHY_EXT_MINCCA_PWR);
if (IS_CHAN_HT40(ah->curchan))
nfarray[3] = sign_extend32(nf, 8);
if (AR_SREV_9285(ah) || AR_SREV_9271(ah))
return;
nf = MS(REG_READ(ah, AR_PHY_CH1_CCA), AR9280_PHY_CH1_MINCCA_PWR);
nfarray[1] = sign_extend32(nf, 8);
nf = MS(REG_READ(ah, AR_PHY_CH1_EXT_CCA), AR9280_PHY_CH1_EXT_MINCCA_PWR);
if (IS_CHAN_HT40(ah->curchan))
nfarray[4] = sign_extend32(nf, 8);
}
static void ar9002_hw_set_nf_limits(struct ath_hw *ah)
{
if (AR_SREV_9285(ah)) {
ah->nf_2g.max = AR_PHY_CCA_MAX_GOOD_VAL_9285_2GHZ;
ah->nf_2g.min = AR_PHY_CCA_MIN_GOOD_VAL_9285_2GHZ;
ah->nf_2g.nominal = AR_PHY_CCA_NOM_VAL_9285_2GHZ;
} else if (AR_SREV_9287(ah)) {
ah->nf_2g.max = AR_PHY_CCA_MAX_GOOD_VAL_9287_2GHZ;
ah->nf_2g.min = AR_PHY_CCA_MIN_GOOD_VAL_9287_2GHZ;
ah->nf_2g.nominal = AR_PHY_CCA_NOM_VAL_9287_2GHZ;
} else if (AR_SREV_9271(ah)) {
ah->nf_2g.max = AR_PHY_CCA_MAX_GOOD_VAL_9271_2GHZ;
ah->nf_2g.min = AR_PHY_CCA_MIN_GOOD_VAL_9271_2GHZ;
ah->nf_2g.nominal = AR_PHY_CCA_NOM_VAL_9271_2GHZ;
} else {
ah->nf_2g.max = AR_PHY_CCA_MAX_GOOD_VAL_9280_2GHZ;
ah->nf_2g.min = AR_PHY_CCA_MIN_GOOD_VAL_9280_2GHZ;
ah->nf_2g.nominal = AR_PHY_CCA_NOM_VAL_9280_2GHZ;
ah->nf_5g.max = AR_PHY_CCA_MAX_GOOD_VAL_9280_5GHZ;
ah->nf_5g.min = AR_PHY_CCA_MIN_GOOD_VAL_9280_5GHZ;
ah->nf_5g.nominal = AR_PHY_CCA_NOM_VAL_9280_5GHZ;
}
}
static void ar9002_hw_antdiv_comb_conf_get(struct ath_hw *ah,
struct ath_hw_antcomb_conf *antconf)
{
u32 regval;
regval = REG_READ(ah, AR_PHY_MULTICHAIN_GAIN_CTL);
antconf->main_lna_conf = (regval & AR_PHY_9285_ANT_DIV_MAIN_LNACONF) >>
AR_PHY_9285_ANT_DIV_MAIN_LNACONF_S;
antconf->alt_lna_conf = (regval & AR_PHY_9285_ANT_DIV_ALT_LNACONF) >>
AR_PHY_9285_ANT_DIV_ALT_LNACONF_S;
antconf->fast_div_bias = (regval & AR_PHY_9285_FAST_DIV_BIAS) >>
AR_PHY_9285_FAST_DIV_BIAS_S;
antconf->lna1_lna2_delta = -3;
antconf->div_group = 0;
}
static void ar9002_hw_antdiv_comb_conf_set(struct ath_hw *ah,
struct ath_hw_antcomb_conf *antconf)
{
u32 regval;
regval = REG_READ(ah, AR_PHY_MULTICHAIN_GAIN_CTL);
regval &= ~(AR_PHY_9285_ANT_DIV_MAIN_LNACONF |
AR_PHY_9285_ANT_DIV_ALT_LNACONF |
AR_PHY_9285_FAST_DIV_BIAS);
regval |= ((antconf->main_lna_conf << AR_PHY_9285_ANT_DIV_MAIN_LNACONF_S)
& AR_PHY_9285_ANT_DIV_MAIN_LNACONF);
regval |= ((antconf->alt_lna_conf << AR_PHY_9285_ANT_DIV_ALT_LNACONF_S)
& AR_PHY_9285_ANT_DIV_ALT_LNACONF);
regval |= ((antconf->fast_div_bias << AR_PHY_9285_FAST_DIV_BIAS_S)
& AR_PHY_9285_FAST_DIV_BIAS);
REG_WRITE(ah, AR_PHY_MULTICHAIN_GAIN_CTL, regval);
}
void ar9002_hw_attach_phy_ops(struct ath_hw *ah)
{
struct ath_hw_private_ops *priv_ops = ath9k_hw_private_ops(ah);
struct ath_hw_ops *ops = ath9k_hw_ops(ah);
priv_ops->set_rf_regs = NULL;
priv_ops->rf_alloc_ext_banks = NULL;
priv_ops->rf_free_ext_banks = NULL;
priv_ops->rf_set_freq = ar9002_hw_set_channel;
priv_ops->spur_mitigate_freq = ar9002_hw_spur_mitigate;
priv_ops->olc_init = ar9002_olc_init;
priv_ops->compute_pll_control = ar9002_hw_compute_pll_control;
priv_ops->do_getnf = ar9002_hw_do_getnf;
ops->antdiv_comb_conf_get = ar9002_hw_antdiv_comb_conf_get;
ops->antdiv_comb_conf_set = ar9002_hw_antdiv_comb_conf_set;
ar9002_hw_set_nf_limits(ah);
}
| gpl-2.0 |
joyoki/android_kernel_lge_g3 | drivers/staging/zcache/zcache-main.c | 2837 | 56164 | /*
* zcache.c
*
* Copyright (c) 2010,2011, Dan Magenheimer, Oracle Corp.
* Copyright (c) 2010,2011, Nitin Gupta
*
* Zcache provides an in-kernel "host implementation" for transcendent memory
* and, thus indirectly, for cleancache and frontswap. Zcache includes two
* page-accessible memory [1] interfaces, both utilizing the crypto compression
* API:
* 1) "compression buddies" ("zbud") is used for ephemeral pages
* 2) zsmalloc is used for persistent pages.
* Xvmalloc (based on the TLSF allocator) has very low fragmentation
* so maximizes space efficiency, while zbud allows pairs (and potentially,
* in the future, more than a pair of) compressed pages to be closely linked
* so that reclaiming can be done via the kernel's physical-page-oriented
* "shrinker" interface.
*
* [1] For a definition of page-accessible memory (aka PAM), see:
* http://marc.info/?l=linux-mm&m=127811271605009
*/
#include <linux/module.h>
#include <linux/cpu.h>
#include <linux/highmem.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/atomic.h>
#include <linux/math64.h>
#include <linux/crypto.h>
#include <linux/string.h>
#include "tmem.h"
#include "../zsmalloc/zsmalloc.h"
#if (!defined(CONFIG_CLEANCACHE) && !defined(CONFIG_FRONTSWAP))
#error "zcache is useless without CONFIG_CLEANCACHE or CONFIG_FRONTSWAP"
#endif
#ifdef CONFIG_CLEANCACHE
#include <linux/cleancache.h>
#endif
#ifdef CONFIG_FRONTSWAP
#include <linux/frontswap.h>
#endif
#if 0
/* this is more aggressive but may cause other problems? */
#define ZCACHE_GFP_MASK (GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN)
#else
#define ZCACHE_GFP_MASK \
(__GFP_FS | __GFP_NORETRY | __GFP_NOWARN | __GFP_NOMEMALLOC)
#endif
#define MAX_POOLS_PER_CLIENT 16
#define MAX_CLIENTS 16
#define LOCAL_CLIENT ((uint16_t)-1)
MODULE_LICENSE("GPL");
struct zcache_client {
struct tmem_pool *tmem_pools[MAX_POOLS_PER_CLIENT];
struct zs_pool *zspool;
bool allocated;
atomic_t refcount;
};
static struct zcache_client zcache_host;
static struct zcache_client zcache_clients[MAX_CLIENTS];
static inline uint16_t get_client_id_from_client(struct zcache_client *cli)
{
BUG_ON(cli == NULL);
if (cli == &zcache_host)
return LOCAL_CLIENT;
return cli - &zcache_clients[0];
}
static inline bool is_local_client(struct zcache_client *cli)
{
return cli == &zcache_host;
}
/* crypto API for zcache */
#define ZCACHE_COMP_NAME_SZ CRYPTO_MAX_ALG_NAME
static char zcache_comp_name[ZCACHE_COMP_NAME_SZ];
static struct crypto_comp * __percpu *zcache_comp_pcpu_tfms;
enum comp_op {
ZCACHE_COMPOP_COMPRESS,
ZCACHE_COMPOP_DECOMPRESS
};
static inline int zcache_comp_op(enum comp_op op,
const u8 *src, unsigned int slen,
u8 *dst, unsigned int *dlen)
{
struct crypto_comp *tfm;
int ret;
BUG_ON(!zcache_comp_pcpu_tfms);
tfm = *per_cpu_ptr(zcache_comp_pcpu_tfms, get_cpu());
BUG_ON(!tfm);
switch (op) {
case ZCACHE_COMPOP_COMPRESS:
ret = crypto_comp_compress(tfm, src, slen, dst, dlen);
break;
case ZCACHE_COMPOP_DECOMPRESS:
ret = crypto_comp_decompress(tfm, src, slen, dst, dlen);
break;
}
put_cpu();
return ret;
}
/**********
* Compression buddies ("zbud") provides for packing two (or, possibly
* in the future, more) compressed ephemeral pages into a single "raw"
* (physical) page and tracking them with data structures so that
* the raw pages can be easily reclaimed.
*
* A zbud page ("zbpg") is an aligned page containing a list_head,
* a lock, and two "zbud headers". The remainder of the physical
* page is divided up into aligned 64-byte "chunks" which contain
* the compressed data for zero, one, or two zbuds. Each zbpg
* resides on: (1) an "unused list" if it has no zbuds; (2) a
* "buddied" list if it is fully populated with two zbuds; or
* (3) one of PAGE_SIZE/64 "unbuddied" lists indexed by how many chunks
* the one unbuddied zbud uses. The data inside a zbpg cannot be
* read or written unless the zbpg's lock is held.
*/
#define ZBH_SENTINEL 0x43214321
#define ZBPG_SENTINEL 0xdeadbeef
#define ZBUD_MAX_BUDS 2
struct zbud_hdr {
uint16_t client_id;
uint16_t pool_id;
struct tmem_oid oid;
uint32_t index;
uint16_t size; /* compressed size in bytes, zero means unused */
DECL_SENTINEL
};
struct zbud_page {
struct list_head bud_list;
spinlock_t lock;
struct zbud_hdr buddy[ZBUD_MAX_BUDS];
DECL_SENTINEL
/* followed by NUM_CHUNK aligned CHUNK_SIZE-byte chunks */
};
#define CHUNK_SHIFT 6
#define CHUNK_SIZE (1 << CHUNK_SHIFT)
#define CHUNK_MASK (~(CHUNK_SIZE-1))
#define NCHUNKS (((PAGE_SIZE - sizeof(struct zbud_page)) & \
CHUNK_MASK) >> CHUNK_SHIFT)
#define MAX_CHUNK (NCHUNKS-1)
static struct {
struct list_head list;
unsigned count;
} zbud_unbuddied[NCHUNKS];
/* list N contains pages with N chunks USED and NCHUNKS-N unused */
/* element 0 is never used but optimizing that isn't worth it */
static unsigned long zbud_cumul_chunk_counts[NCHUNKS];
struct list_head zbud_buddied_list;
static unsigned long zcache_zbud_buddied_count;
/* protects the buddied list and all unbuddied lists */
static DEFINE_SPINLOCK(zbud_budlists_spinlock);
static LIST_HEAD(zbpg_unused_list);
static unsigned long zcache_zbpg_unused_list_count;
/* protects the unused page list */
static DEFINE_SPINLOCK(zbpg_unused_list_spinlock);
static atomic_t zcache_zbud_curr_raw_pages;
static atomic_t zcache_zbud_curr_zpages;
static unsigned long zcache_zbud_curr_zbytes;
static unsigned long zcache_zbud_cumul_zpages;
static unsigned long zcache_zbud_cumul_zbytes;
static unsigned long zcache_compress_poor;
static unsigned long zcache_mean_compress_poor;
/* forward references */
static void *zcache_get_free_page(void);
static void zcache_free_page(void *p);
/*
* zbud helper functions
*/
static inline unsigned zbud_max_buddy_size(void)
{
return MAX_CHUNK << CHUNK_SHIFT;
}
static inline unsigned zbud_size_to_chunks(unsigned size)
{
BUG_ON(size == 0 || size > zbud_max_buddy_size());
return (size + CHUNK_SIZE - 1) >> CHUNK_SHIFT;
}
static inline int zbud_budnum(struct zbud_hdr *zh)
{
unsigned offset = (unsigned long)zh & (PAGE_SIZE - 1);
struct zbud_page *zbpg = NULL;
unsigned budnum = -1U;
int i;
for (i = 0; i < ZBUD_MAX_BUDS; i++)
if (offset == offsetof(typeof(*zbpg), buddy[i])) {
budnum = i;
break;
}
BUG_ON(budnum == -1U);
return budnum;
}
static char *zbud_data(struct zbud_hdr *zh, unsigned size)
{
struct zbud_page *zbpg;
char *p;
unsigned budnum;
ASSERT_SENTINEL(zh, ZBH);
budnum = zbud_budnum(zh);
BUG_ON(size == 0 || size > zbud_max_buddy_size());
zbpg = container_of(zh, struct zbud_page, buddy[budnum]);
ASSERT_SPINLOCK(&zbpg->lock);
p = (char *)zbpg;
if (budnum == 0)
p += ((sizeof(struct zbud_page) + CHUNK_SIZE - 1) &
CHUNK_MASK);
else if (budnum == 1)
p += PAGE_SIZE - ((size + CHUNK_SIZE - 1) & CHUNK_MASK);
return p;
}
/*
* zbud raw page management
*/
static struct zbud_page *zbud_alloc_raw_page(void)
{
struct zbud_page *zbpg = NULL;
struct zbud_hdr *zh0, *zh1;
bool recycled = 0;
/* if any pages on the zbpg list, use one */
spin_lock(&zbpg_unused_list_spinlock);
if (!list_empty(&zbpg_unused_list)) {
zbpg = list_first_entry(&zbpg_unused_list,
struct zbud_page, bud_list);
list_del_init(&zbpg->bud_list);
zcache_zbpg_unused_list_count--;
recycled = 1;
}
spin_unlock(&zbpg_unused_list_spinlock);
if (zbpg == NULL)
/* none on zbpg list, try to get a kernel page */
zbpg = zcache_get_free_page();
if (likely(zbpg != NULL)) {
INIT_LIST_HEAD(&zbpg->bud_list);
zh0 = &zbpg->buddy[0]; zh1 = &zbpg->buddy[1];
spin_lock_init(&zbpg->lock);
if (recycled) {
ASSERT_INVERTED_SENTINEL(zbpg, ZBPG);
SET_SENTINEL(zbpg, ZBPG);
BUG_ON(zh0->size != 0 || tmem_oid_valid(&zh0->oid));
BUG_ON(zh1->size != 0 || tmem_oid_valid(&zh1->oid));
} else {
atomic_inc(&zcache_zbud_curr_raw_pages);
INIT_LIST_HEAD(&zbpg->bud_list);
SET_SENTINEL(zbpg, ZBPG);
zh0->size = 0; zh1->size = 0;
tmem_oid_set_invalid(&zh0->oid);
tmem_oid_set_invalid(&zh1->oid);
}
}
return zbpg;
}
static void zbud_free_raw_page(struct zbud_page *zbpg)
{
struct zbud_hdr *zh0 = &zbpg->buddy[0], *zh1 = &zbpg->buddy[1];
ASSERT_SENTINEL(zbpg, ZBPG);
BUG_ON(!list_empty(&zbpg->bud_list));
ASSERT_SPINLOCK(&zbpg->lock);
BUG_ON(zh0->size != 0 || tmem_oid_valid(&zh0->oid));
BUG_ON(zh1->size != 0 || tmem_oid_valid(&zh1->oid));
INVERT_SENTINEL(zbpg, ZBPG);
spin_unlock(&zbpg->lock);
spin_lock(&zbpg_unused_list_spinlock);
list_add(&zbpg->bud_list, &zbpg_unused_list);
zcache_zbpg_unused_list_count++;
spin_unlock(&zbpg_unused_list_spinlock);
}
/*
* core zbud handling routines
*/
static unsigned zbud_free(struct zbud_hdr *zh)
{
unsigned size;
ASSERT_SENTINEL(zh, ZBH);
BUG_ON(!tmem_oid_valid(&zh->oid));
size = zh->size;
BUG_ON(zh->size == 0 || zh->size > zbud_max_buddy_size());
zh->size = 0;
tmem_oid_set_invalid(&zh->oid);
INVERT_SENTINEL(zh, ZBH);
zcache_zbud_curr_zbytes -= size;
atomic_dec(&zcache_zbud_curr_zpages);
return size;
}
static void zbud_free_and_delist(struct zbud_hdr *zh)
{
unsigned chunks;
struct zbud_hdr *zh_other;
unsigned budnum = zbud_budnum(zh), size;
struct zbud_page *zbpg =
container_of(zh, struct zbud_page, buddy[budnum]);
spin_lock(&zbud_budlists_spinlock);
spin_lock(&zbpg->lock);
if (list_empty(&zbpg->bud_list)) {
/* ignore zombie page... see zbud_evict_pages() */
spin_unlock(&zbpg->lock);
spin_unlock(&zbud_budlists_spinlock);
return;
}
size = zbud_free(zh);
ASSERT_SPINLOCK(&zbpg->lock);
zh_other = &zbpg->buddy[(budnum == 0) ? 1 : 0];
if (zh_other->size == 0) { /* was unbuddied: unlist and free */
chunks = zbud_size_to_chunks(size) ;
BUG_ON(list_empty(&zbud_unbuddied[chunks].list));
list_del_init(&zbpg->bud_list);
zbud_unbuddied[chunks].count--;
spin_unlock(&zbud_budlists_spinlock);
zbud_free_raw_page(zbpg);
} else { /* was buddied: move remaining buddy to unbuddied list */
chunks = zbud_size_to_chunks(zh_other->size) ;
list_del_init(&zbpg->bud_list);
zcache_zbud_buddied_count--;
list_add_tail(&zbpg->bud_list, &zbud_unbuddied[chunks].list);
zbud_unbuddied[chunks].count++;
spin_unlock(&zbud_budlists_spinlock);
spin_unlock(&zbpg->lock);
}
}
static struct zbud_hdr *zbud_create(uint16_t client_id, uint16_t pool_id,
struct tmem_oid *oid,
uint32_t index, struct page *page,
void *cdata, unsigned size)
{
struct zbud_hdr *zh0, *zh1, *zh = NULL;
struct zbud_page *zbpg = NULL, *ztmp;
unsigned nchunks;
char *to;
int i, found_good_buddy = 0;
nchunks = zbud_size_to_chunks(size) ;
for (i = MAX_CHUNK - nchunks + 1; i > 0; i--) {
spin_lock(&zbud_budlists_spinlock);
if (!list_empty(&zbud_unbuddied[i].list)) {
list_for_each_entry_safe(zbpg, ztmp,
&zbud_unbuddied[i].list, bud_list) {
if (spin_trylock(&zbpg->lock)) {
found_good_buddy = i;
goto found_unbuddied;
}
}
}
spin_unlock(&zbud_budlists_spinlock);
}
/* didn't find a good buddy, try allocating a new page */
zbpg = zbud_alloc_raw_page();
if (unlikely(zbpg == NULL))
goto out;
/* ok, have a page, now compress the data before taking locks */
spin_lock(&zbud_budlists_spinlock);
spin_lock(&zbpg->lock);
list_add_tail(&zbpg->bud_list, &zbud_unbuddied[nchunks].list);
zbud_unbuddied[nchunks].count++;
zh = &zbpg->buddy[0];
goto init_zh;
found_unbuddied:
ASSERT_SPINLOCK(&zbpg->lock);
zh0 = &zbpg->buddy[0]; zh1 = &zbpg->buddy[1];
BUG_ON(!((zh0->size == 0) ^ (zh1->size == 0)));
if (zh0->size != 0) { /* buddy0 in use, buddy1 is vacant */
ASSERT_SENTINEL(zh0, ZBH);
zh = zh1;
} else if (zh1->size != 0) { /* buddy1 in use, buddy0 is vacant */
ASSERT_SENTINEL(zh1, ZBH);
zh = zh0;
} else
BUG();
list_del_init(&zbpg->bud_list);
zbud_unbuddied[found_good_buddy].count--;
list_add_tail(&zbpg->bud_list, &zbud_buddied_list);
zcache_zbud_buddied_count++;
init_zh:
SET_SENTINEL(zh, ZBH);
zh->size = size;
zh->index = index;
zh->oid = *oid;
zh->pool_id = pool_id;
zh->client_id = client_id;
to = zbud_data(zh, size);
memcpy(to, cdata, size);
spin_unlock(&zbpg->lock);
spin_unlock(&zbud_budlists_spinlock);
zbud_cumul_chunk_counts[nchunks]++;
atomic_inc(&zcache_zbud_curr_zpages);
zcache_zbud_cumul_zpages++;
zcache_zbud_curr_zbytes += size;
zcache_zbud_cumul_zbytes += size;
out:
return zh;
}
static int zbud_decompress(struct page *page, struct zbud_hdr *zh)
{
struct zbud_page *zbpg;
unsigned budnum = zbud_budnum(zh);
unsigned int out_len = PAGE_SIZE;
char *to_va, *from_va;
unsigned size;
int ret = 0;
zbpg = container_of(zh, struct zbud_page, buddy[budnum]);
spin_lock(&zbpg->lock);
if (list_empty(&zbpg->bud_list)) {
/* ignore zombie page... see zbud_evict_pages() */
ret = -EINVAL;
goto out;
}
ASSERT_SENTINEL(zh, ZBH);
BUG_ON(zh->size == 0 || zh->size > zbud_max_buddy_size());
to_va = kmap_atomic(page);
size = zh->size;
from_va = zbud_data(zh, size);
ret = zcache_comp_op(ZCACHE_COMPOP_DECOMPRESS, from_va, size,
to_va, &out_len);
BUG_ON(ret);
BUG_ON(out_len != PAGE_SIZE);
kunmap_atomic(to_va);
out:
spin_unlock(&zbpg->lock);
return ret;
}
/*
* The following routines handle shrinking of ephemeral pages by evicting
* pages "least valuable" first.
*/
static unsigned long zcache_evicted_raw_pages;
static unsigned long zcache_evicted_buddied_pages;
static unsigned long zcache_evicted_unbuddied_pages;
static struct tmem_pool *zcache_get_pool_by_id(uint16_t cli_id,
uint16_t poolid);
static void zcache_put_pool(struct tmem_pool *pool);
/*
* Flush and free all zbuds in a zbpg, then free the pageframe
*/
static void zbud_evict_zbpg(struct zbud_page *zbpg)
{
struct zbud_hdr *zh;
int i, j;
uint32_t pool_id[ZBUD_MAX_BUDS], client_id[ZBUD_MAX_BUDS];
uint32_t index[ZBUD_MAX_BUDS];
struct tmem_oid oid[ZBUD_MAX_BUDS];
struct tmem_pool *pool;
ASSERT_SPINLOCK(&zbpg->lock);
BUG_ON(!list_empty(&zbpg->bud_list));
for (i = 0, j = 0; i < ZBUD_MAX_BUDS; i++) {
zh = &zbpg->buddy[i];
if (zh->size) {
client_id[j] = zh->client_id;
pool_id[j] = zh->pool_id;
oid[j] = zh->oid;
index[j] = zh->index;
j++;
zbud_free(zh);
}
}
spin_unlock(&zbpg->lock);
for (i = 0; i < j; i++) {
pool = zcache_get_pool_by_id(client_id[i], pool_id[i]);
if (pool != NULL) {
tmem_flush_page(pool, &oid[i], index[i]);
zcache_put_pool(pool);
}
}
ASSERT_SENTINEL(zbpg, ZBPG);
spin_lock(&zbpg->lock);
zbud_free_raw_page(zbpg);
}
/*
* Free nr pages. This code is funky because we want to hold the locks
* protecting various lists for as short a time as possible, and in some
* circumstances the list may change asynchronously when the list lock is
* not held. In some cases we also trylock not only to avoid waiting on a
* page in use by another cpu, but also to avoid potential deadlock due to
* lock inversion.
*/
static void zbud_evict_pages(int nr)
{
struct zbud_page *zbpg;
int i;
/* first try freeing any pages on unused list */
retry_unused_list:
spin_lock_bh(&zbpg_unused_list_spinlock);
if (!list_empty(&zbpg_unused_list)) {
/* can't walk list here, since it may change when unlocked */
zbpg = list_first_entry(&zbpg_unused_list,
struct zbud_page, bud_list);
list_del_init(&zbpg->bud_list);
zcache_zbpg_unused_list_count--;
atomic_dec(&zcache_zbud_curr_raw_pages);
spin_unlock_bh(&zbpg_unused_list_spinlock);
zcache_free_page(zbpg);
zcache_evicted_raw_pages++;
if (--nr <= 0)
goto out;
goto retry_unused_list;
}
spin_unlock_bh(&zbpg_unused_list_spinlock);
/* now try freeing unbuddied pages, starting with least space avail */
for (i = 0; i < MAX_CHUNK; i++) {
retry_unbud_list_i:
spin_lock_bh(&zbud_budlists_spinlock);
if (list_empty(&zbud_unbuddied[i].list)) {
spin_unlock_bh(&zbud_budlists_spinlock);
continue;
}
list_for_each_entry(zbpg, &zbud_unbuddied[i].list, bud_list) {
if (unlikely(!spin_trylock(&zbpg->lock)))
continue;
list_del_init(&zbpg->bud_list);
zbud_unbuddied[i].count--;
spin_unlock(&zbud_budlists_spinlock);
zcache_evicted_unbuddied_pages++;
/* want budlists unlocked when doing zbpg eviction */
zbud_evict_zbpg(zbpg);
local_bh_enable();
if (--nr <= 0)
goto out;
goto retry_unbud_list_i;
}
spin_unlock_bh(&zbud_budlists_spinlock);
}
/* as a last resort, free buddied pages */
retry_bud_list:
spin_lock_bh(&zbud_budlists_spinlock);
if (list_empty(&zbud_buddied_list)) {
spin_unlock_bh(&zbud_budlists_spinlock);
goto out;
}
list_for_each_entry(zbpg, &zbud_buddied_list, bud_list) {
if (unlikely(!spin_trylock(&zbpg->lock)))
continue;
list_del_init(&zbpg->bud_list);
zcache_zbud_buddied_count--;
spin_unlock(&zbud_budlists_spinlock);
zcache_evicted_buddied_pages++;
/* want budlists unlocked when doing zbpg eviction */
zbud_evict_zbpg(zbpg);
local_bh_enable();
if (--nr <= 0)
goto out;
goto retry_bud_list;
}
spin_unlock_bh(&zbud_budlists_spinlock);
out:
return;
}
static void zbud_init(void)
{
int i;
INIT_LIST_HEAD(&zbud_buddied_list);
zcache_zbud_buddied_count = 0;
for (i = 0; i < NCHUNKS; i++) {
INIT_LIST_HEAD(&zbud_unbuddied[i].list);
zbud_unbuddied[i].count = 0;
}
}
#ifdef CONFIG_SYSFS
/*
* These sysfs routines show a nice distribution of how many zbpg's are
* currently (and have ever been placed) in each unbuddied list. It's fun
* to watch but can probably go away before final merge.
*/
static int zbud_show_unbuddied_list_counts(char *buf)
{
int i;
char *p = buf;
for (i = 0; i < NCHUNKS; i++)
p += sprintf(p, "%u ", zbud_unbuddied[i].count);
return p - buf;
}
static int zbud_show_cumul_chunk_counts(char *buf)
{
unsigned long i, chunks = 0, total_chunks = 0, sum_total_chunks = 0;
unsigned long total_chunks_lte_21 = 0, total_chunks_lte_32 = 0;
unsigned long total_chunks_lte_42 = 0;
char *p = buf;
for (i = 0; i < NCHUNKS; i++) {
p += sprintf(p, "%lu ", zbud_cumul_chunk_counts[i]);
chunks += zbud_cumul_chunk_counts[i];
total_chunks += zbud_cumul_chunk_counts[i];
sum_total_chunks += i * zbud_cumul_chunk_counts[i];
if (i == 21)
total_chunks_lte_21 = total_chunks;
if (i == 32)
total_chunks_lte_32 = total_chunks;
if (i == 42)
total_chunks_lte_42 = total_chunks;
}
p += sprintf(p, "<=21:%lu <=32:%lu <=42:%lu, mean:%lu\n",
total_chunks_lte_21, total_chunks_lte_32, total_chunks_lte_42,
chunks == 0 ? 0 : sum_total_chunks / chunks);
return p - buf;
}
#endif
/**********
* This "zv" PAM implementation combines the slab-based zsmalloc
* with the crypto compression API to maximize the amount of data that can
* be packed into a physical page.
*
* Zv represents a PAM page with the index and object (plus a "size" value
* necessary for decompression) immediately preceding the compressed data.
*/
#define ZVH_SENTINEL 0x43214321
struct zv_hdr {
uint32_t pool_id;
struct tmem_oid oid;
uint32_t index;
size_t size;
DECL_SENTINEL
};
/* rudimentary policy limits */
/* total number of persistent pages may not exceed this percentage */
static unsigned int zv_page_count_policy_percent = 75;
/*
* byte count defining poor compression; pages with greater zsize will be
* rejected
*/
static unsigned int zv_max_zsize = (PAGE_SIZE / 8) * 7;
/*
* byte count defining poor *mean* compression; pages with greater zsize
* will be rejected until sufficient better-compressed pages are accepted
* driving the mean below this threshold
*/
static unsigned int zv_max_mean_zsize = (PAGE_SIZE / 8) * 5;
static atomic_t zv_curr_dist_counts[NCHUNKS];
static atomic_t zv_cumul_dist_counts[NCHUNKS];
static struct zv_hdr *zv_create(struct zs_pool *pool, uint32_t pool_id,
struct tmem_oid *oid, uint32_t index,
void *cdata, unsigned clen)
{
struct zv_hdr *zv;
u32 size = clen + sizeof(struct zv_hdr);
int chunks = (size + (CHUNK_SIZE - 1)) >> CHUNK_SHIFT;
void *handle = NULL;
BUG_ON(!irqs_disabled());
BUG_ON(chunks >= NCHUNKS);
handle = zs_malloc(pool, size);
if (!handle)
goto out;
atomic_inc(&zv_curr_dist_counts[chunks]);
atomic_inc(&zv_cumul_dist_counts[chunks]);
zv = zs_map_object(pool, handle);
zv->index = index;
zv->oid = *oid;
zv->pool_id = pool_id;
zv->size = clen;
SET_SENTINEL(zv, ZVH);
memcpy((char *)zv + sizeof(struct zv_hdr), cdata, clen);
zs_unmap_object(pool, handle);
out:
return handle;
}
static void zv_free(struct zs_pool *pool, void *handle)
{
unsigned long flags;
struct zv_hdr *zv;
uint16_t size;
int chunks;
zv = zs_map_object(pool, handle);
ASSERT_SENTINEL(zv, ZVH);
size = zv->size + sizeof(struct zv_hdr);
INVERT_SENTINEL(zv, ZVH);
zs_unmap_object(pool, handle);
chunks = (size + (CHUNK_SIZE - 1)) >> CHUNK_SHIFT;
BUG_ON(chunks >= NCHUNKS);
atomic_dec(&zv_curr_dist_counts[chunks]);
local_irq_save(flags);
zs_free(pool, handle);
local_irq_restore(flags);
}
static void zv_decompress(struct page *page, void *handle)
{
unsigned int clen = PAGE_SIZE;
char *to_va;
int ret;
struct zv_hdr *zv;
zv = zs_map_object(zcache_host.zspool, handle);
BUG_ON(zv->size == 0);
ASSERT_SENTINEL(zv, ZVH);
to_va = kmap_atomic(page);
ret = zcache_comp_op(ZCACHE_COMPOP_DECOMPRESS, (char *)zv + sizeof(*zv),
zv->size, to_va, &clen);
kunmap_atomic(to_va);
zs_unmap_object(zcache_host.zspool, handle);
BUG_ON(ret);
BUG_ON(clen != PAGE_SIZE);
}
#ifdef CONFIG_SYSFS
/*
* show a distribution of compression stats for zv pages.
*/
static int zv_curr_dist_counts_show(char *buf)
{
unsigned long i, n, chunks = 0, sum_total_chunks = 0;
char *p = buf;
for (i = 0; i < NCHUNKS; i++) {
n = atomic_read(&zv_curr_dist_counts[i]);
p += sprintf(p, "%lu ", n);
chunks += n;
sum_total_chunks += i * n;
}
p += sprintf(p, "mean:%lu\n",
chunks == 0 ? 0 : sum_total_chunks / chunks);
return p - buf;
}
static int zv_cumul_dist_counts_show(char *buf)
{
unsigned long i, n, chunks = 0, sum_total_chunks = 0;
char *p = buf;
for (i = 0; i < NCHUNKS; i++) {
n = atomic_read(&zv_cumul_dist_counts[i]);
p += sprintf(p, "%lu ", n);
chunks += n;
sum_total_chunks += i * n;
}
p += sprintf(p, "mean:%lu\n",
chunks == 0 ? 0 : sum_total_chunks / chunks);
return p - buf;
}
/*
* setting zv_max_zsize via sysfs causes all persistent (e.g. swap)
* pages that don't compress to less than this value (including metadata
* overhead) to be rejected. We don't allow the value to get too close
* to PAGE_SIZE.
*/
static ssize_t zv_max_zsize_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", zv_max_zsize);
}
static ssize_t zv_max_zsize_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned long val;
int err;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
err = kstrtoul(buf, 10, &val);
if (err || (val == 0) || (val > (PAGE_SIZE / 8) * 7))
return -EINVAL;
zv_max_zsize = val;
return count;
}
/*
* setting zv_max_mean_zsize via sysfs causes all persistent (e.g. swap)
* pages that don't compress to less than this value (including metadata
* overhead) to be rejected UNLESS the mean compression is also smaller
* than this value. In other words, we are load-balancing-by-zsize the
* accepted pages. Again, we don't allow the value to get too close
* to PAGE_SIZE.
*/
static ssize_t zv_max_mean_zsize_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", zv_max_mean_zsize);
}
static ssize_t zv_max_mean_zsize_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned long val;
int err;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
err = kstrtoul(buf, 10, &val);
if (err || (val == 0) || (val > (PAGE_SIZE / 8) * 7))
return -EINVAL;
zv_max_mean_zsize = val;
return count;
}
/*
* setting zv_page_count_policy_percent via sysfs sets an upper bound of
* persistent (e.g. swap) pages that will be retained according to:
* (zv_page_count_policy_percent * totalram_pages) / 100)
* when that limit is reached, further puts will be rejected (until
* some pages have been flushed). Note that, due to compression,
* this number may exceed 100; it defaults to 75 and we set an
* arbitary limit of 150. A poor choice will almost certainly result
* in OOM's, so this value should only be changed prudently.
*/
static ssize_t zv_page_count_policy_percent_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", zv_page_count_policy_percent);
}
static ssize_t zv_page_count_policy_percent_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned long val;
int err;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
err = kstrtoul(buf, 10, &val);
if (err || (val == 0) || (val > 150))
return -EINVAL;
zv_page_count_policy_percent = val;
return count;
}
static struct kobj_attribute zcache_zv_max_zsize_attr = {
.attr = { .name = "zv_max_zsize", .mode = 0644 },
.show = zv_max_zsize_show,
.store = zv_max_zsize_store,
};
static struct kobj_attribute zcache_zv_max_mean_zsize_attr = {
.attr = { .name = "zv_max_mean_zsize", .mode = 0644 },
.show = zv_max_mean_zsize_show,
.store = zv_max_mean_zsize_store,
};
static struct kobj_attribute zcache_zv_page_count_policy_percent_attr = {
.attr = { .name = "zv_page_count_policy_percent",
.mode = 0644 },
.show = zv_page_count_policy_percent_show,
.store = zv_page_count_policy_percent_store,
};
#endif
/*
* zcache core code starts here
*/
/* useful stats not collected by cleancache or frontswap */
static unsigned long zcache_flush_total;
static unsigned long zcache_flush_found;
static unsigned long zcache_flobj_total;
static unsigned long zcache_flobj_found;
static unsigned long zcache_failed_eph_puts;
static unsigned long zcache_failed_pers_puts;
/*
* Tmem operations assume the poolid implies the invoking client.
* Zcache only has one client (the kernel itself): LOCAL_CLIENT.
* RAMster has each client numbered by cluster node, and a KVM version
* of zcache would have one client per guest and each client might
* have a poolid==N.
*/
static struct tmem_pool *zcache_get_pool_by_id(uint16_t cli_id, uint16_t poolid)
{
struct tmem_pool *pool = NULL;
struct zcache_client *cli = NULL;
if (cli_id == LOCAL_CLIENT)
cli = &zcache_host;
else {
if (cli_id >= MAX_CLIENTS)
goto out;
cli = &zcache_clients[cli_id];
if (cli == NULL)
goto out;
atomic_inc(&cli->refcount);
}
if (poolid < MAX_POOLS_PER_CLIENT) {
pool = cli->tmem_pools[poolid];
if (pool != NULL)
atomic_inc(&pool->refcount);
}
out:
return pool;
}
static void zcache_put_pool(struct tmem_pool *pool)
{
struct zcache_client *cli = NULL;
if (pool == NULL)
BUG();
cli = pool->client;
atomic_dec(&pool->refcount);
atomic_dec(&cli->refcount);
}
int zcache_new_client(uint16_t cli_id)
{
struct zcache_client *cli = NULL;
int ret = -1;
if (cli_id == LOCAL_CLIENT)
cli = &zcache_host;
else if ((unsigned int)cli_id < MAX_CLIENTS)
cli = &zcache_clients[cli_id];
if (cli == NULL)
goto out;
if (cli->allocated)
goto out;
cli->allocated = 1;
#ifdef CONFIG_FRONTSWAP
cli->zspool = zs_create_pool("zcache", ZCACHE_GFP_MASK);
if (cli->zspool == NULL)
goto out;
#endif
ret = 0;
out:
return ret;
}
/* counters for debugging */
static unsigned long zcache_failed_get_free_pages;
static unsigned long zcache_failed_alloc;
static unsigned long zcache_put_to_flush;
/*
* for now, used named slabs so can easily track usage; later can
* either just use kmalloc, or perhaps add a slab-like allocator
* to more carefully manage total memory utilization
*/
static struct kmem_cache *zcache_objnode_cache;
static struct kmem_cache *zcache_obj_cache;
static atomic_t zcache_curr_obj_count = ATOMIC_INIT(0);
static unsigned long zcache_curr_obj_count_max;
static atomic_t zcache_curr_objnode_count = ATOMIC_INIT(0);
static unsigned long zcache_curr_objnode_count_max;
/*
* to avoid memory allocation recursion (e.g. due to direct reclaim), we
* preload all necessary data structures so the hostops callbacks never
* actually do a malloc
*/
struct zcache_preload {
void *page;
struct tmem_obj *obj;
int nr;
struct tmem_objnode *objnodes[OBJNODE_TREE_MAX_PATH];
};
static DEFINE_PER_CPU(struct zcache_preload, zcache_preloads) = { 0, };
static int zcache_do_preload(struct tmem_pool *pool)
{
struct zcache_preload *kp;
struct tmem_objnode *objnode;
struct tmem_obj *obj;
void *page;
int ret = -ENOMEM;
if (unlikely(zcache_objnode_cache == NULL))
goto out;
if (unlikely(zcache_obj_cache == NULL))
goto out;
preempt_disable();
kp = &__get_cpu_var(zcache_preloads);
while (kp->nr < ARRAY_SIZE(kp->objnodes)) {
preempt_enable_no_resched();
objnode = kmem_cache_alloc(zcache_objnode_cache,
ZCACHE_GFP_MASK);
if (unlikely(objnode == NULL)) {
zcache_failed_alloc++;
goto out;
}
preempt_disable();
kp = &__get_cpu_var(zcache_preloads);
if (kp->nr < ARRAY_SIZE(kp->objnodes))
kp->objnodes[kp->nr++] = objnode;
else
kmem_cache_free(zcache_objnode_cache, objnode);
}
preempt_enable_no_resched();
obj = kmem_cache_alloc(zcache_obj_cache, ZCACHE_GFP_MASK);
if (unlikely(obj == NULL)) {
zcache_failed_alloc++;
goto out;
}
page = (void *)__get_free_page(ZCACHE_GFP_MASK);
if (unlikely(page == NULL)) {
zcache_failed_get_free_pages++;
kmem_cache_free(zcache_obj_cache, obj);
goto out;
}
preempt_disable();
kp = &__get_cpu_var(zcache_preloads);
if (kp->obj == NULL)
kp->obj = obj;
else
kmem_cache_free(zcache_obj_cache, obj);
if (kp->page == NULL)
kp->page = page;
else
free_page((unsigned long)page);
ret = 0;
out:
return ret;
}
static void *zcache_get_free_page(void)
{
struct zcache_preload *kp;
void *page;
kp = &__get_cpu_var(zcache_preloads);
page = kp->page;
BUG_ON(page == NULL);
kp->page = NULL;
return page;
}
static void zcache_free_page(void *p)
{
free_page((unsigned long)p);
}
/*
* zcache implementation for tmem host ops
*/
static struct tmem_objnode *zcache_objnode_alloc(struct tmem_pool *pool)
{
struct tmem_objnode *objnode = NULL;
unsigned long count;
struct zcache_preload *kp;
kp = &__get_cpu_var(zcache_preloads);
if (kp->nr <= 0)
goto out;
objnode = kp->objnodes[kp->nr - 1];
BUG_ON(objnode == NULL);
kp->objnodes[kp->nr - 1] = NULL;
kp->nr--;
count = atomic_inc_return(&zcache_curr_objnode_count);
if (count > zcache_curr_objnode_count_max)
zcache_curr_objnode_count_max = count;
out:
return objnode;
}
static void zcache_objnode_free(struct tmem_objnode *objnode,
struct tmem_pool *pool)
{
atomic_dec(&zcache_curr_objnode_count);
BUG_ON(atomic_read(&zcache_curr_objnode_count) < 0);
kmem_cache_free(zcache_objnode_cache, objnode);
}
static struct tmem_obj *zcache_obj_alloc(struct tmem_pool *pool)
{
struct tmem_obj *obj = NULL;
unsigned long count;
struct zcache_preload *kp;
kp = &__get_cpu_var(zcache_preloads);
obj = kp->obj;
BUG_ON(obj == NULL);
kp->obj = NULL;
count = atomic_inc_return(&zcache_curr_obj_count);
if (count > zcache_curr_obj_count_max)
zcache_curr_obj_count_max = count;
return obj;
}
static void zcache_obj_free(struct tmem_obj *obj, struct tmem_pool *pool)
{
atomic_dec(&zcache_curr_obj_count);
BUG_ON(atomic_read(&zcache_curr_obj_count) < 0);
kmem_cache_free(zcache_obj_cache, obj);
}
static struct tmem_hostops zcache_hostops = {
.obj_alloc = zcache_obj_alloc,
.obj_free = zcache_obj_free,
.objnode_alloc = zcache_objnode_alloc,
.objnode_free = zcache_objnode_free,
};
/*
* zcache implementations for PAM page descriptor ops
*/
static atomic_t zcache_curr_eph_pampd_count = ATOMIC_INIT(0);
static unsigned long zcache_curr_eph_pampd_count_max;
static atomic_t zcache_curr_pers_pampd_count = ATOMIC_INIT(0);
static unsigned long zcache_curr_pers_pampd_count_max;
/* forward reference */
static int zcache_compress(struct page *from, void **out_va, unsigned *out_len);
static void *zcache_pampd_create(char *data, size_t size, bool raw, int eph,
struct tmem_pool *pool, struct tmem_oid *oid,
uint32_t index)
{
void *pampd = NULL, *cdata;
unsigned clen;
int ret;
unsigned long count;
struct page *page = (struct page *)(data);
struct zcache_client *cli = pool->client;
uint16_t client_id = get_client_id_from_client(cli);
unsigned long zv_mean_zsize;
unsigned long curr_pers_pampd_count;
u64 total_zsize;
if (eph) {
ret = zcache_compress(page, &cdata, &clen);
if (ret == 0)
goto out;
if (clen == 0 || clen > zbud_max_buddy_size()) {
zcache_compress_poor++;
goto out;
}
pampd = (void *)zbud_create(client_id, pool->pool_id, oid,
index, page, cdata, clen);
if (pampd != NULL) {
count = atomic_inc_return(&zcache_curr_eph_pampd_count);
if (count > zcache_curr_eph_pampd_count_max)
zcache_curr_eph_pampd_count_max = count;
}
} else {
curr_pers_pampd_count =
atomic_read(&zcache_curr_pers_pampd_count);
if (curr_pers_pampd_count >
(zv_page_count_policy_percent * totalram_pages) / 100)
goto out;
ret = zcache_compress(page, &cdata, &clen);
if (ret == 0)
goto out;
/* reject if compression is too poor */
if (clen > zv_max_zsize) {
zcache_compress_poor++;
goto out;
}
/* reject if mean compression is too poor */
if ((clen > zv_max_mean_zsize) && (curr_pers_pampd_count > 0)) {
total_zsize = zs_get_total_size_bytes(cli->zspool);
zv_mean_zsize = div_u64(total_zsize,
curr_pers_pampd_count);
if (zv_mean_zsize > zv_max_mean_zsize) {
zcache_mean_compress_poor++;
goto out;
}
}
pampd = (void *)zv_create(cli->zspool, pool->pool_id,
oid, index, cdata, clen);
if (pampd == NULL)
goto out;
count = atomic_inc_return(&zcache_curr_pers_pampd_count);
if (count > zcache_curr_pers_pampd_count_max)
zcache_curr_pers_pampd_count_max = count;
}
out:
return pampd;
}
/*
* fill the pageframe corresponding to the struct page with the data
* from the passed pampd
*/
static int zcache_pampd_get_data(char *data, size_t *bufsize, bool raw,
void *pampd, struct tmem_pool *pool,
struct tmem_oid *oid, uint32_t index)
{
int ret = 0;
BUG_ON(is_ephemeral(pool));
zv_decompress((struct page *)(data), pampd);
return ret;
}
/*
* fill the pageframe corresponding to the struct page with the data
* from the passed pampd
*/
static int zcache_pampd_get_data_and_free(char *data, size_t *bufsize, bool raw,
void *pampd, struct tmem_pool *pool,
struct tmem_oid *oid, uint32_t index)
{
int ret = 0;
BUG_ON(!is_ephemeral(pool));
zbud_decompress((struct page *)(data), pampd);
zbud_free_and_delist((struct zbud_hdr *)pampd);
atomic_dec(&zcache_curr_eph_pampd_count);
return ret;
}
/*
* free the pampd and remove it from any zcache lists
* pampd must no longer be pointed to from any tmem data structures!
*/
static void zcache_pampd_free(void *pampd, struct tmem_pool *pool,
struct tmem_oid *oid, uint32_t index)
{
struct zcache_client *cli = pool->client;
if (is_ephemeral(pool)) {
zbud_free_and_delist((struct zbud_hdr *)pampd);
atomic_dec(&zcache_curr_eph_pampd_count);
BUG_ON(atomic_read(&zcache_curr_eph_pampd_count) < 0);
} else {
zv_free(cli->zspool, pampd);
atomic_dec(&zcache_curr_pers_pampd_count);
BUG_ON(atomic_read(&zcache_curr_pers_pampd_count) < 0);
}
}
static void zcache_pampd_free_obj(struct tmem_pool *pool, struct tmem_obj *obj)
{
}
static void zcache_pampd_new_obj(struct tmem_obj *obj)
{
}
static int zcache_pampd_replace_in_obj(void *pampd, struct tmem_obj *obj)
{
return -1;
}
static bool zcache_pampd_is_remote(void *pampd)
{
return 0;
}
static struct tmem_pamops zcache_pamops = {
.create = zcache_pampd_create,
.get_data = zcache_pampd_get_data,
.get_data_and_free = zcache_pampd_get_data_and_free,
.free = zcache_pampd_free,
.free_obj = zcache_pampd_free_obj,
.new_obj = zcache_pampd_new_obj,
.replace_in_obj = zcache_pampd_replace_in_obj,
.is_remote = zcache_pampd_is_remote,
};
/*
* zcache compression/decompression and related per-cpu stuff
*/
static DEFINE_PER_CPU(unsigned char *, zcache_dstmem);
#define ZCACHE_DSTMEM_ORDER 1
static int zcache_compress(struct page *from, void **out_va, unsigned *out_len)
{
int ret = 0;
unsigned char *dmem = __get_cpu_var(zcache_dstmem);
char *from_va;
BUG_ON(!irqs_disabled());
if (unlikely(dmem == NULL))
goto out; /* no buffer or no compressor so can't compress */
*out_len = PAGE_SIZE << ZCACHE_DSTMEM_ORDER;
from_va = kmap_atomic(from);
mb();
ret = zcache_comp_op(ZCACHE_COMPOP_COMPRESS, from_va, PAGE_SIZE, dmem,
out_len);
BUG_ON(ret);
*out_va = dmem;
kunmap_atomic(from_va);
ret = 1;
out:
return ret;
}
static int zcache_comp_cpu_up(int cpu)
{
struct crypto_comp *tfm;
tfm = crypto_alloc_comp(zcache_comp_name, 0, 0);
if (IS_ERR(tfm))
return NOTIFY_BAD;
*per_cpu_ptr(zcache_comp_pcpu_tfms, cpu) = tfm;
return NOTIFY_OK;
}
static void zcache_comp_cpu_down(int cpu)
{
struct crypto_comp *tfm;
tfm = *per_cpu_ptr(zcache_comp_pcpu_tfms, cpu);
crypto_free_comp(tfm);
*per_cpu_ptr(zcache_comp_pcpu_tfms, cpu) = NULL;
}
static int zcache_cpu_notifier(struct notifier_block *nb,
unsigned long action, void *pcpu)
{
int ret, cpu = (long)pcpu;
struct zcache_preload *kp;
switch (action) {
case CPU_UP_PREPARE:
ret = zcache_comp_cpu_up(cpu);
if (ret != NOTIFY_OK) {
pr_err("zcache: can't allocate compressor transform\n");
return ret;
}
per_cpu(zcache_dstmem, cpu) = (void *)__get_free_pages(
GFP_KERNEL | __GFP_REPEAT, ZCACHE_DSTMEM_ORDER);
break;
case CPU_DEAD:
case CPU_UP_CANCELED:
zcache_comp_cpu_down(cpu);
free_pages((unsigned long)per_cpu(zcache_dstmem, cpu),
ZCACHE_DSTMEM_ORDER);
per_cpu(zcache_dstmem, cpu) = NULL;
kp = &per_cpu(zcache_preloads, cpu);
while (kp->nr) {
kmem_cache_free(zcache_objnode_cache,
kp->objnodes[kp->nr - 1]);
kp->objnodes[kp->nr - 1] = NULL;
kp->nr--;
}
if (kp->obj) {
kmem_cache_free(zcache_obj_cache, kp->obj);
kp->obj = NULL;
}
if (kp->page) {
free_page((unsigned long)kp->page);
kp->page = NULL;
}
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block zcache_cpu_notifier_block = {
.notifier_call = zcache_cpu_notifier
};
#ifdef CONFIG_SYSFS
#define ZCACHE_SYSFS_RO(_name) \
static ssize_t zcache_##_name##_show(struct kobject *kobj, \
struct kobj_attribute *attr, char *buf) \
{ \
return sprintf(buf, "%lu\n", zcache_##_name); \
} \
static struct kobj_attribute zcache_##_name##_attr = { \
.attr = { .name = __stringify(_name), .mode = 0444 }, \
.show = zcache_##_name##_show, \
}
#define ZCACHE_SYSFS_RO_ATOMIC(_name) \
static ssize_t zcache_##_name##_show(struct kobject *kobj, \
struct kobj_attribute *attr, char *buf) \
{ \
return sprintf(buf, "%d\n", atomic_read(&zcache_##_name)); \
} \
static struct kobj_attribute zcache_##_name##_attr = { \
.attr = { .name = __stringify(_name), .mode = 0444 }, \
.show = zcache_##_name##_show, \
}
#define ZCACHE_SYSFS_RO_CUSTOM(_name, _func) \
static ssize_t zcache_##_name##_show(struct kobject *kobj, \
struct kobj_attribute *attr, char *buf) \
{ \
return _func(buf); \
} \
static struct kobj_attribute zcache_##_name##_attr = { \
.attr = { .name = __stringify(_name), .mode = 0444 }, \
.show = zcache_##_name##_show, \
}
ZCACHE_SYSFS_RO(curr_obj_count_max);
ZCACHE_SYSFS_RO(curr_objnode_count_max);
ZCACHE_SYSFS_RO(flush_total);
ZCACHE_SYSFS_RO(flush_found);
ZCACHE_SYSFS_RO(flobj_total);
ZCACHE_SYSFS_RO(flobj_found);
ZCACHE_SYSFS_RO(failed_eph_puts);
ZCACHE_SYSFS_RO(failed_pers_puts);
ZCACHE_SYSFS_RO(zbud_curr_zbytes);
ZCACHE_SYSFS_RO(zbud_cumul_zpages);
ZCACHE_SYSFS_RO(zbud_cumul_zbytes);
ZCACHE_SYSFS_RO(zbud_buddied_count);
ZCACHE_SYSFS_RO(zbpg_unused_list_count);
ZCACHE_SYSFS_RO(evicted_raw_pages);
ZCACHE_SYSFS_RO(evicted_unbuddied_pages);
ZCACHE_SYSFS_RO(evicted_buddied_pages);
ZCACHE_SYSFS_RO(failed_get_free_pages);
ZCACHE_SYSFS_RO(failed_alloc);
ZCACHE_SYSFS_RO(put_to_flush);
ZCACHE_SYSFS_RO(compress_poor);
ZCACHE_SYSFS_RO(mean_compress_poor);
ZCACHE_SYSFS_RO_ATOMIC(zbud_curr_raw_pages);
ZCACHE_SYSFS_RO_ATOMIC(zbud_curr_zpages);
ZCACHE_SYSFS_RO_ATOMIC(curr_obj_count);
ZCACHE_SYSFS_RO_ATOMIC(curr_objnode_count);
ZCACHE_SYSFS_RO_CUSTOM(zbud_unbuddied_list_counts,
zbud_show_unbuddied_list_counts);
ZCACHE_SYSFS_RO_CUSTOM(zbud_cumul_chunk_counts,
zbud_show_cumul_chunk_counts);
ZCACHE_SYSFS_RO_CUSTOM(zv_curr_dist_counts,
zv_curr_dist_counts_show);
ZCACHE_SYSFS_RO_CUSTOM(zv_cumul_dist_counts,
zv_cumul_dist_counts_show);
static struct attribute *zcache_attrs[] = {
&zcache_curr_obj_count_attr.attr,
&zcache_curr_obj_count_max_attr.attr,
&zcache_curr_objnode_count_attr.attr,
&zcache_curr_objnode_count_max_attr.attr,
&zcache_flush_total_attr.attr,
&zcache_flobj_total_attr.attr,
&zcache_flush_found_attr.attr,
&zcache_flobj_found_attr.attr,
&zcache_failed_eph_puts_attr.attr,
&zcache_failed_pers_puts_attr.attr,
&zcache_compress_poor_attr.attr,
&zcache_mean_compress_poor_attr.attr,
&zcache_zbud_curr_raw_pages_attr.attr,
&zcache_zbud_curr_zpages_attr.attr,
&zcache_zbud_curr_zbytes_attr.attr,
&zcache_zbud_cumul_zpages_attr.attr,
&zcache_zbud_cumul_zbytes_attr.attr,
&zcache_zbud_buddied_count_attr.attr,
&zcache_zbpg_unused_list_count_attr.attr,
&zcache_evicted_raw_pages_attr.attr,
&zcache_evicted_unbuddied_pages_attr.attr,
&zcache_evicted_buddied_pages_attr.attr,
&zcache_failed_get_free_pages_attr.attr,
&zcache_failed_alloc_attr.attr,
&zcache_put_to_flush_attr.attr,
&zcache_zbud_unbuddied_list_counts_attr.attr,
&zcache_zbud_cumul_chunk_counts_attr.attr,
&zcache_zv_curr_dist_counts_attr.attr,
&zcache_zv_cumul_dist_counts_attr.attr,
&zcache_zv_max_zsize_attr.attr,
&zcache_zv_max_mean_zsize_attr.attr,
&zcache_zv_page_count_policy_percent_attr.attr,
NULL,
};
static struct attribute_group zcache_attr_group = {
.attrs = zcache_attrs,
.name = "zcache",
};
#endif /* CONFIG_SYSFS */
/*
* When zcache is disabled ("frozen"), pools can be created and destroyed,
* but all puts (and thus all other operations that require memory allocation)
* must fail. If zcache is unfrozen, accepts puts, then frozen again,
* data consistency requires all puts while frozen to be converted into
* flushes.
*/
static bool zcache_freeze;
/*
* zcache shrinker interface (only useful for ephemeral pages, so zbud only)
*/
static int shrink_zcache_memory(struct shrinker *shrink,
struct shrink_control *sc)
{
int ret = -1;
int nr = sc->nr_to_scan;
gfp_t gfp_mask = sc->gfp_mask;
if (nr >= 0) {
if (!(gfp_mask & __GFP_FS))
/* does this case really need to be skipped? */
goto out;
zbud_evict_pages(nr);
}
ret = (int)atomic_read(&zcache_zbud_curr_raw_pages);
out:
return ret;
}
static struct shrinker zcache_shrinker = {
.shrink = shrink_zcache_memory,
.seeks = DEFAULT_SEEKS,
};
/*
* zcache shims between cleancache/frontswap ops and tmem
*/
static int zcache_put_page(int cli_id, int pool_id, struct tmem_oid *oidp,
uint32_t index, struct page *page)
{
struct tmem_pool *pool;
int ret = -1;
BUG_ON(!irqs_disabled());
pool = zcache_get_pool_by_id(cli_id, pool_id);
if (unlikely(pool == NULL))
goto out;
if (!zcache_freeze && zcache_do_preload(pool) == 0) {
/* preload does preempt_disable on success */
ret = tmem_put(pool, oidp, index, (char *)(page),
PAGE_SIZE, 0, is_ephemeral(pool));
if (ret < 0) {
if (is_ephemeral(pool))
zcache_failed_eph_puts++;
else
zcache_failed_pers_puts++;
}
zcache_put_pool(pool);
preempt_enable_no_resched();
} else {
zcache_put_to_flush++;
if (atomic_read(&pool->obj_count) > 0)
/* the put fails whether the flush succeeds or not */
(void)tmem_flush_page(pool, oidp, index);
zcache_put_pool(pool);
}
out:
return ret;
}
static int zcache_get_page(int cli_id, int pool_id, struct tmem_oid *oidp,
uint32_t index, struct page *page)
{
struct tmem_pool *pool;
int ret = -1;
unsigned long flags;
size_t size = PAGE_SIZE;
local_irq_save(flags);
pool = zcache_get_pool_by_id(cli_id, pool_id);
if (likely(pool != NULL)) {
if (atomic_read(&pool->obj_count) > 0)
ret = tmem_get(pool, oidp, index, (char *)(page),
&size, 0, is_ephemeral(pool));
zcache_put_pool(pool);
}
local_irq_restore(flags);
return ret;
}
static int zcache_flush_page(int cli_id, int pool_id,
struct tmem_oid *oidp, uint32_t index)
{
struct tmem_pool *pool;
int ret = -1;
unsigned long flags;
local_irq_save(flags);
zcache_flush_total++;
pool = zcache_get_pool_by_id(cli_id, pool_id);
if (likely(pool != NULL)) {
if (atomic_read(&pool->obj_count) > 0)
ret = tmem_flush_page(pool, oidp, index);
zcache_put_pool(pool);
}
if (ret >= 0)
zcache_flush_found++;
local_irq_restore(flags);
return ret;
}
static int zcache_flush_object(int cli_id, int pool_id,
struct tmem_oid *oidp)
{
struct tmem_pool *pool;
int ret = -1;
unsigned long flags;
local_irq_save(flags);
zcache_flobj_total++;
pool = zcache_get_pool_by_id(cli_id, pool_id);
if (likely(pool != NULL)) {
if (atomic_read(&pool->obj_count) > 0)
ret = tmem_flush_object(pool, oidp);
zcache_put_pool(pool);
}
if (ret >= 0)
zcache_flobj_found++;
local_irq_restore(flags);
return ret;
}
static int zcache_destroy_pool(int cli_id, int pool_id)
{
struct tmem_pool *pool = NULL;
struct zcache_client *cli = NULL;
int ret = -1;
if (pool_id < 0)
goto out;
if (cli_id == LOCAL_CLIENT)
cli = &zcache_host;
else if ((unsigned int)cli_id < MAX_CLIENTS)
cli = &zcache_clients[cli_id];
if (cli == NULL)
goto out;
atomic_inc(&cli->refcount);
pool = cli->tmem_pools[pool_id];
if (pool == NULL)
goto out;
cli->tmem_pools[pool_id] = NULL;
/* wait for pool activity on other cpus to quiesce */
while (atomic_read(&pool->refcount) != 0)
;
atomic_dec(&cli->refcount);
local_bh_disable();
ret = tmem_destroy_pool(pool);
local_bh_enable();
kfree(pool);
pr_info("zcache: destroyed pool id=%d, cli_id=%d\n",
pool_id, cli_id);
out:
return ret;
}
static int zcache_new_pool(uint16_t cli_id, uint32_t flags)
{
int poolid = -1;
struct tmem_pool *pool;
struct zcache_client *cli = NULL;
if (cli_id == LOCAL_CLIENT)
cli = &zcache_host;
else if ((unsigned int)cli_id < MAX_CLIENTS)
cli = &zcache_clients[cli_id];
if (cli == NULL)
goto out;
atomic_inc(&cli->refcount);
pool = kmalloc(sizeof(struct tmem_pool), GFP_ATOMIC);
if (pool == NULL) {
pr_info("zcache: pool creation failed: out of memory\n");
goto out;
}
for (poolid = 0; poolid < MAX_POOLS_PER_CLIENT; poolid++)
if (cli->tmem_pools[poolid] == NULL)
break;
if (poolid >= MAX_POOLS_PER_CLIENT) {
pr_info("zcache: pool creation failed: max exceeded\n");
kfree(pool);
poolid = -1;
goto out;
}
atomic_set(&pool->refcount, 0);
pool->client = cli;
pool->pool_id = poolid;
tmem_new_pool(pool, flags);
cli->tmem_pools[poolid] = pool;
pr_info("zcache: created %s tmem pool, id=%d, client=%d\n",
flags & TMEM_POOL_PERSIST ? "persistent" : "ephemeral",
poolid, cli_id);
out:
if (cli != NULL)
atomic_dec(&cli->refcount);
return poolid;
}
/**********
* Two kernel functionalities currently can be layered on top of tmem.
* These are "cleancache" which is used as a second-chance cache for clean
* page cache pages; and "frontswap" which is used for swap pages
* to avoid writes to disk. A generic "shim" is provided here for each
* to translate in-kernel semantics to zcache semantics.
*/
#ifdef CONFIG_CLEANCACHE
static void zcache_cleancache_put_page(int pool_id,
struct cleancache_filekey key,
pgoff_t index, struct page *page)
{
u32 ind = (u32) index;
struct tmem_oid oid = *(struct tmem_oid *)&key;
if (likely(ind == index))
(void)zcache_put_page(LOCAL_CLIENT, pool_id, &oid, index, page);
}
static int zcache_cleancache_get_page(int pool_id,
struct cleancache_filekey key,
pgoff_t index, struct page *page)
{
u32 ind = (u32) index;
struct tmem_oid oid = *(struct tmem_oid *)&key;
int ret = -1;
if (likely(ind == index))
ret = zcache_get_page(LOCAL_CLIENT, pool_id, &oid, index, page);
return ret;
}
static void zcache_cleancache_flush_page(int pool_id,
struct cleancache_filekey key,
pgoff_t index)
{
u32 ind = (u32) index;
struct tmem_oid oid = *(struct tmem_oid *)&key;
if (likely(ind == index))
(void)zcache_flush_page(LOCAL_CLIENT, pool_id, &oid, ind);
}
static void zcache_cleancache_flush_inode(int pool_id,
struct cleancache_filekey key)
{
struct tmem_oid oid = *(struct tmem_oid *)&key;
(void)zcache_flush_object(LOCAL_CLIENT, pool_id, &oid);
}
static void zcache_cleancache_flush_fs(int pool_id)
{
if (pool_id >= 0)
(void)zcache_destroy_pool(LOCAL_CLIENT, pool_id);
}
static int zcache_cleancache_init_fs(size_t pagesize)
{
BUG_ON(sizeof(struct cleancache_filekey) !=
sizeof(struct tmem_oid));
BUG_ON(pagesize != PAGE_SIZE);
return zcache_new_pool(LOCAL_CLIENT, 0);
}
static int zcache_cleancache_init_shared_fs(char *uuid, size_t pagesize)
{
/* shared pools are unsupported and map to private */
BUG_ON(sizeof(struct cleancache_filekey) !=
sizeof(struct tmem_oid));
BUG_ON(pagesize != PAGE_SIZE);
return zcache_new_pool(LOCAL_CLIENT, 0);
}
static struct cleancache_ops zcache_cleancache_ops = {
.put_page = zcache_cleancache_put_page,
.get_page = zcache_cleancache_get_page,
.invalidate_page = zcache_cleancache_flush_page,
.invalidate_inode = zcache_cleancache_flush_inode,
.invalidate_fs = zcache_cleancache_flush_fs,
.init_shared_fs = zcache_cleancache_init_shared_fs,
.init_fs = zcache_cleancache_init_fs
};
struct cleancache_ops zcache_cleancache_register_ops(void)
{
struct cleancache_ops old_ops =
cleancache_register_ops(&zcache_cleancache_ops);
return old_ops;
}
#endif
#ifdef CONFIG_FRONTSWAP
/* a single tmem poolid is used for all frontswap "types" (swapfiles) */
static int zcache_frontswap_poolid = -1;
/*
* Swizzling increases objects per swaptype, increasing tmem concurrency
* for heavy swaploads. Later, larger nr_cpus -> larger SWIZ_BITS
* Setting SWIZ_BITS to 27 basically reconstructs the swap entry from
* frontswap_get_page(), but has side-effects. Hence using 8.
*/
#define SWIZ_BITS 8
#define SWIZ_MASK ((1 << SWIZ_BITS) - 1)
#define _oswiz(_type, _ind) ((_type << SWIZ_BITS) | (_ind & SWIZ_MASK))
#define iswiz(_ind) (_ind >> SWIZ_BITS)
static inline struct tmem_oid oswiz(unsigned type, u32 ind)
{
struct tmem_oid oid = { .oid = { 0 } };
oid.oid[0] = _oswiz(type, ind);
return oid;
}
static int zcache_frontswap_put_page(unsigned type, pgoff_t offset,
struct page *page)
{
u64 ind64 = (u64)offset;
u32 ind = (u32)offset;
struct tmem_oid oid = oswiz(type, ind);
int ret = -1;
unsigned long flags;
BUG_ON(!PageLocked(page));
if (likely(ind64 == ind)) {
local_irq_save(flags);
ret = zcache_put_page(LOCAL_CLIENT, zcache_frontswap_poolid,
&oid, iswiz(ind), page);
local_irq_restore(flags);
}
return ret;
}
/* returns 0 if the page was successfully gotten from frontswap, -1 if
* was not present (should never happen!) */
static int zcache_frontswap_get_page(unsigned type, pgoff_t offset,
struct page *page)
{
u64 ind64 = (u64)offset;
u32 ind = (u32)offset;
struct tmem_oid oid = oswiz(type, ind);
int ret = -1;
BUG_ON(!PageLocked(page));
if (likely(ind64 == ind))
ret = zcache_get_page(LOCAL_CLIENT, zcache_frontswap_poolid,
&oid, iswiz(ind), page);
return ret;
}
/* flush a single page from frontswap */
static void zcache_frontswap_flush_page(unsigned type, pgoff_t offset)
{
u64 ind64 = (u64)offset;
u32 ind = (u32)offset;
struct tmem_oid oid = oswiz(type, ind);
if (likely(ind64 == ind))
(void)zcache_flush_page(LOCAL_CLIENT, zcache_frontswap_poolid,
&oid, iswiz(ind));
}
/* flush all pages from the passed swaptype */
static void zcache_frontswap_flush_area(unsigned type)
{
struct tmem_oid oid;
int ind;
for (ind = SWIZ_MASK; ind >= 0; ind--) {
oid = oswiz(type, ind);
(void)zcache_flush_object(LOCAL_CLIENT,
zcache_frontswap_poolid, &oid);
}
}
static void zcache_frontswap_init(unsigned ignored)
{
/* a single tmem poolid is used for all frontswap "types" (swapfiles) */
if (zcache_frontswap_poolid < 0)
zcache_frontswap_poolid =
zcache_new_pool(LOCAL_CLIENT, TMEM_POOL_PERSIST);
}
static struct frontswap_ops zcache_frontswap_ops = {
.put_page = zcache_frontswap_put_page,
.get_page = zcache_frontswap_get_page,
.invalidate_page = zcache_frontswap_flush_page,
.invalidate_area = zcache_frontswap_flush_area,
.init = zcache_frontswap_init
};
struct frontswap_ops zcache_frontswap_register_ops(void)
{
struct frontswap_ops old_ops =
frontswap_register_ops(&zcache_frontswap_ops);
return old_ops;
}
#endif
/*
* zcache initialization
* NOTE FOR NOW zcache MUST BE PROVIDED AS A KERNEL BOOT PARAMETER OR
* NOTHING HAPPENS!
*/
static int zcache_enabled;
static int __init enable_zcache(char *s)
{
zcache_enabled = 1;
return 1;
}
__setup("zcache", enable_zcache);
/* allow independent dynamic disabling of cleancache and frontswap */
static int use_cleancache = 1;
static int __init no_cleancache(char *s)
{
use_cleancache = 0;
return 1;
}
__setup("nocleancache", no_cleancache);
static int use_frontswap = 1;
static int __init no_frontswap(char *s)
{
use_frontswap = 0;
return 1;
}
__setup("nofrontswap", no_frontswap);
static int __init enable_zcache_compressor(char *s)
{
strncpy(zcache_comp_name, s, ZCACHE_COMP_NAME_SZ);
zcache_enabled = 1;
return 1;
}
__setup("zcache=", enable_zcache_compressor);
static int zcache_comp_init(void)
{
int ret = 0;
/* check crypto algorithm */
if (*zcache_comp_name != '\0') {
ret = crypto_has_comp(zcache_comp_name, 0, 0);
if (!ret)
pr_info("zcache: %s not supported\n",
zcache_comp_name);
}
if (!ret)
strcpy(zcache_comp_name, "lzo");
ret = crypto_has_comp(zcache_comp_name, 0, 0);
if (!ret) {
ret = 1;
goto out;
}
pr_info("zcache: using %s compressor\n", zcache_comp_name);
/* alloc percpu transforms */
ret = 0;
zcache_comp_pcpu_tfms = alloc_percpu(struct crypto_comp *);
if (!zcache_comp_pcpu_tfms)
ret = 1;
out:
return ret;
}
static int __init zcache_init(void)
{
int ret = 0;
#ifdef CONFIG_SYSFS
ret = sysfs_create_group(mm_kobj, &zcache_attr_group);
if (ret) {
pr_err("zcache: can't create sysfs\n");
goto out;
}
#endif /* CONFIG_SYSFS */
#if defined(CONFIG_CLEANCACHE) || defined(CONFIG_FRONTSWAP)
if (zcache_enabled) {
unsigned int cpu;
tmem_register_hostops(&zcache_hostops);
tmem_register_pamops(&zcache_pamops);
ret = register_cpu_notifier(&zcache_cpu_notifier_block);
if (ret) {
pr_err("zcache: can't register cpu notifier\n");
goto out;
}
ret = zcache_comp_init();
if (ret) {
pr_err("zcache: compressor initialization failed\n");
goto out;
}
for_each_online_cpu(cpu) {
void *pcpu = (void *)(long)cpu;
zcache_cpu_notifier(&zcache_cpu_notifier_block,
CPU_UP_PREPARE, pcpu);
}
}
zcache_objnode_cache = kmem_cache_create("zcache_objnode",
sizeof(struct tmem_objnode), 0, 0, NULL);
zcache_obj_cache = kmem_cache_create("zcache_obj",
sizeof(struct tmem_obj), 0, 0, NULL);
ret = zcache_new_client(LOCAL_CLIENT);
if (ret) {
pr_err("zcache: can't create client\n");
goto out;
}
#endif
#ifdef CONFIG_CLEANCACHE
if (zcache_enabled && use_cleancache) {
struct cleancache_ops old_ops;
zbud_init();
register_shrinker(&zcache_shrinker);
old_ops = zcache_cleancache_register_ops();
pr_info("zcache: cleancache enabled using kernel "
"transcendent memory and compression buddies\n");
if (old_ops.init_fs != NULL)
pr_warning("zcache: cleancache_ops overridden");
}
#endif
#ifdef CONFIG_FRONTSWAP
if (zcache_enabled && use_frontswap) {
struct frontswap_ops old_ops;
old_ops = zcache_frontswap_register_ops();
pr_info("zcache: frontswap enabled using kernel "
"transcendent memory and zsmalloc\n");
if (old_ops.init != NULL)
pr_warning("zcache: frontswap_ops overridden");
}
#endif
out:
return ret;
}
module_init(zcache_init)
| gpl-2.0 |
mzueger/linux-phycore-mpc5200b | drivers/media/video/saa7185.c | 3349 | 10375 | /*
* saa7185 - Philips SAA7185B video encoder driver version 0.0.3
*
* Copyright (C) 1998 Dave Perks <dperks@ibm.net>
*
* Slight changes for video timing and attachment output by
* Wolfgang Scherr <scherr@net4you.net>
*
* Changes by Ronald Bultje <rbultje@ronald.bitfreak.net>
* - moved over to linux>=2.4.x i2c protocol (1/1/2003)
*
* 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/types.h>
#include <linux/slab.h>
#include <linux/ioctl.h>
#include <asm/uaccess.h>
#include <linux/i2c.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
MODULE_DESCRIPTION("Philips SAA7185 video encoder driver");
MODULE_AUTHOR("Dave Perks");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
/* ----------------------------------------------------------------------- */
struct saa7185 {
struct v4l2_subdev sd;
unsigned char reg[128];
v4l2_std_id norm;
};
static inline struct saa7185 *to_saa7185(struct v4l2_subdev *sd)
{
return container_of(sd, struct saa7185, sd);
}
/* ----------------------------------------------------------------------- */
static inline int saa7185_read(struct v4l2_subdev *sd)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return i2c_smbus_read_byte(client);
}
static int saa7185_write(struct v4l2_subdev *sd, u8 reg, u8 value)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct saa7185 *encoder = to_saa7185(sd);
v4l2_dbg(1, debug, sd, "%02x set to %02x\n", reg, value);
encoder->reg[reg] = value;
return i2c_smbus_write_byte_data(client, reg, value);
}
static int saa7185_write_block(struct v4l2_subdev *sd,
const u8 *data, unsigned int len)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct saa7185 *encoder = to_saa7185(sd);
int ret = -1;
u8 reg;
/* the adv7175 has an autoincrement function, use it if
* the adapter understands raw I2C */
if (i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
/* do raw I2C, not smbus compatible */
u8 block_data[32];
int block_len;
while (len >= 2) {
block_len = 0;
block_data[block_len++] = reg = data[0];
do {
block_data[block_len++] =
encoder->reg[reg++] = data[1];
len -= 2;
data += 2;
} while (len >= 2 && data[0] == reg && block_len < 32);
ret = i2c_master_send(client, block_data, block_len);
if (ret < 0)
break;
}
} else {
/* do some slow I2C emulation kind of thing */
while (len >= 2) {
reg = *data++;
ret = saa7185_write(sd, reg, *data++);
if (ret < 0)
break;
len -= 2;
}
}
return ret;
}
/* ----------------------------------------------------------------------- */
static const unsigned char init_common[] = {
0x3a, 0x0f, /* CBENB=0, V656=0, VY2C=1,
* YUV2C=1, MY2C=1, MUV2C=1 */
0x42, 0x6b, /* OVLY0=107 */
0x43, 0x00, /* OVLU0=0 white */
0x44, 0x00, /* OVLV0=0 */
0x45, 0x22, /* OVLY1=34 */
0x46, 0xac, /* OVLU1=172 yellow */
0x47, 0x0e, /* OVLV1=14 */
0x48, 0x03, /* OVLY2=3 */
0x49, 0x1d, /* OVLU2=29 cyan */
0x4a, 0xac, /* OVLV2=172 */
0x4b, 0xf0, /* OVLY3=240 */
0x4c, 0xc8, /* OVLU3=200 green */
0x4d, 0xb9, /* OVLV3=185 */
0x4e, 0xd4, /* OVLY4=212 */
0x4f, 0x38, /* OVLU4=56 magenta */
0x50, 0x47, /* OVLV4=71 */
0x51, 0xc1, /* OVLY5=193 */
0x52, 0xe3, /* OVLU5=227 red */
0x53, 0x54, /* OVLV5=84 */
0x54, 0xa3, /* OVLY6=163 */
0x55, 0x54, /* OVLU6=84 blue */
0x56, 0xf2, /* OVLV6=242 */
0x57, 0x90, /* OVLY7=144 */
0x58, 0x00, /* OVLU7=0 black */
0x59, 0x00, /* OVLV7=0 */
0x5a, 0x00, /* CHPS=0 */
0x5b, 0x76, /* GAINU=118 */
0x5c, 0xa5, /* GAINV=165 */
0x5d, 0x3c, /* BLCKL=60 */
0x5e, 0x3a, /* BLNNL=58 */
0x5f, 0x3a, /* CCRS=0, BLNVB=58 */
0x60, 0x00, /* NULL */
/* 0x61 - 0x66 set according to norm */
0x67, 0x00, /* 0 : caption 1st byte odd field */
0x68, 0x00, /* 0 : caption 2nd byte odd field */
0x69, 0x00, /* 0 : caption 1st byte even field */
0x6a, 0x00, /* 0 : caption 2nd byte even field */
0x6b, 0x91, /* MODIN=2, PCREF=0, SCCLN=17 */
0x6c, 0x20, /* SRCV1=0, TRCV2=1, ORCV1=0, PRCV1=0,
* CBLF=0, ORCV2=0, PRCV2=0 */
0x6d, 0x00, /* SRCM1=0, CCEN=0 */
0x6e, 0x0e, /* HTRIG=0x005, approx. centered, at
* least for PAL */
0x6f, 0x00, /* HTRIG upper bits */
0x70, 0x20, /* PHRES=0, SBLN=1, VTRIG=0 */
/* The following should not be needed */
0x71, 0x15, /* BMRQ=0x115 */
0x72, 0x90, /* EMRQ=0x690 */
0x73, 0x61, /* EMRQ=0x690, BMRQ=0x115 */
0x74, 0x00, /* NULL */
0x75, 0x00, /* NULL */
0x76, 0x00, /* NULL */
0x77, 0x15, /* BRCV=0x115 */
0x78, 0x90, /* ERCV=0x690 */
0x79, 0x61, /* ERCV=0x690, BRCV=0x115 */
/* Field length controls */
0x7a, 0x70, /* FLC=0 */
/* The following should not be needed if SBLN = 1 */
0x7b, 0x16, /* FAL=22 */
0x7c, 0x35, /* LAL=244 */
0x7d, 0x20, /* LAL=244, FAL=22 */
};
static const unsigned char init_pal[] = {
0x61, 0x1e, /* FISE=0, PAL=1, SCBW=1, RTCE=1,
* YGS=1, INPI=0, DOWN=0 */
0x62, 0xc8, /* DECTYP=1, BSTA=72 */
0x63, 0xcb, /* FSC0 */
0x64, 0x8a, /* FSC1 */
0x65, 0x09, /* FSC2 */
0x66, 0x2a, /* FSC3 */
};
static const unsigned char init_ntsc[] = {
0x61, 0x1d, /* FISE=1, PAL=0, SCBW=1, RTCE=1,
* YGS=1, INPI=0, DOWN=0 */
0x62, 0xe6, /* DECTYP=1, BSTA=102 */
0x63, 0x1f, /* FSC0 */
0x64, 0x7c, /* FSC1 */
0x65, 0xf0, /* FSC2 */
0x66, 0x21, /* FSC3 */
};
static int saa7185_init(struct v4l2_subdev *sd, u32 val)
{
struct saa7185 *encoder = to_saa7185(sd);
saa7185_write_block(sd, init_common, sizeof(init_common));
if (encoder->norm & V4L2_STD_NTSC)
saa7185_write_block(sd, init_ntsc, sizeof(init_ntsc));
else
saa7185_write_block(sd, init_pal, sizeof(init_pal));
return 0;
}
static int saa7185_s_std_output(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct saa7185 *encoder = to_saa7185(sd);
if (std & V4L2_STD_NTSC)
saa7185_write_block(sd, init_ntsc, sizeof(init_ntsc));
else if (std & V4L2_STD_PAL)
saa7185_write_block(sd, init_pal, sizeof(init_pal));
else
return -EINVAL;
encoder->norm = std;
return 0;
}
static int saa7185_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct saa7185 *encoder = to_saa7185(sd);
/* RJ: input = 0: input is from SA7111
input = 1: input is from ZR36060 */
switch (input) {
case 0:
/* turn off colorbar */
saa7185_write(sd, 0x3a, 0x0f);
/* Switch RTCE to 1 */
saa7185_write(sd, 0x61, (encoder->reg[0x61] & 0xf7) | 0x08);
saa7185_write(sd, 0x6e, 0x01);
break;
case 1:
/* turn off colorbar */
saa7185_write(sd, 0x3a, 0x0f);
/* Switch RTCE to 0 */
saa7185_write(sd, 0x61, (encoder->reg[0x61] & 0xf7) | 0x00);
/* SW: a slight sync problem... */
saa7185_write(sd, 0x6e, 0x00);
break;
case 2:
/* turn on colorbar */
saa7185_write(sd, 0x3a, 0x8f);
/* Switch RTCE to 0 */
saa7185_write(sd, 0x61, (encoder->reg[0x61] & 0xf7) | 0x08);
/* SW: a slight sync problem... */
saa7185_write(sd, 0x6e, 0x01);
break;
default:
return -EINVAL;
}
return 0;
}
static int saa7185_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_SAA7185, 0);
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops saa7185_core_ops = {
.g_chip_ident = saa7185_g_chip_ident,
.init = saa7185_init,
};
static const struct v4l2_subdev_video_ops saa7185_video_ops = {
.s_std_output = saa7185_s_std_output,
.s_routing = saa7185_s_routing,
};
static const struct v4l2_subdev_ops saa7185_ops = {
.core = &saa7185_core_ops,
.video = &saa7185_video_ops,
};
/* ----------------------------------------------------------------------- */
static int saa7185_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int i;
struct saa7185 *encoder;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
encoder = kzalloc(sizeof(struct saa7185), GFP_KERNEL);
if (encoder == NULL)
return -ENOMEM;
encoder->norm = V4L2_STD_NTSC;
sd = &encoder->sd;
v4l2_i2c_subdev_init(sd, client, &saa7185_ops);
i = saa7185_write_block(sd, init_common, sizeof(init_common));
if (i >= 0)
i = saa7185_write_block(sd, init_ntsc, sizeof(init_ntsc));
if (i < 0)
v4l2_dbg(1, debug, sd, "init error %d\n", i);
else
v4l2_dbg(1, debug, sd, "revision 0x%x\n",
saa7185_read(sd) >> 5);
return 0;
}
static int saa7185_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct saa7185 *encoder = to_saa7185(sd);
v4l2_device_unregister_subdev(sd);
/* SW: output off is active */
saa7185_write(sd, 0x61, (encoder->reg[0x61]) | 0x40);
kfree(encoder);
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct i2c_device_id saa7185_id[] = {
{ "saa7185", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, saa7185_id);
static struct i2c_driver saa7185_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "saa7185",
},
.probe = saa7185_probe,
.remove = saa7185_remove,
.id_table = saa7185_id,
};
static __init int init_saa7185(void)
{
return i2c_add_driver(&saa7185_driver);
}
static __exit void exit_saa7185(void)
{
i2c_del_driver(&saa7185_driver);
}
module_init(init_saa7185);
module_exit(exit_saa7185);
| gpl-2.0 |
unixbhaskar/Linux-kernel | sound/pci/emu10k1/voice.c | 7957 | 4642 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Creative Labs, Inc.
* Lee Revell <rlrevell@joe-job.com>
* Routines for control of EMU10K1 chips - voice manager
*
* Rewrote voice allocator for multichannel support - rlrevell 12/2004
*
* BUGS:
* --
*
* TODO:
* --
*
* 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/time.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/emu10k1.h>
/* Previously the voice allocator started at 0 every time. The new voice
* allocator uses a round robin scheme. The next free voice is tracked in
* the card record and each allocation begins where the last left off. The
* hardware requires stereo interleaved voices be aligned to an even/odd
* boundary. For multichannel voice allocation we ensure than the block of
* voices does not cross the 32 voice boundary. This simplifies the
* multichannel support and ensures we can use a single write to the
* (set|clear)_loop_stop registers. Otherwise (for example) the voices would
* get out of sync when pausing/resuming a stream.
* --rlrevell
*/
static int voice_alloc(struct snd_emu10k1 *emu, int type, int number,
struct snd_emu10k1_voice **rvoice)
{
struct snd_emu10k1_voice *voice;
int i, j, k, first_voice, last_voice, skip;
*rvoice = NULL;
first_voice = last_voice = 0;
for (i = emu->next_free_voice, j = 0; j < NUM_G ; i += number, j += number) {
/*
printk(KERN_DEBUG "i %d j %d next free %d!\n",
i, j, emu->next_free_voice);
*/
i %= NUM_G;
/* stereo voices must be even/odd */
if ((number == 2) && (i % 2)) {
i++;
continue;
}
skip = 0;
for (k = 0; k < number; k++) {
voice = &emu->voices[(i+k) % NUM_G];
if (voice->use) {
skip = 1;
break;
}
}
if (!skip) {
/* printk(KERN_DEBUG "allocated voice %d\n", i); */
first_voice = i;
last_voice = (i + number) % NUM_G;
emu->next_free_voice = last_voice;
break;
}
}
if (first_voice == last_voice)
return -ENOMEM;
for (i = 0; i < number; i++) {
voice = &emu->voices[(first_voice + i) % NUM_G];
/*
printk(kERN_DEBUG "voice alloc - %i, %i of %i\n",
voice->number, idx-first_voice+1, number);
*/
voice->use = 1;
switch (type) {
case EMU10K1_PCM:
voice->pcm = 1;
break;
case EMU10K1_SYNTH:
voice->synth = 1;
break;
case EMU10K1_MIDI:
voice->midi = 1;
break;
case EMU10K1_EFX:
voice->efx = 1;
break;
}
}
*rvoice = &emu->voices[first_voice];
return 0;
}
int snd_emu10k1_voice_alloc(struct snd_emu10k1 *emu, int type, int number,
struct snd_emu10k1_voice **rvoice)
{
unsigned long flags;
int result;
if (snd_BUG_ON(!rvoice))
return -EINVAL;
if (snd_BUG_ON(!number))
return -EINVAL;
spin_lock_irqsave(&emu->voice_lock, flags);
for (;;) {
result = voice_alloc(emu, type, number, rvoice);
if (result == 0 || type == EMU10K1_SYNTH || type == EMU10K1_MIDI)
break;
/* free a voice from synth */
if (emu->get_synth_voice) {
result = emu->get_synth_voice(emu);
if (result >= 0) {
struct snd_emu10k1_voice *pvoice = &emu->voices[result];
pvoice->interrupt = NULL;
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = pvoice->efx = 0;
pvoice->epcm = NULL;
}
}
if (result < 0)
break;
}
spin_unlock_irqrestore(&emu->voice_lock, flags);
return result;
}
EXPORT_SYMBOL(snd_emu10k1_voice_alloc);
int snd_emu10k1_voice_free(struct snd_emu10k1 *emu,
struct snd_emu10k1_voice *pvoice)
{
unsigned long flags;
if (snd_BUG_ON(!pvoice))
return -EINVAL;
spin_lock_irqsave(&emu->voice_lock, flags);
pvoice->interrupt = NULL;
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = pvoice->efx = 0;
pvoice->epcm = NULL;
snd_emu10k1_voice_init(emu, pvoice->number);
spin_unlock_irqrestore(&emu->voice_lock, flags);
return 0;
}
EXPORT_SYMBOL(snd_emu10k1_voice_free);
| gpl-2.0 |
sid1607/linux-3.14.65-src | drivers/tc/tc.c | 12053 | 5224 | /*
* TURBOchannel bus services.
*
* Copyright (c) Harald Koerfgen, 1998
* Copyright (c) 2001, 2003, 2005, 2006 Maciej W. Rozycki
* Copyright (c) 2005 James Simmons
*
* 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/compiler.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/tc.h>
#include <linux/types.h>
#include <asm/io.h>
static struct tc_bus tc_bus = {
.name = "TURBOchannel",
};
/*
* Probing for TURBOchannel modules.
*/
static void __init tc_bus_add_devices(struct tc_bus *tbus)
{
resource_size_t slotsize = tbus->info.slot_size << 20;
resource_size_t extslotsize = tbus->ext_slot_size;
resource_size_t slotaddr;
resource_size_t extslotaddr;
resource_size_t devsize;
void __iomem *module;
struct tc_dev *tdev;
int i, slot, err;
u8 pattern[4];
long offset;
for (slot = 0; slot < tbus->num_tcslots; slot++) {
slotaddr = tbus->slot_base + slot * slotsize;
extslotaddr = tbus->ext_slot_base + slot * extslotsize;
module = ioremap_nocache(slotaddr, slotsize);
BUG_ON(!module);
offset = TC_OLDCARD;
err = 0;
err |= tc_preadb(pattern + 0, module + offset + TC_PATTERN0);
err |= tc_preadb(pattern + 1, module + offset + TC_PATTERN1);
err |= tc_preadb(pattern + 2, module + offset + TC_PATTERN2);
err |= tc_preadb(pattern + 3, module + offset + TC_PATTERN3);
if (err)
goto out_err;
if (pattern[0] != 0x55 || pattern[1] != 0x00 ||
pattern[2] != 0xaa || pattern[3] != 0xff) {
offset = TC_NEWCARD;
err = 0;
err |= tc_preadb(pattern + 0,
module + offset + TC_PATTERN0);
err |= tc_preadb(pattern + 1,
module + offset + TC_PATTERN1);
err |= tc_preadb(pattern + 2,
module + offset + TC_PATTERN2);
err |= tc_preadb(pattern + 3,
module + offset + TC_PATTERN3);
if (err)
goto out_err;
}
if (pattern[0] != 0x55 || pattern[1] != 0x00 ||
pattern[2] != 0xaa || pattern[3] != 0xff)
goto out_err;
/* Found a board, allocate it an entry in the list */
tdev = kzalloc(sizeof(*tdev), GFP_KERNEL);
if (!tdev) {
printk(KERN_ERR "tc%x: unable to allocate tc_dev\n",
slot);
goto out_err;
}
dev_set_name(&tdev->dev, "tc%x", slot);
tdev->bus = tbus;
tdev->dev.parent = &tbus->dev;
tdev->dev.bus = &tc_bus_type;
tdev->slot = slot;
for (i = 0; i < 8; i++) {
tdev->firmware[i] =
readb(module + offset + TC_FIRM_VER + 4 * i);
tdev->vendor[i] =
readb(module + offset + TC_VENDOR + 4 * i);
tdev->name[i] =
readb(module + offset + TC_MODULE + 4 * i);
}
tdev->firmware[8] = 0;
tdev->vendor[8] = 0;
tdev->name[8] = 0;
pr_info("%s: %s %s %s\n", dev_name(&tdev->dev), tdev->vendor,
tdev->name, tdev->firmware);
devsize = readb(module + offset + TC_SLOT_SIZE);
devsize <<= 22;
if (devsize <= slotsize) {
tdev->resource.start = slotaddr;
tdev->resource.end = slotaddr + devsize - 1;
} else if (devsize <= extslotsize) {
tdev->resource.start = extslotaddr;
tdev->resource.end = extslotaddr + devsize - 1;
} else {
printk(KERN_ERR "%s: Cannot provide slot space "
"(%dMiB required, up to %dMiB supported)\n",
dev_name(&tdev->dev), devsize >> 20,
max(slotsize, extslotsize) >> 20);
kfree(tdev);
goto out_err;
}
tdev->resource.name = tdev->name;
tdev->resource.flags = IORESOURCE_MEM;
tc_device_get_irq(tdev);
device_register(&tdev->dev);
list_add_tail(&tdev->node, &tbus->devices);
out_err:
iounmap(module);
}
}
/*
* The main entry.
*/
static int __init tc_init(void)
{
/* Initialize the TURBOchannel bus */
if (tc_bus_get_info(&tc_bus))
return 0;
INIT_LIST_HEAD(&tc_bus.devices);
dev_set_name(&tc_bus.dev, "tc");
device_register(&tc_bus.dev);
if (tc_bus.info.slot_size) {
unsigned int tc_clock = tc_get_speed(&tc_bus) / 100000;
pr_info("tc: TURBOchannel rev. %d at %d.%d MHz "
"(with%s parity)\n", tc_bus.info.revision,
tc_clock / 10, tc_clock % 10,
tc_bus.info.parity ? "" : "out");
tc_bus.resource[0].start = tc_bus.slot_base;
tc_bus.resource[0].end = tc_bus.slot_base +
(tc_bus.info.slot_size << 20) *
tc_bus.num_tcslots - 1;
tc_bus.resource[0].name = tc_bus.name;
tc_bus.resource[0].flags = IORESOURCE_MEM;
if (request_resource(&iomem_resource,
&tc_bus.resource[0]) < 0) {
printk(KERN_ERR "tc: Cannot reserve resource\n");
return 0;
}
if (tc_bus.ext_slot_size) {
tc_bus.resource[1].start = tc_bus.ext_slot_base;
tc_bus.resource[1].end = tc_bus.ext_slot_base +
tc_bus.ext_slot_size *
tc_bus.num_tcslots - 1;
tc_bus.resource[1].name = tc_bus.name;
tc_bus.resource[1].flags = IORESOURCE_MEM;
if (request_resource(&iomem_resource,
&tc_bus.resource[1]) < 0) {
printk(KERN_ERR
"tc: Cannot reserve resource\n");
release_resource(&tc_bus.resource[0]);
return 0;
}
}
tc_bus_add_devices(&tc_bus);
}
return 0;
}
subsys_initcall(tc_init);
| gpl-2.0 |
XxXPachaXxX/PachaRX-VS4-3.0.16 | fs/nls/nls_cp1251.c | 12565 | 12751 | /*
* linux/fs/nls/nls_cp1251.c
*
* Charset cp1251 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x0402, 0x0403, 0x201a, 0x0453,
0x201e, 0x2026, 0x2020, 0x2021,
0x20ac, 0x2030, 0x0409, 0x2039,
0x040a, 0x040c, 0x040b, 0x040f,
/* 0x90*/
0x0452, 0x2018, 0x2019, 0x201c,
0x201d, 0x2022, 0x2013, 0x2014,
0x0000, 0x2122, 0x0459, 0x203a,
0x045a, 0x045c, 0x045b, 0x045f,
/* 0xa0*/
0x00a0, 0x040e, 0x045e, 0x0408,
0x00a4, 0x0490, 0x00a6, 0x00a7,
0x0401, 0x00a9, 0x0404, 0x00ab,
0x00ac, 0x00ad, 0x00ae, 0x0407,
/* 0xb0*/
0x00b0, 0x00b1, 0x0406, 0x0456,
0x0491, 0x00b5, 0x00b6, 0x00b7,
0x0451, 0x2116, 0x0454, 0x00bb,
0x0458, 0x0405, 0x0455, 0x0457,
/* 0xc0*/
0x0410, 0x0411, 0x0412, 0x0413,
0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041a, 0x041b,
0x041c, 0x041d, 0x041e, 0x041f,
/* 0xd0*/
0x0420, 0x0421, 0x0422, 0x0423,
0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b,
0x042c, 0x042d, 0x042e, 0x042f,
/* 0xe0*/
0x0430, 0x0431, 0x0432, 0x0433,
0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0439, 0x043a, 0x043b,
0x043c, 0x043d, 0x043e, 0x043f,
/* 0xf0*/
0x0440, 0x0441, 0x0442, 0x0443,
0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b,
0x044c, 0x044d, 0x044e, 0x044f,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xa0, 0x00, 0x00, 0x00, 0xa4, 0x00, 0xa6, 0xa7, /* 0xa0-0xa7 */
0x00, 0xa9, 0x00, 0xab, 0xac, 0xad, 0xae, 0x00, /* 0xa8-0xaf */
0xb0, 0xb1, 0x00, 0x00, 0x00, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0xbb, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page04[256] = {
0x00, 0xa8, 0x80, 0x81, 0xaa, 0xbd, 0xb2, 0xaf, /* 0x00-0x07 */
0xa3, 0x8a, 0x8c, 0x8e, 0x8d, 0x00, 0xa1, 0x8f, /* 0x08-0x0f */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0x10-0x17 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0x18-0x1f */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0x20-0x27 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0x28-0x2f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x30-0x37 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x38-0x3f */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0x40-0x47 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0x48-0x4f */
0x00, 0xb8, 0x90, 0x83, 0xba, 0xbe, 0xb3, 0xbf, /* 0x50-0x57 */
0xbc, 0x9a, 0x9c, 0x9e, 0x9d, 0x00, 0xa2, 0x9f, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0xa5, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
};
static const unsigned char page20[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x96, 0x97, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x91, 0x92, 0x82, 0x00, 0x93, 0x94, 0x84, 0x00, /* 0x18-0x1f */
0x86, 0x87, 0x95, 0x00, 0x00, 0x00, 0x85, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x89, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x8b, 0x9b, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
};
static const unsigned char page21[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, NULL, NULL, NULL, page04, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
page20, page21, NULL, NULL, NULL, NULL, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x90, 0x83, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x9a, 0x8b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa2, 0xa2, 0xbc, 0xa4, 0xb4, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xb8, 0xa9, 0xba, 0xab, 0xac, 0xad, 0xae, 0xbf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb3, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbe, 0xbe, 0xbf, /* 0xb8-0xbf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xc0-0xc7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xc8-0xcf */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xd0-0xd7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x81, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x80, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x8a, 0x9b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa1, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb2, 0xa5, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xa8, 0xb9, 0xaa, 0xbb, 0xa3, 0xbd, 0xbd, 0xaf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xe0-0xe7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xe8-0xef */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xf0-0xf7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp1251",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp1251(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp1251(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp1251)
module_exit(exit_nls_cp1251)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
assusdan/cyanogenmod_kernel_prestigio_muzed3 | lib/is_single_threaded.c | 13589 | 1363 | /* Function to determine if a thread group is single threaded or not
*
* Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
* - Derived from security/selinux/hooks.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/sched.h>
/*
* Returns true if the task does not share ->mm with another thread/process.
*/
bool current_is_single_threaded(void)
{
struct task_struct *task = current;
struct mm_struct *mm = task->mm;
struct task_struct *p, *t;
bool ret;
if (atomic_read(&task->signal->live) != 1)
return false;
if (atomic_read(&mm->mm_users) == 1)
return true;
ret = false;
rcu_read_lock();
for_each_process(p) {
if (unlikely(p->flags & PF_KTHREAD))
continue;
if (unlikely(p == task->group_leader))
continue;
t = p;
do {
if (unlikely(t->mm == mm))
goto found;
if (likely(t->mm))
break;
/*
* t->mm == NULL. Make sure next_thread/next_task
* will see other CLONE_VM tasks which might be
* forked before exiting.
*/
smp_rmb();
} while_each_thread(p, t);
}
ret = true;
found:
rcu_read_unlock();
return ret;
}
| gpl-2.0 |
ZolaIII/android_kernel_synopsis_deprecated | drivers/infiniband/hw/amso1100/c2_mq.c | 14101 | 4622 | /*
* Copyright (c) 2005 Ammasso, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, 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 "c2.h"
#include "c2_mq.h"
void *c2_mq_alloc(struct c2_mq *q)
{
BUG_ON(q->magic != C2_MQ_MAGIC);
BUG_ON(q->type != C2_MQ_ADAPTER_TARGET);
if (c2_mq_full(q)) {
return NULL;
} else {
#ifdef DEBUG
struct c2wr_hdr *m =
(struct c2wr_hdr *) (q->msg_pool.host + q->priv * q->msg_size);
#ifdef CCMSGMAGIC
BUG_ON(m->magic != be32_to_cpu(~CCWR_MAGIC));
m->magic = cpu_to_be32(CCWR_MAGIC);
#endif
return m;
#else
return q->msg_pool.host + q->priv * q->msg_size;
#endif
}
}
void c2_mq_produce(struct c2_mq *q)
{
BUG_ON(q->magic != C2_MQ_MAGIC);
BUG_ON(q->type != C2_MQ_ADAPTER_TARGET);
if (!c2_mq_full(q)) {
q->priv = (q->priv + 1) % q->q_size;
q->hint_count++;
/* Update peer's offset. */
__raw_writew((__force u16) cpu_to_be16(q->priv), &q->peer->shared);
}
}
void *c2_mq_consume(struct c2_mq *q)
{
BUG_ON(q->magic != C2_MQ_MAGIC);
BUG_ON(q->type != C2_MQ_HOST_TARGET);
if (c2_mq_empty(q)) {
return NULL;
} else {
#ifdef DEBUG
struct c2wr_hdr *m = (struct c2wr_hdr *)
(q->msg_pool.host + q->priv * q->msg_size);
#ifdef CCMSGMAGIC
BUG_ON(m->magic != be32_to_cpu(CCWR_MAGIC));
#endif
return m;
#else
return q->msg_pool.host + q->priv * q->msg_size;
#endif
}
}
void c2_mq_free(struct c2_mq *q)
{
BUG_ON(q->magic != C2_MQ_MAGIC);
BUG_ON(q->type != C2_MQ_HOST_TARGET);
if (!c2_mq_empty(q)) {
#ifdef CCMSGMAGIC
{
struct c2wr_hdr __iomem *m = (struct c2wr_hdr __iomem *)
(q->msg_pool.adapter + q->priv * q->msg_size);
__raw_writel(cpu_to_be32(~CCWR_MAGIC), &m->magic);
}
#endif
q->priv = (q->priv + 1) % q->q_size;
/* Update peer's offset. */
__raw_writew((__force u16) cpu_to_be16(q->priv), &q->peer->shared);
}
}
void c2_mq_lconsume(struct c2_mq *q, u32 wqe_count)
{
BUG_ON(q->magic != C2_MQ_MAGIC);
BUG_ON(q->type != C2_MQ_ADAPTER_TARGET);
while (wqe_count--) {
BUG_ON(c2_mq_empty(q));
*q->shared = cpu_to_be16((be16_to_cpu(*q->shared)+1) % q->q_size);
}
}
#if 0
u32 c2_mq_count(struct c2_mq *q)
{
s32 count;
if (q->type == C2_MQ_HOST_TARGET)
count = be16_to_cpu(*q->shared) - q->priv;
else
count = q->priv - be16_to_cpu(*q->shared);
if (count < 0)
count += q->q_size;
return (u32) count;
}
#endif /* 0 */
void c2_mq_req_init(struct c2_mq *q, u32 index, u32 q_size, u32 msg_size,
u8 __iomem *pool_start, u16 __iomem *peer, u32 type)
{
BUG_ON(!q->shared);
/* This code assumes the byte swapping has already been done! */
q->index = index;
q->q_size = q_size;
q->msg_size = msg_size;
q->msg_pool.adapter = pool_start;
q->peer = (struct c2_mq_shared __iomem *) peer;
q->magic = C2_MQ_MAGIC;
q->type = type;
q->priv = 0;
q->hint_count = 0;
return;
}
void c2_mq_rep_init(struct c2_mq *q, u32 index, u32 q_size, u32 msg_size,
u8 *pool_start, u16 __iomem *peer, u32 type)
{
BUG_ON(!q->shared);
/* This code assumes the byte swapping has already been done! */
q->index = index;
q->q_size = q_size;
q->msg_size = msg_size;
q->msg_pool.host = pool_start;
q->peer = (struct c2_mq_shared __iomem *) peer;
q->magic = C2_MQ_MAGIC;
q->type = type;
q->priv = 0;
q->hint_count = 0;
return;
}
| gpl-2.0 |
dastuam/linux37-beaglebone | arch/arm/plat-omap/i2c.c | 22 | 7180 | /*
* linux/arch/arm/plat-omap/i2c.c
*
* Helper module for board specific I2C bus registration
*
* Copyright (C) 2007 Nokia Corporation.
*
* Contact: Jarkko Nikula <jhnikula@gmail.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 <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/i2c-omap.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <mach/irqs.h>
#include <plat/i2c.h>
#include <plat/omap-pm.h>
#include <plat/omap_device.h>
#define OMAP_I2C_SIZE 0x3f
#define OMAP1_I2C_BASE 0xfffb3800
#define OMAP1_INT_I2C (32 + 4)
static const char name[] = "omap_i2c";
#define I2C_RESOURCE_BUILDER(base, irq) \
{ \
.start = (base), \
.end = (base) + OMAP_I2C_SIZE, \
.flags = IORESOURCE_MEM, \
}, \
{ \
.start = (irq), \
.flags = IORESOURCE_IRQ, \
},
static struct resource i2c_resources[][2] = {
{ I2C_RESOURCE_BUILDER(0, 0) },
};
#define I2C_DEV_BUILDER(bus_id, res, data) \
{ \
.id = (bus_id), \
.name = name, \
.num_resources = ARRAY_SIZE(res), \
.resource = (res), \
.dev = { \
.platform_data = (data), \
}, \
}
#define MAX_OMAP_I2C_HWMOD_NAME_LEN 16
#define OMAP_I2C_MAX_CONTROLLERS 4
static struct omap_i2c_bus_platform_data i2c_pdata[OMAP_I2C_MAX_CONTROLLERS];
static struct platform_device omap_i2c_devices[] = {
I2C_DEV_BUILDER(1, i2c_resources[0], &i2c_pdata[0]),
};
#define OMAP_I2C_CMDLINE_SETUP (BIT(31))
static int __init omap_i2c_nr_ports(void)
{
int ports = 0;
if (cpu_class_is_omap1())
ports = 1;
else if (cpu_is_omap24xx())
ports = 2;
else if (cpu_is_omap34xx())
ports = 3;
else if (cpu_is_omap44xx())
ports = 4;
return ports;
}
static inline int omap1_i2c_add_bus(int bus_id)
{
struct platform_device *pdev;
struct omap_i2c_bus_platform_data *pdata;
struct resource *res;
omap1_i2c_mux_pins(bus_id);
pdev = &omap_i2c_devices[bus_id - 1];
res = pdev->resource;
res[0].start = OMAP1_I2C_BASE;
res[0].end = res[0].start + OMAP_I2C_SIZE;
res[1].start = OMAP1_INT_I2C;
pdata = &i2c_pdata[bus_id - 1];
/* all OMAP1 have IP version 1 register set */
pdata->rev = OMAP_I2C_IP_VERSION_1;
/* all OMAP1 I2C are implemented like this */
pdata->flags = OMAP_I2C_FLAG_NO_FIFO |
OMAP_I2C_FLAG_SIMPLE_CLOCK |
OMAP_I2C_FLAG_16BIT_DATA_REG |
OMAP_I2C_FLAG_ALWAYS_ARMXOR_CLK;
/* how the cpu bus is wired up differs for 7xx only */
if (cpu_is_omap7xx())
pdata->flags |= OMAP_I2C_FLAG_BUS_SHIFT_1;
else
pdata->flags |= OMAP_I2C_FLAG_BUS_SHIFT_2;
return platform_device_register(pdev);
}
#ifdef CONFIG_ARCH_OMAP2PLUS
/*
* XXX This function is a temporary compatibility wrapper - only
* needed until the I2C driver can be converted to call
* omap_pm_set_max_dev_wakeup_lat() and handle a return code.
*/
static void omap_pm_set_max_mpu_wakeup_lat_compat(struct device *dev, long t)
{
omap_pm_set_max_mpu_wakeup_lat(dev, t);
}
static inline int omap2_i2c_add_bus(int bus_id)
{
int l;
struct omap_hwmod *oh;
struct platform_device *pdev;
char oh_name[MAX_OMAP_I2C_HWMOD_NAME_LEN];
struct omap_i2c_bus_platform_data *pdata;
struct omap_i2c_dev_attr *dev_attr;
omap2_i2c_mux_pins(bus_id);
l = snprintf(oh_name, MAX_OMAP_I2C_HWMOD_NAME_LEN, "i2c%d", bus_id);
WARN(l >= MAX_OMAP_I2C_HWMOD_NAME_LEN,
"String buffer overflow in I2C%d device setup\n", bus_id);
oh = omap_hwmod_lookup(oh_name);
if (!oh) {
pr_err("Could not look up %s\n", oh_name);
return -EEXIST;
}
pdata = &i2c_pdata[bus_id - 1];
/*
* pass the hwmod class's CPU-specific knowledge of I2C IP revision in
* use, and functionality implementation flags, up to the OMAP I2C
* driver via platform data
*/
pdata->rev = oh->class->rev;
dev_attr = (struct omap_i2c_dev_attr *)oh->dev_attr;
pdata->flags = dev_attr->flags;
/*
* When waiting for completion of a i2c transfer, we need to
* set a wake up latency constraint for the MPU. This is to
* ensure quick enough wakeup from idle, when transfer
* completes.
* Only omap3 has support for constraints
*/
if (cpu_is_omap34xx())
pdata->set_mpu_wkup_lat = omap_pm_set_max_mpu_wakeup_lat_compat;
pdev = omap_device_build(name, bus_id, oh, pdata,
sizeof(struct omap_i2c_bus_platform_data),
NULL, 0, 0);
WARN(IS_ERR(pdev), "Could not build omap_device for %s\n", name);
return PTR_RET(pdev);
}
#else
static inline int omap2_i2c_add_bus(int bus_id)
{
return 0;
}
#endif
static int __init omap_i2c_add_bus(int bus_id)
{
if (cpu_class_is_omap1())
return omap1_i2c_add_bus(bus_id);
else
return omap2_i2c_add_bus(bus_id);
}
/**
* omap_i2c_bus_setup - Process command line options for the I2C bus speed
* @str: String of options
*
* This function allow to override the default I2C bus speed for given I2C
* bus with a command line option.
*
* Format: i2c_bus=bus_id,clkrate (in kHz)
*
* Returns 1 on success, 0 otherwise.
*/
static int __init omap_i2c_bus_setup(char *str)
{
int ports;
int ints[3];
ports = omap_i2c_nr_ports();
get_options(str, 3, ints);
if (ints[0] < 2 || ints[1] < 1 || ints[1] > ports)
return 0;
i2c_pdata[ints[1] - 1].clkrate = ints[2];
i2c_pdata[ints[1] - 1].clkrate |= OMAP_I2C_CMDLINE_SETUP;
return 1;
}
__setup("i2c_bus=", omap_i2c_bus_setup);
/*
* Register busses defined in command line but that are not registered with
* omap_register_i2c_bus from board initialization code.
*/
static int __init omap_register_i2c_bus_cmdline(void)
{
int i, err = 0;
for (i = 0; i < ARRAY_SIZE(i2c_pdata); i++)
if (i2c_pdata[i].clkrate & OMAP_I2C_CMDLINE_SETUP) {
i2c_pdata[i].clkrate &= ~OMAP_I2C_CMDLINE_SETUP;
err = omap_i2c_add_bus(i + 1);
if (err)
goto out;
}
out:
return err;
}
subsys_initcall(omap_register_i2c_bus_cmdline);
/**
* omap_register_i2c_bus - register I2C bus with device descriptors
* @bus_id: bus id counting from number 1
* @clkrate: clock rate of the bus in kHz
* @info: pointer into I2C device descriptor table or NULL
* @len: number of descriptors in the table
*
* Returns 0 on success or an error code.
*/
int __init omap_register_i2c_bus(int bus_id, u32 clkrate,
struct i2c_board_info const *info,
unsigned len)
{
int err;
BUG_ON(bus_id < 1 || bus_id > omap_i2c_nr_ports());
if (info) {
err = i2c_register_board_info(bus_id, info, len);
if (err)
return err;
}
if (!i2c_pdata[bus_id - 1].clkrate)
i2c_pdata[bus_id - 1].clkrate = clkrate;
i2c_pdata[bus_id - 1].clkrate &= ~OMAP_I2C_CMDLINE_SETUP;
return omap_i2c_add_bus(bus_id);
}
| gpl-2.0 |
groeck/coreboot | src/vendorcode/amd/agesa/f14/Proc/HT/Fam10/htNbOptimizationFam10.c | 22 | 8229 | /* $NoKeywords:$ */
/**
* @file
*
* Link optimization support specific to family 10h processors.
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: HyperTransport
* @e \$Revision: 35136 $ @e \$Date: 2010-07-16 11:29:48 +0800 (Fri, 16 Jul 2010) $
*
*/
/*
*****************************************************************************
*
* Copyright (c) 2011, Advanced Micro Devices, 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:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, 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 ADVANCED MICRO DEVICES, INC. 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.
*
* ***************************************************************************
*
*/
/*
*----------------------------------------------------------------------------
* MODULES USED
*
*----------------------------------------------------------------------------
*/
#include "AGESA.h"
#include "Ids.h"
#include "Topology.h"
#include "htFeat.h"
#include "htInterface.h"
#include "htNb.h"
#include "htNbOptimizationFam10.h"
#include "Filecode.h"
CODE_GROUP (G1_PEICC)
RDATA_GROUP (G1_PEICC)
#define FILECODE PROC_HT_FAM10_HTNBOPTIMIZATIONFAM10_FILECODE
/*----------------------------------------------------------------------------
* DEFINITIONS AND MACROS
*
*----------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------------------*/
/**
* Northbridge specific Frequency limit.
*
* @HtNbMethod{::F_NORTH_BRIDGE_FREQ_MASK}
*
* Return a mask that eliminates HT frequencies that cannot be used due to a slow
* northbridge frequency.
*
* @param[in] Node Result could (later) be for a specific Node
* @param[in] Interface Access to non-HT support functions.
* @param[in] PlatformConfig Platform profile/build option config structure.
* @param[in] Nb this northbridge
*
* @return Frequency mask
*/
UINT32
Fam10NorthBridgeFreqMask (
IN UINT8 Node,
IN HT_INTERFACE *Interface,
IN PLATFORM_CONFIGURATION *PlatformConfig,
IN NORTHBRIDGE *Nb
)
{
UINT32 NbCoreFreq;
UINT32 Supported;
ASSERT (Node < MAX_NODES);
ASSERT (Interface != NULL);
// The interface to power management will return a system based result.
// So we only need to call it once, not on every link. Save the answer,
// and check to see if we can use a saved answer on subsequent calls.
//
if (Nb->CoreFrequency == 0) {
NbCoreFreq = Interface->GetMinNbCoreFreq (PlatformConfig, Nb->ConfigHandle);
NbCoreFreq = (NbCoreFreq / 100);
ASSERT (NbCoreFreq != 0);
Nb->CoreFrequency = NbCoreFreq;
} else {
NbCoreFreq = Nb->CoreFrequency;
}
//
// NbCoreFreq is minimum northbridge speed in hundreds of MHz.
// HT can not go faster than the minimum speed of the northbridge.
//
if ((NbCoreFreq >= 6) && (NbCoreFreq <= 26)) {
// Convert frequency to bit and all less significant bits,
// by setting next power of 2 and subtracting 1.
//
Supported = ((UINT32)1 << ((NbCoreFreq >> 1) + 2)) - 1;
} else if ((NbCoreFreq > 26) && (NbCoreFreq <= 32)) {
// Convert frequency to bit and all less significant bits,
// by setting next power of 2 and subtracting 1, noting that
// next power of two is two greater than non-extended frequencies
// (because of the register break).
//
Supported = ((UINT32)1 << ((NbCoreFreq >> 1) + 4)) - 1;
} else if (NbCoreFreq > 32) {
Supported = HT_FREQUENCY_LIMIT_MAX;
} else if (NbCoreFreq == 4) {
// unlikely cases, but include as a defensive measure, also avoid trick above
Supported = HT_FREQUENCY_LIMIT_400M;
} else if (NbCoreFreq == 2) {
Supported = HT_FREQUENCY_LIMIT_200M;
} else {
ASSERT (FALSE);
Supported = HT_FREQUENCY_LIMIT_200M;
}
return (Supported);
}
/*----------------------------------------------------------------------------------------*/
/**
* Northbridge specific Frequency limit.
*
* @HtNbMethod{::F_NORTH_BRIDGE_FREQ_MASK}
*
* Return a mask that eliminates HT frequencies that cannot be used due to a slow
* northbridge frequency.
*
* @param[in] Node Result could (later) be for a specific Node
* @param[in] Interface Access to non-HT support functions.
* @param[in] PlatformConfig Platform profile/build option config structure.
* @param[in] Nb this northbridge
*
* @return Frequency mask
*/
UINT32
Fam10RevDNorthBridgeFreqMask (
IN UINT8 Node,
IN HT_INTERFACE *Interface,
IN PLATFORM_CONFIGURATION *PlatformConfig,
IN NORTHBRIDGE *Nb
)
{
UINT32 NbCoreFreq;
UINT32 Supported;
ASSERT (Node < MAX_NODES);
ASSERT (Interface != NULL);
// The interface to power management will return a system based result.
// So we only need to call it once, not on every link. Save the answer,
// and check to see if we can use a saved answer on subsequent calls.
//
if (Nb->CoreFrequency == 0) {
NbCoreFreq = Interface->GetMinNbCoreFreq (PlatformConfig, Nb->ConfigHandle);
NbCoreFreq = (NbCoreFreq / 100);
ASSERT (NbCoreFreq != 0);
Nb->CoreFrequency = NbCoreFreq;
} else {
NbCoreFreq = Nb->CoreFrequency;
}
// For Rev D, the Ht frequency can go twice the Nb COF, as long as it's HT3.
// (side note: we are not speculatively upgrading HT1 at 6 .. 10 to HT3,
// to avoid complicated recovery if the final speed is HT1.)
if (NbCoreFreq > 10) {
NbCoreFreq = NbCoreFreq * 2;
}
//
// NbCoreFreq is minimum northbridge speed in hundreds of MHz.
// HT can not go faster than the minimum speed of the northbridge.
//
if ((NbCoreFreq >= 6) && (NbCoreFreq <= 26)) {
// Convert frequency to bit and all less significant bits,
// by setting next power of 2 and subtracting 1.
//
Supported = ((UINT32)1 << ((NbCoreFreq >> 1) + 2)) - 1;
} else if ((NbCoreFreq > 26) && (NbCoreFreq <= 32)) {
// Convert frequency to bit and all less significant bits,
// by setting next power of 2 and subtracting 1, noting that
// next power of two is two greater than non-extended frequencies
// (because of the register break).
//
Supported = ((UINT32)1 << ((NbCoreFreq >> 1) + 4)) - 1;
} else if (NbCoreFreq > 32) {
Supported = HT_FREQUENCY_LIMIT_MAX;
} else if (NbCoreFreq == 4) {
// unlikely cases, but include as a defensive measure, also avoid trick above
Supported = HT_FREQUENCY_LIMIT_400M;
} else if (NbCoreFreq == 2) {
Supported = HT_FREQUENCY_LIMIT_200M;
} else {
ASSERT (FALSE);
Supported = HT_FREQUENCY_LIMIT_200M;
}
return (Supported);
}
| gpl-2.0 |
5ha5hank/backports-3.18.1-1 | drivers/net/wireless/iwlwifi/dvm/scan.c | 22 | 30379 | /******************************************************************************
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2014 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*****************************************************************************/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/etherdevice.h>
#include <net/mac80211.h>
#include "dev.h"
#include "agn.h"
/* For active scan, listen ACTIVE_DWELL_TIME (msec) on each channel after
* sending probe req. This should be set long enough to hear probe responses
* from more than one AP. */
#define IWL_ACTIVE_DWELL_TIME_24 (30) /* all times in msec */
#define IWL_ACTIVE_DWELL_TIME_52 (20)
#define IWL_ACTIVE_DWELL_FACTOR_24GHZ (3)
#define IWL_ACTIVE_DWELL_FACTOR_52GHZ (2)
/* For passive scan, listen PASSIVE_DWELL_TIME (msec) on each channel.
* Must be set longer than active dwell time.
* For the most reliable scan, set > AP beacon interval (typically 100msec). */
#define IWL_PASSIVE_DWELL_TIME_24 (20) /* all times in msec */
#define IWL_PASSIVE_DWELL_TIME_52 (10)
#define IWL_PASSIVE_DWELL_BASE (100)
#define IWL_CHANNEL_TUNE_TIME 5
#define MAX_SCAN_CHANNEL 50
/* For reset radio, need minimal dwell time only */
#define IWL_RADIO_RESET_DWELL_TIME 5
static int iwl_send_scan_abort(struct iwl_priv *priv)
{
int ret;
struct iwl_host_cmd cmd = {
.id = REPLY_SCAN_ABORT_CMD,
.flags = CMD_WANT_SKB,
};
__le32 *status;
/* Exit instantly with error when device is not ready
* to receive scan abort command or it does not perform
* hardware scan currently */
if (!test_bit(STATUS_READY, &priv->status) ||
!test_bit(STATUS_SCAN_HW, &priv->status) ||
test_bit(STATUS_FW_ERROR, &priv->status))
return -EIO;
ret = iwl_dvm_send_cmd(priv, &cmd);
if (ret)
return ret;
status = (void *)cmd.resp_pkt->data;
if (*status != CAN_ABORT_STATUS) {
/* The scan abort will return 1 for success or
* 2 for "failure". A failure condition can be
* due to simply not being in an active scan which
* can occur if we send the scan abort before we
* the microcode has notified us that a scan is
* completed. */
IWL_DEBUG_SCAN(priv, "SCAN_ABORT ret %d.\n",
le32_to_cpu(*status));
ret = -EIO;
}
iwl_free_resp(&cmd);
return ret;
}
static void iwl_complete_scan(struct iwl_priv *priv, bool aborted)
{
/* check if scan was requested from mac80211 */
if (priv->scan_request) {
IWL_DEBUG_SCAN(priv, "Complete scan in mac80211\n");
ieee80211_scan_completed(priv->hw, aborted);
}
priv->scan_type = IWL_SCAN_NORMAL;
priv->scan_vif = NULL;
priv->scan_request = NULL;
}
static void iwl_process_scan_complete(struct iwl_priv *priv)
{
bool aborted;
lockdep_assert_held(&priv->mutex);
if (!test_and_clear_bit(STATUS_SCAN_COMPLETE, &priv->status))
return;
IWL_DEBUG_SCAN(priv, "Completed scan.\n");
cancel_delayed_work(&priv->scan_check);
aborted = test_and_clear_bit(STATUS_SCAN_ABORTING, &priv->status);
if (aborted)
IWL_DEBUG_SCAN(priv, "Aborted scan completed.\n");
if (!test_and_clear_bit(STATUS_SCANNING, &priv->status)) {
IWL_DEBUG_SCAN(priv, "Scan already completed.\n");
goto out_settings;
}
if (priv->scan_type != IWL_SCAN_NORMAL && !aborted) {
int err;
/* Check if mac80211 requested scan during our internal scan */
if (priv->scan_request == NULL)
goto out_complete;
/* If so request a new scan */
err = iwl_scan_initiate(priv, priv->scan_vif, IWL_SCAN_NORMAL,
priv->scan_request->channels[0]->band);
if (err) {
IWL_DEBUG_SCAN(priv,
"failed to initiate pending scan: %d\n", err);
aborted = true;
goto out_complete;
}
return;
}
out_complete:
iwl_complete_scan(priv, aborted);
out_settings:
/* Can we still talk to firmware ? */
if (!iwl_is_ready_rf(priv))
return;
iwlagn_post_scan(priv);
}
void iwl_force_scan_end(struct iwl_priv *priv)
{
lockdep_assert_held(&priv->mutex);
if (!test_bit(STATUS_SCANNING, &priv->status)) {
IWL_DEBUG_SCAN(priv, "Forcing scan end while not scanning\n");
return;
}
IWL_DEBUG_SCAN(priv, "Forcing scan end\n");
clear_bit(STATUS_SCANNING, &priv->status);
clear_bit(STATUS_SCAN_HW, &priv->status);
clear_bit(STATUS_SCAN_ABORTING, &priv->status);
clear_bit(STATUS_SCAN_COMPLETE, &priv->status);
iwl_complete_scan(priv, true);
}
static void iwl_do_scan_abort(struct iwl_priv *priv)
{
int ret;
lockdep_assert_held(&priv->mutex);
if (!test_bit(STATUS_SCANNING, &priv->status)) {
IWL_DEBUG_SCAN(priv, "Not performing scan to abort\n");
return;
}
if (test_and_set_bit(STATUS_SCAN_ABORTING, &priv->status)) {
IWL_DEBUG_SCAN(priv, "Scan abort in progress\n");
return;
}
ret = iwl_send_scan_abort(priv);
if (ret) {
IWL_DEBUG_SCAN(priv, "Send scan abort failed %d\n", ret);
iwl_force_scan_end(priv);
} else
IWL_DEBUG_SCAN(priv, "Successfully send scan abort\n");
}
/**
* iwl_scan_cancel - Cancel any currently executing HW scan
*/
int iwl_scan_cancel(struct iwl_priv *priv)
{
IWL_DEBUG_SCAN(priv, "Queuing abort scan\n");
queue_work(priv->workqueue, &priv->abort_scan);
return 0;
}
/**
* iwl_scan_cancel_timeout - Cancel any currently executing HW scan
* @ms: amount of time to wait (in milliseconds) for scan to abort
*
*/
void iwl_scan_cancel_timeout(struct iwl_priv *priv, unsigned long ms)
{
unsigned long timeout = jiffies + msecs_to_jiffies(ms);
lockdep_assert_held(&priv->mutex);
IWL_DEBUG_SCAN(priv, "Scan cancel timeout\n");
iwl_do_scan_abort(priv);
while (time_before_eq(jiffies, timeout)) {
if (!test_bit(STATUS_SCAN_HW, &priv->status))
goto finished;
msleep(20);
}
return;
finished:
/*
* Now STATUS_SCAN_HW is clear. This means that the
* device finished, but the background work is going
* to execute at best as soon as we release the mutex.
* Since we need to be able to issue a new scan right
* after this function returns, run the complete here.
* The STATUS_SCAN_COMPLETE bit will then be cleared
* and prevent the background work from "completing"
* a possible new scan.
*/
iwl_process_scan_complete(priv);
}
/* Service response to REPLY_SCAN_CMD (0x80) */
static int iwl_rx_reply_scan(struct iwl_priv *priv,
struct iwl_rx_cmd_buffer *rxb,
struct iwl_device_cmd *cmd)
{
#ifdef CPTCFG_IWLWIFI_DEBUG
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_scanreq_notification *notif = (void *)pkt->data;
IWL_DEBUG_SCAN(priv, "Scan request status = 0x%x\n", notif->status);
#endif
return 0;
}
/* Service SCAN_START_NOTIFICATION (0x82) */
static int iwl_rx_scan_start_notif(struct iwl_priv *priv,
struct iwl_rx_cmd_buffer *rxb,
struct iwl_device_cmd *cmd)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_scanstart_notification *notif = (void *)pkt->data;
priv->scan_start_tsf = le32_to_cpu(notif->tsf_low);
IWL_DEBUG_SCAN(priv, "Scan start: "
"%d [802.11%s] "
"(TSF: 0x%08X:%08X) - %d (beacon timer %u)\n",
notif->channel,
notif->band ? "bg" : "a",
le32_to_cpu(notif->tsf_high),
le32_to_cpu(notif->tsf_low),
notif->status, notif->beacon_timer);
return 0;
}
/* Service SCAN_RESULTS_NOTIFICATION (0x83) */
static int iwl_rx_scan_results_notif(struct iwl_priv *priv,
struct iwl_rx_cmd_buffer *rxb,
struct iwl_device_cmd *cmd)
{
#ifdef CPTCFG_IWLWIFI_DEBUG
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_scanresults_notification *notif = (void *)pkt->data;
IWL_DEBUG_SCAN(priv, "Scan ch.res: "
"%d [802.11%s] "
"probe status: %u:%u "
"(TSF: 0x%08X:%08X) - %d "
"elapsed=%lu usec\n",
notif->channel,
notif->band ? "bg" : "a",
notif->probe_status, notif->num_probe_not_sent,
le32_to_cpu(notif->tsf_high),
le32_to_cpu(notif->tsf_low),
le32_to_cpu(notif->statistics[0]),
le32_to_cpu(notif->tsf_low) - priv->scan_start_tsf);
#endif
return 0;
}
/* Service SCAN_COMPLETE_NOTIFICATION (0x84) */
static int iwl_rx_scan_complete_notif(struct iwl_priv *priv,
struct iwl_rx_cmd_buffer *rxb,
struct iwl_device_cmd *cmd)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_scancomplete_notification *scan_notif = (void *)pkt->data;
IWL_DEBUG_SCAN(priv, "Scan complete: %d channels (TSF 0x%08X:%08X) - %d\n",
scan_notif->scanned_channels,
scan_notif->tsf_low,
scan_notif->tsf_high, scan_notif->status);
IWL_DEBUG_SCAN(priv, "Scan on %sGHz took %dms\n",
(priv->scan_band == IEEE80211_BAND_2GHZ) ? "2.4" : "5.2",
jiffies_to_msecs(jiffies - priv->scan_start));
/*
* When aborting, we run the scan completed background work inline
* and the background work must then do nothing. The SCAN_COMPLETE
* bit helps implement that logic and thus needs to be set before
* queueing the work. Also, since the scan abort waits for SCAN_HW
* to clear, we need to set SCAN_COMPLETE before clearing SCAN_HW
* to avoid a race there.
*/
set_bit(STATUS_SCAN_COMPLETE, &priv->status);
clear_bit(STATUS_SCAN_HW, &priv->status);
queue_work(priv->workqueue, &priv->scan_completed);
if (priv->iw_mode != NL80211_IFTYPE_ADHOC &&
iwl_advanced_bt_coexist(priv) &&
priv->bt_status != scan_notif->bt_status) {
if (scan_notif->bt_status) {
/* BT on */
if (!priv->bt_ch_announce)
priv->bt_traffic_load =
IWL_BT_COEX_TRAFFIC_LOAD_HIGH;
/*
* otherwise, no traffic load information provided
* no changes made
*/
} else {
/* BT off */
priv->bt_traffic_load =
IWL_BT_COEX_TRAFFIC_LOAD_NONE;
}
priv->bt_status = scan_notif->bt_status;
queue_work(priv->workqueue,
&priv->bt_traffic_change_work);
}
return 0;
}
void iwl_setup_rx_scan_handlers(struct iwl_priv *priv)
{
/* scan handlers */
priv->rx_handlers[REPLY_SCAN_CMD] = iwl_rx_reply_scan;
priv->rx_handlers[SCAN_START_NOTIFICATION] = iwl_rx_scan_start_notif;
priv->rx_handlers[SCAN_RESULTS_NOTIFICATION] =
iwl_rx_scan_results_notif;
priv->rx_handlers[SCAN_COMPLETE_NOTIFICATION] =
iwl_rx_scan_complete_notif;
}
static u16 iwl_get_active_dwell_time(struct iwl_priv *priv,
enum ieee80211_band band, u8 n_probes)
{
if (band == IEEE80211_BAND_5GHZ)
return IWL_ACTIVE_DWELL_TIME_52 +
IWL_ACTIVE_DWELL_FACTOR_52GHZ * (n_probes + 1);
else
return IWL_ACTIVE_DWELL_TIME_24 +
IWL_ACTIVE_DWELL_FACTOR_24GHZ * (n_probes + 1);
}
static u16 iwl_limit_dwell(struct iwl_priv *priv, u16 dwell_time)
{
struct iwl_rxon_context *ctx;
int limits[NUM_IWL_RXON_CTX] = {};
int n_active = 0;
u16 limit;
BUILD_BUG_ON(NUM_IWL_RXON_CTX != 2);
/*
* If we're associated, we clamp the dwell time 98%
* of the beacon interval (minus 2 * channel tune time)
* If both contexts are active, we have to restrict to
* 1/2 of the minimum of them, because they might be in
* lock-step with the time inbetween only half of what
* time we'd have in each of them.
*/
for_each_context(priv, ctx) {
switch (ctx->staging.dev_type) {
case RXON_DEV_TYPE_P2P:
/* no timing constraints */
continue;
case RXON_DEV_TYPE_ESS:
default:
/* timing constraints if associated */
if (!iwl_is_associated_ctx(ctx))
continue;
break;
case RXON_DEV_TYPE_CP:
case RXON_DEV_TYPE_2STA:
/*
* These seem to always have timers for TBTT
* active in uCode even when not associated yet.
*/
break;
}
limits[n_active++] = ctx->beacon_int ?: IWL_PASSIVE_DWELL_BASE;
}
switch (n_active) {
case 0:
return dwell_time;
case 2:
limit = (limits[1] * 98) / 100 - IWL_CHANNEL_TUNE_TIME * 2;
limit /= 2;
dwell_time = min(limit, dwell_time);
/* fall through to limit further */
case 1:
limit = (limits[0] * 98) / 100 - IWL_CHANNEL_TUNE_TIME * 2;
limit /= n_active;
return min(limit, dwell_time);
default:
WARN_ON_ONCE(1);
return dwell_time;
}
}
static u16 iwl_get_passive_dwell_time(struct iwl_priv *priv,
enum ieee80211_band band)
{
u16 passive = (band == IEEE80211_BAND_2GHZ) ?
IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_24 :
IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_52;
return iwl_limit_dwell(priv, passive);
}
/* Return valid, unused, channel for a passive scan to reset the RF */
static u8 iwl_get_single_channel_number(struct iwl_priv *priv,
enum ieee80211_band band)
{
struct ieee80211_supported_band *sband = priv->hw->wiphy->bands[band];
struct iwl_rxon_context *ctx;
int i;
for (i = 0; i < sband->n_channels; i++) {
bool busy = false;
for_each_context(priv, ctx) {
busy = sband->channels[i].hw_value ==
le16_to_cpu(ctx->staging.channel);
if (busy)
break;
}
if (busy)
continue;
if (!(sband->channels[i].flags & IEEE80211_CHAN_DISABLED))
return sband->channels[i].hw_value;
}
return 0;
}
static int iwl_get_channel_for_reset_scan(struct iwl_priv *priv,
struct ieee80211_vif *vif,
enum ieee80211_band band,
struct iwl_scan_channel *scan_ch)
{
const struct ieee80211_supported_band *sband;
u16 channel;
sband = iwl_get_hw_mode(priv, band);
if (!sband) {
IWL_ERR(priv, "invalid band\n");
return 0;
}
channel = iwl_get_single_channel_number(priv, band);
if (channel) {
scan_ch->channel = cpu_to_le16(channel);
scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
scan_ch->active_dwell =
cpu_to_le16(IWL_RADIO_RESET_DWELL_TIME);
scan_ch->passive_dwell =
cpu_to_le16(IWL_RADIO_RESET_DWELL_TIME);
/* Set txpower levels to defaults */
scan_ch->dsp_atten = 110;
if (band == IEEE80211_BAND_5GHZ)
scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
else
scan_ch->tx_gain = ((1 << 5) | (5 << 3));
return 1;
}
IWL_ERR(priv, "no valid channel found\n");
return 0;
}
static int iwl_get_channels_for_scan(struct iwl_priv *priv,
struct ieee80211_vif *vif,
enum ieee80211_band band,
u8 is_active, u8 n_probes,
struct iwl_scan_channel *scan_ch)
{
struct ieee80211_channel *chan;
const struct ieee80211_supported_band *sband;
u16 passive_dwell = 0;
u16 active_dwell = 0;
int added, i;
u16 channel;
sband = iwl_get_hw_mode(priv, band);
if (!sband)
return 0;
active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
passive_dwell = iwl_get_passive_dwell_time(priv, band);
if (passive_dwell <= active_dwell)
passive_dwell = active_dwell + 1;
for (i = 0, added = 0; i < priv->scan_request->n_channels; i++) {
chan = priv->scan_request->channels[i];
if (chan->band != band)
continue;
channel = chan->hw_value;
scan_ch->channel = cpu_to_le16(channel);
if (!is_active || (chan->flags & IEEE80211_CHAN_NO_IR))
scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
else
scan_ch->type = SCAN_CHANNEL_TYPE_ACTIVE;
if (n_probes)
scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
scan_ch->active_dwell = cpu_to_le16(active_dwell);
scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
/* Set txpower levels to defaults */
scan_ch->dsp_atten = 110;
/* NOTE: if we were doing 6Mb OFDM for scans we'd use
* power level:
* scan_ch->tx_gain = ((1 << 5) | (2 << 3)) | 3;
*/
if (band == IEEE80211_BAND_5GHZ)
scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
else
scan_ch->tx_gain = ((1 << 5) | (5 << 3));
IWL_DEBUG_SCAN(priv, "Scanning ch=%d prob=0x%X [%s %d]\n",
channel, le32_to_cpu(scan_ch->type),
(scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
"ACTIVE" : "PASSIVE",
(scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
active_dwell : passive_dwell);
scan_ch++;
added++;
}
IWL_DEBUG_SCAN(priv, "total channels to scan %d\n", added);
return added;
}
/**
* iwl_fill_probe_req - fill in all required fields and IE for probe request
*/
static u16 iwl_fill_probe_req(struct ieee80211_mgmt *frame, const u8 *ta,
const u8 *ies, int ie_len, const u8 *ssid,
u8 ssid_len, int left)
{
int len = 0;
u8 *pos = NULL;
/* Make sure there is enough space for the probe request,
* two mandatory IEs and the data */
left -= 24;
if (left < 0)
return 0;
frame->frame_control = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
eth_broadcast_addr(frame->da);
memcpy(frame->sa, ta, ETH_ALEN);
eth_broadcast_addr(frame->bssid);
frame->seq_ctrl = 0;
len += 24;
/* ...next IE... */
pos = &frame->u.probe_req.variable[0];
/* fill in our SSID IE */
left -= ssid_len + 2;
if (left < 0)
return 0;
*pos++ = WLAN_EID_SSID;
*pos++ = ssid_len;
if (ssid && ssid_len) {
memcpy(pos, ssid, ssid_len);
pos += ssid_len;
}
len += ssid_len + 2;
if (WARN_ON(left < ie_len))
return len;
if (ies && ie_len) {
memcpy(pos, ies, ie_len);
len += ie_len;
}
return (u16)len;
}
static int iwlagn_request_scan(struct iwl_priv *priv, struct ieee80211_vif *vif)
{
struct iwl_host_cmd cmd = {
.id = REPLY_SCAN_CMD,
.len = { sizeof(struct iwl_scan_cmd), },
};
struct iwl_scan_cmd *scan;
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
u32 rate_flags = 0;
u16 cmd_len = 0;
u16 rx_chain = 0;
enum ieee80211_band band;
u8 n_probes = 0;
u8 rx_ant = priv->nvm_data->valid_rx_ant;
u8 rate;
bool is_active = false;
int chan_mod;
u8 active_chains;
u8 scan_tx_antennas = priv->nvm_data->valid_tx_ant;
int ret;
int scan_cmd_size = sizeof(struct iwl_scan_cmd) +
MAX_SCAN_CHANNEL * sizeof(struct iwl_scan_channel) +
priv->fw->ucode_capa.max_probe_length;
const u8 *ssid = NULL;
u8 ssid_len = 0;
if (WARN_ON(priv->scan_type == IWL_SCAN_NORMAL &&
(!priv->scan_request ||
priv->scan_request->n_channels > MAX_SCAN_CHANNEL)))
return -EINVAL;
lockdep_assert_held(&priv->mutex);
if (vif)
ctx = iwl_rxon_ctx_from_vif(vif);
if (!priv->scan_cmd) {
priv->scan_cmd = kmalloc(scan_cmd_size, GFP_KERNEL);
if (!priv->scan_cmd) {
IWL_DEBUG_SCAN(priv,
"fail to allocate memory for scan\n");
return -ENOMEM;
}
}
scan = priv->scan_cmd;
memset(scan, 0, scan_cmd_size);
scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
if (iwl_is_any_associated(priv)) {
u16 interval = 0;
u32 extra;
u32 suspend_time = 100;
u32 scan_suspend_time = 100;
IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
switch (priv->scan_type) {
case IWL_SCAN_RADIO_RESET:
interval = 0;
break;
case IWL_SCAN_NORMAL:
interval = vif->bss_conf.beacon_int;
break;
}
scan->suspend_time = 0;
scan->max_out_time = cpu_to_le32(200 * 1024);
if (!interval)
interval = suspend_time;
extra = (suspend_time / interval) << 22;
scan_suspend_time = (extra |
((suspend_time % interval) * 1024));
scan->suspend_time = cpu_to_le32(scan_suspend_time);
IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
scan_suspend_time, interval);
}
switch (priv->scan_type) {
case IWL_SCAN_RADIO_RESET:
IWL_DEBUG_SCAN(priv, "Start internal passive scan.\n");
/*
* Override quiet time as firmware checks that active
* dwell is >= quiet; since we use passive scan it'll
* not actually be used.
*/
scan->quiet_time = cpu_to_le16(IWL_RADIO_RESET_DWELL_TIME);
break;
case IWL_SCAN_NORMAL:
if (priv->scan_request->n_ssids) {
int i, p = 0;
IWL_DEBUG_SCAN(priv, "Kicking off active scan\n");
/*
* The highest priority SSID is inserted to the
* probe request template.
*/
ssid_len = priv->scan_request->ssids[0].ssid_len;
ssid = priv->scan_request->ssids[0].ssid;
/*
* Invert the order of ssids, the firmware will invert
* it back.
*/
for (i = priv->scan_request->n_ssids - 1; i >= 1; i--) {
scan->direct_scan[p].id = WLAN_EID_SSID;
scan->direct_scan[p].len =
priv->scan_request->ssids[i].ssid_len;
memcpy(scan->direct_scan[p].ssid,
priv->scan_request->ssids[i].ssid,
priv->scan_request->ssids[i].ssid_len);
n_probes++;
p++;
}
is_active = true;
} else
IWL_DEBUG_SCAN(priv, "Start passive scan.\n");
break;
}
scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
scan->tx_cmd.sta_id = ctx->bcast_sta_id;
scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
switch (priv->scan_band) {
case IEEE80211_BAND_2GHZ:
scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
chan_mod = le32_to_cpu(
priv->contexts[IWL_RXON_CTX_BSS].active.flags &
RXON_FLG_CHANNEL_MODE_MSK)
>> RXON_FLG_CHANNEL_MODE_POS;
if ((priv->scan_request && priv->scan_request->no_cck) ||
chan_mod == CHANNEL_MODE_PURE_40) {
rate = IWL_RATE_6M_PLCP;
} else {
rate = IWL_RATE_1M_PLCP;
rate_flags = RATE_MCS_CCK_MSK;
}
/*
* Internal scans are passive, so we can indiscriminately set
* the BT ignore flag on 2.4 GHz since it applies to TX only.
*/
if (priv->lib->bt_params &&
priv->lib->bt_params->advanced_bt_coexist)
scan->tx_cmd.tx_flags |= TX_CMD_FLG_IGNORE_BT;
break;
case IEEE80211_BAND_5GHZ:
rate = IWL_RATE_6M_PLCP;
break;
default:
IWL_WARN(priv, "Invalid scan band\n");
return -EIO;
}
/*
* If active scanning is requested but a certain channel is
* marked passive, we can do active scanning if we detect
* transmissions.
*
* There is an issue with some firmware versions that triggers
* a sysassert on a "good CRC threshold" of zero (== disabled),
* on a radar channel even though this means that we should NOT
* send probes.
*
* The "good CRC threshold" is the number of frames that we
* need to receive during our dwell time on a channel before
* sending out probes -- setting this to a huge value will
* mean we never reach it, but at the same time work around
* the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
* here instead of IWL_GOOD_CRC_TH_DISABLED.
*
* This was fixed in later versions along with some other
* scan changes, and the threshold behaves as a flag in those
* versions.
*/
if (priv->new_scan_threshold_behaviour)
scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
IWL_GOOD_CRC_TH_DISABLED;
else
scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
IWL_GOOD_CRC_TH_NEVER;
band = priv->scan_band;
if (band == IEEE80211_BAND_2GHZ &&
priv->lib->bt_params &&
priv->lib->bt_params->advanced_bt_coexist) {
/* transmit 2.4 GHz probes only on first antenna */
scan_tx_antennas = first_antenna(scan_tx_antennas);
}
priv->scan_tx_ant[band] = iwl_toggle_tx_ant(priv,
priv->scan_tx_ant[band],
scan_tx_antennas);
rate_flags |= iwl_ant_idx_to_flags(priv->scan_tx_ant[band]);
scan->tx_cmd.rate_n_flags = iwl_hw_set_rate_n_flags(rate, rate_flags);
/*
* In power save mode while associated use one chain,
* otherwise use all chains
*/
if (test_bit(STATUS_POWER_PMI, &priv->status) &&
!(priv->hw->conf.flags & IEEE80211_CONF_IDLE)) {
/* rx_ant has been set to all valid chains previously */
active_chains = rx_ant &
((u8)(priv->chain_noise_data.active_chains));
if (!active_chains)
active_chains = rx_ant;
IWL_DEBUG_SCAN(priv, "chain_noise_data.active_chains: %u\n",
priv->chain_noise_data.active_chains);
rx_ant = first_antenna(active_chains);
}
if (priv->lib->bt_params &&
priv->lib->bt_params->advanced_bt_coexist &&
priv->bt_full_concurrent) {
/* operated as 1x1 in full concurrency mode */
rx_ant = first_antenna(rx_ant);
}
/* MIMO is not used here, but value is required */
rx_chain |=
priv->nvm_data->valid_rx_ant << RXON_RX_CHAIN_VALID_POS;
rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_MIMO_SEL_POS;
rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_SEL_POS;
rx_chain |= 0x1 << RXON_RX_CHAIN_DRIVER_FORCE_POS;
scan->rx_chain = cpu_to_le16(rx_chain);
switch (priv->scan_type) {
case IWL_SCAN_NORMAL:
cmd_len = iwl_fill_probe_req(
(struct ieee80211_mgmt *)scan->data,
vif->addr,
priv->scan_request->ie,
priv->scan_request->ie_len,
ssid, ssid_len,
scan_cmd_size - sizeof(*scan));
break;
case IWL_SCAN_RADIO_RESET:
/* use bcast addr, will not be transmitted but must be valid */
cmd_len = iwl_fill_probe_req(
(struct ieee80211_mgmt *)scan->data,
iwl_bcast_addr, NULL, 0,
NULL, 0,
scan_cmd_size - sizeof(*scan));
break;
default:
BUG();
}
scan->tx_cmd.len = cpu_to_le16(cmd_len);
scan->filter_flags |= (RXON_FILTER_ACCEPT_GRP_MSK |
RXON_FILTER_BCON_AWARE_MSK);
switch (priv->scan_type) {
case IWL_SCAN_RADIO_RESET:
scan->channel_count =
iwl_get_channel_for_reset_scan(priv, vif, band,
(void *)&scan->data[cmd_len]);
break;
case IWL_SCAN_NORMAL:
scan->channel_count =
iwl_get_channels_for_scan(priv, vif, band,
is_active, n_probes,
(void *)&scan->data[cmd_len]);
break;
}
if (scan->channel_count == 0) {
IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
return -EIO;
}
cmd.len[0] += le16_to_cpu(scan->tx_cmd.len) +
scan->channel_count * sizeof(struct iwl_scan_channel);
cmd.data[0] = scan;
cmd.dataflags[0] = IWL_HCMD_DFL_NOCOPY;
scan->len = cpu_to_le16(cmd.len[0]);
/* set scan bit here for PAN params */
set_bit(STATUS_SCAN_HW, &priv->status);
ret = iwlagn_set_pan_params(priv);
if (ret) {
clear_bit(STATUS_SCAN_HW, &priv->status);
return ret;
}
ret = iwl_dvm_send_cmd(priv, &cmd);
if (ret) {
clear_bit(STATUS_SCAN_HW, &priv->status);
iwlagn_set_pan_params(priv);
}
return ret;
}
void iwl_init_scan_params(struct iwl_priv *priv)
{
u8 ant_idx = fls(priv->nvm_data->valid_tx_ant) - 1;
if (!priv->scan_tx_ant[IEEE80211_BAND_5GHZ])
priv->scan_tx_ant[IEEE80211_BAND_5GHZ] = ant_idx;
if (!priv->scan_tx_ant[IEEE80211_BAND_2GHZ])
priv->scan_tx_ant[IEEE80211_BAND_2GHZ] = ant_idx;
}
int __must_check iwl_scan_initiate(struct iwl_priv *priv,
struct ieee80211_vif *vif,
enum iwl_scan_type scan_type,
enum ieee80211_band band)
{
int ret;
lockdep_assert_held(&priv->mutex);
cancel_delayed_work(&priv->scan_check);
if (!iwl_is_ready_rf(priv)) {
IWL_WARN(priv, "Request scan called when driver not ready.\n");
return -EIO;
}
if (test_bit(STATUS_SCAN_HW, &priv->status)) {
IWL_DEBUG_SCAN(priv,
"Multiple concurrent scan requests in parallel.\n");
return -EBUSY;
}
if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
IWL_DEBUG_SCAN(priv, "Scan request while abort pending.\n");
return -EBUSY;
}
IWL_DEBUG_SCAN(priv, "Starting %sscan...\n",
scan_type == IWL_SCAN_NORMAL ? "" :
"internal short ");
set_bit(STATUS_SCANNING, &priv->status);
priv->scan_type = scan_type;
priv->scan_start = jiffies;
priv->scan_band = band;
ret = iwlagn_request_scan(priv, vif);
if (ret) {
clear_bit(STATUS_SCANNING, &priv->status);
priv->scan_type = IWL_SCAN_NORMAL;
return ret;
}
queue_delayed_work(priv->workqueue, &priv->scan_check,
IWL_SCAN_CHECK_WATCHDOG);
return 0;
}
/*
* internal short scan, this function should only been called while associated.
* It will reset and tune the radio to prevent possible RF related problem
*/
void iwl_internal_short_hw_scan(struct iwl_priv *priv)
{
queue_work(priv->workqueue, &priv->start_internal_scan);
}
static void iwl_bg_start_internal_scan(struct work_struct *work)
{
struct iwl_priv *priv =
container_of(work, struct iwl_priv, start_internal_scan);
IWL_DEBUG_SCAN(priv, "Start internal scan\n");
mutex_lock(&priv->mutex);
if (priv->scan_type == IWL_SCAN_RADIO_RESET) {
IWL_DEBUG_SCAN(priv, "Internal scan already in progress\n");
goto unlock;
}
if (test_bit(STATUS_SCANNING, &priv->status)) {
IWL_DEBUG_SCAN(priv, "Scan already in progress.\n");
goto unlock;
}
if (iwl_scan_initiate(priv, NULL, IWL_SCAN_RADIO_RESET, priv->band))
IWL_DEBUG_SCAN(priv, "failed to start internal short scan\n");
unlock:
mutex_unlock(&priv->mutex);
}
static void iwl_bg_scan_check(struct work_struct *data)
{
struct iwl_priv *priv =
container_of(data, struct iwl_priv, scan_check.work);
IWL_DEBUG_SCAN(priv, "Scan check work\n");
/* Since we are here firmware does not finish scan and
* most likely is in bad shape, so we don't bother to
* send abort command, just force scan complete to mac80211 */
mutex_lock(&priv->mutex);
iwl_force_scan_end(priv);
mutex_unlock(&priv->mutex);
}
static void iwl_bg_abort_scan(struct work_struct *work)
{
struct iwl_priv *priv = container_of(work, struct iwl_priv, abort_scan);
IWL_DEBUG_SCAN(priv, "Abort scan work\n");
/* We keep scan_check work queued in case when firmware will not
* report back scan completed notification */
mutex_lock(&priv->mutex);
iwl_scan_cancel_timeout(priv, 200);
mutex_unlock(&priv->mutex);
}
static void iwl_bg_scan_completed(struct work_struct *work)
{
struct iwl_priv *priv =
container_of(work, struct iwl_priv, scan_completed);
mutex_lock(&priv->mutex);
iwl_process_scan_complete(priv);
mutex_unlock(&priv->mutex);
}
void iwl_setup_scan_deferred_work(struct iwl_priv *priv)
{
INIT_WORK(&priv->scan_completed, iwl_bg_scan_completed);
INIT_WORK(&priv->abort_scan, iwl_bg_abort_scan);
INIT_WORK(&priv->start_internal_scan, iwl_bg_start_internal_scan);
INIT_DELAYED_WORK(&priv->scan_check, iwl_bg_scan_check);
}
void iwl_cancel_scan_deferred_work(struct iwl_priv *priv)
{
cancel_work_sync(&priv->start_internal_scan);
cancel_work_sync(&priv->abort_scan);
cancel_work_sync(&priv->scan_completed);
if (cancel_delayed_work_sync(&priv->scan_check)) {
mutex_lock(&priv->mutex);
iwl_force_scan_end(priv);
mutex_unlock(&priv->mutex);
}
}
| gpl-2.0 |
mhei/linux | drivers/hid/hid-sensor-hub.c | 22 | 24490 | /*
* HID Sensors Driver
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mfd/core.h>
#include <linux/list.h>
#include <linux/hid-sensor-ids.h>
#include <linux/hid-sensor-hub.h>
#include "hid-ids.h"
#define HID_SENSOR_HUB_ENUM_QUIRK 0x01
/**
* struct sensor_hub_data - Hold a instance data for a HID hub device
* @hsdev: Stored hid instance for current hub device.
* @mutex: Mutex to serialize synchronous request.
* @lock: Spin lock to protect pending request structure.
* @dyn_callback_list: Holds callback function
* @dyn_callback_lock: spin lock to protect callback list
* @hid_sensor_hub_client_devs: Stores all MFD cells for a hub instance.
* @hid_sensor_client_cnt: Number of MFD cells, (no of sensors attached).
* @ref_cnt: Number of MFD clients have opened this device
*/
struct sensor_hub_data {
struct mutex mutex;
spinlock_t lock;
struct list_head dyn_callback_list;
spinlock_t dyn_callback_lock;
struct mfd_cell *hid_sensor_hub_client_devs;
int hid_sensor_client_cnt;
unsigned long quirks;
int ref_cnt;
};
/**
* struct hid_sensor_hub_callbacks_list - Stores callback list
* @list: list head.
* @usage_id: usage id for a physical device.
* @usage_callback: Stores registered callback functions.
* @priv: Private data for a physical device.
*/
struct hid_sensor_hub_callbacks_list {
struct list_head list;
u32 usage_id;
struct hid_sensor_hub_device *hsdev;
struct hid_sensor_hub_callbacks *usage_callback;
void *priv;
};
static struct hid_report *sensor_hub_report(int id, struct hid_device *hdev,
int dir)
{
struct hid_report *report;
list_for_each_entry(report, &hdev->report_enum[dir].report_list, list) {
if (report->id == id)
return report;
}
hid_warn(hdev, "No report with id 0x%x found\n", id);
return NULL;
}
static int sensor_hub_get_physical_device_count(struct hid_device *hdev)
{
int i;
int count = 0;
for (i = 0; i < hdev->maxcollection; ++i) {
struct hid_collection *collection = &hdev->collection[i];
if (collection->type == HID_COLLECTION_PHYSICAL ||
collection->type == HID_COLLECTION_APPLICATION)
++count;
}
return count;
}
static void sensor_hub_fill_attr_info(
struct hid_sensor_hub_attribute_info *info,
s32 index, s32 report_id, struct hid_field *field)
{
info->index = index;
info->report_id = report_id;
info->units = field->unit;
info->unit_expo = field->unit_exponent;
info->size = (field->report_size * field->report_count)/8;
info->logical_minimum = field->logical_minimum;
info->logical_maximum = field->logical_maximum;
}
static struct hid_sensor_hub_callbacks *sensor_hub_get_callback(
struct hid_device *hdev,
u32 usage_id,
int collection_index,
struct hid_sensor_hub_device **hsdev,
void **priv)
{
struct hid_sensor_hub_callbacks_list *callback;
struct sensor_hub_data *pdata = hid_get_drvdata(hdev);
unsigned long flags;
spin_lock_irqsave(&pdata->dyn_callback_lock, flags);
list_for_each_entry(callback, &pdata->dyn_callback_list, list)
if ((callback->usage_id == usage_id ||
callback->usage_id == HID_USAGE_SENSOR_COLLECTION) &&
(collection_index >=
callback->hsdev->start_collection_index) &&
(collection_index <
callback->hsdev->end_collection_index)) {
*priv = callback->priv;
*hsdev = callback->hsdev;
spin_unlock_irqrestore(&pdata->dyn_callback_lock,
flags);
return callback->usage_callback;
}
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return NULL;
}
int sensor_hub_register_callback(struct hid_sensor_hub_device *hsdev,
u32 usage_id,
struct hid_sensor_hub_callbacks *usage_callback)
{
struct hid_sensor_hub_callbacks_list *callback;
struct sensor_hub_data *pdata = hid_get_drvdata(hsdev->hdev);
unsigned long flags;
spin_lock_irqsave(&pdata->dyn_callback_lock, flags);
list_for_each_entry(callback, &pdata->dyn_callback_list, list)
if (callback->usage_id == usage_id &&
callback->hsdev == hsdev) {
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return -EINVAL;
}
callback = kzalloc(sizeof(*callback), GFP_ATOMIC);
if (!callback) {
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return -ENOMEM;
}
callback->hsdev = hsdev;
callback->usage_callback = usage_callback;
callback->usage_id = usage_id;
callback->priv = NULL;
/*
* If there is a handler registered for the collection type, then
* it will handle all reports for sensors in this collection. If
* there is also an individual sensor handler registration, then
* we want to make sure that the reports are directed to collection
* handler, as this may be a fusion sensor. So add collection handlers
* to the beginning of the list, so that they are matched first.
*/
if (usage_id == HID_USAGE_SENSOR_COLLECTION)
list_add(&callback->list, &pdata->dyn_callback_list);
else
list_add_tail(&callback->list, &pdata->dyn_callback_list);
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(sensor_hub_register_callback);
int sensor_hub_remove_callback(struct hid_sensor_hub_device *hsdev,
u32 usage_id)
{
struct hid_sensor_hub_callbacks_list *callback;
struct sensor_hub_data *pdata = hid_get_drvdata(hsdev->hdev);
unsigned long flags;
spin_lock_irqsave(&pdata->dyn_callback_lock, flags);
list_for_each_entry(callback, &pdata->dyn_callback_list, list)
if (callback->usage_id == usage_id &&
callback->hsdev == hsdev) {
list_del(&callback->list);
kfree(callback);
break;
}
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(sensor_hub_remove_callback);
int sensor_hub_set_feature(struct hid_sensor_hub_device *hsdev, u32 report_id,
u32 field_index, int buffer_size, void *buffer)
{
struct hid_report *report;
struct sensor_hub_data *data = hid_get_drvdata(hsdev->hdev);
__s32 *buf32 = buffer;
int i = 0;
int remaining_bytes;
__s32 value;
int ret = 0;
mutex_lock(&data->mutex);
report = sensor_hub_report(report_id, hsdev->hdev, HID_FEATURE_REPORT);
if (!report || (field_index >= report->maxfield)) {
ret = -EINVAL;
goto done_proc;
}
remaining_bytes = buffer_size % sizeof(__s32);
buffer_size = buffer_size / sizeof(__s32);
if (buffer_size) {
for (i = 0; i < buffer_size; ++i) {
hid_set_field(report->field[field_index], i,
(__force __s32)cpu_to_le32(*buf32));
++buf32;
}
}
if (remaining_bytes) {
value = 0;
memcpy(&value, (u8 *)buf32, remaining_bytes);
hid_set_field(report->field[field_index], i,
(__force __s32)cpu_to_le32(value));
}
hid_hw_request(hsdev->hdev, report, HID_REQ_SET_REPORT);
hid_hw_wait(hsdev->hdev);
done_proc:
mutex_unlock(&data->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sensor_hub_set_feature);
int sensor_hub_get_feature(struct hid_sensor_hub_device *hsdev, u32 report_id,
u32 field_index, int buffer_size, void *buffer)
{
struct hid_report *report;
struct sensor_hub_data *data = hid_get_drvdata(hsdev->hdev);
int report_size;
int ret = 0;
mutex_lock(&data->mutex);
report = sensor_hub_report(report_id, hsdev->hdev, HID_FEATURE_REPORT);
if (!report || (field_index >= report->maxfield) ||
report->field[field_index]->report_count < 1) {
ret = -EINVAL;
goto done_proc;
}
hid_hw_request(hsdev->hdev, report, HID_REQ_GET_REPORT);
hid_hw_wait(hsdev->hdev);
/* calculate number of bytes required to read this field */
report_size = DIV_ROUND_UP(report->field[field_index]->report_size,
8) *
report->field[field_index]->report_count;
if (!report_size) {
ret = -EINVAL;
goto done_proc;
}
ret = min(report_size, buffer_size);
memcpy(buffer, report->field[field_index]->value, ret);
done_proc:
mutex_unlock(&data->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sensor_hub_get_feature);
int sensor_hub_input_attr_get_raw_value(struct hid_sensor_hub_device *hsdev,
u32 usage_id,
u32 attr_usage_id, u32 report_id,
enum sensor_hub_read_flags flag)
{
struct sensor_hub_data *data = hid_get_drvdata(hsdev->hdev);
unsigned long flags;
struct hid_report *report;
int ret_val = 0;
report = sensor_hub_report(report_id, hsdev->hdev,
HID_INPUT_REPORT);
if (!report)
return -EINVAL;
mutex_lock(hsdev->mutex_ptr);
if (flag == SENSOR_HUB_SYNC) {
memset(&hsdev->pending, 0, sizeof(hsdev->pending));
init_completion(&hsdev->pending.ready);
hsdev->pending.usage_id = usage_id;
hsdev->pending.attr_usage_id = attr_usage_id;
hsdev->pending.raw_size = 0;
spin_lock_irqsave(&data->lock, flags);
hsdev->pending.status = true;
spin_unlock_irqrestore(&data->lock, flags);
}
mutex_lock(&data->mutex);
hid_hw_request(hsdev->hdev, report, HID_REQ_GET_REPORT);
mutex_unlock(&data->mutex);
if (flag == SENSOR_HUB_SYNC) {
wait_for_completion_interruptible_timeout(
&hsdev->pending.ready, HZ*5);
switch (hsdev->pending.raw_size) {
case 1:
ret_val = *(u8 *)hsdev->pending.raw_data;
break;
case 2:
ret_val = *(u16 *)hsdev->pending.raw_data;
break;
case 4:
ret_val = *(u32 *)hsdev->pending.raw_data;
break;
default:
ret_val = 0;
}
kfree(hsdev->pending.raw_data);
hsdev->pending.status = false;
}
mutex_unlock(hsdev->mutex_ptr);
return ret_val;
}
EXPORT_SYMBOL_GPL(sensor_hub_input_attr_get_raw_value);
int hid_sensor_get_usage_index(struct hid_sensor_hub_device *hsdev,
u32 report_id, int field_index, u32 usage_id)
{
struct hid_report *report;
struct hid_field *field;
int i;
report = sensor_hub_report(report_id, hsdev->hdev, HID_FEATURE_REPORT);
if (!report || (field_index >= report->maxfield))
goto done_proc;
field = report->field[field_index];
for (i = 0; i < field->maxusage; ++i) {
if (field->usage[i].hid == usage_id)
return field->usage[i].usage_index;
}
done_proc:
return -EINVAL;
}
EXPORT_SYMBOL_GPL(hid_sensor_get_usage_index);
int sensor_hub_input_get_attribute_info(struct hid_sensor_hub_device *hsdev,
u8 type,
u32 usage_id,
u32 attr_usage_id,
struct hid_sensor_hub_attribute_info *info)
{
int ret = -1;
int i;
struct hid_report *report;
struct hid_field *field;
struct hid_report_enum *report_enum;
struct hid_device *hdev = hsdev->hdev;
/* Initialize with defaults */
info->usage_id = usage_id;
info->attrib_id = attr_usage_id;
info->report_id = -1;
info->index = -1;
info->units = -1;
info->unit_expo = -1;
report_enum = &hdev->report_enum[type];
list_for_each_entry(report, &report_enum->report_list, list) {
for (i = 0; i < report->maxfield; ++i) {
field = report->field[i];
if (field->maxusage) {
if (field->physical == usage_id &&
(field->logical == attr_usage_id ||
field->usage[0].hid ==
attr_usage_id) &&
(field->usage[0].collection_index >=
hsdev->start_collection_index) &&
(field->usage[0].collection_index <
hsdev->end_collection_index)) {
sensor_hub_fill_attr_info(info, i,
report->id,
field);
ret = 0;
break;
}
}
}
}
return ret;
}
EXPORT_SYMBOL_GPL(sensor_hub_input_get_attribute_info);
#ifdef CONFIG_PM
static int sensor_hub_suspend(struct hid_device *hdev, pm_message_t message)
{
struct sensor_hub_data *pdata = hid_get_drvdata(hdev);
struct hid_sensor_hub_callbacks_list *callback;
unsigned long flags;
hid_dbg(hdev, " sensor_hub_suspend\n");
spin_lock_irqsave(&pdata->dyn_callback_lock, flags);
list_for_each_entry(callback, &pdata->dyn_callback_list, list) {
if (callback->usage_callback->suspend)
callback->usage_callback->suspend(
callback->hsdev, callback->priv);
}
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return 0;
}
static int sensor_hub_resume(struct hid_device *hdev)
{
struct sensor_hub_data *pdata = hid_get_drvdata(hdev);
struct hid_sensor_hub_callbacks_list *callback;
unsigned long flags;
hid_dbg(hdev, " sensor_hub_resume\n");
spin_lock_irqsave(&pdata->dyn_callback_lock, flags);
list_for_each_entry(callback, &pdata->dyn_callback_list, list) {
if (callback->usage_callback->resume)
callback->usage_callback->resume(
callback->hsdev, callback->priv);
}
spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags);
return 0;
}
static int sensor_hub_reset_resume(struct hid_device *hdev)
{
return 0;
}
#endif
/*
* Handle raw report as sent by device
*/
static int sensor_hub_raw_event(struct hid_device *hdev,
struct hid_report *report, u8 *raw_data, int size)
{
int i;
u8 *ptr;
int sz;
struct sensor_hub_data *pdata = hid_get_drvdata(hdev);
unsigned long flags;
struct hid_sensor_hub_callbacks *callback = NULL;
struct hid_collection *collection = NULL;
void *priv = NULL;
struct hid_sensor_hub_device *hsdev = NULL;
hid_dbg(hdev, "sensor_hub_raw_event report id:0x%x size:%d type:%d\n",
report->id, size, report->type);
hid_dbg(hdev, "maxfield:%d\n", report->maxfield);
if (report->type != HID_INPUT_REPORT)
return 1;
ptr = raw_data;
ptr++; /* Skip report id */
spin_lock_irqsave(&pdata->lock, flags);
for (i = 0; i < report->maxfield; ++i) {
hid_dbg(hdev, "%d collection_index:%x hid:%x sz:%x\n",
i, report->field[i]->usage->collection_index,
report->field[i]->usage->hid,
(report->field[i]->report_size *
report->field[i]->report_count)/8);
sz = (report->field[i]->report_size *
report->field[i]->report_count)/8;
collection = &hdev->collection[
report->field[i]->usage->collection_index];
hid_dbg(hdev, "collection->usage %x\n",
collection->usage);
callback = sensor_hub_get_callback(hdev,
report->field[i]->physical,
report->field[i]->usage[0].collection_index,
&hsdev, &priv);
if (!callback) {
ptr += sz;
continue;
}
if (hsdev->pending.status && (hsdev->pending.attr_usage_id ==
report->field[i]->usage->hid ||
hsdev->pending.attr_usage_id ==
report->field[i]->logical)) {
hid_dbg(hdev, "data was pending ...\n");
hsdev->pending.raw_data = kmemdup(ptr, sz, GFP_ATOMIC);
if (hsdev->pending.raw_data)
hsdev->pending.raw_size = sz;
else
hsdev->pending.raw_size = 0;
complete(&hsdev->pending.ready);
}
if (callback->capture_sample) {
if (report->field[i]->logical)
callback->capture_sample(hsdev,
report->field[i]->logical, sz, ptr,
callback->pdev);
else
callback->capture_sample(hsdev,
report->field[i]->usage->hid, sz, ptr,
callback->pdev);
}
ptr += sz;
}
if (callback && collection && callback->send_event)
callback->send_event(hsdev, collection->usage,
callback->pdev);
spin_unlock_irqrestore(&pdata->lock, flags);
return 1;
}
int sensor_hub_device_open(struct hid_sensor_hub_device *hsdev)
{
int ret = 0;
struct sensor_hub_data *data = hid_get_drvdata(hsdev->hdev);
mutex_lock(&data->mutex);
if (!data->ref_cnt) {
ret = hid_hw_open(hsdev->hdev);
if (ret) {
hid_err(hsdev->hdev, "failed to open hid device\n");
mutex_unlock(&data->mutex);
return ret;
}
}
data->ref_cnt++;
mutex_unlock(&data->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(sensor_hub_device_open);
void sensor_hub_device_close(struct hid_sensor_hub_device *hsdev)
{
struct sensor_hub_data *data = hid_get_drvdata(hsdev->hdev);
mutex_lock(&data->mutex);
data->ref_cnt--;
if (!data->ref_cnt)
hid_hw_close(hsdev->hdev);
mutex_unlock(&data->mutex);
}
EXPORT_SYMBOL_GPL(sensor_hub_device_close);
static __u8 *sensor_hub_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
int index;
struct sensor_hub_data *sd = hid_get_drvdata(hdev);
unsigned char report_block[] = {
0x0a, 0x16, 0x03, 0x15, 0x00, 0x25, 0x05};
unsigned char power_block[] = {
0x0a, 0x19, 0x03, 0x15, 0x00, 0x25, 0x05};
if (!(sd->quirks & HID_SENSOR_HUB_ENUM_QUIRK)) {
hid_dbg(hdev, "No Enum quirks\n");
return rdesc;
}
/* Looks for power and report state usage id and force to 1 */
for (index = 0; index < *rsize; ++index) {
if (((*rsize - index) > sizeof(report_block)) &&
!memcmp(&rdesc[index], report_block,
sizeof(report_block))) {
rdesc[index + 4] = 0x01;
index += sizeof(report_block);
}
if (((*rsize - index) > sizeof(power_block)) &&
!memcmp(&rdesc[index], power_block,
sizeof(power_block))) {
rdesc[index + 4] = 0x01;
index += sizeof(power_block);
}
}
/* Checks if the report descriptor of Thinkpad Helix 2 has a logical
* minimum for magnetic flux axis greater than the maximum */
if (hdev->product == USB_DEVICE_ID_TEXAS_INSTRUMENTS_LENOVO_YOGA &&
*rsize == 2558 && rdesc[913] == 0x17 && rdesc[914] == 0x40 &&
rdesc[915] == 0x81 && rdesc[916] == 0x08 &&
rdesc[917] == 0x00 && rdesc[918] == 0x27 &&
rdesc[921] == 0x07 && rdesc[922] == 0x00) {
/* Sets negative logical minimum for mag x, y and z */
rdesc[914] = rdesc[935] = rdesc[956] = 0xc0;
rdesc[915] = rdesc[936] = rdesc[957] = 0x7e;
rdesc[916] = rdesc[937] = rdesc[958] = 0xf7;
rdesc[917] = rdesc[938] = rdesc[959] = 0xff;
}
return rdesc;
}
static int sensor_hub_probe(struct hid_device *hdev,
const struct hid_device_id *id)
{
int ret;
struct sensor_hub_data *sd;
int i;
char *name;
int dev_cnt;
struct hid_sensor_hub_device *hsdev;
struct hid_sensor_hub_device *last_hsdev = NULL;
struct hid_sensor_hub_device *collection_hsdev = NULL;
sd = devm_kzalloc(&hdev->dev, sizeof(*sd), GFP_KERNEL);
if (!sd) {
hid_err(hdev, "cannot allocate Sensor data\n");
return -ENOMEM;
}
hid_set_drvdata(hdev, sd);
sd->quirks = id->driver_data;
spin_lock_init(&sd->lock);
spin_lock_init(&sd->dyn_callback_lock);
mutex_init(&sd->mutex);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
return ret;
}
INIT_LIST_HEAD(&hdev->inputs);
ret = hid_hw_start(hdev, 0);
if (ret) {
hid_err(hdev, "hw start failed\n");
return ret;
}
INIT_LIST_HEAD(&sd->dyn_callback_list);
sd->hid_sensor_client_cnt = 0;
dev_cnt = sensor_hub_get_physical_device_count(hdev);
if (dev_cnt > HID_MAX_PHY_DEVICES) {
hid_err(hdev, "Invalid Physical device count\n");
ret = -EINVAL;
goto err_stop_hw;
}
sd->hid_sensor_hub_client_devs = devm_kzalloc(&hdev->dev, dev_cnt *
sizeof(struct mfd_cell),
GFP_KERNEL);
if (sd->hid_sensor_hub_client_devs == NULL) {
hid_err(hdev, "Failed to allocate memory for mfd cells\n");
ret = -ENOMEM;
goto err_stop_hw;
}
for (i = 0; i < hdev->maxcollection; ++i) {
struct hid_collection *collection = &hdev->collection[i];
if (collection->type == HID_COLLECTION_PHYSICAL ||
collection->type == HID_COLLECTION_APPLICATION) {
hsdev = devm_kzalloc(&hdev->dev, sizeof(*hsdev),
GFP_KERNEL);
if (!hsdev) {
hid_err(hdev, "cannot allocate hid_sensor_hub_device\n");
ret = -ENOMEM;
goto err_stop_hw;
}
hsdev->hdev = hdev;
hsdev->vendor_id = hdev->vendor;
hsdev->product_id = hdev->product;
hsdev->usage = collection->usage;
hsdev->mutex_ptr = devm_kzalloc(&hdev->dev,
sizeof(struct mutex),
GFP_KERNEL);
if (!hsdev->mutex_ptr) {
ret = -ENOMEM;
goto err_stop_hw;
}
mutex_init(hsdev->mutex_ptr);
hsdev->start_collection_index = i;
if (last_hsdev)
last_hsdev->end_collection_index = i;
last_hsdev = hsdev;
name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
"HID-SENSOR-%x",
collection->usage);
if (name == NULL) {
hid_err(hdev, "Failed MFD device name\n");
ret = -ENOMEM;
goto err_stop_hw;
}
sd->hid_sensor_hub_client_devs[
sd->hid_sensor_client_cnt].name = name;
sd->hid_sensor_hub_client_devs[
sd->hid_sensor_client_cnt].platform_data =
hsdev;
sd->hid_sensor_hub_client_devs[
sd->hid_sensor_client_cnt].pdata_size =
sizeof(*hsdev);
hid_dbg(hdev, "Adding %s:%d\n", name,
hsdev->start_collection_index);
sd->hid_sensor_client_cnt++;
if (collection_hsdev)
collection_hsdev->end_collection_index = i;
if (collection->type == HID_COLLECTION_APPLICATION &&
collection->usage == HID_USAGE_SENSOR_COLLECTION)
collection_hsdev = hsdev;
}
}
if (last_hsdev)
last_hsdev->end_collection_index = i;
if (collection_hsdev)
collection_hsdev->end_collection_index = i;
ret = mfd_add_hotplug_devices(&hdev->dev,
sd->hid_sensor_hub_client_devs,
sd->hid_sensor_client_cnt);
if (ret < 0)
goto err_stop_hw;
return ret;
err_stop_hw:
hid_hw_stop(hdev);
return ret;
}
static void sensor_hub_remove(struct hid_device *hdev)
{
struct sensor_hub_data *data = hid_get_drvdata(hdev);
unsigned long flags;
int i;
hid_dbg(hdev, " hardware removed\n");
hid_hw_close(hdev);
hid_hw_stop(hdev);
spin_lock_irqsave(&data->lock, flags);
for (i = 0; i < data->hid_sensor_client_cnt; ++i) {
struct hid_sensor_hub_device *hsdev =
data->hid_sensor_hub_client_devs[i].platform_data;
if (hsdev->pending.status)
complete(&hsdev->pending.ready);
}
spin_unlock_irqrestore(&data->lock, flags);
mfd_remove_devices(&hdev->dev);
hid_set_drvdata(hdev, NULL);
mutex_destroy(&data->mutex);
}
static const struct hid_device_id sensor_hub_devices[] = {
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_INTEL_0,
USB_DEVICE_ID_INTEL_HID_SENSOR_0),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_INTEL_1,
USB_DEVICE_ID_INTEL_HID_SENSOR_0),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_INTEL_1,
USB_DEVICE_ID_INTEL_HID_SENSOR_1),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_MICROSOFT,
USB_DEVICE_ID_MS_SURFACE_PRO_2),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_MICROSOFT,
USB_DEVICE_ID_MS_TOUCH_COVER_2),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_MICROSOFT,
USB_DEVICE_ID_MS_TYPE_COVER_2),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_STM_0,
USB_DEVICE_ID_STM_HID_SENSOR),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_STM_0,
USB_DEVICE_ID_STM_HID_SENSOR_1),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_TEXAS_INSTRUMENTS,
USB_DEVICE_ID_TEXAS_INSTRUMENTS_LENOVO_YOGA),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_ITE,
USB_DEVICE_ID_ITE_LENOVO_YOGA),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_ITE,
USB_DEVICE_ID_ITE_LENOVO_YOGA2),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_ITE,
USB_DEVICE_ID_ITE_LENOVO_YOGA900),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, USB_VENDOR_ID_INTEL_0,
0x22D8),
.driver_data = HID_SENSOR_HUB_ENUM_QUIRK},
{ HID_DEVICE(HID_BUS_ANY, HID_GROUP_SENSOR_HUB, HID_ANY_ID,
HID_ANY_ID) },
{ }
};
MODULE_DEVICE_TABLE(hid, sensor_hub_devices);
static struct hid_driver sensor_hub_driver = {
.name = "hid-sensor-hub",
.id_table = sensor_hub_devices,
.probe = sensor_hub_probe,
.remove = sensor_hub_remove,
.raw_event = sensor_hub_raw_event,
.report_fixup = sensor_hub_report_fixup,
#ifdef CONFIG_PM
.suspend = sensor_hub_suspend,
.resume = sensor_hub_resume,
.reset_resume = sensor_hub_reset_resume,
#endif
};
module_hid_driver(sensor_hub_driver);
MODULE_DESCRIPTION("HID Sensor Hub driver");
MODULE_AUTHOR("Srinivas Pandruvada <srinivas.pandruvada@intel.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ltangvald/mysql-5.5 | sql-common/pack.c | 22 | 2874 | /* Copyright (c) 2000-2003, 2007 MySQL AB
Use is subject to license terms
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
#include <my_global.h>
#include <mysql_com.h>
#include <mysql.h>
/* Get the length of next field. Change parameter to point at fieldstart */
ulong STDCALL net_field_length(uchar **packet)
{
reg1 uchar *pos= (uchar *)*packet;
if (*pos < 251)
{
(*packet)++;
return (ulong) *pos;
}
if (*pos == 251)
{
(*packet)++;
return NULL_LENGTH;
}
if (*pos == 252)
{
(*packet)+=3;
return (ulong) uint2korr(pos+1);
}
if (*pos == 253)
{
(*packet)+=4;
return (ulong) uint3korr(pos+1);
}
(*packet)+=9; /* Must be 254 when here */
return (ulong) uint4korr(pos+1);
}
/* The same as above but returns longlong */
my_ulonglong net_field_length_ll(uchar **packet)
{
reg1 uchar *pos= *packet;
if (*pos < 251)
{
(*packet)++;
return (my_ulonglong) *pos;
}
if (*pos == 251)
{
(*packet)++;
return (my_ulonglong) NULL_LENGTH;
}
if (*pos == 252)
{
(*packet)+=3;
return (my_ulonglong) uint2korr(pos+1);
}
if (*pos == 253)
{
(*packet)+=4;
return (my_ulonglong) uint3korr(pos+1);
}
(*packet)+=9; /* Must be 254 when here */
#ifdef NO_CLIENT_LONGLONG
return (my_ulonglong) uint4korr(pos+1);
#else
return (my_ulonglong) uint8korr(pos+1);
#endif
}
/*
Store an integer with simple packing into a output package
SYNOPSIS
net_store_length()
pkg Store the packed integer here
length integers to store
NOTES
This is mostly used to store lengths of strings.
We have to cast the result for the LL() becasue of a bug in Forte CC
compiler.
RETURN
Position in 'pkg' after the packed length
*/
uchar *net_store_length(uchar *packet, ulonglong length)
{
if (length < (ulonglong) LL(251))
{
*packet=(uchar) length;
return packet+1;
}
/* 251 is reserved for NULL */
if (length < (ulonglong) LL(65536))
{
*packet++=252;
int2store(packet,(uint) length);
return packet+2;
}
if (length < (ulonglong) LL(16777216))
{
*packet++=253;
int3store(packet,(ulong) length);
return packet+3;
}
*packet++=254;
int8store(packet,length);
return packet+8;
}
| gpl-2.0 |
tonychee7000/lmms | plugins/LadspaEffect/LadspaEffect.cpp | 22 | 13876 | /*
* LadspaEffect.cpp - class for processing LADSPA effects
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - http://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QMessageBox>
#include "LadspaEffect.h"
#include "DataFile.h"
#include "AudioDevice.h"
#include "ConfigManager.h"
#include "Ladspa2LMMS.h"
#include "LadspaControl.h"
#include "LadspaSubPluginFeatures.h"
#include "Mixer.h"
#include "EffectChain.h"
#include "AutomationPattern.h"
#include "ControllerConnection.h"
#include "MemoryManager.h"
#include "ValueBuffer.h"
#include "Song.h"
#include "embed.cpp"
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT ladspaeffect_plugin_descriptor =
{
STRINGIFY( PLUGIN_NAME ),
"LADSPA",
QT_TRANSLATE_NOOP( "pluginBrowser",
"plugin for using arbitrary LADSPA-effects "
"inside LMMS." ),
"Danny McRae <khjklujn/at/users.sourceforge.net>",
0x0100,
Plugin::Effect,
new PluginPixmapLoader( "logo" ),
NULL,
new LadspaSubPluginFeatures( Plugin::Effect )
} ;
}
LadspaEffect::LadspaEffect( Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &ladspaeffect_plugin_descriptor, _parent, _key ),
m_controls( NULL ),
m_maxSampleRate( 0 ),
m_key( LadspaSubPluginFeatures::subPluginKeyToLadspaKey( _key ) )
{
Ladspa2LMMS * manager = Engine::getLADSPAManager();
if( manager->getDescription( m_key ) == NULL )
{
Engine::getSong()->collectError(tr( "Unknown LADSPA plugin %1 requested." ).arg(
m_key.second ) );
setOkay( false );
return;
}
setDisplayName( manager->getShortName( m_key ) );
pluginInstantiation();
connect( Engine::mixer(), SIGNAL( sampleRateChanged() ),
this, SLOT( changeSampleRate() ) );
}
LadspaEffect::~LadspaEffect()
{
pluginDestruction();
}
void LadspaEffect::changeSampleRate()
{
DataFile dataFile( DataFile::EffectSettings );
m_controls->saveState( dataFile, dataFile.content() );
LadspaControls * controls = m_controls;
m_controls = NULL;
m_pluginMutex.lock();
pluginDestruction();
pluginInstantiation();
m_pluginMutex.unlock();
controls->effectModelChanged( m_controls );
delete controls;
m_controls->restoreState( dataFile.content().firstChild().toElement() );
// the IDs of re-created controls have been saved and now need to be
// resolved again
AutomationPattern::resolveAllIDs();
// make sure, connections are ok
ControllerConnection::finalizeConnections();
}
bool LadspaEffect::processAudioBuffer( sampleFrame * _buf,
const fpp_t _frames )
{
m_pluginMutex.lock();
if( !isOkay() || dontRun() || !isRunning() || !isEnabled() )
{
m_pluginMutex.unlock();
return( false );
}
int frames = _frames;
sampleFrame * o_buf = NULL;
sampleFrame sBuf [_frames];
if( m_maxSampleRate < Engine::mixer()->processingSampleRate() )
{
o_buf = _buf;
_buf = &sBuf[0];
sampleDown( o_buf, _buf, m_maxSampleRate );
frames = _frames * m_maxSampleRate /
Engine::mixer()->processingSampleRate();
}
// Copy the LMMS audio buffer to the LADSPA input buffer and initialize
// the control ports.
ch_cnt_t channel = 0;
for( ch_cnt_t proc = 0; proc < processorCount(); ++proc )
{
for( int port = 0; port < m_portCount; ++port )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
switch( pp->rate )
{
case CHANNEL_IN:
for( fpp_t frame = 0;
frame < frames; ++frame )
{
pp->buffer[frame] =
_buf[frame][channel];
}
++channel;
break;
case AUDIO_RATE_INPUT:
{
ValueBuffer * vb = pp->control->valueBuffer();
if( vb )
{
memcpy( pp->buffer, vb->values(), frames * sizeof(float) );
}
else
{
pp->value = static_cast<LADSPA_Data>(
pp->control->value() / pp->scale );
// This only supports control rate ports, so the audio rates are
// treated as though they were control rate by setting the
// port buffer to all the same value.
for( fpp_t frame = 0;
frame < frames; ++frame )
{
pp->buffer[frame] =
pp->value;
}
}
break;
}
case CONTROL_RATE_INPUT:
if( pp->control == NULL )
{
break;
}
pp->value = static_cast<LADSPA_Data>(
pp->control->value() / pp->scale );
pp->buffer[0] =
pp->value;
break;
case CHANNEL_OUT:
case AUDIO_RATE_OUTPUT:
case CONTROL_RATE_OUTPUT:
break;
default:
break;
}
}
}
// Process the buffers.
for( ch_cnt_t proc = 0; proc < processorCount(); ++proc )
{
(m_descriptor->run)( m_handles[proc], frames );
}
// Copy the LADSPA output buffers to the LMMS buffer.
double out_sum = 0.0;
channel = 0;
const float d = dryLevel();
const float w = wetLevel();
for( ch_cnt_t proc = 0; proc < processorCount(); ++proc )
{
for( int port = 0; port < m_portCount; ++port )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
switch( pp->rate )
{
case CHANNEL_IN:
case AUDIO_RATE_INPUT:
case CONTROL_RATE_INPUT:
break;
case CHANNEL_OUT:
for( fpp_t frame = 0;
frame < frames; ++frame )
{
_buf[frame][channel] = d * _buf[frame][channel] + w * pp->buffer[frame];
out_sum += _buf[frame][channel] * _buf[frame][channel];
}
++channel;
break;
case AUDIO_RATE_OUTPUT:
case CONTROL_RATE_OUTPUT:
break;
default:
break;
}
}
}
if( o_buf != NULL )
{
sampleBack( _buf, o_buf, m_maxSampleRate );
}
checkGate( out_sum / frames );
bool is_running = isRunning();
m_pluginMutex.unlock();
return( is_running );
}
void LadspaEffect::setControl( int _control, LADSPA_Data _value )
{
if( !isOkay() )
{
return;
}
m_portControls[_control]->value = _value;
}
void LadspaEffect::pluginInstantiation()
{
m_maxSampleRate = maxSamplerate( displayName() );
Ladspa2LMMS * manager = Engine::getLADSPAManager();
// Calculate how many processing units are needed.
const ch_cnt_t lmms_chnls = Engine::mixer()->audioDev()->channels();
int effect_channels = manager->getDescription( m_key )->inputChannels;
setProcessorCount( lmms_chnls / effect_channels );
// get inPlaceBroken property
m_inPlaceBroken = manager->isInplaceBroken( m_key );
// Categorize the ports, and create the buffers.
m_portCount = manager->getPortCount( m_key );
int inputch = 0;
int outputch = 0;
LADSPA_Data * inbuf [2];
inbuf[0] = NULL;
inbuf[1] = NULL;
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
multi_proc_t ports;
for( int port = 0; port < m_portCount; port++ )
{
port_desc_t * p = new PortDescription;
p->name = manager->getPortName( m_key, port );
p->proc = proc;
p->port_id = port;
p->control = NULL;
p->buffer = NULL;
// Determine the port's category.
if( manager->isPortAudio( m_key, port ) )
{
if( p->name.toUpper().contains( "IN" ) &&
manager->isPortInput( m_key, port ) )
{
p->rate = CHANNEL_IN;
p->buffer = MM_ALLOC( LADSPA_Data, Engine::mixer()->framesPerPeriod() );
inbuf[ inputch ] = p->buffer;
inputch++;
}
else if( p->name.toUpper().contains( "OUT" ) &&
manager->isPortOutput( m_key, port ) )
{
p->rate = CHANNEL_OUT;
if( ! m_inPlaceBroken && inbuf[ outputch ] )
{
p->buffer = inbuf[ outputch ];
outputch++;
}
else
{
p->buffer = MM_ALLOC( LADSPA_Data, Engine::mixer()->framesPerPeriod() );
m_inPlaceBroken = true;
}
}
else if( manager->isPortInput( m_key, port ) )
{
p->rate = AUDIO_RATE_INPUT;
p->buffer = MM_ALLOC( LADSPA_Data, Engine::mixer()->framesPerPeriod() );
}
else
{
p->rate = AUDIO_RATE_OUTPUT;
p->buffer = MM_ALLOC( LADSPA_Data, Engine::mixer()->framesPerPeriod() );
}
}
else
{
p->buffer = MM_ALLOC( LADSPA_Data, 1 );
if( manager->isPortInput( m_key, port ) )
{
p->rate = CONTROL_RATE_INPUT;
}
else
{
p->rate = CONTROL_RATE_OUTPUT;
}
}
p->scale = 1.0f;
if( manager->isPortToggled( m_key, port ) )
{
p->data_type = TOGGLED;
}
else if( manager->isInteger( m_key, port ) )
{
p->data_type = INTEGER;
}
else if( p->name.toUpper().contains( "(SECONDS)" ) )
{
p->data_type = TIME;
p->scale = 1000.0f;
int loc = p->name.toUpper().indexOf(
"(SECONDS)" );
p->name.replace( loc, 9, "(ms)" );
}
else if( p->name.toUpper().contains( "(S)" ) )
{
p->data_type = TIME;
p->scale = 1000.0f;
int loc = p->name.toUpper().indexOf( "(S)" );
p->name.replace( loc, 3, "(ms)" );
}
else if( p->name.toUpper().contains( "(MS)" ) )
{
p->data_type = TIME;
int loc = p->name.toUpper().indexOf( "(MS)" );
p->name.replace( loc, 4, "(ms)" );
}
else
{
p->data_type = FLOATING;
}
// Get the range and default values.
p->max = manager->getUpperBound( m_key, port );
if( p->max == NOHINT )
{
p->max = p->name.toUpper() == "GAIN" ? 10.0f :
1.0f;
}
if( manager->areHintsSampleRateDependent(
m_key, port ) )
{
p->max *= m_maxSampleRate;
}
p->min = manager->getLowerBound( m_key, port );
if( p->min == NOHINT )
{
p->min = 0.0f;
}
if( manager->areHintsSampleRateDependent(
m_key, port ) )
{
p->min *= m_maxSampleRate;
}
p->def = manager->getDefaultSetting( m_key, port );
if( p->def == NOHINT )
{
if( p->data_type != TOGGLED )
{
p->def = ( p->min + p->max ) / 2.0f;
}
else
{
p->def = 1.0f;
}
}
else if( manager->areHintsSampleRateDependent( m_key, port ) )
{
p->def *= m_maxSampleRate;
}
p->max *= p->scale;
p->min *= p->scale;
p->def *= p->scale;
p->value = p->def;
p->suggests_logscale = manager->isLogarithmic( m_key, port );
ports.append( p );
// For convenience, keep a separate list of the ports that are used
// to control the processors.
if( p->rate == AUDIO_RATE_INPUT ||
p->rate == CONTROL_RATE_INPUT )
{
p->control_id = m_portControls.count();
m_portControls.append( p );
}
}
m_ports.append( ports );
}
// Instantiate the processing units.
m_descriptor = manager->getDescriptor( m_key );
if( m_descriptor == NULL )
{
QMessageBox::warning( 0, "Effect",
"Can't get LADSPA descriptor function: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setOkay( false );
return;
}
if( m_descriptor->run == NULL )
{
QMessageBox::warning( 0, "Effect",
"Plugin has no processor: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setDontRun( true );
}
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
LADSPA_Handle effect = manager->instantiate( m_key,
m_maxSampleRate );
if( effect == NULL )
{
QMessageBox::warning( 0, "Effect",
"Can't get LADSPA instance: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setOkay( false );
return;
}
m_handles.append( effect );
}
// Connect the ports.
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
for( int port = 0; port < m_portCount; port++ )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
if( !manager->connectPort( m_key,
m_handles[proc],
port,
pp->buffer ) )
{
QMessageBox::warning( 0, "Effect",
"Failed to connect port: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setDontRun( true );
return;
}
}
}
// Activate the processing units.
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
manager->activate( m_key, m_handles[proc] );
}
m_controls = new LadspaControls( this );
}
void LadspaEffect::pluginDestruction()
{
if( !isOkay() )
{
return;
}
delete m_controls;
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
Ladspa2LMMS * manager = Engine::getLADSPAManager();
manager->deactivate( m_key, m_handles[proc] );
manager->cleanup( m_key, m_handles[proc] );
for( int port = 0; port < m_portCount; port++ )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
if( m_inPlaceBroken || pp->rate != CHANNEL_OUT )
{
if( pp->buffer) MM_FREE( pp->buffer );
}
delete pp;
}
m_ports[proc].clear();
}
m_ports.clear();
m_handles.clear();
m_portControls.clear();
}
static QMap<QString, sample_rate_t> __buggy_plugins;
sample_rate_t LadspaEffect::maxSamplerate( const QString & _name )
{
if( __buggy_plugins.isEmpty() )
{
__buggy_plugins["C* AmpVTS"] = 88200;
__buggy_plugins["Chorus2"] = 44100;
__buggy_plugins["Notch Filter"] = 96000;
__buggy_plugins["TAP Reflector"] = 192000;
}
if( __buggy_plugins.contains( _name ) )
{
return( __buggy_plugins[_name] );
}
return( Engine::mixer()->processingSampleRate() );
}
extern "C"
{
// necessary for getting instance out of shared lib
Plugin * PLUGIN_EXPORT lmms_plugin_main( Model * _parent, void * _data )
{
return new LadspaEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) );
}
}
| gpl-2.0 |
loongson-community/linux_loongson | drivers/scsi/sun3x_esp.c | 22 | 7377 | /* sun3x_esp.c: ESP front-end for Sun3x systems.
*
* Copyright (C) 2007,2008 Thomas Bogendoerfer (tsbogend@alpha.franken.de)
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <asm/sun3x.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/dvma.h>
/* DMA controller reg offsets */
#define DMA_CSR 0x00UL /* rw DMA control/status register 0x00 */
#define DMA_ADDR 0x04UL /* rw DMA transfer address register 0x04 */
#define DMA_COUNT 0x08UL /* rw DMA transfer count register 0x08 */
#define DMA_TEST 0x0cUL /* rw DMA test/debug register 0x0c */
#include <scsi/scsi_host.h>
#include "esp_scsi.h"
#define DRV_MODULE_NAME "sun3x_esp"
#define PFX DRV_MODULE_NAME ": "
#define DRV_VERSION "1.000"
#define DRV_MODULE_RELDATE "Nov 1, 2007"
/*
* m68k always assumes readl/writel operate on little endian
* mmio space; this is wrong at least for Sun3x, so we
* need to workaround this until a proper way is found
*/
#if 0
#define dma_read32(REG) \
readl(esp->dma_regs + (REG))
#define dma_write32(VAL, REG) \
writel((VAL), esp->dma_regs + (REG))
#else
#define dma_read32(REG) \
*(volatile u32 *)(esp->dma_regs + (REG))
#define dma_write32(VAL, REG) \
do { *(volatile u32 *)(esp->dma_regs + (REG)) = (VAL); } while (0)
#endif
static void sun3x_esp_write8(struct esp *esp, u8 val, unsigned long reg)
{
writeb(val, esp->regs + (reg * 4UL));
}
static u8 sun3x_esp_read8(struct esp *esp, unsigned long reg)
{
return readb(esp->regs + (reg * 4UL));
}
static dma_addr_t sun3x_esp_map_single(struct esp *esp, void *buf,
size_t sz, int dir)
{
return dma_map_single(esp->dev, buf, sz, dir);
}
static int sun3x_esp_map_sg(struct esp *esp, struct scatterlist *sg,
int num_sg, int dir)
{
return dma_map_sg(esp->dev, sg, num_sg, dir);
}
static void sun3x_esp_unmap_single(struct esp *esp, dma_addr_t addr,
size_t sz, int dir)
{
dma_unmap_single(esp->dev, addr, sz, dir);
}
static void sun3x_esp_unmap_sg(struct esp *esp, struct scatterlist *sg,
int num_sg, int dir)
{
dma_unmap_sg(esp->dev, sg, num_sg, dir);
}
static int sun3x_esp_irq_pending(struct esp *esp)
{
if (dma_read32(DMA_CSR) & (DMA_HNDL_INTR | DMA_HNDL_ERROR))
return 1;
return 0;
}
static void sun3x_esp_reset_dma(struct esp *esp)
{
u32 val;
val = dma_read32(DMA_CSR);
dma_write32(val | DMA_RST_SCSI, DMA_CSR);
dma_write32(val & ~DMA_RST_SCSI, DMA_CSR);
/* Enable interrupts. */
val = dma_read32(DMA_CSR);
dma_write32(val | DMA_INT_ENAB, DMA_CSR);
}
static void sun3x_esp_dma_drain(struct esp *esp)
{
u32 csr;
int lim;
csr = dma_read32(DMA_CSR);
if (!(csr & DMA_FIFO_ISDRAIN))
return;
dma_write32(csr | DMA_FIFO_STDRAIN, DMA_CSR);
lim = 1000;
while (dma_read32(DMA_CSR) & DMA_FIFO_ISDRAIN) {
if (--lim == 0) {
printk(KERN_ALERT PFX "esp%d: DMA will not drain!\n",
esp->host->unique_id);
break;
}
udelay(1);
}
}
static void sun3x_esp_dma_invalidate(struct esp *esp)
{
u32 val;
int lim;
lim = 1000;
while ((val = dma_read32(DMA_CSR)) & DMA_PEND_READ) {
if (--lim == 0) {
printk(KERN_ALERT PFX "esp%d: DMA will not "
"invalidate!\n", esp->host->unique_id);
break;
}
udelay(1);
}
val &= ~(DMA_ENABLE | DMA_ST_WRITE | DMA_BCNT_ENAB);
val |= DMA_FIFO_INV;
dma_write32(val, DMA_CSR);
val &= ~DMA_FIFO_INV;
dma_write32(val, DMA_CSR);
}
static void sun3x_esp_send_dma_cmd(struct esp *esp, u32 addr, u32 esp_count,
u32 dma_count, int write, u8 cmd)
{
u32 csr;
BUG_ON(!(cmd & ESP_CMD_DMA));
sun3x_esp_write8(esp, (esp_count >> 0) & 0xff, ESP_TCLOW);
sun3x_esp_write8(esp, (esp_count >> 8) & 0xff, ESP_TCMED);
csr = dma_read32(DMA_CSR);
csr |= DMA_ENABLE;
if (write)
csr |= DMA_ST_WRITE;
else
csr &= ~DMA_ST_WRITE;
dma_write32(csr, DMA_CSR);
dma_write32(addr, DMA_ADDR);
scsi_esp_cmd(esp, cmd);
}
static int sun3x_esp_dma_error(struct esp *esp)
{
u32 csr = dma_read32(DMA_CSR);
if (csr & DMA_HNDL_ERROR)
return 1;
return 0;
}
static const struct esp_driver_ops sun3x_esp_ops = {
.esp_write8 = sun3x_esp_write8,
.esp_read8 = sun3x_esp_read8,
.map_single = sun3x_esp_map_single,
.map_sg = sun3x_esp_map_sg,
.unmap_single = sun3x_esp_unmap_single,
.unmap_sg = sun3x_esp_unmap_sg,
.irq_pending = sun3x_esp_irq_pending,
.reset_dma = sun3x_esp_reset_dma,
.dma_drain = sun3x_esp_dma_drain,
.dma_invalidate = sun3x_esp_dma_invalidate,
.send_dma_cmd = sun3x_esp_send_dma_cmd,
.dma_error = sun3x_esp_dma_error,
};
static int __devinit esp_sun3x_probe(struct platform_device *dev)
{
struct scsi_host_template *tpnt = &scsi_esp_template;
struct Scsi_Host *host;
struct esp *esp;
struct resource *res;
int err = -ENOMEM;
host = scsi_host_alloc(tpnt, sizeof(struct esp));
if (!host)
goto fail;
host->max_id = 8;
esp = shost_priv(host);
esp->host = host;
esp->dev = dev;
esp->ops = &sun3x_esp_ops;
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (!res && !res->start)
goto fail_unlink;
esp->regs = ioremap_nocache(res->start, 0x20);
if (!esp->regs)
goto fail_unmap_regs;
res = platform_get_resource(dev, IORESOURCE_MEM, 1);
if (!res && !res->start)
goto fail_unmap_regs;
esp->dma_regs = ioremap_nocache(res->start, 0x10);
esp->command_block = dma_alloc_coherent(esp->dev, 16,
&esp->command_block_dma,
GFP_KERNEL);
if (!esp->command_block)
goto fail_unmap_regs_dma;
host->irq = platform_get_irq(dev, 0);
err = request_irq(host->irq, scsi_esp_intr, IRQF_SHARED,
"SUN3X ESP", esp);
if (err < 0)
goto fail_unmap_command_block;
esp->scsi_id = 7;
esp->host->this_id = esp->scsi_id;
esp->scsi_id_mask = (1 << esp->scsi_id);
esp->cfreq = 20000000;
dev_set_drvdata(&dev->dev, esp);
err = scsi_esp_register(esp, &dev->dev);
if (err)
goto fail_free_irq;
return 0;
fail_free_irq:
free_irq(host->irq, esp);
fail_unmap_command_block:
dma_free_coherent(esp->dev, 16,
esp->command_block,
esp->command_block_dma);
fail_unmap_regs_dma:
iounmap(esp->dma_regs);
fail_unmap_regs:
iounmap(esp->regs);
fail_unlink:
scsi_host_put(host);
fail:
return err;
}
static int __devexit esp_sun3x_remove(struct platform_device *dev)
{
struct esp *esp = dev_get_drvdata(&dev->dev);
unsigned int irq = esp->host->irq;
u32 val;
scsi_esp_unregister(esp);
/* Disable interrupts. */
val = dma_read32(DMA_CSR);
dma_write32(val & ~DMA_INT_ENAB, DMA_CSR);
free_irq(irq, esp);
dma_free_coherent(esp->dev, 16,
esp->command_block,
esp->command_block_dma);
scsi_host_put(esp->host);
return 0;
}
static struct platform_driver esp_sun3x_driver = {
.probe = esp_sun3x_probe,
.remove = __devexit_p(esp_sun3x_remove),
.driver = {
.name = "sun3x_esp",
.owner = THIS_MODULE,
},
};
static int __init sun3x_esp_init(void)
{
return platform_driver_register(&esp_sun3x_driver);
}
static void __exit sun3x_esp_exit(void)
{
platform_driver_unregister(&esp_sun3x_driver);
}
MODULE_DESCRIPTION("Sun3x ESP SCSI driver");
MODULE_AUTHOR("Thomas Bogendoerfer (tsbogend@alpha.franken.de)");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
module_init(sun3x_esp_init);
module_exit(sun3x_esp_exit);
MODULE_ALIAS("platform:sun3x_esp");
| gpl-2.0 |
jabez1314/linux | drivers/iommu/amd_iommu_init.c | 22 | 64166 | /*
* Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
* Author: Joerg Roedel <jroedel@suse.de>
* Leo Duran <leo.duran@amd.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/pci.h>
#include <linux/acpi.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/syscore_ops.h>
#include <linux/interrupt.h>
#include <linux/msi.h>
#include <linux/amd-iommu.h>
#include <linux/export.h>
#include <linux/iommu.h>
#include <asm/pci-direct.h>
#include <asm/iommu.h>
#include <asm/gart.h>
#include <asm/x86_init.h>
#include <asm/iommu_table.h>
#include <asm/io_apic.h>
#include <asm/irq_remapping.h>
#include "amd_iommu_proto.h"
#include "amd_iommu_types.h"
#include "irq_remapping.h"
/*
* definitions for the ACPI scanning code
*/
#define IVRS_HEADER_LENGTH 48
#define ACPI_IVHD_TYPE_MAX_SUPPORTED 0x40
#define ACPI_IVMD_TYPE_ALL 0x20
#define ACPI_IVMD_TYPE 0x21
#define ACPI_IVMD_TYPE_RANGE 0x22
#define IVHD_DEV_ALL 0x01
#define IVHD_DEV_SELECT 0x02
#define IVHD_DEV_SELECT_RANGE_START 0x03
#define IVHD_DEV_RANGE_END 0x04
#define IVHD_DEV_ALIAS 0x42
#define IVHD_DEV_ALIAS_RANGE 0x43
#define IVHD_DEV_EXT_SELECT 0x46
#define IVHD_DEV_EXT_SELECT_RANGE 0x47
#define IVHD_DEV_SPECIAL 0x48
#define IVHD_DEV_ACPI_HID 0xf0
#define UID_NOT_PRESENT 0
#define UID_IS_INTEGER 1
#define UID_IS_CHARACTER 2
#define IVHD_SPECIAL_IOAPIC 1
#define IVHD_SPECIAL_HPET 2
#define IVHD_FLAG_HT_TUN_EN_MASK 0x01
#define IVHD_FLAG_PASSPW_EN_MASK 0x02
#define IVHD_FLAG_RESPASSPW_EN_MASK 0x04
#define IVHD_FLAG_ISOC_EN_MASK 0x08
#define IVMD_FLAG_EXCL_RANGE 0x08
#define IVMD_FLAG_UNITY_MAP 0x01
#define ACPI_DEVFLAG_INITPASS 0x01
#define ACPI_DEVFLAG_EXTINT 0x02
#define ACPI_DEVFLAG_NMI 0x04
#define ACPI_DEVFLAG_SYSMGT1 0x10
#define ACPI_DEVFLAG_SYSMGT2 0x20
#define ACPI_DEVFLAG_LINT0 0x40
#define ACPI_DEVFLAG_LINT1 0x80
#define ACPI_DEVFLAG_ATSDIS 0x10000000
/*
* ACPI table definitions
*
* These data structures are laid over the table to parse the important values
* out of it.
*/
/*
* structure describing one IOMMU in the ACPI table. Typically followed by one
* or more ivhd_entrys.
*/
struct ivhd_header {
u8 type;
u8 flags;
u16 length;
u16 devid;
u16 cap_ptr;
u64 mmio_phys;
u16 pci_seg;
u16 info;
u32 efr_attr;
/* Following only valid on IVHD type 11h and 40h */
u64 efr_reg; /* Exact copy of MMIO_EXT_FEATURES */
u64 res;
} __attribute__((packed));
/*
* A device entry describing which devices a specific IOMMU translates and
* which requestor ids they use.
*/
struct ivhd_entry {
u8 type;
u16 devid;
u8 flags;
u32 ext;
u32 hidh;
u64 cid;
u8 uidf;
u8 uidl;
u8 uid;
} __attribute__((packed));
/*
* An AMD IOMMU memory definition structure. It defines things like exclusion
* ranges for devices and regions that should be unity mapped.
*/
struct ivmd_header {
u8 type;
u8 flags;
u16 length;
u16 devid;
u16 aux;
u64 resv;
u64 range_start;
u64 range_length;
} __attribute__((packed));
bool amd_iommu_dump;
bool amd_iommu_irq_remap __read_mostly;
static bool amd_iommu_detected;
static bool __initdata amd_iommu_disabled;
static int amd_iommu_target_ivhd_type;
u16 amd_iommu_last_bdf; /* largest PCI device id we have
to handle */
LIST_HEAD(amd_iommu_unity_map); /* a list of required unity mappings
we find in ACPI */
bool amd_iommu_unmap_flush; /* if true, flush on every unmap */
LIST_HEAD(amd_iommu_list); /* list of all AMD IOMMUs in the
system */
/* Array to assign indices to IOMMUs*/
struct amd_iommu *amd_iommus[MAX_IOMMUS];
int amd_iommus_present;
/* IOMMUs have a non-present cache? */
bool amd_iommu_np_cache __read_mostly;
bool amd_iommu_iotlb_sup __read_mostly = true;
u32 amd_iommu_max_pasid __read_mostly = ~0;
bool amd_iommu_v2_present __read_mostly;
static bool amd_iommu_pc_present __read_mostly;
bool amd_iommu_force_isolation __read_mostly;
/*
* List of protection domains - used during resume
*/
LIST_HEAD(amd_iommu_pd_list);
spinlock_t amd_iommu_pd_lock;
/*
* Pointer to the device table which is shared by all AMD IOMMUs
* it is indexed by the PCI device id or the HT unit id and contains
* information about the domain the device belongs to as well as the
* page table root pointer.
*/
struct dev_table_entry *amd_iommu_dev_table;
/*
* The alias table is a driver specific data structure which contains the
* mappings of the PCI device ids to the actual requestor ids on the IOMMU.
* More than one device can share the same requestor id.
*/
u16 *amd_iommu_alias_table;
/*
* The rlookup table is used to find the IOMMU which is responsible
* for a specific device. It is also indexed by the PCI device id.
*/
struct amd_iommu **amd_iommu_rlookup_table;
/*
* This table is used to find the irq remapping table for a given device id
* quickly.
*/
struct irq_remap_table **irq_lookup_table;
/*
* AMD IOMMU allows up to 2^16 different protection domains. This is a bitmap
* to know which ones are already in use.
*/
unsigned long *amd_iommu_pd_alloc_bitmap;
static u32 dev_table_size; /* size of the device table */
static u32 alias_table_size; /* size of the alias table */
static u32 rlookup_table_size; /* size if the rlookup table */
enum iommu_init_state {
IOMMU_START_STATE,
IOMMU_IVRS_DETECTED,
IOMMU_ACPI_FINISHED,
IOMMU_ENABLED,
IOMMU_PCI_INIT,
IOMMU_INTERRUPTS_EN,
IOMMU_DMA_OPS,
IOMMU_INITIALIZED,
IOMMU_NOT_FOUND,
IOMMU_INIT_ERROR,
};
/* Early ioapic and hpet maps from kernel command line */
#define EARLY_MAP_SIZE 4
static struct devid_map __initdata early_ioapic_map[EARLY_MAP_SIZE];
static struct devid_map __initdata early_hpet_map[EARLY_MAP_SIZE];
static struct acpihid_map_entry __initdata early_acpihid_map[EARLY_MAP_SIZE];
static int __initdata early_ioapic_map_size;
static int __initdata early_hpet_map_size;
static int __initdata early_acpihid_map_size;
static bool __initdata cmdline_maps;
static enum iommu_init_state init_state = IOMMU_START_STATE;
static int amd_iommu_enable_interrupts(void);
static int __init iommu_go_to_state(enum iommu_init_state state);
static void init_device_table_dma(void);
static int iommu_pc_get_set_reg_val(struct amd_iommu *iommu,
u8 bank, u8 cntr, u8 fxn,
u64 *value, bool is_write);
static inline void update_last_devid(u16 devid)
{
if (devid > amd_iommu_last_bdf)
amd_iommu_last_bdf = devid;
}
static inline unsigned long tbl_size(int entry_size)
{
unsigned shift = PAGE_SHIFT +
get_order(((int)amd_iommu_last_bdf + 1) * entry_size);
return 1UL << shift;
}
/* Access to l1 and l2 indexed register spaces */
static u32 iommu_read_l1(struct amd_iommu *iommu, u16 l1, u8 address)
{
u32 val;
pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
pci_read_config_dword(iommu->dev, 0xfc, &val);
return val;
}
static void iommu_write_l1(struct amd_iommu *iommu, u16 l1, u8 address, u32 val)
{
pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16 | 1 << 31));
pci_write_config_dword(iommu->dev, 0xfc, val);
pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
}
static u32 iommu_read_l2(struct amd_iommu *iommu, u8 address)
{
u32 val;
pci_write_config_dword(iommu->dev, 0xf0, address);
pci_read_config_dword(iommu->dev, 0xf4, &val);
return val;
}
static void iommu_write_l2(struct amd_iommu *iommu, u8 address, u32 val)
{
pci_write_config_dword(iommu->dev, 0xf0, (address | 1 << 8));
pci_write_config_dword(iommu->dev, 0xf4, val);
}
/****************************************************************************
*
* AMD IOMMU MMIO register space handling functions
*
* These functions are used to program the IOMMU device registers in
* MMIO space required for that driver.
*
****************************************************************************/
/*
* This function set the exclusion range in the IOMMU. DMA accesses to the
* exclusion range are passed through untranslated
*/
static void iommu_set_exclusion_range(struct amd_iommu *iommu)
{
u64 start = iommu->exclusion_start & PAGE_MASK;
u64 limit = (start + iommu->exclusion_length) & PAGE_MASK;
u64 entry;
if (!iommu->exclusion_start)
return;
entry = start | MMIO_EXCL_ENABLE_MASK;
memcpy_toio(iommu->mmio_base + MMIO_EXCL_BASE_OFFSET,
&entry, sizeof(entry));
entry = limit;
memcpy_toio(iommu->mmio_base + MMIO_EXCL_LIMIT_OFFSET,
&entry, sizeof(entry));
}
/* Programs the physical address of the device table into the IOMMU hardware */
static void iommu_set_device_table(struct amd_iommu *iommu)
{
u64 entry;
BUG_ON(iommu->mmio_base == NULL);
entry = virt_to_phys(amd_iommu_dev_table);
entry |= (dev_table_size >> 12) - 1;
memcpy_toio(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET,
&entry, sizeof(entry));
}
/* Generic functions to enable/disable certain features of the IOMMU. */
static void iommu_feature_enable(struct amd_iommu *iommu, u8 bit)
{
u32 ctrl;
ctrl = readl(iommu->mmio_base + MMIO_CONTROL_OFFSET);
ctrl |= (1 << bit);
writel(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
}
static void iommu_feature_disable(struct amd_iommu *iommu, u8 bit)
{
u32 ctrl;
ctrl = readl(iommu->mmio_base + MMIO_CONTROL_OFFSET);
ctrl &= ~(1 << bit);
writel(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
}
static void iommu_set_inv_tlb_timeout(struct amd_iommu *iommu, int timeout)
{
u32 ctrl;
ctrl = readl(iommu->mmio_base + MMIO_CONTROL_OFFSET);
ctrl &= ~CTRL_INV_TO_MASK;
ctrl |= (timeout << CONTROL_INV_TIMEOUT) & CTRL_INV_TO_MASK;
writel(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
}
/* Function to enable the hardware */
static void iommu_enable(struct amd_iommu *iommu)
{
iommu_feature_enable(iommu, CONTROL_IOMMU_EN);
}
static void iommu_disable(struct amd_iommu *iommu)
{
/* Disable command buffer */
iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
/* Disable event logging and event interrupts */
iommu_feature_disable(iommu, CONTROL_EVT_INT_EN);
iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
/* Disable IOMMU hardware itself */
iommu_feature_disable(iommu, CONTROL_IOMMU_EN);
}
/*
* mapping and unmapping functions for the IOMMU MMIO space. Each AMD IOMMU in
* the system has one.
*/
static u8 __iomem * __init iommu_map_mmio_space(u64 address, u64 end)
{
if (!request_mem_region(address, end, "amd_iommu")) {
pr_err("AMD-Vi: Can not reserve memory region %llx-%llx for mmio\n",
address, end);
pr_err("AMD-Vi: This is a BIOS bug. Please contact your hardware vendor\n");
return NULL;
}
return (u8 __iomem *)ioremap_nocache(address, end);
}
static void __init iommu_unmap_mmio_space(struct amd_iommu *iommu)
{
if (iommu->mmio_base)
iounmap(iommu->mmio_base);
release_mem_region(iommu->mmio_phys, iommu->mmio_phys_end);
}
static inline u32 get_ivhd_header_size(struct ivhd_header *h)
{
u32 size = 0;
switch (h->type) {
case 0x10:
size = 24;
break;
case 0x11:
case 0x40:
size = 40;
break;
}
return size;
}
/****************************************************************************
*
* The functions below belong to the first pass of AMD IOMMU ACPI table
* parsing. In this pass we try to find out the highest device id this
* code has to handle. Upon this information the size of the shared data
* structures is determined later.
*
****************************************************************************/
/*
* This function calculates the length of a given IVHD entry
*/
static inline int ivhd_entry_length(u8 *ivhd)
{
u32 type = ((struct ivhd_entry *)ivhd)->type;
if (type < 0x80) {
return 0x04 << (*ivhd >> 6);
} else if (type == IVHD_DEV_ACPI_HID) {
/* For ACPI_HID, offset 21 is uid len */
return *((u8 *)ivhd + 21) + 22;
}
return 0;
}
/*
* After reading the highest device id from the IOMMU PCI capability header
* this function looks if there is a higher device id defined in the ACPI table
*/
static int __init find_last_devid_from_ivhd(struct ivhd_header *h)
{
u8 *p = (void *)h, *end = (void *)h;
struct ivhd_entry *dev;
u32 ivhd_size = get_ivhd_header_size(h);
if (!ivhd_size) {
pr_err("AMD-Vi: Unsupported IVHD type %#x\n", h->type);
return -EINVAL;
}
p += ivhd_size;
end += h->length;
while (p < end) {
dev = (struct ivhd_entry *)p;
switch (dev->type) {
case IVHD_DEV_ALL:
/* Use maximum BDF value for DEV_ALL */
update_last_devid(0xffff);
break;
case IVHD_DEV_SELECT:
case IVHD_DEV_RANGE_END:
case IVHD_DEV_ALIAS:
case IVHD_DEV_EXT_SELECT:
/* all the above subfield types refer to device ids */
update_last_devid(dev->devid);
break;
default:
break;
}
p += ivhd_entry_length(p);
}
WARN_ON(p != end);
return 0;
}
static int __init check_ivrs_checksum(struct acpi_table_header *table)
{
int i;
u8 checksum = 0, *p = (u8 *)table;
for (i = 0; i < table->length; ++i)
checksum += p[i];
if (checksum != 0) {
/* ACPI table corrupt */
pr_err(FW_BUG "AMD-Vi: IVRS invalid checksum\n");
return -ENODEV;
}
return 0;
}
/*
* Iterate over all IVHD entries in the ACPI table and find the highest device
* id which we need to handle. This is the first of three functions which parse
* the ACPI table. So we check the checksum here.
*/
static int __init find_last_devid_acpi(struct acpi_table_header *table)
{
u8 *p = (u8 *)table, *end = (u8 *)table;
struct ivhd_header *h;
p += IVRS_HEADER_LENGTH;
end += table->length;
while (p < end) {
h = (struct ivhd_header *)p;
if (h->type == amd_iommu_target_ivhd_type) {
int ret = find_last_devid_from_ivhd(h);
if (ret)
return ret;
}
p += h->length;
}
WARN_ON(p != end);
return 0;
}
/****************************************************************************
*
* The following functions belong to the code path which parses the ACPI table
* the second time. In this ACPI parsing iteration we allocate IOMMU specific
* data structures, initialize the device/alias/rlookup table and also
* basically initialize the hardware.
*
****************************************************************************/
/*
* Allocates the command buffer. This buffer is per AMD IOMMU. We can
* write commands to that buffer later and the IOMMU will execute them
* asynchronously
*/
static int __init alloc_command_buffer(struct amd_iommu *iommu)
{
iommu->cmd_buf = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(CMD_BUFFER_SIZE));
return iommu->cmd_buf ? 0 : -ENOMEM;
}
/*
* This function resets the command buffer if the IOMMU stopped fetching
* commands from it.
*/
void amd_iommu_reset_cmd_buffer(struct amd_iommu *iommu)
{
iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
writel(0x00, iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
writel(0x00, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
iommu_feature_enable(iommu, CONTROL_CMDBUF_EN);
}
/*
* This function writes the command buffer address to the hardware and
* enables it.
*/
static void iommu_enable_command_buffer(struct amd_iommu *iommu)
{
u64 entry;
BUG_ON(iommu->cmd_buf == NULL);
entry = (u64)virt_to_phys(iommu->cmd_buf);
entry |= MMIO_CMD_SIZE_512;
memcpy_toio(iommu->mmio_base + MMIO_CMD_BUF_OFFSET,
&entry, sizeof(entry));
amd_iommu_reset_cmd_buffer(iommu);
}
static void __init free_command_buffer(struct amd_iommu *iommu)
{
free_pages((unsigned long)iommu->cmd_buf, get_order(CMD_BUFFER_SIZE));
}
/* allocates the memory where the IOMMU will log its events to */
static int __init alloc_event_buffer(struct amd_iommu *iommu)
{
iommu->evt_buf = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(EVT_BUFFER_SIZE));
return iommu->evt_buf ? 0 : -ENOMEM;
}
static void iommu_enable_event_buffer(struct amd_iommu *iommu)
{
u64 entry;
BUG_ON(iommu->evt_buf == NULL);
entry = (u64)virt_to_phys(iommu->evt_buf) | EVT_LEN_MASK;
memcpy_toio(iommu->mmio_base + MMIO_EVT_BUF_OFFSET,
&entry, sizeof(entry));
/* set head and tail to zero manually */
writel(0x00, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
writel(0x00, iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
iommu_feature_enable(iommu, CONTROL_EVT_LOG_EN);
}
static void __init free_event_buffer(struct amd_iommu *iommu)
{
free_pages((unsigned long)iommu->evt_buf, get_order(EVT_BUFFER_SIZE));
}
/* allocates the memory where the IOMMU will log its events to */
static int __init alloc_ppr_log(struct amd_iommu *iommu)
{
iommu->ppr_log = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(PPR_LOG_SIZE));
return iommu->ppr_log ? 0 : -ENOMEM;
}
static void iommu_enable_ppr_log(struct amd_iommu *iommu)
{
u64 entry;
if (iommu->ppr_log == NULL)
return;
entry = (u64)virt_to_phys(iommu->ppr_log) | PPR_LOG_SIZE_512;
memcpy_toio(iommu->mmio_base + MMIO_PPR_LOG_OFFSET,
&entry, sizeof(entry));
/* set head and tail to zero manually */
writel(0x00, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
writel(0x00, iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
iommu_feature_enable(iommu, CONTROL_PPFLOG_EN);
iommu_feature_enable(iommu, CONTROL_PPR_EN);
}
static void __init free_ppr_log(struct amd_iommu *iommu)
{
if (iommu->ppr_log == NULL)
return;
free_pages((unsigned long)iommu->ppr_log, get_order(PPR_LOG_SIZE));
}
static void iommu_enable_gt(struct amd_iommu *iommu)
{
if (!iommu_feature(iommu, FEATURE_GT))
return;
iommu_feature_enable(iommu, CONTROL_GT_EN);
}
/* sets a specific bit in the device table entry. */
static void set_dev_entry_bit(u16 devid, u8 bit)
{
int i = (bit >> 6) & 0x03;
int _bit = bit & 0x3f;
amd_iommu_dev_table[devid].data[i] |= (1UL << _bit);
}
static int get_dev_entry_bit(u16 devid, u8 bit)
{
int i = (bit >> 6) & 0x03;
int _bit = bit & 0x3f;
return (amd_iommu_dev_table[devid].data[i] & (1UL << _bit)) >> _bit;
}
void amd_iommu_apply_erratum_63(u16 devid)
{
int sysmgt;
sysmgt = get_dev_entry_bit(devid, DEV_ENTRY_SYSMGT1) |
(get_dev_entry_bit(devid, DEV_ENTRY_SYSMGT2) << 1);
if (sysmgt == 0x01)
set_dev_entry_bit(devid, DEV_ENTRY_IW);
}
/* Writes the specific IOMMU for a device into the rlookup table */
static void __init set_iommu_for_device(struct amd_iommu *iommu, u16 devid)
{
amd_iommu_rlookup_table[devid] = iommu;
}
/*
* This function takes the device specific flags read from the ACPI
* table and sets up the device table entry with that information
*/
static void __init set_dev_entry_from_acpi(struct amd_iommu *iommu,
u16 devid, u32 flags, u32 ext_flags)
{
if (flags & ACPI_DEVFLAG_INITPASS)
set_dev_entry_bit(devid, DEV_ENTRY_INIT_PASS);
if (flags & ACPI_DEVFLAG_EXTINT)
set_dev_entry_bit(devid, DEV_ENTRY_EINT_PASS);
if (flags & ACPI_DEVFLAG_NMI)
set_dev_entry_bit(devid, DEV_ENTRY_NMI_PASS);
if (flags & ACPI_DEVFLAG_SYSMGT1)
set_dev_entry_bit(devid, DEV_ENTRY_SYSMGT1);
if (flags & ACPI_DEVFLAG_SYSMGT2)
set_dev_entry_bit(devid, DEV_ENTRY_SYSMGT2);
if (flags & ACPI_DEVFLAG_LINT0)
set_dev_entry_bit(devid, DEV_ENTRY_LINT0_PASS);
if (flags & ACPI_DEVFLAG_LINT1)
set_dev_entry_bit(devid, DEV_ENTRY_LINT1_PASS);
amd_iommu_apply_erratum_63(devid);
set_iommu_for_device(iommu, devid);
}
static int __init add_special_device(u8 type, u8 id, u16 *devid, bool cmd_line)
{
struct devid_map *entry;
struct list_head *list;
if (type == IVHD_SPECIAL_IOAPIC)
list = &ioapic_map;
else if (type == IVHD_SPECIAL_HPET)
list = &hpet_map;
else
return -EINVAL;
list_for_each_entry(entry, list, list) {
if (!(entry->id == id && entry->cmd_line))
continue;
pr_info("AMD-Vi: Command-line override present for %s id %d - ignoring\n",
type == IVHD_SPECIAL_IOAPIC ? "IOAPIC" : "HPET", id);
*devid = entry->devid;
return 0;
}
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
entry->id = id;
entry->devid = *devid;
entry->cmd_line = cmd_line;
list_add_tail(&entry->list, list);
return 0;
}
static int __init add_acpi_hid_device(u8 *hid, u8 *uid, u16 *devid,
bool cmd_line)
{
struct acpihid_map_entry *entry;
struct list_head *list = &acpihid_map;
list_for_each_entry(entry, list, list) {
if (strcmp(entry->hid, hid) ||
(*uid && *entry->uid && strcmp(entry->uid, uid)) ||
!entry->cmd_line)
continue;
pr_info("AMD-Vi: Command-line override for hid:%s uid:%s\n",
hid, uid);
*devid = entry->devid;
return 0;
}
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
memcpy(entry->uid, uid, strlen(uid));
memcpy(entry->hid, hid, strlen(hid));
entry->devid = *devid;
entry->cmd_line = cmd_line;
entry->root_devid = (entry->devid & (~0x7));
pr_info("AMD-Vi:%s, add hid:%s, uid:%s, rdevid:%d\n",
entry->cmd_line ? "cmd" : "ivrs",
entry->hid, entry->uid, entry->root_devid);
list_add_tail(&entry->list, list);
return 0;
}
static int __init add_early_maps(void)
{
int i, ret;
for (i = 0; i < early_ioapic_map_size; ++i) {
ret = add_special_device(IVHD_SPECIAL_IOAPIC,
early_ioapic_map[i].id,
&early_ioapic_map[i].devid,
early_ioapic_map[i].cmd_line);
if (ret)
return ret;
}
for (i = 0; i < early_hpet_map_size; ++i) {
ret = add_special_device(IVHD_SPECIAL_HPET,
early_hpet_map[i].id,
&early_hpet_map[i].devid,
early_hpet_map[i].cmd_line);
if (ret)
return ret;
}
for (i = 0; i < early_acpihid_map_size; ++i) {
ret = add_acpi_hid_device(early_acpihid_map[i].hid,
early_acpihid_map[i].uid,
&early_acpihid_map[i].devid,
early_acpihid_map[i].cmd_line);
if (ret)
return ret;
}
return 0;
}
/*
* Reads the device exclusion range from ACPI and initializes the IOMMU with
* it
*/
static void __init set_device_exclusion_range(u16 devid, struct ivmd_header *m)
{
struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
if (!(m->flags & IVMD_FLAG_EXCL_RANGE))
return;
if (iommu) {
/*
* We only can configure exclusion ranges per IOMMU, not
* per device. But we can enable the exclusion range per
* device. This is done here
*/
set_dev_entry_bit(devid, DEV_ENTRY_EX);
iommu->exclusion_start = m->range_start;
iommu->exclusion_length = m->range_length;
}
}
/*
* Takes a pointer to an AMD IOMMU entry in the ACPI table and
* initializes the hardware and our data structures with it.
*/
static int __init init_iommu_from_acpi(struct amd_iommu *iommu,
struct ivhd_header *h)
{
u8 *p = (u8 *)h;
u8 *end = p, flags = 0;
u16 devid = 0, devid_start = 0, devid_to = 0;
u32 dev_i, ext_flags = 0;
bool alias = false;
struct ivhd_entry *e;
u32 ivhd_size;
int ret;
ret = add_early_maps();
if (ret)
return ret;
/*
* First save the recommended feature enable bits from ACPI
*/
iommu->acpi_flags = h->flags;
/*
* Done. Now parse the device entries
*/
ivhd_size = get_ivhd_header_size(h);
if (!ivhd_size) {
pr_err("AMD-Vi: Unsupported IVHD type %#x\n", h->type);
return -EINVAL;
}
p += ivhd_size;
end += h->length;
while (p < end) {
e = (struct ivhd_entry *)p;
switch (e->type) {
case IVHD_DEV_ALL:
DUMP_printk(" DEV_ALL\t\t\tflags: %02x\n", e->flags);
for (dev_i = 0; dev_i <= amd_iommu_last_bdf; ++dev_i)
set_dev_entry_from_acpi(iommu, dev_i, e->flags, 0);
break;
case IVHD_DEV_SELECT:
DUMP_printk(" DEV_SELECT\t\t\t devid: %02x:%02x.%x "
"flags: %02x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid),
e->flags);
devid = e->devid;
set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
break;
case IVHD_DEV_SELECT_RANGE_START:
DUMP_printk(" DEV_SELECT_RANGE_START\t "
"devid: %02x:%02x.%x flags: %02x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid),
e->flags);
devid_start = e->devid;
flags = e->flags;
ext_flags = 0;
alias = false;
break;
case IVHD_DEV_ALIAS:
DUMP_printk(" DEV_ALIAS\t\t\t devid: %02x:%02x.%x "
"flags: %02x devid_to: %02x:%02x.%x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid),
e->flags,
PCI_BUS_NUM(e->ext >> 8),
PCI_SLOT(e->ext >> 8),
PCI_FUNC(e->ext >> 8));
devid = e->devid;
devid_to = e->ext >> 8;
set_dev_entry_from_acpi(iommu, devid , e->flags, 0);
set_dev_entry_from_acpi(iommu, devid_to, e->flags, 0);
amd_iommu_alias_table[devid] = devid_to;
break;
case IVHD_DEV_ALIAS_RANGE:
DUMP_printk(" DEV_ALIAS_RANGE\t\t "
"devid: %02x:%02x.%x flags: %02x "
"devid_to: %02x:%02x.%x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid),
e->flags,
PCI_BUS_NUM(e->ext >> 8),
PCI_SLOT(e->ext >> 8),
PCI_FUNC(e->ext >> 8));
devid_start = e->devid;
flags = e->flags;
devid_to = e->ext >> 8;
ext_flags = 0;
alias = true;
break;
case IVHD_DEV_EXT_SELECT:
DUMP_printk(" DEV_EXT_SELECT\t\t devid: %02x:%02x.%x "
"flags: %02x ext: %08x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid),
e->flags, e->ext);
devid = e->devid;
set_dev_entry_from_acpi(iommu, devid, e->flags,
e->ext);
break;
case IVHD_DEV_EXT_SELECT_RANGE:
DUMP_printk(" DEV_EXT_SELECT_RANGE\t devid: "
"%02x:%02x.%x flags: %02x ext: %08x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid),
e->flags, e->ext);
devid_start = e->devid;
flags = e->flags;
ext_flags = e->ext;
alias = false;
break;
case IVHD_DEV_RANGE_END:
DUMP_printk(" DEV_RANGE_END\t\t devid: %02x:%02x.%x\n",
PCI_BUS_NUM(e->devid),
PCI_SLOT(e->devid),
PCI_FUNC(e->devid));
devid = e->devid;
for (dev_i = devid_start; dev_i <= devid; ++dev_i) {
if (alias) {
amd_iommu_alias_table[dev_i] = devid_to;
set_dev_entry_from_acpi(iommu,
devid_to, flags, ext_flags);
}
set_dev_entry_from_acpi(iommu, dev_i,
flags, ext_flags);
}
break;
case IVHD_DEV_SPECIAL: {
u8 handle, type;
const char *var;
u16 devid;
int ret;
handle = e->ext & 0xff;
devid = (e->ext >> 8) & 0xffff;
type = (e->ext >> 24) & 0xff;
if (type == IVHD_SPECIAL_IOAPIC)
var = "IOAPIC";
else if (type == IVHD_SPECIAL_HPET)
var = "HPET";
else
var = "UNKNOWN";
DUMP_printk(" DEV_SPECIAL(%s[%d])\t\tdevid: %02x:%02x.%x\n",
var, (int)handle,
PCI_BUS_NUM(devid),
PCI_SLOT(devid),
PCI_FUNC(devid));
ret = add_special_device(type, handle, &devid, false);
if (ret)
return ret;
/*
* add_special_device might update the devid in case a
* command-line override is present. So call
* set_dev_entry_from_acpi after add_special_device.
*/
set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
break;
}
case IVHD_DEV_ACPI_HID: {
u16 devid;
u8 hid[ACPIHID_HID_LEN] = {0};
u8 uid[ACPIHID_UID_LEN] = {0};
int ret;
if (h->type != 0x40) {
pr_err(FW_BUG "Invalid IVHD device type %#x\n",
e->type);
break;
}
memcpy(hid, (u8 *)(&e->ext), ACPIHID_HID_LEN - 1);
hid[ACPIHID_HID_LEN - 1] = '\0';
if (!(*hid)) {
pr_err(FW_BUG "Invalid HID.\n");
break;
}
switch (e->uidf) {
case UID_NOT_PRESENT:
if (e->uidl != 0)
pr_warn(FW_BUG "Invalid UID length.\n");
break;
case UID_IS_INTEGER:
sprintf(uid, "%d", e->uid);
break;
case UID_IS_CHARACTER:
memcpy(uid, (u8 *)(&e->uid), ACPIHID_UID_LEN - 1);
uid[ACPIHID_UID_LEN - 1] = '\0';
break;
default:
break;
}
DUMP_printk(" DEV_ACPI_HID(%s[%s])\t\tdevid: %02x:%02x.%x\n",
hid, uid,
PCI_BUS_NUM(devid),
PCI_SLOT(devid),
PCI_FUNC(devid));
devid = e->devid;
flags = e->flags;
ret = add_acpi_hid_device(hid, uid, &devid, false);
if (ret)
return ret;
/*
* add_special_device might update the devid in case a
* command-line override is present. So call
* set_dev_entry_from_acpi after add_special_device.
*/
set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
break;
}
default:
break;
}
p += ivhd_entry_length(p);
}
return 0;
}
static void __init free_iommu_one(struct amd_iommu *iommu)
{
free_command_buffer(iommu);
free_event_buffer(iommu);
free_ppr_log(iommu);
iommu_unmap_mmio_space(iommu);
}
static void __init free_iommu_all(void)
{
struct amd_iommu *iommu, *next;
for_each_iommu_safe(iommu, next) {
list_del(&iommu->list);
free_iommu_one(iommu);
kfree(iommu);
}
}
/*
* Family15h Model 10h-1fh erratum 746 (IOMMU Logging May Stall Translations)
* Workaround:
* BIOS should disable L2B micellaneous clock gating by setting
* L2_L2B_CK_GATE_CONTROL[CKGateL2BMiscDisable](D0F2xF4_x90[2]) = 1b
*/
static void amd_iommu_erratum_746_workaround(struct amd_iommu *iommu)
{
u32 value;
if ((boot_cpu_data.x86 != 0x15) ||
(boot_cpu_data.x86_model < 0x10) ||
(boot_cpu_data.x86_model > 0x1f))
return;
pci_write_config_dword(iommu->dev, 0xf0, 0x90);
pci_read_config_dword(iommu->dev, 0xf4, &value);
if (value & BIT(2))
return;
/* Select NB indirect register 0x90 and enable writing */
pci_write_config_dword(iommu->dev, 0xf0, 0x90 | (1 << 8));
pci_write_config_dword(iommu->dev, 0xf4, value | 0x4);
pr_info("AMD-Vi: Applying erratum 746 workaround for IOMMU at %s\n",
dev_name(&iommu->dev->dev));
/* Clear the enable writing bit */
pci_write_config_dword(iommu->dev, 0xf0, 0x90);
}
/*
* Family15h Model 30h-3fh (IOMMU Mishandles ATS Write Permission)
* Workaround:
* BIOS should enable ATS write permission check by setting
* L2_DEBUG_3[AtsIgnoreIWDis](D0F2xF4_x47[0]) = 1b
*/
static void amd_iommu_ats_write_check_workaround(struct amd_iommu *iommu)
{
u32 value;
if ((boot_cpu_data.x86 != 0x15) ||
(boot_cpu_data.x86_model < 0x30) ||
(boot_cpu_data.x86_model > 0x3f))
return;
/* Test L2_DEBUG_3[AtsIgnoreIWDis] == 1 */
value = iommu_read_l2(iommu, 0x47);
if (value & BIT(0))
return;
/* Set L2_DEBUG_3[AtsIgnoreIWDis] = 1 */
iommu_write_l2(iommu, 0x47, value | BIT(0));
pr_info("AMD-Vi: Applying ATS write check workaround for IOMMU at %s\n",
dev_name(&iommu->dev->dev));
}
/*
* This function clues the initialization function for one IOMMU
* together and also allocates the command buffer and programs the
* hardware. It does NOT enable the IOMMU. This is done afterwards.
*/
static int __init init_iommu_one(struct amd_iommu *iommu, struct ivhd_header *h)
{
int ret;
spin_lock_init(&iommu->lock);
/* Add IOMMU to internal data structures */
list_add_tail(&iommu->list, &amd_iommu_list);
iommu->index = amd_iommus_present++;
if (unlikely(iommu->index >= MAX_IOMMUS)) {
WARN(1, "AMD-Vi: System has more IOMMUs than supported by this driver\n");
return -ENOSYS;
}
/* Index is fine - add IOMMU to the array */
amd_iommus[iommu->index] = iommu;
/*
* Copy data from ACPI table entry to the iommu struct
*/
iommu->devid = h->devid;
iommu->cap_ptr = h->cap_ptr;
iommu->pci_seg = h->pci_seg;
iommu->mmio_phys = h->mmio_phys;
switch (h->type) {
case 0x10:
/* Check if IVHD EFR contains proper max banks/counters */
if ((h->efr_attr != 0) &&
((h->efr_attr & (0xF << 13)) != 0) &&
((h->efr_attr & (0x3F << 17)) != 0))
iommu->mmio_phys_end = MMIO_REG_END_OFFSET;
else
iommu->mmio_phys_end = MMIO_CNTR_CONF_OFFSET;
break;
case 0x11:
case 0x40:
if (h->efr_reg & (1 << 9))
iommu->mmio_phys_end = MMIO_REG_END_OFFSET;
else
iommu->mmio_phys_end = MMIO_CNTR_CONF_OFFSET;
break;
default:
return -EINVAL;
}
iommu->mmio_base = iommu_map_mmio_space(iommu->mmio_phys,
iommu->mmio_phys_end);
if (!iommu->mmio_base)
return -ENOMEM;
if (alloc_command_buffer(iommu))
return -ENOMEM;
if (alloc_event_buffer(iommu))
return -ENOMEM;
iommu->int_enabled = false;
ret = init_iommu_from_acpi(iommu, h);
if (ret)
return ret;
ret = amd_iommu_create_irq_domain(iommu);
if (ret)
return ret;
/*
* Make sure IOMMU is not considered to translate itself. The IVRS
* table tells us so, but this is a lie!
*/
amd_iommu_rlookup_table[iommu->devid] = NULL;
return 0;
}
/**
* get_highest_supported_ivhd_type - Look up the appropriate IVHD type
* @ivrs Pointer to the IVRS header
*
* This function search through all IVDB of the maximum supported IVHD
*/
static u8 get_highest_supported_ivhd_type(struct acpi_table_header *ivrs)
{
u8 *base = (u8 *)ivrs;
struct ivhd_header *ivhd = (struct ivhd_header *)
(base + IVRS_HEADER_LENGTH);
u8 last_type = ivhd->type;
u16 devid = ivhd->devid;
while (((u8 *)ivhd - base < ivrs->length) &&
(ivhd->type <= ACPI_IVHD_TYPE_MAX_SUPPORTED)) {
u8 *p = (u8 *) ivhd;
if (ivhd->devid == devid)
last_type = ivhd->type;
ivhd = (struct ivhd_header *)(p + ivhd->length);
}
return last_type;
}
/*
* Iterates over all IOMMU entries in the ACPI table, allocates the
* IOMMU structure and initializes it with init_iommu_one()
*/
static int __init init_iommu_all(struct acpi_table_header *table)
{
u8 *p = (u8 *)table, *end = (u8 *)table;
struct ivhd_header *h;
struct amd_iommu *iommu;
int ret;
end += table->length;
p += IVRS_HEADER_LENGTH;
while (p < end) {
h = (struct ivhd_header *)p;
if (*p == amd_iommu_target_ivhd_type) {
DUMP_printk("device: %02x:%02x.%01x cap: %04x "
"seg: %d flags: %01x info %04x\n",
PCI_BUS_NUM(h->devid), PCI_SLOT(h->devid),
PCI_FUNC(h->devid), h->cap_ptr,
h->pci_seg, h->flags, h->info);
DUMP_printk(" mmio-addr: %016llx\n",
h->mmio_phys);
iommu = kzalloc(sizeof(struct amd_iommu), GFP_KERNEL);
if (iommu == NULL)
return -ENOMEM;
ret = init_iommu_one(iommu, h);
if (ret)
return ret;
}
p += h->length;
}
WARN_ON(p != end);
return 0;
}
static void init_iommu_perf_ctr(struct amd_iommu *iommu)
{
u64 val = 0xabcd, val2 = 0;
if (!iommu_feature(iommu, FEATURE_PC))
return;
amd_iommu_pc_present = true;
/* Check if the performance counters can be written to */
if ((0 != iommu_pc_get_set_reg_val(iommu, 0, 0, 0, &val, true)) ||
(0 != iommu_pc_get_set_reg_val(iommu, 0, 0, 0, &val2, false)) ||
(val != val2)) {
pr_err("AMD-Vi: Unable to write to IOMMU perf counter.\n");
amd_iommu_pc_present = false;
return;
}
pr_info("AMD-Vi: IOMMU performance counters supported\n");
val = readl(iommu->mmio_base + MMIO_CNTR_CONF_OFFSET);
iommu->max_banks = (u8) ((val >> 12) & 0x3f);
iommu->max_counters = (u8) ((val >> 7) & 0xf);
}
static ssize_t amd_iommu_show_cap(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct amd_iommu *iommu = dev_get_drvdata(dev);
return sprintf(buf, "%x\n", iommu->cap);
}
static DEVICE_ATTR(cap, S_IRUGO, amd_iommu_show_cap, NULL);
static ssize_t amd_iommu_show_features(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct amd_iommu *iommu = dev_get_drvdata(dev);
return sprintf(buf, "%llx\n", iommu->features);
}
static DEVICE_ATTR(features, S_IRUGO, amd_iommu_show_features, NULL);
static struct attribute *amd_iommu_attrs[] = {
&dev_attr_cap.attr,
&dev_attr_features.attr,
NULL,
};
static struct attribute_group amd_iommu_group = {
.name = "amd-iommu",
.attrs = amd_iommu_attrs,
};
static const struct attribute_group *amd_iommu_groups[] = {
&amd_iommu_group,
NULL,
};
static int iommu_init_pci(struct amd_iommu *iommu)
{
int cap_ptr = iommu->cap_ptr;
u32 range, misc, low, high;
iommu->dev = pci_get_bus_and_slot(PCI_BUS_NUM(iommu->devid),
iommu->devid & 0xff);
if (!iommu->dev)
return -ENODEV;
/* Prevent binding other PCI device drivers to IOMMU devices */
iommu->dev->match_driver = false;
pci_read_config_dword(iommu->dev, cap_ptr + MMIO_CAP_HDR_OFFSET,
&iommu->cap);
pci_read_config_dword(iommu->dev, cap_ptr + MMIO_RANGE_OFFSET,
&range);
pci_read_config_dword(iommu->dev, cap_ptr + MMIO_MISC_OFFSET,
&misc);
if (!(iommu->cap & (1 << IOMMU_CAP_IOTLB)))
amd_iommu_iotlb_sup = false;
/* read extended feature bits */
low = readl(iommu->mmio_base + MMIO_EXT_FEATURES);
high = readl(iommu->mmio_base + MMIO_EXT_FEATURES + 4);
iommu->features = ((u64)high << 32) | low;
if (iommu_feature(iommu, FEATURE_GT)) {
int glxval;
u32 max_pasid;
u64 pasmax;
pasmax = iommu->features & FEATURE_PASID_MASK;
pasmax >>= FEATURE_PASID_SHIFT;
max_pasid = (1 << (pasmax + 1)) - 1;
amd_iommu_max_pasid = min(amd_iommu_max_pasid, max_pasid);
BUG_ON(amd_iommu_max_pasid & ~PASID_MASK);
glxval = iommu->features & FEATURE_GLXVAL_MASK;
glxval >>= FEATURE_GLXVAL_SHIFT;
if (amd_iommu_max_glx_val == -1)
amd_iommu_max_glx_val = glxval;
else
amd_iommu_max_glx_val = min(amd_iommu_max_glx_val, glxval);
}
if (iommu_feature(iommu, FEATURE_GT) &&
iommu_feature(iommu, FEATURE_PPR)) {
iommu->is_iommu_v2 = true;
amd_iommu_v2_present = true;
}
if (iommu_feature(iommu, FEATURE_PPR) && alloc_ppr_log(iommu))
return -ENOMEM;
if (iommu->cap & (1UL << IOMMU_CAP_NPCACHE))
amd_iommu_np_cache = true;
init_iommu_perf_ctr(iommu);
if (is_rd890_iommu(iommu->dev)) {
int i, j;
iommu->root_pdev = pci_get_bus_and_slot(iommu->dev->bus->number,
PCI_DEVFN(0, 0));
/*
* Some rd890 systems may not be fully reconfigured by the
* BIOS, so it's necessary for us to store this information so
* it can be reprogrammed on resume
*/
pci_read_config_dword(iommu->dev, iommu->cap_ptr + 4,
&iommu->stored_addr_lo);
pci_read_config_dword(iommu->dev, iommu->cap_ptr + 8,
&iommu->stored_addr_hi);
/* Low bit locks writes to configuration space */
iommu->stored_addr_lo &= ~1;
for (i = 0; i < 6; i++)
for (j = 0; j < 0x12; j++)
iommu->stored_l1[i][j] = iommu_read_l1(iommu, i, j);
for (i = 0; i < 0x83; i++)
iommu->stored_l2[i] = iommu_read_l2(iommu, i);
}
amd_iommu_erratum_746_workaround(iommu);
amd_iommu_ats_write_check_workaround(iommu);
iommu->iommu_dev = iommu_device_create(&iommu->dev->dev, iommu,
amd_iommu_groups, "ivhd%d",
iommu->index);
return pci_enable_device(iommu->dev);
}
static void print_iommu_info(void)
{
static const char * const feat_str[] = {
"PreF", "PPR", "X2APIC", "NX", "GT", "[5]",
"IA", "GA", "HE", "PC"
};
struct amd_iommu *iommu;
for_each_iommu(iommu) {
int i;
pr_info("AMD-Vi: Found IOMMU at %s cap 0x%hx\n",
dev_name(&iommu->dev->dev), iommu->cap_ptr);
if (iommu->cap & (1 << IOMMU_CAP_EFR)) {
pr_info("AMD-Vi: Extended features: ");
for (i = 0; i < ARRAY_SIZE(feat_str); ++i) {
if (iommu_feature(iommu, (1ULL << i)))
pr_cont(" %s", feat_str[i]);
}
pr_cont("\n");
}
}
if (irq_remapping_enabled)
pr_info("AMD-Vi: Interrupt remapping enabled\n");
}
static int __init amd_iommu_init_pci(void)
{
struct amd_iommu *iommu;
int ret = 0;
for_each_iommu(iommu) {
ret = iommu_init_pci(iommu);
if (ret)
break;
}
init_device_table_dma();
for_each_iommu(iommu)
iommu_flush_all_caches(iommu);
ret = amd_iommu_init_api();
if (!ret)
print_iommu_info();
return ret;
}
/****************************************************************************
*
* The following functions initialize the MSI interrupts for all IOMMUs
* in the system. It's a bit challenging because there could be multiple
* IOMMUs per PCI BDF but we can call pci_enable_msi(x) only once per
* pci_dev.
*
****************************************************************************/
static int iommu_setup_msi(struct amd_iommu *iommu)
{
int r;
r = pci_enable_msi(iommu->dev);
if (r)
return r;
r = request_threaded_irq(iommu->dev->irq,
amd_iommu_int_handler,
amd_iommu_int_thread,
0, "AMD-Vi",
iommu);
if (r) {
pci_disable_msi(iommu->dev);
return r;
}
iommu->int_enabled = true;
return 0;
}
static int iommu_init_msi(struct amd_iommu *iommu)
{
int ret;
if (iommu->int_enabled)
goto enable_faults;
if (iommu->dev->msi_cap)
ret = iommu_setup_msi(iommu);
else
ret = -ENODEV;
if (ret)
return ret;
enable_faults:
iommu_feature_enable(iommu, CONTROL_EVT_INT_EN);
if (iommu->ppr_log != NULL)
iommu_feature_enable(iommu, CONTROL_PPFINT_EN);
return 0;
}
/****************************************************************************
*
* The next functions belong to the third pass of parsing the ACPI
* table. In this last pass the memory mapping requirements are
* gathered (like exclusion and unity mapping ranges).
*
****************************************************************************/
static void __init free_unity_maps(void)
{
struct unity_map_entry *entry, *next;
list_for_each_entry_safe(entry, next, &amd_iommu_unity_map, list) {
list_del(&entry->list);
kfree(entry);
}
}
/* called when we find an exclusion range definition in ACPI */
static int __init init_exclusion_range(struct ivmd_header *m)
{
int i;
switch (m->type) {
case ACPI_IVMD_TYPE:
set_device_exclusion_range(m->devid, m);
break;
case ACPI_IVMD_TYPE_ALL:
for (i = 0; i <= amd_iommu_last_bdf; ++i)
set_device_exclusion_range(i, m);
break;
case ACPI_IVMD_TYPE_RANGE:
for (i = m->devid; i <= m->aux; ++i)
set_device_exclusion_range(i, m);
break;
default:
break;
}
return 0;
}
/* called for unity map ACPI definition */
static int __init init_unity_map_range(struct ivmd_header *m)
{
struct unity_map_entry *e = NULL;
char *s;
e = kzalloc(sizeof(*e), GFP_KERNEL);
if (e == NULL)
return -ENOMEM;
switch (m->type) {
default:
kfree(e);
return 0;
case ACPI_IVMD_TYPE:
s = "IVMD_TYPEi\t\t\t";
e->devid_start = e->devid_end = m->devid;
break;
case ACPI_IVMD_TYPE_ALL:
s = "IVMD_TYPE_ALL\t\t";
e->devid_start = 0;
e->devid_end = amd_iommu_last_bdf;
break;
case ACPI_IVMD_TYPE_RANGE:
s = "IVMD_TYPE_RANGE\t\t";
e->devid_start = m->devid;
e->devid_end = m->aux;
break;
}
e->address_start = PAGE_ALIGN(m->range_start);
e->address_end = e->address_start + PAGE_ALIGN(m->range_length);
e->prot = m->flags >> 1;
DUMP_printk("%s devid_start: %02x:%02x.%x devid_end: %02x:%02x.%x"
" range_start: %016llx range_end: %016llx flags: %x\n", s,
PCI_BUS_NUM(e->devid_start), PCI_SLOT(e->devid_start),
PCI_FUNC(e->devid_start), PCI_BUS_NUM(e->devid_end),
PCI_SLOT(e->devid_end), PCI_FUNC(e->devid_end),
e->address_start, e->address_end, m->flags);
list_add_tail(&e->list, &amd_iommu_unity_map);
return 0;
}
/* iterates over all memory definitions we find in the ACPI table */
static int __init init_memory_definitions(struct acpi_table_header *table)
{
u8 *p = (u8 *)table, *end = (u8 *)table;
struct ivmd_header *m;
end += table->length;
p += IVRS_HEADER_LENGTH;
while (p < end) {
m = (struct ivmd_header *)p;
if (m->flags & IVMD_FLAG_EXCL_RANGE)
init_exclusion_range(m);
else if (m->flags & IVMD_FLAG_UNITY_MAP)
init_unity_map_range(m);
p += m->length;
}
return 0;
}
/*
* Init the device table to not allow DMA access for devices and
* suppress all page faults
*/
static void init_device_table_dma(void)
{
u32 devid;
for (devid = 0; devid <= amd_iommu_last_bdf; ++devid) {
set_dev_entry_bit(devid, DEV_ENTRY_VALID);
set_dev_entry_bit(devid, DEV_ENTRY_TRANSLATION);
}
}
static void __init uninit_device_table_dma(void)
{
u32 devid;
for (devid = 0; devid <= amd_iommu_last_bdf; ++devid) {
amd_iommu_dev_table[devid].data[0] = 0ULL;
amd_iommu_dev_table[devid].data[1] = 0ULL;
}
}
static void init_device_table(void)
{
u32 devid;
if (!amd_iommu_irq_remap)
return;
for (devid = 0; devid <= amd_iommu_last_bdf; ++devid)
set_dev_entry_bit(devid, DEV_ENTRY_IRQ_TBL_EN);
}
static void iommu_init_flags(struct amd_iommu *iommu)
{
iommu->acpi_flags & IVHD_FLAG_HT_TUN_EN_MASK ?
iommu_feature_enable(iommu, CONTROL_HT_TUN_EN) :
iommu_feature_disable(iommu, CONTROL_HT_TUN_EN);
iommu->acpi_flags & IVHD_FLAG_PASSPW_EN_MASK ?
iommu_feature_enable(iommu, CONTROL_PASSPW_EN) :
iommu_feature_disable(iommu, CONTROL_PASSPW_EN);
iommu->acpi_flags & IVHD_FLAG_RESPASSPW_EN_MASK ?
iommu_feature_enable(iommu, CONTROL_RESPASSPW_EN) :
iommu_feature_disable(iommu, CONTROL_RESPASSPW_EN);
iommu->acpi_flags & IVHD_FLAG_ISOC_EN_MASK ?
iommu_feature_enable(iommu, CONTROL_ISOC_EN) :
iommu_feature_disable(iommu, CONTROL_ISOC_EN);
/*
* make IOMMU memory accesses cache coherent
*/
iommu_feature_enable(iommu, CONTROL_COHERENT_EN);
/* Set IOTLB invalidation timeout to 1s */
iommu_set_inv_tlb_timeout(iommu, CTRL_INV_TO_1S);
}
static void iommu_apply_resume_quirks(struct amd_iommu *iommu)
{
int i, j;
u32 ioc_feature_control;
struct pci_dev *pdev = iommu->root_pdev;
/* RD890 BIOSes may not have completely reconfigured the iommu */
if (!is_rd890_iommu(iommu->dev) || !pdev)
return;
/*
* First, we need to ensure that the iommu is enabled. This is
* controlled by a register in the northbridge
*/
/* Select Northbridge indirect register 0x75 and enable writing */
pci_write_config_dword(pdev, 0x60, 0x75 | (1 << 7));
pci_read_config_dword(pdev, 0x64, &ioc_feature_control);
/* Enable the iommu */
if (!(ioc_feature_control & 0x1))
pci_write_config_dword(pdev, 0x64, ioc_feature_control | 1);
/* Restore the iommu BAR */
pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
iommu->stored_addr_lo);
pci_write_config_dword(iommu->dev, iommu->cap_ptr + 8,
iommu->stored_addr_hi);
/* Restore the l1 indirect regs for each of the 6 l1s */
for (i = 0; i < 6; i++)
for (j = 0; j < 0x12; j++)
iommu_write_l1(iommu, i, j, iommu->stored_l1[i][j]);
/* Restore the l2 indirect regs */
for (i = 0; i < 0x83; i++)
iommu_write_l2(iommu, i, iommu->stored_l2[i]);
/* Lock PCI setup registers */
pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
iommu->stored_addr_lo | 1);
}
/*
* This function finally enables all IOMMUs found in the system after
* they have been initialized
*/
static void early_enable_iommus(void)
{
struct amd_iommu *iommu;
for_each_iommu(iommu) {
iommu_disable(iommu);
iommu_init_flags(iommu);
iommu_set_device_table(iommu);
iommu_enable_command_buffer(iommu);
iommu_enable_event_buffer(iommu);
iommu_set_exclusion_range(iommu);
iommu_enable(iommu);
iommu_flush_all_caches(iommu);
}
}
static void enable_iommus_v2(void)
{
struct amd_iommu *iommu;
for_each_iommu(iommu) {
iommu_enable_ppr_log(iommu);
iommu_enable_gt(iommu);
}
}
static void enable_iommus(void)
{
early_enable_iommus();
enable_iommus_v2();
}
static void disable_iommus(void)
{
struct amd_iommu *iommu;
for_each_iommu(iommu)
iommu_disable(iommu);
}
/*
* Suspend/Resume support
* disable suspend until real resume implemented
*/
static void amd_iommu_resume(void)
{
struct amd_iommu *iommu;
for_each_iommu(iommu)
iommu_apply_resume_quirks(iommu);
/* re-load the hardware */
enable_iommus();
amd_iommu_enable_interrupts();
}
static int amd_iommu_suspend(void)
{
/* disable IOMMUs to go out of the way for BIOS */
disable_iommus();
return 0;
}
static struct syscore_ops amd_iommu_syscore_ops = {
.suspend = amd_iommu_suspend,
.resume = amd_iommu_resume,
};
static void __init free_on_init_error(void)
{
free_pages((unsigned long)irq_lookup_table,
get_order(rlookup_table_size));
kmem_cache_destroy(amd_iommu_irq_cache);
amd_iommu_irq_cache = NULL;
free_pages((unsigned long)amd_iommu_rlookup_table,
get_order(rlookup_table_size));
free_pages((unsigned long)amd_iommu_alias_table,
get_order(alias_table_size));
free_pages((unsigned long)amd_iommu_dev_table,
get_order(dev_table_size));
free_iommu_all();
#ifdef CONFIG_GART_IOMMU
/*
* We failed to initialize the AMD IOMMU - try fallback to GART
* if possible.
*/
gart_iommu_init();
#endif
}
/* SB IOAPIC is always on this device in AMD systems */
#define IOAPIC_SB_DEVID ((0x00 << 8) | PCI_DEVFN(0x14, 0))
static bool __init check_ioapic_information(void)
{
const char *fw_bug = FW_BUG;
bool ret, has_sb_ioapic;
int idx;
has_sb_ioapic = false;
ret = false;
/*
* If we have map overrides on the kernel command line the
* messages in this function might not describe firmware bugs
* anymore - so be careful
*/
if (cmdline_maps)
fw_bug = "";
for (idx = 0; idx < nr_ioapics; idx++) {
int devid, id = mpc_ioapic_id(idx);
devid = get_ioapic_devid(id);
if (devid < 0) {
pr_err("%sAMD-Vi: IOAPIC[%d] not in IVRS table\n",
fw_bug, id);
ret = false;
} else if (devid == IOAPIC_SB_DEVID) {
has_sb_ioapic = true;
ret = true;
}
}
if (!has_sb_ioapic) {
/*
* We expect the SB IOAPIC to be listed in the IVRS
* table. The system timer is connected to the SB IOAPIC
* and if we don't have it in the list the system will
* panic at boot time. This situation usually happens
* when the BIOS is buggy and provides us the wrong
* device id for the IOAPIC in the system.
*/
pr_err("%sAMD-Vi: No southbridge IOAPIC found\n", fw_bug);
}
if (!ret)
pr_err("AMD-Vi: Disabling interrupt remapping\n");
return ret;
}
static void __init free_dma_resources(void)
{
free_pages((unsigned long)amd_iommu_pd_alloc_bitmap,
get_order(MAX_DOMAIN_ID/8));
free_unity_maps();
}
/*
* This is the hardware init function for AMD IOMMU in the system.
* This function is called either from amd_iommu_init or from the interrupt
* remapping setup code.
*
* This function basically parses the ACPI table for AMD IOMMU (IVRS)
* four times:
*
* 1 pass) Discover the most comprehensive IVHD type to use.
*
* 2 pass) Find the highest PCI device id the driver has to handle.
* Upon this information the size of the data structures is
* determined that needs to be allocated.
*
* 3 pass) Initialize the data structures just allocated with the
* information in the ACPI table about available AMD IOMMUs
* in the system. It also maps the PCI devices in the
* system to specific IOMMUs
*
* 4 pass) After the basic data structures are allocated and
* initialized we update them with information about memory
* remapping requirements parsed out of the ACPI table in
* this last pass.
*
* After everything is set up the IOMMUs are enabled and the necessary
* hotplug and suspend notifiers are registered.
*/
static int __init early_amd_iommu_init(void)
{
struct acpi_table_header *ivrs_base;
acpi_size ivrs_size;
acpi_status status;
int i, ret = 0;
if (!amd_iommu_detected)
return -ENODEV;
status = acpi_get_table_with_size("IVRS", 0, &ivrs_base, &ivrs_size);
if (status == AE_NOT_FOUND)
return -ENODEV;
else if (ACPI_FAILURE(status)) {
const char *err = acpi_format_exception(status);
pr_err("AMD-Vi: IVRS table error: %s\n", err);
return -EINVAL;
}
/*
* Validate checksum here so we don't need to do it when
* we actually parse the table
*/
ret = check_ivrs_checksum(ivrs_base);
if (ret)
return ret;
amd_iommu_target_ivhd_type = get_highest_supported_ivhd_type(ivrs_base);
DUMP_printk("Using IVHD type %#x\n", amd_iommu_target_ivhd_type);
/*
* First parse ACPI tables to find the largest Bus/Dev/Func
* we need to handle. Upon this information the shared data
* structures for the IOMMUs in the system will be allocated
*/
ret = find_last_devid_acpi(ivrs_base);
if (ret)
goto out;
dev_table_size = tbl_size(DEV_TABLE_ENTRY_SIZE);
alias_table_size = tbl_size(ALIAS_TABLE_ENTRY_SIZE);
rlookup_table_size = tbl_size(RLOOKUP_TABLE_ENTRY_SIZE);
/* Device table - directly used by all IOMMUs */
ret = -ENOMEM;
amd_iommu_dev_table = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(dev_table_size));
if (amd_iommu_dev_table == NULL)
goto out;
/*
* Alias table - map PCI Bus/Dev/Func to Bus/Dev/Func the
* IOMMU see for that device
*/
amd_iommu_alias_table = (void *)__get_free_pages(GFP_KERNEL,
get_order(alias_table_size));
if (amd_iommu_alias_table == NULL)
goto out;
/* IOMMU rlookup table - find the IOMMU for a specific device */
amd_iommu_rlookup_table = (void *)__get_free_pages(
GFP_KERNEL | __GFP_ZERO,
get_order(rlookup_table_size));
if (amd_iommu_rlookup_table == NULL)
goto out;
amd_iommu_pd_alloc_bitmap = (void *)__get_free_pages(
GFP_KERNEL | __GFP_ZERO,
get_order(MAX_DOMAIN_ID/8));
if (amd_iommu_pd_alloc_bitmap == NULL)
goto out;
/*
* let all alias entries point to itself
*/
for (i = 0; i <= amd_iommu_last_bdf; ++i)
amd_iommu_alias_table[i] = i;
/*
* never allocate domain 0 because its used as the non-allocated and
* error value placeholder
*/
amd_iommu_pd_alloc_bitmap[0] = 1;
spin_lock_init(&amd_iommu_pd_lock);
/*
* now the data structures are allocated and basically initialized
* start the real acpi table scan
*/
ret = init_iommu_all(ivrs_base);
if (ret)
goto out;
if (amd_iommu_irq_remap)
amd_iommu_irq_remap = check_ioapic_information();
if (amd_iommu_irq_remap) {
/*
* Interrupt remapping enabled, create kmem_cache for the
* remapping tables.
*/
ret = -ENOMEM;
amd_iommu_irq_cache = kmem_cache_create("irq_remap_cache",
MAX_IRQS_PER_TABLE * sizeof(u32),
IRQ_TABLE_ALIGNMENT,
0, NULL);
if (!amd_iommu_irq_cache)
goto out;
irq_lookup_table = (void *)__get_free_pages(
GFP_KERNEL | __GFP_ZERO,
get_order(rlookup_table_size));
if (!irq_lookup_table)
goto out;
}
ret = init_memory_definitions(ivrs_base);
if (ret)
goto out;
/* init the device table */
init_device_table();
out:
/* Don't leak any ACPI memory */
early_acpi_os_unmap_memory((char __iomem *)ivrs_base, ivrs_size);
ivrs_base = NULL;
return ret;
}
static int amd_iommu_enable_interrupts(void)
{
struct amd_iommu *iommu;
int ret = 0;
for_each_iommu(iommu) {
ret = iommu_init_msi(iommu);
if (ret)
goto out;
}
out:
return ret;
}
static bool detect_ivrs(void)
{
struct acpi_table_header *ivrs_base;
acpi_size ivrs_size;
acpi_status status;
status = acpi_get_table_with_size("IVRS", 0, &ivrs_base, &ivrs_size);
if (status == AE_NOT_FOUND)
return false;
else if (ACPI_FAILURE(status)) {
const char *err = acpi_format_exception(status);
pr_err("AMD-Vi: IVRS table error: %s\n", err);
return false;
}
early_acpi_os_unmap_memory((char __iomem *)ivrs_base, ivrs_size);
/* Make sure ACS will be enabled during PCI probe */
pci_request_acs();
return true;
}
/****************************************************************************
*
* AMD IOMMU Initialization State Machine
*
****************************************************************************/
static int __init state_next(void)
{
int ret = 0;
switch (init_state) {
case IOMMU_START_STATE:
if (!detect_ivrs()) {
init_state = IOMMU_NOT_FOUND;
ret = -ENODEV;
} else {
init_state = IOMMU_IVRS_DETECTED;
}
break;
case IOMMU_IVRS_DETECTED:
ret = early_amd_iommu_init();
init_state = ret ? IOMMU_INIT_ERROR : IOMMU_ACPI_FINISHED;
break;
case IOMMU_ACPI_FINISHED:
early_enable_iommus();
register_syscore_ops(&amd_iommu_syscore_ops);
x86_platform.iommu_shutdown = disable_iommus;
init_state = IOMMU_ENABLED;
break;
case IOMMU_ENABLED:
ret = amd_iommu_init_pci();
init_state = ret ? IOMMU_INIT_ERROR : IOMMU_PCI_INIT;
enable_iommus_v2();
break;
case IOMMU_PCI_INIT:
ret = amd_iommu_enable_interrupts();
init_state = ret ? IOMMU_INIT_ERROR : IOMMU_INTERRUPTS_EN;
break;
case IOMMU_INTERRUPTS_EN:
ret = amd_iommu_init_dma_ops();
init_state = ret ? IOMMU_INIT_ERROR : IOMMU_DMA_OPS;
break;
case IOMMU_DMA_OPS:
init_state = IOMMU_INITIALIZED;
break;
case IOMMU_INITIALIZED:
/* Nothing to do */
break;
case IOMMU_NOT_FOUND:
case IOMMU_INIT_ERROR:
/* Error states => do nothing */
ret = -EINVAL;
break;
default:
/* Unknown state */
BUG();
}
return ret;
}
static int __init iommu_go_to_state(enum iommu_init_state state)
{
int ret = 0;
while (init_state != state) {
ret = state_next();
if (init_state == IOMMU_NOT_FOUND ||
init_state == IOMMU_INIT_ERROR)
break;
}
return ret;
}
#ifdef CONFIG_IRQ_REMAP
int __init amd_iommu_prepare(void)
{
int ret;
amd_iommu_irq_remap = true;
ret = iommu_go_to_state(IOMMU_ACPI_FINISHED);
if (ret)
return ret;
return amd_iommu_irq_remap ? 0 : -ENODEV;
}
int __init amd_iommu_enable(void)
{
int ret;
ret = iommu_go_to_state(IOMMU_ENABLED);
if (ret)
return ret;
irq_remapping_enabled = 1;
return 0;
}
void amd_iommu_disable(void)
{
amd_iommu_suspend();
}
int amd_iommu_reenable(int mode)
{
amd_iommu_resume();
return 0;
}
int __init amd_iommu_enable_faulting(void)
{
/* We enable MSI later when PCI is initialized */
return 0;
}
#endif
/*
* This is the core init function for AMD IOMMU hardware in the system.
* This function is called from the generic x86 DMA layer initialization
* code.
*/
static int __init amd_iommu_init(void)
{
int ret;
ret = iommu_go_to_state(IOMMU_INITIALIZED);
if (ret) {
free_dma_resources();
if (!irq_remapping_enabled) {
disable_iommus();
free_on_init_error();
} else {
struct amd_iommu *iommu;
uninit_device_table_dma();
for_each_iommu(iommu)
iommu_flush_all_caches(iommu);
}
}
return ret;
}
/****************************************************************************
*
* Early detect code. This code runs at IOMMU detection time in the DMA
* layer. It just looks if there is an IVRS ACPI table to detect AMD
* IOMMUs
*
****************************************************************************/
int __init amd_iommu_detect(void)
{
int ret;
if (no_iommu || (iommu_detected && !gart_iommu_aperture))
return -ENODEV;
if (amd_iommu_disabled)
return -ENODEV;
ret = iommu_go_to_state(IOMMU_IVRS_DETECTED);
if (ret)
return ret;
amd_iommu_detected = true;
iommu_detected = 1;
x86_init.iommu.iommu_init = amd_iommu_init;
return 1;
}
/****************************************************************************
*
* Parsing functions for the AMD IOMMU specific kernel command line
* options.
*
****************************************************************************/
static int __init parse_amd_iommu_dump(char *str)
{
amd_iommu_dump = true;
return 1;
}
static int __init parse_amd_iommu_options(char *str)
{
for (; *str; ++str) {
if (strncmp(str, "fullflush", 9) == 0)
amd_iommu_unmap_flush = true;
if (strncmp(str, "off", 3) == 0)
amd_iommu_disabled = true;
if (strncmp(str, "force_isolation", 15) == 0)
amd_iommu_force_isolation = true;
}
return 1;
}
static int __init parse_ivrs_ioapic(char *str)
{
unsigned int bus, dev, fn;
int ret, id, i;
u16 devid;
ret = sscanf(str, "[%d]=%x:%x.%x", &id, &bus, &dev, &fn);
if (ret != 4) {
pr_err("AMD-Vi: Invalid command line: ivrs_ioapic%s\n", str);
return 1;
}
if (early_ioapic_map_size == EARLY_MAP_SIZE) {
pr_err("AMD-Vi: Early IOAPIC map overflow - ignoring ivrs_ioapic%s\n",
str);
return 1;
}
devid = ((bus & 0xff) << 8) | ((dev & 0x1f) << 3) | (fn & 0x7);
cmdline_maps = true;
i = early_ioapic_map_size++;
early_ioapic_map[i].id = id;
early_ioapic_map[i].devid = devid;
early_ioapic_map[i].cmd_line = true;
return 1;
}
static int __init parse_ivrs_hpet(char *str)
{
unsigned int bus, dev, fn;
int ret, id, i;
u16 devid;
ret = sscanf(str, "[%d]=%x:%x.%x", &id, &bus, &dev, &fn);
if (ret != 4) {
pr_err("AMD-Vi: Invalid command line: ivrs_hpet%s\n", str);
return 1;
}
if (early_hpet_map_size == EARLY_MAP_SIZE) {
pr_err("AMD-Vi: Early HPET map overflow - ignoring ivrs_hpet%s\n",
str);
return 1;
}
devid = ((bus & 0xff) << 8) | ((dev & 0x1f) << 3) | (fn & 0x7);
cmdline_maps = true;
i = early_hpet_map_size++;
early_hpet_map[i].id = id;
early_hpet_map[i].devid = devid;
early_hpet_map[i].cmd_line = true;
return 1;
}
static int __init parse_ivrs_acpihid(char *str)
{
u32 bus, dev, fn;
char *hid, *uid, *p;
char acpiid[ACPIHID_UID_LEN + ACPIHID_HID_LEN] = {0};
int ret, i;
ret = sscanf(str, "[%x:%x.%x]=%s", &bus, &dev, &fn, acpiid);
if (ret != 4) {
pr_err("AMD-Vi: Invalid command line: ivrs_acpihid(%s)\n", str);
return 1;
}
p = acpiid;
hid = strsep(&p, ":");
uid = p;
if (!hid || !(*hid) || !uid) {
pr_err("AMD-Vi: Invalid command line: hid or uid\n");
return 1;
}
i = early_acpihid_map_size++;
memcpy(early_acpihid_map[i].hid, hid, strlen(hid));
memcpy(early_acpihid_map[i].uid, uid, strlen(uid));
early_acpihid_map[i].devid =
((bus & 0xff) << 8) | ((dev & 0x1f) << 3) | (fn & 0x7);
early_acpihid_map[i].cmd_line = true;
return 1;
}
__setup("amd_iommu_dump", parse_amd_iommu_dump);
__setup("amd_iommu=", parse_amd_iommu_options);
__setup("ivrs_ioapic", parse_ivrs_ioapic);
__setup("ivrs_hpet", parse_ivrs_hpet);
__setup("ivrs_acpihid", parse_ivrs_acpihid);
IOMMU_INIT_FINISH(amd_iommu_detect,
gart_iommu_hole_init,
NULL,
NULL);
bool amd_iommu_v2_supported(void)
{
return amd_iommu_v2_present;
}
EXPORT_SYMBOL(amd_iommu_v2_supported);
/****************************************************************************
*
* IOMMU EFR Performance Counter support functionality. This code allows
* access to the IOMMU PC functionality.
*
****************************************************************************/
u8 amd_iommu_pc_get_max_banks(u16 devid)
{
struct amd_iommu *iommu;
u8 ret = 0;
/* locate the iommu governing the devid */
iommu = amd_iommu_rlookup_table[devid];
if (iommu)
ret = iommu->max_banks;
return ret;
}
EXPORT_SYMBOL(amd_iommu_pc_get_max_banks);
bool amd_iommu_pc_supported(void)
{
return amd_iommu_pc_present;
}
EXPORT_SYMBOL(amd_iommu_pc_supported);
u8 amd_iommu_pc_get_max_counters(u16 devid)
{
struct amd_iommu *iommu;
u8 ret = 0;
/* locate the iommu governing the devid */
iommu = amd_iommu_rlookup_table[devid];
if (iommu)
ret = iommu->max_counters;
return ret;
}
EXPORT_SYMBOL(amd_iommu_pc_get_max_counters);
static int iommu_pc_get_set_reg_val(struct amd_iommu *iommu,
u8 bank, u8 cntr, u8 fxn,
u64 *value, bool is_write)
{
u32 offset;
u32 max_offset_lim;
/* Check for valid iommu and pc register indexing */
if (WARN_ON((fxn > 0x28) || (fxn & 7)))
return -ENODEV;
offset = (u32)(((0x40|bank) << 12) | (cntr << 8) | fxn);
/* Limit the offset to the hw defined mmio region aperture */
max_offset_lim = (u32)(((0x40|iommu->max_banks) << 12) |
(iommu->max_counters << 8) | 0x28);
if ((offset < MMIO_CNTR_REG_OFFSET) ||
(offset > max_offset_lim))
return -EINVAL;
if (is_write) {
writel((u32)*value, iommu->mmio_base + offset);
writel((*value >> 32), iommu->mmio_base + offset + 4);
} else {
*value = readl(iommu->mmio_base + offset + 4);
*value <<= 32;
*value = readl(iommu->mmio_base + offset);
}
return 0;
}
EXPORT_SYMBOL(amd_iommu_pc_get_set_reg_val);
int amd_iommu_pc_get_set_reg_val(u16 devid, u8 bank, u8 cntr, u8 fxn,
u64 *value, bool is_write)
{
struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
/* Make sure the IOMMU PC resource is available */
if (!amd_iommu_pc_present || iommu == NULL)
return -ENODEV;
return iommu_pc_get_set_reg_val(iommu, bank, cntr, fxn,
value, is_write);
}
| gpl-2.0 |
slade87/ALE21-Kernel | drivers/hisi/modem_hi3xxx/ps/comm/comm/NFEXT/Interpeak/ip_net2-6.8/ipcom/port/vxworks/src/ipcom_pshell.c | 22 | 22321 | /*
******************************************************************************
* INTERPEAK SOURCE FILE
*
* Document no: @(#) $Name: VXWORKS_ITER18A_FRZ10 $ $RCSfile: ipcom_pshell.c,v $ $Revision: 1.31.16.1 $
* $Source: /home/interpeak/CVSRoot/ipcom/port/vxworks/src/ipcom_pshell.c,v $
* $Author: ulf $
* $State: Exp $ $Locker: $
*
* INTERPEAK_COPYRIGHT_STRING
* Design and implementation by Roger Boden <roger@interpeak.se>
******************************************************************************
*/
/*
****************************************************************************
* 1 DESCRIPTION
****************************************************************************
*/
/*
****************************************************************************
* 2 CONFIGURATION
****************************************************************************
*/
#define IPCOM_SKIP_NATIVE_SOCK_API
#include "ipcom_config.h"
/*
****************************************************************************
* 3 INCLUDE FILES
****************************************************************************
*/
#if IPCOM_USE_SHELL == IPCOM_SHELL_NATIVE
#include <ipcom_type.h>
#include <ipcom_cstyle.h>
#include <ipcom_clib.h>
#include <ipcom_sock.h>
#include <ipcom_sock2.h>
#include <ipcom_err.h>
#include <ipcom_syslog.h>
#include <ipcom_shell.h>
#include <ipcom_list.h>
#include <ipcom_os.h>
#ifdef IPCOM_USE_INET6
#include <ipcom_sock6.h>
#endif
#undef s6_addr /* Remove the ipcom definition, vxWorks 6.0 has a conflicting macro definition */
#undef ifa_dstaddr /* The ifa_dstaddr #define in ipcom_sock2.h breaks code in target/h/.../ifvar.h */
#undef ifa_broadaddr /* The ifa_broadaddr #define in ipcom_sock2.h breaks code in target/h/.../ifvar.h */
#include <vxWorks.h>
#include <stdio.h>
#include <string.h>
#include <shellLib.h>
#include <sockLib.h>
#include <taskLib.h>
#include <wrn/coreip/telnetLib.h>
#include <ptyDrv.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
/*
****************************************************************************
* 4 DEFINES
****************************************************************************
*/
#define IPCOM_SYSLOG_PRIORITY IPCOM_SYSLOG_IPCOM_PRIORITY
#define IPCOM_SYSLOG_FACILITY IPCOM_LOG_IPCOM
#ifndef IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN
#define IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN 64
#endif
#ifndef IPCOM_PSHELL_PTY_BUFFER_SIZE
#define IPCOM_PSHELL_PTY_BUFFER_SIZE 512
#endif
#define IPCOM_PSHELL_TASK_NAME_LEN 32
#define IPCOM_PSHELL_LOGIN_TASK_BASENAME "tLogin"
#define IPCOM_PSHELL_STDIO_PROXY_TASK_BASENAME "tStdioProxy"
/*
* Ideally, we would not define IPCOM_SKIP_NATIVE_SOCK_API above, then we
* would handle the both the case of IPCOM_USE_NATIVE_SOCK_API being defined
* and not defined. Unfortunately, when IPCOM_USE_NATIVE_SOCK_API is defined,
* we get compile errors (inconsistent function declarations for the socket
* API. As a work-around, we therefore define IPCOM_SKIP_NATIVE_SOCK_API,
* include all headers and thereafter define macros that include type casts
* where necessary (below).
*/
#ifdef IPCOM_USE_NATIVE_SOCK_API
#define ipcom_socket socket
#define ipcom_socketclose(fd) close((int)fd)
#define ipcom_shutdown(fd,how) shutdown((int)fd, how)
#define ipcom_bind(s,a,l) bind((int)s,(struct sockaddr*)a,(int)l)
#define ipcom_connect connect
#define ipcom_accept accept
#define ipcom_listen listen
#define ipcom_socketwrite write
#define ipcom_socketwritev writev
#define ipcom_send send
#define ipcom_sendto sendto
#define ipcom_sendmsg sendmsg
#define ipcom_socketread read
#define ipcom_recv recv
#define ipcom_recvfrom recvfrom
#define ipcom_recvmsg recvmsg
#define ipcom_getsockopt getsockopt
#define ipcom_setsockopt(s,l,n,v,d) setsockopt(s,l,n,(char *)v,d)
#define ipcom_getsockname(s,a,l) getsockname((int)s,(struct sockaddr*)a,(int*)l)
#define ipcom_getpeername getpeername
#define ipcom_socketioctl ioctl
#define ipcom_if_nametoindex if_nametoindex
#define ipcom_if_indextoname if_indextoname
#define ipcom_if_nameindex if_nameindex
#define ipcom_if_freenameindex if_freenameindex
#define ipcom_socketselect select
#endif
/*
****************************************************************************
* 5 TYPES
****************************************************************************
*/
typedef struct Ipcom_vxshell_session_s
{
Ipcom_sem shell_exit_sem;
}
Ipcom_vxshell_session_t;
/*
****************************************************************************
* 6 EXTERN PROTOTYPES
****************************************************************************
*/
extern char tyBackspaceChar;
/*
****************************************************************************
* 7 LOCAL PROTOTYPES
****************************************************************************
*/
IP_STATIC void ipcom_vxshell_login_task(int pty_fd, int vx_sock);
IP_STATIC void ipcom_vxworks_shell_logout_cb(void *arg);
IP_STATIC Ip_err ipcom_pshell_create_pty(char* pty_dev_name, int name_len, int *master_fd, int *slave_fd);
IP_STATIC Ip_err ipcom_pshell_spawn_proxy(int vx_sock);
IP_STATIC void ipcom_pshell_stdio_proxy(int vx_sock, int parent_task_id);
IP_STATIC int ipcom_pshell_proxy_data(int read_fd, int write_fd, Ip_bool can_change_direction);
/*
****************************************************************************
* 8 DATA
****************************************************************************
*/
/*
****************************************************************************
* 9 STATIC FUNCTIONS
****************************************************************************
*/
/*
*===========================================================================
* ipcom_pshell_spawn_proxy
*===========================================================================
* Description:
* Parameters:
* Returns:
*
*/
IP_STATIC Ip_err
ipcom_pshell_spawn_proxy(int vx_sock)
{
char task_name[IPCOM_PSHELL_TASK_NAME_LEN];
snprintf(task_name,
sizeof(task_name),
IPCOM_PSHELL_STDIO_PROXY_TASK_BASENAME "%x",
taskIdSelf());
if (taskSpawn(task_name, 50, 0, 6000, (FUNCPTR)ipcom_pshell_stdio_proxy,
vx_sock, taskIdSelf(), 2, 3, 4, 5, 6, 7, 8, 9) == ERROR)
{
IPCOM_LOG2(ERR, "Failed to create stdio proxy task: %s(%d)",
ipcom_strerror(ipcom_errno), ipcom_errno);
return IPCOM_ERR_FAILED;
}
return IPCOM_SUCCESS;
}
/*
*===========================================================================
* ipcom_pshell_stdio_proxy
*===========================================================================
* Description:
* Parameters:
* Returns:
*
*/
IP_STATIC void
ipcom_pshell_stdio_proxy(int vx_sock, int parent_task_id)
{
int master_fd;
int slave_fd;
char task_name[IPCOM_PSHELL_TASK_NAME_LEN];
char pty_dev_name[IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN];
Ip_pid_t pid;
/* Make this process the owner of the "vx_sock" socket */
pid = ipcom_getpid();
(void) ipcom_socketioctl(vx_sock, IP_SIOCSPGRP, &pid);
if (ipcom_pshell_create_pty(pty_dev_name, sizeof(pty_dev_name), &master_fd, &slave_fd) != IPCOM_SUCCESS)
{
IPCOM_LOG0(ERR, "Failed to create ptys");
close(vx_sock);
return;
}
snprintf(task_name,
sizeof(task_name),
IPCOM_PSHELL_LOGIN_TASK_BASENAME "%x",
parent_task_id);
if (taskSpawn (task_name, 50, 0, 6000, (FUNCPTR)ipcom_vxshell_login_task,
slave_fd, vx_sock, 0, 0, 0, 0, 0, 0, 0, 0) == ERROR)
{
IPCOM_LOG1(ERR,
"ipcom_shell_login_task: Failed to create login task: %s",
strerror(errno));
close(slave_fd);
goto cleanup;
}
/* else: the ownership of "slave_fd" has been transferred to the
ipcom_vxshell_login_task at this point */
/* Main loop, proxy data between pty fd and socket to telnet daemon */
for (;;)
{
fd_set read_set;
int read_fd = -1;
int write_fd = -1;
Ip_bool can_change_direction = IP_FALSE;
int ret;
FD_ZERO(&read_set);
FD_SET(master_fd, &read_set);
FD_SET(vx_sock, &read_set);
if ((ret = select(IP_MAX(master_fd, vx_sock)+1, &read_set, NULL, NULL, NULL)) < 0)
{
IPCOM_LOG3(ERR,
"ipcom_shell_login_task: select([%d, %d]) failed: %s",
master_fd,
vx_sock,
strerror(errno));
goto cleanup;
}
if (FD_ISSET(master_fd, &read_set))
{
/* Move data from the shell client to the telnet client */
read_fd = master_fd;
write_fd = vx_sock;
}
else if (FD_ISSET(vx_sock, &read_set))
{
/* Move data from the telnet client to the shell */
read_fd = vx_sock;
write_fd = master_fd;
/* Allow ipcom_pshell_proxy_data() to start move data from
the shell to the telnet client if the shell cannot
accept more data. This is done to avoid a dead lock
where this task waits for the shell file descriptor to
become writable, but the only thing that can make it
writable is if someone dequeus data written by the
shell. */
can_change_direction = IP_TRUE;
}
else
continue;
ret = ipcom_pshell_proxy_data(read_fd, write_fd, can_change_direction);
if (ret == 0)
goto cleanup; /* Either shell or client initiated close */
if (ret < 0)
{
if (ret < 0 && ipcom_errno != ESHUTDOWN)
{
IPCOM_LOG2(ERR, "Failed to proxy data: %s(%d)",
ipcom_strerror(ipcom_errno), ipcom_errno);
}
break;
}
}
cleanup:
close(master_fd);
ptyDevRemove(pty_dev_name);
close(vx_sock);
}
/*
*===========================================================================
* ipcom_pshell_proxy_data
*===========================================================================
* Description: Moves data from the read_fd to the write_fd.
* Parameters: read_fd - file descriptor data is moved from.
* write_fd - file descriptor data is move to.
* can_change_direction - IP_TRUE if data can be moved in the
* opposite direction if the write_fd is full.
* Returns: >0 = number of bytes moved.
* 0 = end of file reached.
* <0 = error code.
*
*/
IP_STATIC int
ipcom_pshell_proxy_data(int read_fd, int write_fd, Ip_bool can_change_direction)
{
char buf[200];
char *ptr;
int rlen;
int wlen;
rlen = read(read_fd, buf, sizeof(buf));
if (rlen <= 0)
return rlen;
ptr = buf;
wlen = rlen;
while (wlen > 0)
{
int bytes_written;
bytes_written = write(write_fd, ptr, wlen == rlen ? wlen : 1);
if (bytes_written < 0)
return bytes_written;
if (bytes_written == 0)
{
fd_set wr_set;
/* When the pty device is in line mode (typically when running a command
* with a sub prompt), typing backspace when there are no characters to
* erase will make write return 0 */
if (ptr[0] == tyBackspaceChar)
return rlen;
if (can_change_direction)
/* Try to move data in the oposite direction to free
up space in the input buffer of the shell file
descriptor. */
(void)ipcom_pshell_proxy_data(write_fd, read_fd, IP_FALSE);
/* Send buffer full, wait until more space becomes
available */
FD_ZERO(&wr_set);
FD_SET(write_fd, &wr_set);
if (select(write_fd + 1, NULL, &wr_set, NULL, NULL) < 0)
return -1;
}
wlen -= bytes_written;
ptr += bytes_written;
}
return rlen;
}
/*
*===========================================================================
* ipcom_pshell_create_pty
*===========================================================================
* Description:
* Parameters:
* Returns:
*
*/
IP_STATIC Ip_err
ipcom_pshell_create_pty(char* pty_dev_name, int name_len, int *master_fd, int *slave_fd)
{
char pty_dev_name_m[IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN];
char pty_dev_name_s[IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN];
*master_fd = ERROR;
*slave_fd = ERROR;
/* Create unique names for the pty device */
snprintf (pty_dev_name, name_len, "%s_%x.", "stdio_pty", (int)taskIdSelf());
snprintf (pty_dev_name_m, IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN, "%sM", pty_dev_name);
snprintf (pty_dev_name_s, IPCOM_PSHELL_PTY_DEV_NAME_MAX_LEN, "%sS", pty_dev_name);
/* pseudo tty device creation */
if (ptyDevCreate (pty_dev_name,
IPCOM_PSHELL_PTY_BUFFER_SIZE,
IPCOM_PSHELL_PTY_BUFFER_SIZE) == ERROR)
{
IPCOM_LOG2(ERR, "ptyDevCreate failed: %s(%d)",
ipcom_strerror(ipcom_errno), ipcom_errno);
return IPCOM_ERR_FAILED;
}
/* Master-side open of pseudo tty */
*master_fd = open (pty_dev_name_m, O_RDWR, 0);
if (*master_fd == ERROR)
{
IPCOM_LOG2(ERR, "open failed on pty device: %s(%d)",
ipcom_strerror(ipcom_errno), ipcom_errno);
goto err;
}
/* Slave-side open of pseudo tty */
*slave_fd = open (pty_dev_name_s, O_RDWR, 0);
if (*slave_fd == ERROR)
{
IPCOM_LOG2(ERR, "open failed on pty device: %s(%d)",
ipcom_strerror(ipcom_errno), ipcom_errno);
goto err;
}
/*
* Set up the slave device to act like a terminal, but no ^C/^X.
* OPT_ABORT and OPT_MON_TRAP will be enabled by the shell parser
* routine after successful login but before restarting the shell.
*/
if (ioctl(*slave_fd, FIOOPTIONS, OPT_TERMINAL & ~(OPT_ABORT|OPT_MON_TRAP)) != OK)
{
IPCOM_LOG2(ERR, "ioctl(FIOOPTIONS) failed: %s(%d)",
ipcom_strerror(ipcom_errno), ipcom_errno);
goto err;
}
return IPCOM_SUCCESS;
err:
ptyDevRemove(pty_dev_name);
if (*master_fd != ERROR)
close(*master_fd);
if (*slave_fd != ERROR)
close(*slave_fd);
return IPCOM_ERR_FAILED;
}
/*
*===========================================================================
* ipcom_vxworks_shell_logout_cb
*===========================================================================
* Description: The vxshell calls this upon exit. This is used to trigger the
* 'ipcom_login_task_task' to tear down the remote connection
*
* Parameters: arg: the session descriptor created by the 'ipcom_vxshell_login_task'
*
*/
IP_STATIC void
ipcom_vxworks_shell_logout_cb(void *arg)
{
Ipcom_vxshell_session_t *session = (Ipcom_vxshell_session_t *) arg;
ipcom_sem_post(session->shell_exit_sem);
}
/*
****************************************************************************
* 10 GLOBAL FUNCTIONS
****************************************************************************
*/
/*
*===========================================================================
* ipcom_vxshell_login_task
*===========================================================================
* Description: Task to provide a context login procedure in 'shellParserControl'
*
* Parameters: pty_fd: the vxworks socket the vxshell should communicate on
* Parameters: vx_sock: the vxworks socket the stdio_proxy is using for
* communication with the telnet server.
*
*/
IP_STATIC void
ipcom_vxshell_login_task(int pty_fd, int vx_sock)
{
Ipcom_vxshell_session_t session;
ipcom_sem_create(&session.shell_exit_sem, 0);
if (shellParserControl(REMOTE_START, (Ip_u32)&session, pty_fd, ipcom_vxworks_shell_logout_cb) == 0)
{
ipcom_sem_wait(session.shell_exit_sem);
shellParserControl(REMOTE_STOP, (Ip_u32)&session, 0, IP_NULL);
}
ipcom_sem_delete(&session.shell_exit_sem);
close(pty_fd);
shutdown(vx_sock, SHUT_RD);
}
/*
****************************************************************************
* 10 GLOBAL FUNCTIONS
****************************************************************************
*/
/*
*===========================================================================
* ipcom_start_extshell
*===========================================================================
* Description:
* Parameters:
* Returns:
*
*/
IP_GLOBAL Ip_err
ipcom_start_extshell(Ip_fd *stdio_sock, Ip_fd cli_sock)
{
Ip_fd ip_sock = IP_INVALID_SOCKET;
Ip_fd ip_listen_sock = IP_INVALID_SOCKET;
int vx_sock = IP_INVALID_SOCKET;
Ip_err rc = IPCOM_ERR_FAILED;
Ip_socklen_t len;
int enable = IP_TRUE;
struct linger linger;
struct Ip_addrinfo hints;
struct Ip_addrinfo *res;
struct Ip_sockaddr_storage ss;
ipcom_memset(&hints, 0, sizeof(hints));
hints.ai_socktype = IP_SOCK_STREAM;
if (ipcom_getaddrinfo(IP_NULL, "0", &hints, &res) != 0)
return rc;
ip_listen_sock = ipcom_socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (ip_listen_sock == IP_INVALID_SOCKET)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: ipcom_socket(AF_INET) failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
if (ipcom_bind(ip_listen_sock, res->ai_addr, res->ai_addrlen) != OK)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: ipcom_bind() failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
if (ipcom_listen(ip_listen_sock, 1) != OK)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: ipcom_listen() failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
/* Fetch the empheral port assigned to our socket */
len = sizeof(ss);
if (ipcom_getsockname(ip_listen_sock, (struct Ip_sockaddr*) &ss, &len) != IPCOM_SUCCESS)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: ipcom_getsockname(AF_INET) failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
vx_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (vx_sock == -1)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: ipcom_socket() failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
if (connect(vx_sock, (struct sockaddr *) &ss, sizeof(ss)) != OK)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: connect() failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
ip_sock = ipcom_accept(ip_listen_sock, NULL, NULL);
if (ip_sock == IP_INVALID_SOCKET)
{
IPCOM_LOG1(ERR, "ipcom_start_extshell :: ipcom_accept() failed: %s", ipcom_strerror(ipcom_errno));
goto err_out;
}
ipcom_socketclose(ip_listen_sock);
/* Disable Nagle (enable no delay) on the sockets since it is an
interactive connection */
(void)setsockopt(vx_sock, IPPROTO_TCP, TCP_NODELAY, (char *) &enable, sizeof(enable));
(void)ipcom_setsockopt(ip_sock, IP_IPPROTO_TCP, IP_TCP_NODELAY, &enable, sizeof(enable));
linger.l_onoff = 1;
linger.l_linger = 0;
(void)setsockopt(vx_sock, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
(void)ipcom_setsockopt(ip_sock, IP_SOL_SOCKET, IP_SO_LINGER, &linger, sizeof(linger));
if (ipcom_pshell_spawn_proxy(vx_sock) != IPCOM_SUCCESS)
{
IPCOM_LOG0(ERR, "ipcom_start_extshell :: Failed to spawn proxy task");
goto err_out;
}
*stdio_sock = ip_sock;
ipcom_freeaddrinfo(res);
return IPCOM_SUCCESS;
err_out:
ipcom_freeaddrinfo(res);
if (ip_listen_sock != IP_INVALID_SOCKET)
ipcom_socketclose(ip_listen_sock);
if (vx_sock != IP_INVALID_SOCKET)
close(vx_sock);
if (ip_sock != IP_INVALID_SOCKET)
ipcom_socketclose(ip_sock);
return rc;
}
/*
*===========================================================================
* ipcom_stdio_set_echo
*===========================================================================
* Description: Enables/disabled local echo on a telnet session.
* Parameters: fd - shell
* echo - IP_TRUE to enabled echo, IP_FALSE to disable
* Returns:
*
*/
IP_GLOBAL void
ipcom_stdio_set_echo (int fd, Ip_bool echo)
{
int opts;
int int_fd;
if (fd == -1)
int_fd = STD_IN;
else
int_fd = fd;
opts = ioctl(int_fd, FIOGETOPTIONS, 0);
if (opts == ERROR)
{
IPCOM_LOG1(ERR, "ipcom_stdio_set_echo :: ioctl(FIOGETOPTIONS) failed, errno=0x%x", errno);
return;
}
if (echo)
opts |= OPT_ECHO;
else
opts &= ~OPT_ECHO;
if (ioctl(int_fd, FIOOPTIONS, opts) == ERROR)
IPCOM_LOG1(ERR, "ipcom_stdio_set_echo :: ioctl(FIOOPTIONS) failed, errno=0x%x", errno);
}
/*
****************************************************************************
* 11 PUBLIC FUNCTIONS
****************************************************************************
*/
#else
int ipcom_pshell_empty_file;
#endif /* IPCOM_USE_SHELL == IPCOM_SHELL_NATIVE */
/*
****************************************************************************
* END OF FILE
****************************************************************************
*/
| gpl-2.0 |
nomefat/ctrl_motor_and_handset | hand/hand/Drivers/CMSIS/DSP_Lib/Source/StatisticsFunctions/arm_std_f32.c | 278 | 6627 | /* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_std_f32.c
*
* Description: Standard deviation of the elements of a floating-point vector.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ---------------------------------------------------------------------------- */
#include "arm_math.h"
/**
* @ingroup groupStats
*/
/**
* @defgroup STD Standard deviation
*
* Calculates the standard deviation of the elements in the input vector.
* The underlying algorithm is used:
*
* <pre>
* Result = sqrt((sumOfSquares - sum<sup>2</sup> / blockSize) / (blockSize - 1))
*
* where, sumOfSquares = pSrc[0] * pSrc[0] + pSrc[1] * pSrc[1] + ... + pSrc[blockSize-1] * pSrc[blockSize-1]
*
* sum = pSrc[0] + pSrc[1] + pSrc[2] + ... + pSrc[blockSize-1]
* </pre>
*
* There are separate functions for floating point, Q31, and Q15 data types.
*/
/**
* @addtogroup STD
* @{
*/
/**
* @brief Standard deviation of the elements of a floating-point vector.
* @param[in] *pSrc points to the input vector
* @param[in] blockSize length of the input vector
* @param[out] *pResult standard deviation value returned here
* @return none.
*
*/
void arm_std_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult)
{
float32_t sum = 0.0f; /* Temporary result storage */
float32_t sumOfSquares = 0.0f; /* Sum of squares */
float32_t in; /* input value */
uint32_t blkCnt; /* loop counter */
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
float32_t meanOfSquares, mean, squareOfMean;
if(blockSize == 1)
{
*pResult = 0;
return;
}
/*loop Unrolling */
blkCnt = blockSize >> 2u;
/* First part of the processing with loop unrolling. Compute 4 outputs at a time.
** a second loop below computes the remaining 1 to 3 samples. */
while(blkCnt > 0u)
{
/* C = (A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1]) */
/* Compute Sum of squares of the input samples
* and then store the result in a temporary variable, sum. */
in = *pSrc++;
sum += in;
sumOfSquares += in * in;
in = *pSrc++;
sum += in;
sumOfSquares += in * in;
in = *pSrc++;
sum += in;
sumOfSquares += in * in;
in = *pSrc++;
sum += in;
sumOfSquares += in * in;
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize % 0x4u;
while(blkCnt > 0u)
{
/* C = (A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1]) */
/* Compute Sum of squares of the input samples
* and then store the result in a temporary variable, sum. */
in = *pSrc++;
sum += in;
sumOfSquares += in * in;
/* Decrement the loop counter */
blkCnt--;
}
/* Compute Mean of squares of the input samples
* and then store the result in a temporary variable, meanOfSquares. */
meanOfSquares = sumOfSquares / ((float32_t) blockSize - 1.0f);
/* Compute mean of all input values */
mean = sum / (float32_t) blockSize;
/* Compute square of mean */
squareOfMean = (mean * mean) * (((float32_t) blockSize) /
((float32_t) blockSize - 1.0f));
/* Compute standard deviation and then store the result to the destination */
arm_sqrt_f32((meanOfSquares - squareOfMean), pResult);
#else
/* Run the below code for Cortex-M0 */
float32_t squareOfSum; /* Square of Sum */
float32_t var; /* Temporary varaince storage */
if(blockSize == 1)
{
*pResult = 0;
return;
}
/* Loop over blockSize number of values */
blkCnt = blockSize;
while(blkCnt > 0u)
{
/* C = (A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1]) */
/* Compute Sum of squares of the input samples
* and then store the result in a temporary variable, sumOfSquares. */
in = *pSrc++;
sumOfSquares += in * in;
/* C = (A[0] + A[1] + ... + A[blockSize-1]) */
/* Compute Sum of the input samples
* and then store the result in a temporary variable, sum. */
sum += in;
/* Decrement the loop counter */
blkCnt--;
}
/* Compute the square of sum */
squareOfSum = ((sum * sum) / (float32_t) blockSize);
/* Compute the variance */
var = ((sumOfSquares - squareOfSum) / (float32_t) (blockSize - 1.0f));
/* Compute standard deviation and then store the result to the destination */
arm_sqrt_f32(var, pResult);
#endif /* #ifndef ARM_MATH_CM0_FAMILY */
}
/**
* @} end of STD group
*/
| gpl-2.0 |
virt2real/dm36x-uboot | board/Marvell/db64360/pci.c | 534 | 32007 | /*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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
*
*/
/* PCI.c - PCI functions */
#include <common.h>
#include <pci.h>
#include "../include/pci.h"
#undef DEBUG
#undef IDE_SET_NATIVE_MODE
static unsigned int local_buses[] = { 0, 0 };
static const unsigned char pci_irq_swizzle[2][PCI_MAX_DEVICES] = {
{0, 0, 0, 0, 0, 0, 0, 27, 27, [9 ... PCI_MAX_DEVICES - 1] = 0 },
{0, 0, 0, 0, 0, 0, 0, 29, 29, [9 ... PCI_MAX_DEVICES - 1] = 0 },
};
#ifdef DEBUG
static const unsigned int pci_bus_list[] = { PCI_0_MODE, PCI_1_MODE };
static void gt_pci_bus_mode_display (PCI_HOST host)
{
unsigned int mode;
mode = (GTREGREAD (pci_bus_list[host]) & (BIT4 | BIT5)) >> 4;
switch (mode) {
case 0:
printf ("PCI %d bus mode: Conventional PCI\n", host);
break;
case 1:
printf ("PCI %d bus mode: 66 MHz PCIX\n", host);
break;
case 2:
printf ("PCI %d bus mode: 100 MHz PCIX\n", host);
break;
case 3:
printf ("PCI %d bus mode: 133 MHz PCIX\n", host);
break;
default:
printf ("Unknown BUS %d\n", mode);
}
}
#endif
static const unsigned int pci_p2p_configuration_reg[] = {
PCI_0P2P_CONFIGURATION, PCI_1P2P_CONFIGURATION
};
static const unsigned int pci_configuration_address[] = {
PCI_0CONFIGURATION_ADDRESS, PCI_1CONFIGURATION_ADDRESS
};
static const unsigned int pci_configuration_data[] = {
PCI_0CONFIGURATION_DATA_VIRTUAL_REGISTER,
PCI_1CONFIGURATION_DATA_VIRTUAL_REGISTER
};
static const unsigned int pci_error_cause_reg[] = {
PCI_0ERROR_CAUSE, PCI_1ERROR_CAUSE
};
static const unsigned int pci_arbiter_control[] = {
PCI_0ARBITER_CONTROL, PCI_1ARBITER_CONTROL
};
static const unsigned int pci_address_space_en[] = {
PCI_0_BASE_ADDR_REG_ENABLE, PCI_1_BASE_ADDR_REG_ENABLE
};
static const unsigned int pci_snoop_control_base_0_low[] = {
PCI_0SNOOP_CONTROL_BASE_0_LOW, PCI_1SNOOP_CONTROL_BASE_0_LOW
};
static const unsigned int pci_snoop_control_top_0[] = {
PCI_0SNOOP_CONTROL_TOP_0, PCI_1SNOOP_CONTROL_TOP_0
};
static const unsigned int pci_access_control_base_0_low[] = {
PCI_0ACCESS_CONTROL_BASE_0_LOW, PCI_1ACCESS_CONTROL_BASE_0_LOW
};
static const unsigned int pci_access_control_top_0[] = {
PCI_0ACCESS_CONTROL_TOP_0, PCI_1ACCESS_CONTROL_TOP_0
};
static const unsigned int pci_scs_bank_size[2][4] = {
{PCI_0SCS_0_BANK_SIZE, PCI_0SCS_1_BANK_SIZE,
PCI_0SCS_2_BANK_SIZE, PCI_0SCS_3_BANK_SIZE},
{PCI_1SCS_0_BANK_SIZE, PCI_1SCS_1_BANK_SIZE,
PCI_1SCS_2_BANK_SIZE, PCI_1SCS_3_BANK_SIZE}
};
static const unsigned int pci_p2p_configuration[] = {
PCI_0P2P_CONFIGURATION, PCI_1P2P_CONFIGURATION
};
/********************************************************************
* pciWriteConfigReg - Write to a PCI configuration register
* - Make sure the GT is configured as a master before writing
* to another device on the PCI.
* - The function takes care of Big/Little endian conversion.
*
*
* Inputs: unsigned int regOffset: The register offset as it apears in the GT spec
* (or any other PCI device spec)
* pciDevNum: The device number needs to be addressed.
*
* Configuration Address 0xCF8:
*
* 31 30 24 23 16 15 11 10 8 7 2 0 <=bit Number
* |congif|Reserved| Bus |Device|Function|Register|00|
* |Enable| |Number|Number| Number | Number | | <=field Name
*
*********************************************************************/
void pciWriteConfigReg (PCI_HOST host, unsigned int regOffset,
unsigned int pciDevNum, unsigned int data)
{
volatile unsigned int DataForAddrReg;
unsigned int functionNum;
unsigned int busNum = 0;
unsigned int addr;
if (pciDevNum > 32) /* illegal device Number */
return;
if (pciDevNum == SELF) { /* configure our configuration space. */
pciDevNum =
(GTREGREAD (pci_p2p_configuration_reg[host]) >> 24) &
0x1f;
busNum = GTREGREAD (pci_p2p_configuration_reg[host]) &
0xff0000;
}
functionNum = regOffset & 0x00000700;
pciDevNum = pciDevNum << 11;
regOffset = regOffset & 0xfc;
DataForAddrReg =
(regOffset | pciDevNum | functionNum | busNum) | BIT31;
GT_REG_WRITE (pci_configuration_address[host], DataForAddrReg);
GT_REG_READ (pci_configuration_address[host], &addr);
if (addr != DataForAddrReg)
return;
GT_REG_WRITE (pci_configuration_data[host], data);
}
/********************************************************************
* pciReadConfigReg - Read from a PCI0 configuration register
* - Make sure the GT is configured as a master before reading
* from another device on the PCI.
* - The function takes care of Big/Little endian conversion.
* INPUTS: regOffset: The register offset as it apears in the GT spec (or PCI
* spec)
* pciDevNum: The device number needs to be addressed.
* RETURNS: data , if the data == 0xffffffff check the master abort bit in the
* cause register to make sure the data is valid
*
* Configuration Address 0xCF8:
*
* 31 30 24 23 16 15 11 10 8 7 2 0 <=bit Number
* |congif|Reserved| Bus |Device|Function|Register|00|
* |Enable| |Number|Number| Number | Number | | <=field Name
*
*********************************************************************/
unsigned int pciReadConfigReg (PCI_HOST host, unsigned int regOffset,
unsigned int pciDevNum)
{
volatile unsigned int DataForAddrReg;
unsigned int data;
unsigned int functionNum;
unsigned int busNum = 0;
if (pciDevNum > 32) /* illegal device Number */
return 0xffffffff;
if (pciDevNum == SELF) { /* configure our configuration space. */
pciDevNum =
(GTREGREAD (pci_p2p_configuration_reg[host]) >> 24) &
0x1f;
busNum = GTREGREAD (pci_p2p_configuration_reg[host]) &
0xff0000;
}
functionNum = regOffset & 0x00000700;
pciDevNum = pciDevNum << 11;
regOffset = regOffset & 0xfc;
DataForAddrReg =
(regOffset | pciDevNum | functionNum | busNum) | BIT31;
GT_REG_WRITE (pci_configuration_address[host], DataForAddrReg);
GT_REG_READ (pci_configuration_address[host], &data);
if (data != DataForAddrReg)
return 0xffffffff;
GT_REG_READ (pci_configuration_data[host], &data);
return data;
}
/********************************************************************
* pciOverBridgeWriteConfigReg - Write to a PCI configuration register where
* the agent is placed on another Bus. For more
* information read P2P in the PCI spec.
*
* Inputs: unsigned int regOffset - The register offset as it apears in the
* GT spec (or any other PCI device spec).
* unsigned int pciDevNum - The device number needs to be addressed.
* unsigned int busNum - On which bus does the Target agent connect
* to.
* unsigned int data - data to be written.
*
* Configuration Address 0xCF8:
*
* 31 30 24 23 16 15 11 10 8 7 2 0 <=bit Number
* |congif|Reserved| Bus |Device|Function|Register|01|
* |Enable| |Number|Number| Number | Number | | <=field Name
*
* The configuration Address is configure as type-I (bits[1:0] = '01') due to
* PCI spec referring to P2P.
*
*********************************************************************/
void pciOverBridgeWriteConfigReg (PCI_HOST host,
unsigned int regOffset,
unsigned int pciDevNum,
unsigned int busNum, unsigned int data)
{
unsigned int DataForReg;
unsigned int functionNum;
functionNum = regOffset & 0x00000700;
pciDevNum = pciDevNum << 11;
regOffset = regOffset & 0xff;
busNum = busNum << 16;
if (pciDevNum == SELF) { /* This board */
DataForReg = (regOffset | pciDevNum | functionNum) | BIT0;
} else {
DataForReg = (regOffset | pciDevNum | functionNum | busNum) |
BIT31 | BIT0;
}
GT_REG_WRITE (pci_configuration_address[host], DataForReg);
GT_REG_WRITE (pci_configuration_data[host], data);
}
/********************************************************************
* pciOverBridgeReadConfigReg - Read from a PCIn configuration register where
* the agent target locate on another PCI bus.
* - Make sure the GT is configured as a master
* before reading from another device on the PCI.
* - The function takes care of Big/Little endian
* conversion.
* INPUTS: regOffset: The register offset as it apears in the GT spec (or PCI
* spec). (configuration register offset.)
* pciDevNum: The device number needs to be addressed.
* busNum: the Bus number where the agent is place.
* RETURNS: data , if the data == 0xffffffff check the master abort bit in the
* cause register to make sure the data is valid
*
* Configuration Address 0xCF8:
*
* 31 30 24 23 16 15 11 10 8 7 2 0 <=bit Number
* |congif|Reserved| Bus |Device|Function|Register|01|
* |Enable| |Number|Number| Number | Number | | <=field Name
*
*********************************************************************/
unsigned int pciOverBridgeReadConfigReg (PCI_HOST host,
unsigned int regOffset,
unsigned int pciDevNum,
unsigned int busNum)
{
unsigned int DataForReg;
unsigned int data;
unsigned int functionNum;
functionNum = regOffset & 0x00000700;
pciDevNum = pciDevNum << 11;
regOffset = regOffset & 0xff;
busNum = busNum << 16;
if (pciDevNum == SELF) { /* This board */
DataForReg = (regOffset | pciDevNum | functionNum) | BIT31;
} else { /* agent on another bus */
DataForReg = (regOffset | pciDevNum | functionNum | busNum) |
BIT0 | BIT31;
}
GT_REG_WRITE (pci_configuration_address[host], DataForReg);
GT_REG_READ (pci_configuration_data[host], &data);
return data;
}
/********************************************************************
* pciGetRegOffset - Gets the register offset for this region config.
*
* INPUT: Bus, Region - The bus and region we ask for its base address.
* OUTPUT: N/A
* RETURNS: PCI register base address
*********************************************************************/
static unsigned int pciGetRegOffset (PCI_HOST host, PCI_REGION region)
{
switch (host) {
case PCI_HOST0:
switch (region) {
case PCI_IO:
return PCI_0I_O_LOW_DECODE_ADDRESS;
case PCI_REGION0:
return PCI_0MEMORY0_LOW_DECODE_ADDRESS;
case PCI_REGION1:
return PCI_0MEMORY1_LOW_DECODE_ADDRESS;
case PCI_REGION2:
return PCI_0MEMORY2_LOW_DECODE_ADDRESS;
case PCI_REGION3:
return PCI_0MEMORY3_LOW_DECODE_ADDRESS;
}
case PCI_HOST1:
switch (region) {
case PCI_IO:
return PCI_1I_O_LOW_DECODE_ADDRESS;
case PCI_REGION0:
return PCI_1MEMORY0_LOW_DECODE_ADDRESS;
case PCI_REGION1:
return PCI_1MEMORY1_LOW_DECODE_ADDRESS;
case PCI_REGION2:
return PCI_1MEMORY2_LOW_DECODE_ADDRESS;
case PCI_REGION3:
return PCI_1MEMORY3_LOW_DECODE_ADDRESS;
}
}
return PCI_0MEMORY0_LOW_DECODE_ADDRESS;
}
static unsigned int pciGetRemapOffset (PCI_HOST host, PCI_REGION region)
{
switch (host) {
case PCI_HOST0:
switch (region) {
case PCI_IO:
return PCI_0I_O_ADDRESS_REMAP;
case PCI_REGION0:
return PCI_0MEMORY0_ADDRESS_REMAP;
case PCI_REGION1:
return PCI_0MEMORY1_ADDRESS_REMAP;
case PCI_REGION2:
return PCI_0MEMORY2_ADDRESS_REMAP;
case PCI_REGION3:
return PCI_0MEMORY3_ADDRESS_REMAP;
}
case PCI_HOST1:
switch (region) {
case PCI_IO:
return PCI_1I_O_ADDRESS_REMAP;
case PCI_REGION0:
return PCI_1MEMORY0_ADDRESS_REMAP;
case PCI_REGION1:
return PCI_1MEMORY1_ADDRESS_REMAP;
case PCI_REGION2:
return PCI_1MEMORY2_ADDRESS_REMAP;
case PCI_REGION3:
return PCI_1MEMORY3_ADDRESS_REMAP;
}
}
return PCI_0MEMORY0_ADDRESS_REMAP;
}
/********************************************************************
* pciGetBaseAddress - Gets the base address of a PCI.
* - If the PCI size is 0 then this base address has no meaning!!!
*
*
* INPUT: Bus, Region - The bus and region we ask for its base address.
* OUTPUT: N/A
* RETURNS: PCI base address.
*********************************************************************/
unsigned int pciGetBaseAddress (PCI_HOST host, PCI_REGION region)
{
unsigned int regBase;
unsigned int regEnd;
unsigned int regOffset = pciGetRegOffset (host, region);
GT_REG_READ (regOffset, ®Base);
GT_REG_READ (regOffset + 8, ®End);
if (regEnd <= regBase)
return 0xffffffff; /* ERROR !!! */
regBase = regBase << 16;
return regBase;
}
bool pciMapSpace (PCI_HOST host, PCI_REGION region, unsigned int remapBase,
unsigned int bankBase, unsigned int bankLength)
{
unsigned int low = 0xfff;
unsigned int high = 0x0;
unsigned int regOffset = pciGetRegOffset (host, region);
unsigned int remapOffset = pciGetRemapOffset (host, region);
if (bankLength != 0) {
low = (bankBase >> 16) & 0xffff;
high = ((bankBase + bankLength) >> 16) - 1;
}
GT_REG_WRITE (regOffset, low | (1 << 24)); /* no swapping */
GT_REG_WRITE (regOffset + 8, high);
if (bankLength != 0) { /* must do AFTER writing maps */
GT_REG_WRITE (remapOffset, remapBase >> 16); /* sorry, 32 bits only.
dont support upper 32
in this driver */
}
return true;
}
unsigned int pciGetSpaceBase (PCI_HOST host, PCI_REGION region)
{
unsigned int low;
unsigned int regOffset = pciGetRegOffset (host, region);
GT_REG_READ (regOffset, &low);
return (low & 0xffff) << 16;
}
unsigned int pciGetSpaceSize (PCI_HOST host, PCI_REGION region)
{
unsigned int low, high;
unsigned int regOffset = pciGetRegOffset (host, region);
GT_REG_READ (regOffset, &low);
GT_REG_READ (regOffset + 8, &high);
return ((high & 0xffff) + 1) << 16;
}
/* ronen - 7/Dec/03*/
/********************************************************************
* gtPciDisable/EnableInternalBAR - This function enable/disable PCI BARS.
* Inputs: one of the PCI BAR
*********************************************************************/
void gtPciEnableInternalBAR (PCI_HOST host, PCI_INTERNAL_BAR pciBAR)
{
RESET_REG_BITS (pci_address_space_en[host], BIT0 << pciBAR);
}
void gtPciDisableInternalBAR (PCI_HOST host, PCI_INTERNAL_BAR pciBAR)
{
SET_REG_BITS (pci_address_space_en[host], BIT0 << pciBAR);
}
/********************************************************************
* pciMapMemoryBank - Maps PCI_host memory bank "bank" for the slave.
*
* Inputs: base and size of PCI SCS
*********************************************************************/
void pciMapMemoryBank (PCI_HOST host, MEMORY_BANK bank,
unsigned int pciDramBase, unsigned int pciDramSize)
{
/*ronen different function for 3rd bank. */
unsigned int offset = (bank < 2) ? bank * 8 : 0x100 + (bank - 2) * 8;
pciDramBase = pciDramBase & 0xfffff000;
pciDramBase = pciDramBase | (pciReadConfigReg (host,
PCI_SCS_0_BASE_ADDRESS
+ offset,
SELF) & 0x00000fff);
pciWriteConfigReg (host, PCI_SCS_0_BASE_ADDRESS + offset, SELF,
pciDramBase);
if (pciDramSize == 0)
pciDramSize++;
GT_REG_WRITE (pci_scs_bank_size[host][bank], pciDramSize - 1);
gtPciEnableInternalBAR (host, bank);
}
/********************************************************************
* pciSetRegionFeatures - This function modifys one of the 8 regions with
* feature bits given as an input.
* - Be advised to check the spec before modifying them.
* Inputs: PCI_PROTECT_REGION region - one of the eight regions.
* unsigned int features - See file: pci.h there are defintion for those
* region features.
* unsigned int baseAddress - The region base Address.
* unsigned int topAddress - The region top Address.
* Returns: false if one of the parameters is erroneous true otherwise.
*********************************************************************/
bool pciSetRegionFeatures (PCI_HOST host, PCI_ACCESS_REGIONS region,
unsigned int features, unsigned int baseAddress,
unsigned int regionLength)
{
unsigned int accessLow;
unsigned int accessHigh;
unsigned int accessTop = baseAddress + regionLength;
if (regionLength == 0) { /* close the region. */
pciDisableAccessRegion (host, region);
return true;
}
/* base Address is store is bits [11:0] */
accessLow = (baseAddress & 0xfff00000) >> 20;
/* All the features are update according to the defines in pci.h (to be on
the safe side we disable bits: [11:0] */
accessLow = accessLow | (features & 0xfffff000);
/* write to the Low Access Region register */
GT_REG_WRITE (pci_access_control_base_0_low[host] + 0x10 * region,
accessLow);
accessHigh = (accessTop & 0xfff00000) >> 20;
/* write to the High Access Region register */
GT_REG_WRITE (pci_access_control_top_0[host] + 0x10 * region,
accessHigh - 1);
return true;
}
/********************************************************************
* pciDisableAccessRegion - Disable The given Region by writing MAX size
* to its low Address and MIN size to its high Address.
*
* Inputs: PCI_ACCESS_REGIONS region - The region we to be Disabled.
* Returns: N/A.
*********************************************************************/
void pciDisableAccessRegion (PCI_HOST host, PCI_ACCESS_REGIONS region)
{
/* writing back the registers default values. */
GT_REG_WRITE (pci_access_control_base_0_low[host] + 0x10 * region,
0x01001fff);
GT_REG_WRITE (pci_access_control_top_0[host] + 0x10 * region, 0);
}
/********************************************************************
* pciArbiterEnable - Enables PCI-0`s Arbitration mechanism.
*
* Inputs: N/A
* Returns: true.
*********************************************************************/
bool pciArbiterEnable (PCI_HOST host)
{
unsigned int regData;
GT_REG_READ (pci_arbiter_control[host], ®Data);
GT_REG_WRITE (pci_arbiter_control[host], regData | BIT31);
return true;
}
/********************************************************************
* pciArbiterDisable - Disable PCI-0`s Arbitration mechanism.
*
* Inputs: N/A
* Returns: true
*********************************************************************/
bool pciArbiterDisable (PCI_HOST host)
{
unsigned int regData;
GT_REG_READ (pci_arbiter_control[host], ®Data);
GT_REG_WRITE (pci_arbiter_control[host], regData & 0x7fffffff);
return true;
}
/********************************************************************
* pciSetArbiterAgentsPriority - Priority setup for the PCI agents (Hi or Low)
*
* Inputs: PCI_AGENT_PRIO internalAgent - priotity for internal agent.
* PCI_AGENT_PRIO externalAgent0 - priotity for external#0 agent.
* PCI_AGENT_PRIO externalAgent1 - priotity for external#1 agent.
* PCI_AGENT_PRIO externalAgent2 - priotity for external#2 agent.
* PCI_AGENT_PRIO externalAgent3 - priotity for external#3 agent.
* PCI_AGENT_PRIO externalAgent4 - priotity for external#4 agent.
* PCI_AGENT_PRIO externalAgent5 - priotity for external#5 agent.
* Returns: true
*********************************************************************/
bool pciSetArbiterAgentsPriority (PCI_HOST host, PCI_AGENT_PRIO internalAgent,
PCI_AGENT_PRIO externalAgent0,
PCI_AGENT_PRIO externalAgent1,
PCI_AGENT_PRIO externalAgent2,
PCI_AGENT_PRIO externalAgent3,
PCI_AGENT_PRIO externalAgent4,
PCI_AGENT_PRIO externalAgent5)
{
unsigned int regData;
unsigned int writeData;
GT_REG_READ (pci_arbiter_control[host], ®Data);
writeData = (internalAgent << 7) + (externalAgent0 << 8) +
(externalAgent1 << 9) + (externalAgent2 << 10) +
(externalAgent3 << 11) + (externalAgent4 << 12) +
(externalAgent5 << 13);
regData = (regData & 0xffffc07f) | writeData;
GT_REG_WRITE (pci_arbiter_control[host], regData & regData);
return true;
}
/********************************************************************
* pciParkingDisable - Park on last option disable, with this function you can
* disable the park on last mechanism for each agent.
* disabling this option for all agents results parking
* on the internal master.
*
* Inputs: PCI_AGENT_PARK internalAgent - parking Disable for internal agent.
* PCI_AGENT_PARK externalAgent0 - parking Disable for external#0 agent.
* PCI_AGENT_PARK externalAgent1 - parking Disable for external#1 agent.
* PCI_AGENT_PARK externalAgent2 - parking Disable for external#2 agent.
* PCI_AGENT_PARK externalAgent3 - parking Disable for external#3 agent.
* PCI_AGENT_PARK externalAgent4 - parking Disable for external#4 agent.
* PCI_AGENT_PARK externalAgent5 - parking Disable for external#5 agent.
* Returns: true
*********************************************************************/
bool pciParkingDisable (PCI_HOST host, PCI_AGENT_PARK internalAgent,
PCI_AGENT_PARK externalAgent0,
PCI_AGENT_PARK externalAgent1,
PCI_AGENT_PARK externalAgent2,
PCI_AGENT_PARK externalAgent3,
PCI_AGENT_PARK externalAgent4,
PCI_AGENT_PARK externalAgent5)
{
unsigned int regData;
unsigned int writeData;
GT_REG_READ (pci_arbiter_control[host], ®Data);
writeData = (internalAgent << 14) + (externalAgent0 << 15) +
(externalAgent1 << 16) + (externalAgent2 << 17) +
(externalAgent3 << 18) + (externalAgent4 << 19) +
(externalAgent5 << 20);
regData = (regData & ~(0x7f << 14)) | writeData;
GT_REG_WRITE (pci_arbiter_control[host], regData);
return true;
}
/********************************************************************
* pciEnableBrokenAgentDetection - A master is said to be broken if it fails to
* respond to grant assertion within a window specified in
* the input value: 'brokenValue'.
*
* Inputs: unsigned char brokenValue - A value which limits the Master to hold the
* grant without asserting frame.
* Returns: Error for illegal broken value otherwise true.
*********************************************************************/
bool pciEnableBrokenAgentDetection (PCI_HOST host, unsigned char brokenValue)
{
unsigned int data;
unsigned int regData;
if (brokenValue > 0xf)
return false; /* brokenValue must be 4 bit */
data = brokenValue << 3;
GT_REG_READ (pci_arbiter_control[host], ®Data);
regData = (regData & 0xffffff87) | data;
GT_REG_WRITE (pci_arbiter_control[host], regData | BIT1);
return true;
}
/********************************************************************
* pciDisableBrokenAgentDetection - This function disable the Broken agent
* Detection mechanism.
* NOTE: This operation may cause a dead lock on the
* pci0 arbitration.
*
* Inputs: N/A
* Returns: true.
*********************************************************************/
bool pciDisableBrokenAgentDetection (PCI_HOST host)
{
unsigned int regData;
GT_REG_READ (pci_arbiter_control[host], ®Data);
regData = regData & 0xfffffffd;
GT_REG_WRITE (pci_arbiter_control[host], regData);
return true;
}
/********************************************************************
* pciP2PConfig - This function set the PCI_n P2P configurate.
* For more information on the P2P read PCI spec.
*
* Inputs: unsigned int SecondBusLow - Secondery PCI interface Bus Range Lower
* Boundry.
* unsigned int SecondBusHigh - Secondry PCI interface Bus Range upper
* Boundry.
* unsigned int busNum - The CPI bus number to which the PCI interface
* is connected.
* unsigned int devNum - The PCI interface's device number.
*
* Returns: true.
*********************************************************************/
bool pciP2PConfig (PCI_HOST host, unsigned int SecondBusLow,
unsigned int SecondBusHigh,
unsigned int busNum, unsigned int devNum)
{
unsigned int regData;
regData = (SecondBusLow & 0xff) | ((SecondBusHigh & 0xff) << 8) |
((busNum & 0xff) << 16) | ((devNum & 0x1f) << 24);
GT_REG_WRITE (pci_p2p_configuration[host], regData);
return true;
}
/********************************************************************
* pciSetRegionSnoopMode - This function modifys one of the 4 regions which
* supports Cache Coherency in the PCI_n interface.
* Inputs: region - One of the four regions.
* snoopType - There is four optional Types:
* 1. No Snoop.
* 2. Snoop to WT region.
* 3. Snoop to WB region.
* 4. Snoop & Invalidate to WB region.
* baseAddress - Base Address of this region.
* regionLength - Region length.
* Returns: false if one of the parameters is wrong otherwise return true.
*********************************************************************/
bool pciSetRegionSnoopMode (PCI_HOST host, PCI_SNOOP_REGION region,
PCI_SNOOP_TYPE snoopType,
unsigned int baseAddress,
unsigned int regionLength)
{
unsigned int snoopXbaseAddress;
unsigned int snoopXtopAddress;
unsigned int data;
unsigned int snoopHigh = baseAddress + regionLength;
if ((region > PCI_SNOOP_REGION3) || (snoopType > PCI_SNOOP_WB))
return false;
snoopXbaseAddress =
pci_snoop_control_base_0_low[host] + 0x10 * region;
snoopXtopAddress = pci_snoop_control_top_0[host] + 0x10 * region;
if (regionLength == 0) { /* closing the region */
GT_REG_WRITE (snoopXbaseAddress, 0x0000ffff);
GT_REG_WRITE (snoopXtopAddress, 0);
return true;
}
baseAddress = baseAddress & 0xfff00000; /* Granularity of 1MByte */
data = (baseAddress >> 20) | snoopType << 12;
GT_REG_WRITE (snoopXbaseAddress, data);
snoopHigh = (snoopHigh & 0xfff00000) >> 20;
GT_REG_WRITE (snoopXtopAddress, snoopHigh - 1);
return true;
}
static int gt_read_config_dword (struct pci_controller *hose,
pci_dev_t dev, int offset, u32 * value)
{
int bus = PCI_BUS (dev);
if ((bus == local_buses[0]) || (bus == local_buses[1])) {
*value = pciReadConfigReg ((PCI_HOST) hose->cfg_addr, offset,
PCI_DEV (dev));
} else {
*value = pciOverBridgeReadConfigReg ((PCI_HOST) hose->
cfg_addr, offset,
PCI_DEV (dev), bus);
}
return 0;
}
static int gt_write_config_dword (struct pci_controller *hose,
pci_dev_t dev, int offset, u32 value)
{
int bus = PCI_BUS (dev);
if ((bus == local_buses[0]) || (bus == local_buses[1])) {
pciWriteConfigReg ((PCI_HOST) hose->cfg_addr, offset,
PCI_DEV (dev), value);
} else {
pciOverBridgeWriteConfigReg ((PCI_HOST) hose->cfg_addr,
offset, PCI_DEV (dev), bus,
value);
}
return 0;
}
static void gt_setup_ide (struct pci_controller *hose,
pci_dev_t dev, struct pci_config_table *entry)
{
static const int ide_bar[] = { 8, 4, 8, 4, 0, 0 };
u32 bar_response, bar_value;
int bar;
for (bar = 0; bar < 6; bar++) {
/*ronen different function for 3rd bank. */
unsigned int offset =
(bar < 2) ? bar * 8 : 0x100 + (bar - 2) * 8;
pci_write_config_dword (dev, PCI_BASE_ADDRESS_0 + offset,
0x0);
pci_read_config_dword (dev, PCI_BASE_ADDRESS_0 + offset,
&bar_response);
pciauto_region_allocate (bar_response &
PCI_BASE_ADDRESS_SPACE_IO ? hose->
pci_io : hose->pci_mem, ide_bar[bar],
&bar_value);
pci_write_config_dword (dev, PCI_BASE_ADDRESS_0 + bar * 4,
bar_value);
}
}
/* TODO BJW: Change this for DB64360. This was pulled from the EV64260 */
/* and is curently not called *. */
#if 0
static void gt_fixup_irq (struct pci_controller *hose, pci_dev_t dev)
{
unsigned char pin, irq;
pci_read_config_byte (dev, PCI_INTERRUPT_PIN, &pin);
if (pin == 1) { /* only allow INT A */
irq = pci_irq_swizzle[(PCI_HOST) hose->
cfg_addr][PCI_DEV (dev)];
if (irq)
pci_write_config_byte (dev, PCI_INTERRUPT_LINE, irq);
}
}
#endif
struct pci_config_table gt_config_table[] = {
{PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE,
PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, gt_setup_ide},
{}
};
struct pci_controller pci0_hose = {
/* fixup_irq: gt_fixup_irq, */
config_table:gt_config_table,
};
struct pci_controller pci1_hose = {
/* fixup_irq: gt_fixup_irq, */
config_table:gt_config_table,
};
void pci_init_board (void)
{
unsigned int command;
#ifdef DEBUG
gt_pci_bus_mode_display (PCI_HOST0);
#endif
pci0_hose.first_busno = 0;
pci0_hose.last_busno = 0xff;
local_buses[0] = pci0_hose.first_busno;
/* PCI memory space */
pci_set_region (pci0_hose.regions + 0,
CONFIG_SYS_PCI0_0_MEM_SPACE,
CONFIG_SYS_PCI0_0_MEM_SPACE,
CONFIG_SYS_PCI0_MEM_SIZE, PCI_REGION_MEM);
/* PCI I/O space */
pci_set_region (pci0_hose.regions + 1,
CONFIG_SYS_PCI0_IO_SPACE_PCI,
CONFIG_SYS_PCI0_IO_SPACE, CONFIG_SYS_PCI0_IO_SIZE, PCI_REGION_IO);
pci_set_ops (&pci0_hose,
pci_hose_read_config_byte_via_dword,
pci_hose_read_config_word_via_dword,
gt_read_config_dword,
pci_hose_write_config_byte_via_dword,
pci_hose_write_config_word_via_dword,
gt_write_config_dword);
pci0_hose.region_count = 2;
pci0_hose.cfg_addr = (unsigned int *) PCI_HOST0;
pci_register_hose (&pci0_hose);
pciArbiterEnable (PCI_HOST0);
pciParkingDisable (PCI_HOST0, 1, 1, 1, 1, 1, 1, 1);
command = pciReadConfigReg (PCI_HOST0, PCI_COMMAND, SELF);
command |= PCI_COMMAND_MASTER;
pciWriteConfigReg (PCI_HOST0, PCI_COMMAND, SELF, command);
command = pciReadConfigReg (PCI_HOST0, PCI_COMMAND, SELF);
command |= PCI_COMMAND_MEMORY;
pciWriteConfigReg (PCI_HOST0, PCI_COMMAND, SELF, command);
pci0_hose.last_busno = pci_hose_scan (&pci0_hose);
#ifdef DEBUG
gt_pci_bus_mode_display (PCI_HOST1);
#endif
pci1_hose.first_busno = pci0_hose.last_busno + 1;
pci1_hose.last_busno = 0xff;
pci1_hose.current_busno = pci1_hose.first_busno;
local_buses[1] = pci1_hose.first_busno;
/* PCI memory space */
pci_set_region (pci1_hose.regions + 0,
CONFIG_SYS_PCI1_0_MEM_SPACE,
CONFIG_SYS_PCI1_0_MEM_SPACE,
CONFIG_SYS_PCI1_MEM_SIZE, PCI_REGION_MEM);
/* PCI I/O space */
pci_set_region (pci1_hose.regions + 1,
CONFIG_SYS_PCI1_IO_SPACE_PCI,
CONFIG_SYS_PCI1_IO_SPACE, CONFIG_SYS_PCI1_IO_SIZE, PCI_REGION_IO);
pci_set_ops (&pci1_hose,
pci_hose_read_config_byte_via_dword,
pci_hose_read_config_word_via_dword,
gt_read_config_dword,
pci_hose_write_config_byte_via_dword,
pci_hose_write_config_word_via_dword,
gt_write_config_dword);
pci1_hose.region_count = 2;
pci1_hose.cfg_addr = (unsigned int *) PCI_HOST1;
pci_register_hose (&pci1_hose);
pciArbiterEnable (PCI_HOST1);
pciParkingDisable (PCI_HOST1, 1, 1, 1, 1, 1, 1, 1);
command = pciReadConfigReg (PCI_HOST1, PCI_COMMAND, SELF);
command |= PCI_COMMAND_MASTER;
pciWriteConfigReg (PCI_HOST1, PCI_COMMAND, SELF, command);
pci1_hose.last_busno = pci_hose_scan (&pci1_hose);
command = pciReadConfigReg (PCI_HOST1, PCI_COMMAND, SELF);
command |= PCI_COMMAND_MEMORY;
pciWriteConfigReg (PCI_HOST1, PCI_COMMAND, SELF, command);
}
| gpl-2.0 |
simo97/linux | arch/m68k/coldfire/m520x.c | 1558 | 5061 | /***************************************************************************/
/*
* m520x.c -- platform support for ColdFire 520x based boards
*
* Copyright (C) 2005, Freescale (www.freescale.com)
* Copyright (C) 2005, Intec Automation (mike@steroidmicros.com)
* Copyright (C) 1999-2007, Greg Ungerer (gerg@snapgear.com)
* Copyright (C) 2001-2003, SnapGear Inc. (www.snapgear.com)
*/
/***************************************************************************/
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/init.h>
#include <linux/io.h>
#include <asm/machdep.h>
#include <asm/coldfire.h>
#include <asm/mcfsim.h>
#include <asm/mcfuart.h>
#include <asm/mcfclk.h>
/***************************************************************************/
DEFINE_CLK(0, "flexbus", 2, MCF_CLK);
DEFINE_CLK(0, "fec.0", 12, MCF_CLK);
DEFINE_CLK(0, "edma", 17, MCF_CLK);
DEFINE_CLK(0, "intc.0", 18, MCF_CLK);
DEFINE_CLK(0, "iack.0", 21, MCF_CLK);
DEFINE_CLK(0, "mcfi2c.0", 22, MCF_CLK);
DEFINE_CLK(0, "mcfqspi.0", 23, MCF_CLK);
DEFINE_CLK(0, "mcfuart.0", 24, MCF_BUSCLK);
DEFINE_CLK(0, "mcfuart.1", 25, MCF_BUSCLK);
DEFINE_CLK(0, "mcfuart.2", 26, MCF_BUSCLK);
DEFINE_CLK(0, "mcftmr.0", 28, MCF_CLK);
DEFINE_CLK(0, "mcftmr.1", 29, MCF_CLK);
DEFINE_CLK(0, "mcftmr.2", 30, MCF_CLK);
DEFINE_CLK(0, "mcftmr.3", 31, MCF_CLK);
DEFINE_CLK(0, "mcfpit.0", 32, MCF_CLK);
DEFINE_CLK(0, "mcfpit.1", 33, MCF_CLK);
DEFINE_CLK(0, "mcfeport.0", 34, MCF_CLK);
DEFINE_CLK(0, "mcfwdt.0", 35, MCF_CLK);
DEFINE_CLK(0, "pll.0", 36, MCF_CLK);
DEFINE_CLK(0, "sys.0", 40, MCF_BUSCLK);
DEFINE_CLK(0, "gpio.0", 41, MCF_BUSCLK);
DEFINE_CLK(0, "sdram.0", 42, MCF_CLK);
struct clk *mcf_clks[] = {
&__clk_0_2, /* flexbus */
&__clk_0_12, /* fec.0 */
&__clk_0_17, /* edma */
&__clk_0_18, /* intc.0 */
&__clk_0_21, /* iack.0 */
&__clk_0_22, /* mcfi2c.0 */
&__clk_0_23, /* mcfqspi.0 */
&__clk_0_24, /* mcfuart.0 */
&__clk_0_25, /* mcfuart.1 */
&__clk_0_26, /* mcfuart.2 */
&__clk_0_28, /* mcftmr.0 */
&__clk_0_29, /* mcftmr.1 */
&__clk_0_30, /* mcftmr.2 */
&__clk_0_31, /* mcftmr.3 */
&__clk_0_32, /* mcfpit.0 */
&__clk_0_33, /* mcfpit.1 */
&__clk_0_34, /* mcfeport.0 */
&__clk_0_35, /* mcfwdt.0 */
&__clk_0_36, /* pll.0 */
&__clk_0_40, /* sys.0 */
&__clk_0_41, /* gpio.0 */
&__clk_0_42, /* sdram.0 */
NULL,
};
static struct clk * const enable_clks[] __initconst = {
&__clk_0_2, /* flexbus */
&__clk_0_18, /* intc.0 */
&__clk_0_21, /* iack.0 */
&__clk_0_24, /* mcfuart.0 */
&__clk_0_25, /* mcfuart.1 */
&__clk_0_26, /* mcfuart.2 */
&__clk_0_32, /* mcfpit.0 */
&__clk_0_33, /* mcfpit.1 */
&__clk_0_34, /* mcfeport.0 */
&__clk_0_36, /* pll.0 */
&__clk_0_40, /* sys.0 */
&__clk_0_41, /* gpio.0 */
&__clk_0_42, /* sdram.0 */
};
static struct clk * const disable_clks[] __initconst = {
&__clk_0_12, /* fec.0 */
&__clk_0_17, /* edma */
&__clk_0_22, /* mcfi2c.0 */
&__clk_0_23, /* mcfqspi.0 */
&__clk_0_28, /* mcftmr.0 */
&__clk_0_29, /* mcftmr.1 */
&__clk_0_30, /* mcftmr.2 */
&__clk_0_31, /* mcftmr.3 */
&__clk_0_35, /* mcfwdt.0 */
};
static void __init m520x_clk_init(void)
{
unsigned i;
/* make sure these clocks are enabled */
for (i = 0; i < ARRAY_SIZE(enable_clks); ++i)
__clk_init_enabled(enable_clks[i]);
/* make sure these clocks are disabled */
for (i = 0; i < ARRAY_SIZE(disable_clks); ++i)
__clk_init_disabled(disable_clks[i]);
}
/***************************************************************************/
static void __init m520x_qspi_init(void)
{
#if IS_ENABLED(CONFIG_SPI_COLDFIRE_QSPI)
u16 par;
/* setup Port QS for QSPI with gpio CS control */
writeb(0x3f, MCF_GPIO_PAR_QSPI);
/* make U1CTS and U2RTS gpio for cs_control */
par = readw(MCF_GPIO_PAR_UART);
par &= 0x00ff;
writew(par, MCF_GPIO_PAR_UART);
#endif /* IS_ENABLED(CONFIG_SPI_COLDFIRE_QSPI) */
}
/***************************************************************************/
static void __init m520x_uarts_init(void)
{
u16 par;
u8 par2;
/* UART0 and UART1 GPIO pin setup */
par = readw(MCF_GPIO_PAR_UART);
par |= MCF_GPIO_PAR_UART_PAR_UTXD0 | MCF_GPIO_PAR_UART_PAR_URXD0;
par |= MCF_GPIO_PAR_UART_PAR_UTXD1 | MCF_GPIO_PAR_UART_PAR_URXD1;
writew(par, MCF_GPIO_PAR_UART);
/* UART1 GPIO pin setup */
par2 = readb(MCF_GPIO_PAR_FECI2C);
par2 &= ~0x0F;
par2 |= MCF_GPIO_PAR_FECI2C_PAR_SCL_UTXD2 |
MCF_GPIO_PAR_FECI2C_PAR_SDA_URXD2;
writeb(par2, MCF_GPIO_PAR_FECI2C);
}
/***************************************************************************/
static void __init m520x_fec_init(void)
{
u8 v;
/* Set multi-function pins to ethernet mode */
v = readb(MCF_GPIO_PAR_FEC);
writeb(v | 0xf0, MCF_GPIO_PAR_FEC);
v = readb(MCF_GPIO_PAR_FECI2C);
writeb(v | 0x0f, MCF_GPIO_PAR_FECI2C);
}
/***************************************************************************/
void __init config_BSP(char *commandp, int size)
{
mach_sched_init = hw_timer_init;
m520x_clk_init();
m520x_uarts_init();
m520x_fec_init();
m520x_qspi_init();
}
/***************************************************************************/
| gpl-2.0 |
SiddheshK15/android_kernel_yu_msm8916_gcc5 | arch/powerpc/sysdev/qe_lib/ucc.c | 2326 | 5578 | /*
* arch/powerpc/sysdev/qe_lib/ucc.c
*
* QE UCC API Set - UCC specific routines implementations.
*
* Copyright (C) 2006 Freescale Semiconductor, Inc. All rights reserved.
*
* Authors: Shlomi Gridish <gridish@freescale.com>
* Li Yang <leoli@freescale.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/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/stddef.h>
#include <linux/spinlock.h>
#include <linux/export.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/immap_qe.h>
#include <asm/qe.h>
#include <asm/ucc.h>
int ucc_set_qe_mux_mii_mng(unsigned int ucc_num)
{
unsigned long flags;
if (ucc_num > UCC_MAX_NUM - 1)
return -EINVAL;
spin_lock_irqsave(&cmxgcr_lock, flags);
clrsetbits_be32(&qe_immr->qmx.cmxgcr, QE_CMXGCR_MII_ENET_MNG,
ucc_num << QE_CMXGCR_MII_ENET_MNG_SHIFT);
spin_unlock_irqrestore(&cmxgcr_lock, flags);
return 0;
}
EXPORT_SYMBOL(ucc_set_qe_mux_mii_mng);
/* Configure the UCC to either Slow or Fast.
*
* A given UCC can be figured to support either "slow" devices (e.g. UART)
* or "fast" devices (e.g. Ethernet).
*
* 'ucc_num' is the UCC number, from 0 - 7.
*
* This function also sets the UCC_GUEMR_SET_RESERVED3 bit because that bit
* must always be set to 1.
*/
int ucc_set_type(unsigned int ucc_num, enum ucc_speed_type speed)
{
u8 __iomem *guemr;
/* The GUEMR register is at the same location for both slow and fast
devices, so we just use uccX.slow.guemr. */
switch (ucc_num) {
case 0: guemr = &qe_immr->ucc1.slow.guemr;
break;
case 1: guemr = &qe_immr->ucc2.slow.guemr;
break;
case 2: guemr = &qe_immr->ucc3.slow.guemr;
break;
case 3: guemr = &qe_immr->ucc4.slow.guemr;
break;
case 4: guemr = &qe_immr->ucc5.slow.guemr;
break;
case 5: guemr = &qe_immr->ucc6.slow.guemr;
break;
case 6: guemr = &qe_immr->ucc7.slow.guemr;
break;
case 7: guemr = &qe_immr->ucc8.slow.guemr;
break;
default:
return -EINVAL;
}
clrsetbits_8(guemr, UCC_GUEMR_MODE_MASK,
UCC_GUEMR_SET_RESERVED3 | speed);
return 0;
}
static void get_cmxucr_reg(unsigned int ucc_num, __be32 __iomem **cmxucr,
unsigned int *reg_num, unsigned int *shift)
{
unsigned int cmx = ((ucc_num & 1) << 1) + (ucc_num > 3);
*reg_num = cmx + 1;
*cmxucr = &qe_immr->qmx.cmxucr[cmx];
*shift = 16 - 8 * (ucc_num & 2);
}
int ucc_mux_set_grant_tsa_bkpt(unsigned int ucc_num, int set, u32 mask)
{
__be32 __iomem *cmxucr;
unsigned int reg_num;
unsigned int shift;
/* check if the UCC number is in range. */
if (ucc_num > UCC_MAX_NUM - 1)
return -EINVAL;
get_cmxucr_reg(ucc_num, &cmxucr, ®_num, &shift);
if (set)
setbits32(cmxucr, mask << shift);
else
clrbits32(cmxucr, mask << shift);
return 0;
}
int ucc_set_qe_mux_rxtx(unsigned int ucc_num, enum qe_clock clock,
enum comm_dir mode)
{
__be32 __iomem *cmxucr;
unsigned int reg_num;
unsigned int shift;
u32 clock_bits = 0;
/* check if the UCC number is in range. */
if (ucc_num > UCC_MAX_NUM - 1)
return -EINVAL;
/* The communications direction must be RX or TX */
if (!((mode == COMM_DIR_RX) || (mode == COMM_DIR_TX)))
return -EINVAL;
get_cmxucr_reg(ucc_num, &cmxucr, ®_num, &shift);
switch (reg_num) {
case 1:
switch (clock) {
case QE_BRG1: clock_bits = 1; break;
case QE_BRG2: clock_bits = 2; break;
case QE_BRG7: clock_bits = 3; break;
case QE_BRG8: clock_bits = 4; break;
case QE_CLK9: clock_bits = 5; break;
case QE_CLK10: clock_bits = 6; break;
case QE_CLK11: clock_bits = 7; break;
case QE_CLK12: clock_bits = 8; break;
case QE_CLK15: clock_bits = 9; break;
case QE_CLK16: clock_bits = 10; break;
default: break;
}
break;
case 2:
switch (clock) {
case QE_BRG5: clock_bits = 1; break;
case QE_BRG6: clock_bits = 2; break;
case QE_BRG7: clock_bits = 3; break;
case QE_BRG8: clock_bits = 4; break;
case QE_CLK13: clock_bits = 5; break;
case QE_CLK14: clock_bits = 6; break;
case QE_CLK19: clock_bits = 7; break;
case QE_CLK20: clock_bits = 8; break;
case QE_CLK15: clock_bits = 9; break;
case QE_CLK16: clock_bits = 10; break;
default: break;
}
break;
case 3:
switch (clock) {
case QE_BRG9: clock_bits = 1; break;
case QE_BRG10: clock_bits = 2; break;
case QE_BRG15: clock_bits = 3; break;
case QE_BRG16: clock_bits = 4; break;
case QE_CLK3: clock_bits = 5; break;
case QE_CLK4: clock_bits = 6; break;
case QE_CLK17: clock_bits = 7; break;
case QE_CLK18: clock_bits = 8; break;
case QE_CLK7: clock_bits = 9; break;
case QE_CLK8: clock_bits = 10; break;
case QE_CLK16: clock_bits = 11; break;
default: break;
}
break;
case 4:
switch (clock) {
case QE_BRG13: clock_bits = 1; break;
case QE_BRG14: clock_bits = 2; break;
case QE_BRG15: clock_bits = 3; break;
case QE_BRG16: clock_bits = 4; break;
case QE_CLK5: clock_bits = 5; break;
case QE_CLK6: clock_bits = 6; break;
case QE_CLK21: clock_bits = 7; break;
case QE_CLK22: clock_bits = 8; break;
case QE_CLK7: clock_bits = 9; break;
case QE_CLK8: clock_bits = 10; break;
case QE_CLK16: clock_bits = 11; break;
default: break;
}
break;
default: break;
}
/* Check for invalid combination of clock and UCC number */
if (!clock_bits)
return -ENOENT;
if (mode == COMM_DIR_RX)
shift += 4;
clrsetbits_be32(cmxucr, QE_CMXUCR_TX_CLK_SRC_MASK << shift,
clock_bits << shift);
return 0;
}
| gpl-2.0 |
htc-mirror/holiday-ics-crc-3.0.16-25afef7 | arch/x86/kvm/svm.c | 2326 | 111159 | /*
* Kernel-based Virtual Machine driver for Linux
*
* AMD SVM support
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Yaniv Kamay <yaniv@qumranet.com>
* Avi Kivity <avi@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <linux/kvm_host.h>
#include "irq.h"
#include "mmu.h"
#include "kvm_cache_regs.h"
#include "x86.h"
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/vmalloc.h>
#include <linux/highmem.h>
#include <linux/sched.h>
#include <linux/ftrace_event.h>
#include <linux/slab.h>
#include <asm/tlbflush.h>
#include <asm/desc.h>
#include <asm/kvm_para.h>
#include <asm/virtext.h>
#include "trace.h"
#define __ex(x) __kvm_handle_fault_on_reboot(x)
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
#define IOPM_ALLOC_ORDER 2
#define MSRPM_ALLOC_ORDER 1
#define SEG_TYPE_LDT 2
#define SEG_TYPE_BUSY_TSS16 3
#define SVM_FEATURE_NPT (1 << 0)
#define SVM_FEATURE_LBRV (1 << 1)
#define SVM_FEATURE_SVML (1 << 2)
#define SVM_FEATURE_NRIP (1 << 3)
#define SVM_FEATURE_TSC_RATE (1 << 4)
#define SVM_FEATURE_VMCB_CLEAN (1 << 5)
#define SVM_FEATURE_FLUSH_ASID (1 << 6)
#define SVM_FEATURE_DECODE_ASSIST (1 << 7)
#define SVM_FEATURE_PAUSE_FILTER (1 << 10)
#define NESTED_EXIT_HOST 0 /* Exit handled on host level */
#define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
#define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
#define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
#define TSC_RATIO_RSVD 0xffffff0000000000ULL
#define TSC_RATIO_MIN 0x0000000000000001ULL
#define TSC_RATIO_MAX 0x000000ffffffffffULL
static bool erratum_383_found __read_mostly;
static const u32 host_save_user_msrs[] = {
#ifdef CONFIG_X86_64
MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
MSR_FS_BASE,
#endif
MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
};
#define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
struct kvm_vcpu;
struct nested_state {
struct vmcb *hsave;
u64 hsave_msr;
u64 vm_cr_msr;
u64 vmcb;
/* These are the merged vectors */
u32 *msrpm;
/* gpa pointers to the real vectors */
u64 vmcb_msrpm;
u64 vmcb_iopm;
/* A VMEXIT is required but not yet emulated */
bool exit_required;
/* cache for intercepts of the guest */
u32 intercept_cr;
u32 intercept_dr;
u32 intercept_exceptions;
u64 intercept;
/* Nested Paging related state */
u64 nested_cr3;
};
#define MSRPM_OFFSETS 16
static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
struct vcpu_svm {
struct kvm_vcpu vcpu;
struct vmcb *vmcb;
unsigned long vmcb_pa;
struct svm_cpu_data *svm_data;
uint64_t asid_generation;
uint64_t sysenter_esp;
uint64_t sysenter_eip;
u64 next_rip;
u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
struct {
u16 fs;
u16 gs;
u16 ldt;
u64 gs_base;
} host;
u32 *msrpm;
ulong nmi_iret_rip;
struct nested_state nested;
bool nmi_singlestep;
unsigned int3_injected;
unsigned long int3_rip;
u32 apf_reason;
u64 tsc_ratio;
};
static DEFINE_PER_CPU(u64, current_tsc_ratio);
#define TSC_RATIO_DEFAULT 0x0100000000ULL
#define MSR_INVALID 0xffffffffU
static struct svm_direct_access_msrs {
u32 index; /* Index of the MSR */
bool always; /* True if intercept is always on */
} direct_access_msrs[] = {
{ .index = MSR_STAR, .always = true },
{ .index = MSR_IA32_SYSENTER_CS, .always = true },
#ifdef CONFIG_X86_64
{ .index = MSR_GS_BASE, .always = true },
{ .index = MSR_FS_BASE, .always = true },
{ .index = MSR_KERNEL_GS_BASE, .always = true },
{ .index = MSR_LSTAR, .always = true },
{ .index = MSR_CSTAR, .always = true },
{ .index = MSR_SYSCALL_MASK, .always = true },
#endif
{ .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
{ .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
{ .index = MSR_IA32_LASTINTFROMIP, .always = false },
{ .index = MSR_IA32_LASTINTTOIP, .always = false },
{ .index = MSR_INVALID, .always = false },
};
/* enable NPT for AMD64 and X86 with PAE */
#if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
static bool npt_enabled = true;
#else
static bool npt_enabled;
#endif
static int npt = 1;
module_param(npt, int, S_IRUGO);
static int nested = 1;
module_param(nested, int, S_IRUGO);
static void svm_flush_tlb(struct kvm_vcpu *vcpu);
static void svm_complete_interrupts(struct vcpu_svm *svm);
static int nested_svm_exit_handled(struct vcpu_svm *svm);
static int nested_svm_intercept(struct vcpu_svm *svm);
static int nested_svm_vmexit(struct vcpu_svm *svm);
static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
bool has_error_code, u32 error_code);
static u64 __scale_tsc(u64 ratio, u64 tsc);
enum {
VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
pause filter count */
VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
VMCB_ASID, /* ASID */
VMCB_INTR, /* int_ctl, int_vector */
VMCB_NPT, /* npt_en, nCR3, gPAT */
VMCB_CR, /* CR0, CR3, CR4, EFER */
VMCB_DR, /* DR6, DR7 */
VMCB_DT, /* GDT, IDT */
VMCB_SEG, /* CS, DS, SS, ES, CPL */
VMCB_CR2, /* CR2 only */
VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
VMCB_DIRTY_MAX,
};
/* TPR and CR2 are always written before VMRUN */
#define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
static inline void mark_all_dirty(struct vmcb *vmcb)
{
vmcb->control.clean = 0;
}
static inline void mark_all_clean(struct vmcb *vmcb)
{
vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
& ~VMCB_ALWAYS_DIRTY_MASK;
}
static inline void mark_dirty(struct vmcb *vmcb, int bit)
{
vmcb->control.clean &= ~(1 << bit);
}
static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
{
return container_of(vcpu, struct vcpu_svm, vcpu);
}
static void recalc_intercepts(struct vcpu_svm *svm)
{
struct vmcb_control_area *c, *h;
struct nested_state *g;
mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
if (!is_guest_mode(&svm->vcpu))
return;
c = &svm->vmcb->control;
h = &svm->nested.hsave->control;
g = &svm->nested;
c->intercept_cr = h->intercept_cr | g->intercept_cr;
c->intercept_dr = h->intercept_dr | g->intercept_dr;
c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
c->intercept = h->intercept | g->intercept;
}
static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
{
if (is_guest_mode(&svm->vcpu))
return svm->nested.hsave;
else
return svm->vmcb;
}
static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_cr |= (1U << bit);
recalc_intercepts(svm);
}
static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_cr &= ~(1U << bit);
recalc_intercepts(svm);
}
static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
return vmcb->control.intercept_cr & (1U << bit);
}
static inline void set_dr_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_dr |= (1U << bit);
recalc_intercepts(svm);
}
static inline void clr_dr_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_dr &= ~(1U << bit);
recalc_intercepts(svm);
}
static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_exceptions |= (1U << bit);
recalc_intercepts(svm);
}
static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_exceptions &= ~(1U << bit);
recalc_intercepts(svm);
}
static inline void set_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept |= (1ULL << bit);
recalc_intercepts(svm);
}
static inline void clr_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept &= ~(1ULL << bit);
recalc_intercepts(svm);
}
static inline void enable_gif(struct vcpu_svm *svm)
{
svm->vcpu.arch.hflags |= HF_GIF_MASK;
}
static inline void disable_gif(struct vcpu_svm *svm)
{
svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
}
static inline bool gif_set(struct vcpu_svm *svm)
{
return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
}
static unsigned long iopm_base;
struct kvm_ldttss_desc {
u16 limit0;
u16 base0;
unsigned base1:8, type:5, dpl:2, p:1;
unsigned limit1:4, zero0:3, g:1, base2:8;
u32 base3;
u32 zero1;
} __attribute__((packed));
struct svm_cpu_data {
int cpu;
u64 asid_generation;
u32 max_asid;
u32 next_asid;
struct kvm_ldttss_desc *tss_desc;
struct page *save_area;
};
static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
struct svm_init_data {
int cpu;
int r;
};
static u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
#define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
#define MSRS_RANGE_SIZE 2048
#define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
static u32 svm_msrpm_offset(u32 msr)
{
u32 offset;
int i;
for (i = 0; i < NUM_MSR_MAPS; i++) {
if (msr < msrpm_ranges[i] ||
msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
continue;
offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
offset += (i * MSRS_RANGE_SIZE); /* add range offset */
/* Now we have the u8 offset - but need the u32 offset */
return offset / 4;
}
/* MSR not in any range */
return MSR_INVALID;
}
#define MAX_INST_SIZE 15
static inline void clgi(void)
{
asm volatile (__ex(SVM_CLGI));
}
static inline void stgi(void)
{
asm volatile (__ex(SVM_STGI));
}
static inline void invlpga(unsigned long addr, u32 asid)
{
asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
}
static int get_npt_level(void)
{
#ifdef CONFIG_X86_64
return PT64_ROOT_LEVEL;
#else
return PT32E_ROOT_LEVEL;
#endif
}
static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
vcpu->arch.efer = efer;
if (!npt_enabled && !(efer & EFER_LMA))
efer &= ~EFER_LME;
to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
}
static int is_external_interrupt(u32 info)
{
info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
}
static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
{
struct vcpu_svm *svm = to_svm(vcpu);
u32 ret = 0;
if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
ret |= KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
return ret & mask;
}
static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (mask == 0)
svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
else
svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
}
static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (svm->vmcb->control.next_rip != 0)
svm->next_rip = svm->vmcb->control.next_rip;
if (!svm->next_rip) {
if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
EMULATE_DONE)
printk(KERN_DEBUG "%s: NOP\n", __func__);
return;
}
if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
__func__, kvm_rip_read(vcpu), svm->next_rip);
kvm_rip_write(vcpu, svm->next_rip);
svm_set_interrupt_shadow(vcpu, 0);
}
static void svm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
bool has_error_code, u32 error_code,
bool reinject)
{
struct vcpu_svm *svm = to_svm(vcpu);
/*
* If we are within a nested VM we'd better #VMEXIT and let the guest
* handle the exception
*/
if (!reinject &&
nested_svm_check_exception(svm, nr, has_error_code, error_code))
return;
if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
/*
* For guest debugging where we have to reinject #BP if some
* INT3 is guest-owned:
* Emulate nRIP by moving RIP forward. Will fail if injection
* raises a fault that is not intercepted. Still better than
* failing in all cases.
*/
skip_emulated_instruction(&svm->vcpu);
rip = kvm_rip_read(&svm->vcpu);
svm->int3_rip = rip + svm->vmcb->save.cs.base;
svm->int3_injected = rip - old_rip;
}
svm->vmcb->control.event_inj = nr
| SVM_EVTINJ_VALID
| (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
| SVM_EVTINJ_TYPE_EXEPT;
svm->vmcb->control.event_inj_err = error_code;
}
static void svm_init_erratum_383(void)
{
u32 low, high;
int err;
u64 val;
if (!cpu_has_amd_erratum(amd_erratum_383))
return;
/* Use _safe variants to not break nested virtualization */
val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
if (err)
return;
val |= (1ULL << 47);
low = lower_32_bits(val);
high = upper_32_bits(val);
native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
erratum_383_found = true;
}
static int has_svm(void)
{
const char *msg;
if (!cpu_has_svm(&msg)) {
printk(KERN_INFO "has_svm: %s\n", msg);
return 0;
}
return 1;
}
static void svm_hardware_disable(void *garbage)
{
/* Make sure we clean up behind us */
if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
cpu_svm_disable();
}
static int svm_hardware_enable(void *garbage)
{
struct svm_cpu_data *sd;
uint64_t efer;
struct desc_ptr gdt_descr;
struct desc_struct *gdt;
int me = raw_smp_processor_id();
rdmsrl(MSR_EFER, efer);
if (efer & EFER_SVME)
return -EBUSY;
if (!has_svm()) {
printk(KERN_ERR "svm_hardware_enable: err EOPNOTSUPP on %d\n",
me);
return -EINVAL;
}
sd = per_cpu(svm_data, me);
if (!sd) {
printk(KERN_ERR "svm_hardware_enable: svm_data is NULL on %d\n",
me);
return -EINVAL;
}
sd->asid_generation = 1;
sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
sd->next_asid = sd->max_asid + 1;
native_store_gdt(&gdt_descr);
gdt = (struct desc_struct *)gdt_descr.address;
sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
wrmsrl(MSR_EFER, efer | EFER_SVME);
wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
__get_cpu_var(current_tsc_ratio) = TSC_RATIO_DEFAULT;
}
svm_init_erratum_383();
return 0;
}
static void svm_cpu_uninit(int cpu)
{
struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
if (!sd)
return;
per_cpu(svm_data, raw_smp_processor_id()) = NULL;
__free_page(sd->save_area);
kfree(sd);
}
static int svm_cpu_init(int cpu)
{
struct svm_cpu_data *sd;
int r;
sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
if (!sd)
return -ENOMEM;
sd->cpu = cpu;
sd->save_area = alloc_page(GFP_KERNEL);
r = -ENOMEM;
if (!sd->save_area)
goto err_1;
per_cpu(svm_data, cpu) = sd;
return 0;
err_1:
kfree(sd);
return r;
}
static bool valid_msr_intercept(u32 index)
{
int i;
for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
if (direct_access_msrs[i].index == index)
return true;
return false;
}
static void set_msr_interception(u32 *msrpm, unsigned msr,
int read, int write)
{
u8 bit_read, bit_write;
unsigned long tmp;
u32 offset;
/*
* If this warning triggers extend the direct_access_msrs list at the
* beginning of the file
*/
WARN_ON(!valid_msr_intercept(msr));
offset = svm_msrpm_offset(msr);
bit_read = 2 * (msr & 0x0f);
bit_write = 2 * (msr & 0x0f) + 1;
tmp = msrpm[offset];
BUG_ON(offset == MSR_INVALID);
read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
msrpm[offset] = tmp;
}
static void svm_vcpu_init_msrpm(u32 *msrpm)
{
int i;
memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
if (!direct_access_msrs[i].always)
continue;
set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
}
}
static void add_msr_offset(u32 offset)
{
int i;
for (i = 0; i < MSRPM_OFFSETS; ++i) {
/* Offset already in list? */
if (msrpm_offsets[i] == offset)
return;
/* Slot used by another offset? */
if (msrpm_offsets[i] != MSR_INVALID)
continue;
/* Add offset to list */
msrpm_offsets[i] = offset;
return;
}
/*
* If this BUG triggers the msrpm_offsets table has an overflow. Just
* increase MSRPM_OFFSETS in this case.
*/
BUG();
}
static void init_msrpm_offsets(void)
{
int i;
memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
u32 offset;
offset = svm_msrpm_offset(direct_access_msrs[i].index);
BUG_ON(offset == MSR_INVALID);
add_msr_offset(offset);
}
}
static void svm_enable_lbrv(struct vcpu_svm *svm)
{
u32 *msrpm = svm->msrpm;
svm->vmcb->control.lbr_ctl = 1;
set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
}
static void svm_disable_lbrv(struct vcpu_svm *svm)
{
u32 *msrpm = svm->msrpm;
svm->vmcb->control.lbr_ctl = 0;
set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
}
static __init int svm_hardware_setup(void)
{
int cpu;
struct page *iopm_pages;
void *iopm_va;
int r;
iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
if (!iopm_pages)
return -ENOMEM;
iopm_va = page_address(iopm_pages);
memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
init_msrpm_offsets();
if (boot_cpu_has(X86_FEATURE_NX))
kvm_enable_efer_bits(EFER_NX);
if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
kvm_enable_efer_bits(EFER_FFXSR);
if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
u64 max;
kvm_has_tsc_control = true;
/*
* Make sure the user can only configure tsc_khz values that
* fit into a signed integer.
* A min value is not calculated needed because it will always
* be 1 on all machines and a value of 0 is used to disable
* tsc-scaling for the vcpu.
*/
max = min(0x7fffffffULL, __scale_tsc(tsc_khz, TSC_RATIO_MAX));
kvm_max_guest_tsc_khz = max;
}
if (nested) {
printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
}
for_each_possible_cpu(cpu) {
r = svm_cpu_init(cpu);
if (r)
goto err;
}
if (!boot_cpu_has(X86_FEATURE_NPT))
npt_enabled = false;
if (npt_enabled && !npt) {
printk(KERN_INFO "kvm: Nested Paging disabled\n");
npt_enabled = false;
}
if (npt_enabled) {
printk(KERN_INFO "kvm: Nested Paging enabled\n");
kvm_enable_tdp();
} else
kvm_disable_tdp();
return 0;
err:
__free_pages(iopm_pages, IOPM_ALLOC_ORDER);
iopm_base = 0;
return r;
}
static __exit void svm_hardware_unsetup(void)
{
int cpu;
for_each_possible_cpu(cpu)
svm_cpu_uninit(cpu);
__free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
iopm_base = 0;
}
static void init_seg(struct vmcb_seg *seg)
{
seg->selector = 0;
seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
seg->limit = 0xffff;
seg->base = 0;
}
static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
{
seg->selector = 0;
seg->attrib = SVM_SELECTOR_P_MASK | type;
seg->limit = 0xffff;
seg->base = 0;
}
static u64 __scale_tsc(u64 ratio, u64 tsc)
{
u64 mult, frac, _tsc;
mult = ratio >> 32;
frac = ratio & ((1ULL << 32) - 1);
_tsc = tsc;
_tsc *= mult;
_tsc += (tsc >> 32) * frac;
_tsc += ((tsc & ((1ULL << 32) - 1)) * frac) >> 32;
return _tsc;
}
static u64 svm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
{
struct vcpu_svm *svm = to_svm(vcpu);
u64 _tsc = tsc;
if (svm->tsc_ratio != TSC_RATIO_DEFAULT)
_tsc = __scale_tsc(svm->tsc_ratio, tsc);
return _tsc;
}
static void svm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
{
struct vcpu_svm *svm = to_svm(vcpu);
u64 ratio;
u64 khz;
/* TSC scaling supported? */
if (!boot_cpu_has(X86_FEATURE_TSCRATEMSR))
return;
/* TSC-Scaling disabled or guest TSC same frequency as host TSC? */
if (user_tsc_khz == 0) {
vcpu->arch.virtual_tsc_khz = 0;
svm->tsc_ratio = TSC_RATIO_DEFAULT;
return;
}
khz = user_tsc_khz;
/* TSC scaling required - calculate ratio */
ratio = khz << 32;
do_div(ratio, tsc_khz);
if (ratio == 0 || ratio & TSC_RATIO_RSVD) {
WARN_ONCE(1, "Invalid TSC ratio - virtual-tsc-khz=%u\n",
user_tsc_khz);
return;
}
vcpu->arch.virtual_tsc_khz = user_tsc_khz;
svm->tsc_ratio = ratio;
}
static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
{
struct vcpu_svm *svm = to_svm(vcpu);
u64 g_tsc_offset = 0;
if (is_guest_mode(vcpu)) {
g_tsc_offset = svm->vmcb->control.tsc_offset -
svm->nested.hsave->control.tsc_offset;
svm->nested.hsave->control.tsc_offset = offset;
}
svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
}
static void svm_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->control.tsc_offset += adjustment;
if (is_guest_mode(vcpu))
svm->nested.hsave->control.tsc_offset += adjustment;
mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
}
static u64 svm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
{
u64 tsc;
tsc = svm_scale_tsc(vcpu, native_read_tsc());
return target_tsc - tsc;
}
static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercept(svm, INTERCEPT_DR0_READ);
set_dr_intercept(svm, INTERCEPT_DR1_READ);
set_dr_intercept(svm, INTERCEPT_DR2_READ);
set_dr_intercept(svm, INTERCEPT_DR3_READ);
set_dr_intercept(svm, INTERCEPT_DR4_READ);
set_dr_intercept(svm, INTERCEPT_DR5_READ);
set_dr_intercept(svm, INTERCEPT_DR6_READ);
set_dr_intercept(svm, INTERCEPT_DR7_READ);
set_dr_intercept(svm, INTERCEPT_DR0_WRITE);
set_dr_intercept(svm, INTERCEPT_DR1_WRITE);
set_dr_intercept(svm, INTERCEPT_DR2_WRITE);
set_dr_intercept(svm, INTERCEPT_DR3_WRITE);
set_dr_intercept(svm, INTERCEPT_DR4_WRITE);
set_dr_intercept(svm, INTERCEPT_DR5_WRITE);
set_dr_intercept(svm, INTERCEPT_DR6_WRITE);
set_dr_intercept(svm, INTERCEPT_DR7_WRITE);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
/*
* cs.base should really be 0xffff0000, but vmx can't handle that, so
* be consistent with it.
*
* Replace when we have real mode working for vmx.
*/
save->cs.base = 0xf0000;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
save->dr7 = 0x400;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* This is the guest-visible cr0 value.
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
*/
svm->vcpu.arch.cr0 = 0;
(void)kvm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_TASK_SWITCH);
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = 0x0007040600070406ULL;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
static int svm_vcpu_reset(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
init_vmcb(svm);
if (!kvm_vcpu_is_bsp(vcpu)) {
kvm_rip_write(vcpu, 0);
svm->vmcb->save.cs.base = svm->vcpu.arch.sipi_vector << 12;
svm->vmcb->save.cs.selector = svm->vcpu.arch.sipi_vector << 8;
}
vcpu->arch.regs_avail = ~0;
vcpu->arch.regs_dirty = ~0;
return 0;
}
static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
{
struct vcpu_svm *svm;
struct page *page;
struct page *msrpm_pages;
struct page *hsave_page;
struct page *nested_msrpm_pages;
int err;
svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
if (!svm) {
err = -ENOMEM;
goto out;
}
svm->tsc_ratio = TSC_RATIO_DEFAULT;
err = kvm_vcpu_init(&svm->vcpu, kvm, id);
if (err)
goto free_svm;
err = -ENOMEM;
page = alloc_page(GFP_KERNEL);
if (!page)
goto uninit;
msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
if (!msrpm_pages)
goto free_page1;
nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
if (!nested_msrpm_pages)
goto free_page2;
hsave_page = alloc_page(GFP_KERNEL);
if (!hsave_page)
goto free_page3;
svm->nested.hsave = page_address(hsave_page);
svm->msrpm = page_address(msrpm_pages);
svm_vcpu_init_msrpm(svm->msrpm);
svm->nested.msrpm = page_address(nested_msrpm_pages);
svm_vcpu_init_msrpm(svm->nested.msrpm);
svm->vmcb = page_address(page);
clear_page(svm->vmcb);
svm->vmcb_pa = page_to_pfn(page) << PAGE_SHIFT;
svm->asid_generation = 0;
init_vmcb(svm);
kvm_write_tsc(&svm->vcpu, 0);
err = fx_init(&svm->vcpu);
if (err)
goto free_page4;
svm->vcpu.arch.apic_base = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
if (kvm_vcpu_is_bsp(&svm->vcpu))
svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
return &svm->vcpu;
free_page4:
__free_page(hsave_page);
free_page3:
__free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
free_page2:
__free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
free_page1:
__free_page(page);
uninit:
kvm_vcpu_uninit(&svm->vcpu);
free_svm:
kmem_cache_free(kvm_vcpu_cache, svm);
out:
return ERR_PTR(err);
}
static void svm_free_vcpu(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
__free_page(pfn_to_page(svm->vmcb_pa >> PAGE_SHIFT));
__free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
__free_page(virt_to_page(svm->nested.hsave));
__free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
kvm_vcpu_uninit(vcpu);
kmem_cache_free(kvm_vcpu_cache, svm);
}
static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
int i;
if (unlikely(cpu != vcpu->cpu)) {
svm->asid_generation = 0;
mark_all_dirty(svm->vmcb);
}
#ifdef CONFIG_X86_64
rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
#endif
savesegment(fs, svm->host.fs);
savesegment(gs, svm->host.gs);
svm->host.ldt = kvm_read_ldt();
for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
if (static_cpu_has(X86_FEATURE_TSCRATEMSR) &&
svm->tsc_ratio != __get_cpu_var(current_tsc_ratio)) {
__get_cpu_var(current_tsc_ratio) = svm->tsc_ratio;
wrmsrl(MSR_AMD64_TSC_RATIO, svm->tsc_ratio);
}
}
static void svm_vcpu_put(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
int i;
++vcpu->stat.host_state_reload;
kvm_load_ldt(svm->host.ldt);
#ifdef CONFIG_X86_64
loadsegment(fs, svm->host.fs);
wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gs);
load_gs_index(svm->host.gs);
#else
#ifdef CONFIG_X86_32_LAZY_GS
loadsegment(gs, svm->host.gs);
#endif
#endif
for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
}
static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
{
return to_svm(vcpu)->vmcb->save.rflags;
}
static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
to_svm(vcpu)->vmcb->save.rflags = rflags;
}
static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
{
switch (reg) {
case VCPU_EXREG_PDPTR:
BUG_ON(!npt_enabled);
load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
break;
default:
BUG();
}
}
static void svm_set_vintr(struct vcpu_svm *svm)
{
set_intercept(svm, INTERCEPT_VINTR);
}
static void svm_clear_vintr(struct vcpu_svm *svm)
{
clr_intercept(svm, INTERCEPT_VINTR);
}
static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
{
struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
switch (seg) {
case VCPU_SREG_CS: return &save->cs;
case VCPU_SREG_DS: return &save->ds;
case VCPU_SREG_ES: return &save->es;
case VCPU_SREG_FS: return &save->fs;
case VCPU_SREG_GS: return &save->gs;
case VCPU_SREG_SS: return &save->ss;
case VCPU_SREG_TR: return &save->tr;
case VCPU_SREG_LDTR: return &save->ldtr;
}
BUG();
return NULL;
}
static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
struct vmcb_seg *s = svm_seg(vcpu, seg);
return s->base;
}
static void svm_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vmcb_seg *s = svm_seg(vcpu, seg);
var->base = s->base;
var->limit = s->limit;
var->selector = s->selector;
var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
var->g = (s->attrib >> SVM_SELECTOR_G_SHIFT) & 1;
/*
* AMD's VMCB does not have an explicit unusable field, so emulate it
* for cross vendor migration purposes by "not present"
*/
var->unusable = !var->present || (var->type == 0);
switch (seg) {
case VCPU_SREG_CS:
/*
* SVM always stores 0 for the 'G' bit in the CS selector in
* the VMCB on a VMEXIT. This hurts cross-vendor migration:
* Intel's VMENTRY has a check on the 'G' bit.
*/
var->g = s->limit > 0xfffff;
break;
case VCPU_SREG_TR:
/*
* Work around a bug where the busy flag in the tr selector
* isn't exposed
*/
var->type |= 0x2;
break;
case VCPU_SREG_DS:
case VCPU_SREG_ES:
case VCPU_SREG_FS:
case VCPU_SREG_GS:
/*
* The accessed bit must always be set in the segment
* descriptor cache, although it can be cleared in the
* descriptor, the cached bit always remains at 1. Since
* Intel has a check on this, set it here to support
* cross-vendor migration.
*/
if (!var->unusable)
var->type |= 0x1;
break;
case VCPU_SREG_SS:
/*
* On AMD CPUs sometimes the DB bit in the segment
* descriptor is left as 1, although the whole segment has
* been made unusable. Clear it here to pass an Intel VMX
* entry check when cross vendor migrating.
*/
if (var->unusable)
var->db = 0;
break;
}
}
static int svm_get_cpl(struct kvm_vcpu *vcpu)
{
struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
return save->cpl;
}
static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
struct vcpu_svm *svm = to_svm(vcpu);
dt->size = svm->vmcb->save.idtr.limit;
dt->address = svm->vmcb->save.idtr.base;
}
static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->save.idtr.limit = dt->size;
svm->vmcb->save.idtr.base = dt->address ;
mark_dirty(svm->vmcb, VMCB_DT);
}
static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
struct vcpu_svm *svm = to_svm(vcpu);
dt->size = svm->vmcb->save.gdtr.limit;
dt->address = svm->vmcb->save.gdtr.base;
}
static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->save.gdtr.limit = dt->size;
svm->vmcb->save.gdtr.base = dt->address ;
mark_dirty(svm->vmcb, VMCB_DT);
}
static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
{
}
static void svm_decache_cr3(struct kvm_vcpu *vcpu)
{
}
static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
{
}
static void update_cr0_intercept(struct vcpu_svm *svm)
{
ulong gcr0 = svm->vcpu.arch.cr0;
u64 *hcr0 = &svm->vmcb->save.cr0;
if (!svm->vcpu.fpu_active)
*hcr0 |= SVM_CR0_SELECTIVE_MASK;
else
*hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
| (gcr0 & SVM_CR0_SELECTIVE_MASK);
mark_dirty(svm->vmcb, VMCB_CR);
if (gcr0 == *hcr0 && svm->vcpu.fpu_active) {
clr_cr_intercept(svm, INTERCEPT_CR0_READ);
clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
} else {
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
}
}
static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
struct vcpu_svm *svm = to_svm(vcpu);
#ifdef CONFIG_X86_64
if (vcpu->arch.efer & EFER_LME) {
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
vcpu->arch.efer |= EFER_LMA;
svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
}
if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
vcpu->arch.efer &= ~EFER_LMA;
svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
}
}
#endif
vcpu->arch.cr0 = cr0;
if (!npt_enabled)
cr0 |= X86_CR0_PG | X86_CR0_WP;
if (!vcpu->fpu_active)
cr0 |= X86_CR0_TS;
/*
* re-enable caching here because the QEMU bios
* does not do it - this results in some delay at
* reboot
*/
cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
svm->vmcb->save.cr0 = cr0;
mark_dirty(svm->vmcb, VMCB_CR);
update_cr0_intercept(svm);
}
static void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
unsigned long host_cr4_mce = read_cr4() & X86_CR4_MCE;
unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
svm_flush_tlb(vcpu);
vcpu->arch.cr4 = cr4;
if (!npt_enabled)
cr4 |= X86_CR4_PAE;
cr4 |= host_cr4_mce;
to_svm(vcpu)->vmcb->save.cr4 = cr4;
mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
}
static void svm_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
struct vcpu_svm *svm = to_svm(vcpu);
struct vmcb_seg *s = svm_seg(vcpu, seg);
s->base = var->base;
s->limit = var->limit;
s->selector = var->selector;
if (var->unusable)
s->attrib = 0;
else {
s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
s->attrib |= (var->present & 1) << SVM_SELECTOR_P_SHIFT;
s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
}
if (seg == VCPU_SREG_CS)
svm->vmcb->save.cpl
= (svm->vmcb->save.cs.attrib
>> SVM_SELECTOR_DPL_SHIFT) & 3;
mark_dirty(svm->vmcb, VMCB_SEG);
}
static void update_db_intercept(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
clr_exception_intercept(svm, DB_VECTOR);
clr_exception_intercept(svm, BP_VECTOR);
if (svm->nmi_singlestep)
set_exception_intercept(svm, DB_VECTOR);
if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
if (vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
set_exception_intercept(svm, DB_VECTOR);
if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
set_exception_intercept(svm, BP_VECTOR);
} else
vcpu->guest_debug = 0;
}
static void svm_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
svm->vmcb->save.dr7 = dbg->arch.debugreg[7];
else
svm->vmcb->save.dr7 = vcpu->arch.dr7;
mark_dirty(svm->vmcb, VMCB_DR);
update_db_intercept(vcpu);
}
static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
{
if (sd->next_asid > sd->max_asid) {
++sd->asid_generation;
sd->next_asid = 1;
svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
}
svm->asid_generation = sd->asid_generation;
svm->vmcb->control.asid = sd->next_asid++;
mark_dirty(svm->vmcb, VMCB_ASID);
}
static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->save.dr7 = value;
mark_dirty(svm->vmcb, VMCB_DR);
}
static int pf_interception(struct vcpu_svm *svm)
{
u64 fault_address = svm->vmcb->control.exit_info_2;
u32 error_code;
int r = 1;
switch (svm->apf_reason) {
default:
error_code = svm->vmcb->control.exit_info_1;
trace_kvm_page_fault(fault_address, error_code);
if (!npt_enabled && kvm_event_needs_reinjection(&svm->vcpu))
kvm_mmu_unprotect_page_virt(&svm->vcpu, fault_address);
r = kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
svm->vmcb->control.insn_bytes,
svm->vmcb->control.insn_len);
break;
case KVM_PV_REASON_PAGE_NOT_PRESENT:
svm->apf_reason = 0;
local_irq_disable();
kvm_async_pf_task_wait(fault_address);
local_irq_enable();
break;
case KVM_PV_REASON_PAGE_READY:
svm->apf_reason = 0;
local_irq_disable();
kvm_async_pf_task_wake(fault_address);
local_irq_enable();
break;
}
return r;
}
static int db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_intercept(&svm->vcpu);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
static int bp_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = BP_VECTOR;
return 0;
}
static int ud_interception(struct vcpu_svm *svm)
{
int er;
er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(&svm->vcpu, UD_VECTOR);
return 1;
}
static void svm_fpu_activate(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
clr_exception_intercept(svm, NM_VECTOR);
svm->vcpu.fpu_active = 1;
update_cr0_intercept(svm);
}
static int nm_interception(struct vcpu_svm *svm)
{
svm_fpu_activate(&svm->vcpu);
return 1;
}
static bool is_erratum_383(void)
{
int err, i;
u64 value;
if (!erratum_383_found)
return false;
value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
if (err)
return false;
/* Bit 62 may or may not be set for this mce */
value &= ~(1ULL << 62);
if (value != 0xb600000000010015ULL)
return false;
/* Clear MCi_STATUS registers */
for (i = 0; i < 6; ++i)
native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
if (!err) {
u32 low, high;
value &= ~(1ULL << 2);
low = lower_32_bits(value);
high = upper_32_bits(value);
native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
}
/* Flush tlb to evict multi-match entries */
__flush_tlb_all();
return true;
}
static void svm_handle_mce(struct vcpu_svm *svm)
{
if (is_erratum_383()) {
/*
* Erratum 383 triggered. Guest state is corrupt so kill the
* guest.
*/
pr_err("KVM: Guest triggered AMD Erratum 383\n");
kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
return;
}
/*
* On an #MC intercept the MCE handler is not called automatically in
* the host. So do it by hand here.
*/
asm volatile (
"int $0x12\n");
/* not sure if we ever come back to this point */
return;
}
static int mc_interception(struct vcpu_svm *svm)
{
return 1;
}
static int shutdown_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
/*
* VMCB is undefined after a SHUTDOWN intercept
* so reinitialize it.
*/
clear_page(svm->vmcb);
init_vmcb(svm);
kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
return 0;
}
static int io_interception(struct vcpu_svm *svm)
{
struct kvm_vcpu *vcpu = &svm->vcpu;
u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
int size, in, string;
unsigned port;
++svm->vcpu.stat.io_exits;
string = (io_info & SVM_IOIO_STR_MASK) != 0;
in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
if (string || in)
return emulate_instruction(vcpu, 0) == EMULATE_DONE;
port = io_info >> 16;
size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
svm->next_rip = svm->vmcb->control.exit_info_2;
skip_emulated_instruction(&svm->vcpu);
return kvm_fast_pio_out(vcpu, size, port);
}
static int nmi_interception(struct vcpu_svm *svm)
{
return 1;
}
static int intr_interception(struct vcpu_svm *svm)
{
++svm->vcpu.stat.irq_exits;
return 1;
}
static int nop_on_interception(struct vcpu_svm *svm)
{
return 1;
}
static int halt_interception(struct vcpu_svm *svm)
{
svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
skip_emulated_instruction(&svm->vcpu);
return kvm_emulate_halt(&svm->vcpu);
}
static int vmmcall_interception(struct vcpu_svm *svm)
{
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
kvm_emulate_hypercall(&svm->vcpu);
return 1;
}
static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
return svm->nested.nested_cr3;
}
static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
unsigned long root)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->control.nested_cr3 = root;
mark_dirty(svm->vmcb, VMCB_NPT);
svm_flush_tlb(vcpu);
}
static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->control.exit_code = SVM_EXIT_NPF;
svm->vmcb->control.exit_code_hi = 0;
svm->vmcb->control.exit_info_1 = fault->error_code;
svm->vmcb->control.exit_info_2 = fault->address;
nested_svm_vmexit(svm);
}
static int nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
{
int r;
r = kvm_init_shadow_mmu(vcpu, &vcpu->arch.mmu);
vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3;
vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3;
vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
vcpu->arch.mmu.shadow_root_level = get_npt_level();
vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
return r;
}
static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
{
vcpu->arch.walk_mmu = &vcpu->arch.mmu;
}
static int nested_svm_check_permissions(struct vcpu_svm *svm)
{
if (!(svm->vcpu.arch.efer & EFER_SVME)
|| !is_paging(&svm->vcpu)) {
kvm_queue_exception(&svm->vcpu, UD_VECTOR);
return 1;
}
if (svm->vmcb->save.cpl) {
kvm_inject_gp(&svm->vcpu, 0);
return 1;
}
return 0;
}
static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
bool has_error_code, u32 error_code)
{
int vmexit;
if (!is_guest_mode(&svm->vcpu))
return 0;
svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
svm->vmcb->control.exit_code_hi = 0;
svm->vmcb->control.exit_info_1 = error_code;
svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
vmexit = nested_svm_intercept(svm);
if (vmexit == NESTED_EXIT_DONE)
svm->nested.exit_required = true;
return vmexit;
}
/* This function returns true if it is save to enable the irq window */
static inline bool nested_svm_intr(struct vcpu_svm *svm)
{
if (!is_guest_mode(&svm->vcpu))
return true;
if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
return true;
if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
return false;
/*
* if vmexit was already requested (by intercepted exception
* for instance) do not overwrite it with "external interrupt"
* vmexit.
*/
if (svm->nested.exit_required)
return false;
svm->vmcb->control.exit_code = SVM_EXIT_INTR;
svm->vmcb->control.exit_info_1 = 0;
svm->vmcb->control.exit_info_2 = 0;
if (svm->nested.intercept & 1ULL) {
/*
* The #vmexit can't be emulated here directly because this
* code path runs with irqs and preemtion disabled. A
* #vmexit emulation might sleep. Only signal request for
* the #vmexit here.
*/
svm->nested.exit_required = true;
trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
return false;
}
return true;
}
/* This function returns true if it is save to enable the nmi window */
static inline bool nested_svm_nmi(struct vcpu_svm *svm)
{
if (!is_guest_mode(&svm->vcpu))
return true;
if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
return true;
svm->vmcb->control.exit_code = SVM_EXIT_NMI;
svm->nested.exit_required = true;
return false;
}
static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
{
struct page *page;
might_sleep();
page = gfn_to_page(svm->vcpu.kvm, gpa >> PAGE_SHIFT);
if (is_error_page(page))
goto error;
*_page = page;
return kmap(page);
error:
kvm_release_page_clean(page);
kvm_inject_gp(&svm->vcpu, 0);
return NULL;
}
static void nested_svm_unmap(struct page *page)
{
kunmap(page);
kvm_release_page_dirty(page);
}
static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
{
unsigned port;
u8 val, bit;
u64 gpa;
if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
return NESTED_EXIT_HOST;
port = svm->vmcb->control.exit_info_1 >> 16;
gpa = svm->nested.vmcb_iopm + (port / 8);
bit = port % 8;
val = 0;
if (kvm_read_guest(svm->vcpu.kvm, gpa, &val, 1))
val &= (1 << bit);
return val ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
}
static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
{
u32 offset, msr, value;
int write, mask;
if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
return NESTED_EXIT_HOST;
msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
offset = svm_msrpm_offset(msr);
write = svm->vmcb->control.exit_info_1 & 1;
mask = 1 << ((2 * (msr & 0xf)) + write);
if (offset == MSR_INVALID)
return NESTED_EXIT_DONE;
/* Offset is in 32 bit units but need in 8 bit units */
offset *= 4;
if (kvm_read_guest(svm->vcpu.kvm, svm->nested.vmcb_msrpm + offset, &value, 4))
return NESTED_EXIT_DONE;
return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
}
static int nested_svm_exit_special(struct vcpu_svm *svm)
{
u32 exit_code = svm->vmcb->control.exit_code;
switch (exit_code) {
case SVM_EXIT_INTR:
case SVM_EXIT_NMI:
case SVM_EXIT_EXCP_BASE + MC_VECTOR:
return NESTED_EXIT_HOST;
case SVM_EXIT_NPF:
/* For now we are always handling NPFs when using them */
if (npt_enabled)
return NESTED_EXIT_HOST;
break;
case SVM_EXIT_EXCP_BASE + PF_VECTOR:
/* When we're shadowing, trap PFs, but not async PF */
if (!npt_enabled && svm->apf_reason == 0)
return NESTED_EXIT_HOST;
break;
case SVM_EXIT_EXCP_BASE + NM_VECTOR:
nm_interception(svm);
break;
default:
break;
}
return NESTED_EXIT_CONTINUE;
}
/*
* If this function returns true, this #vmexit was already handled
*/
static int nested_svm_intercept(struct vcpu_svm *svm)
{
u32 exit_code = svm->vmcb->control.exit_code;
int vmexit = NESTED_EXIT_HOST;
switch (exit_code) {
case SVM_EXIT_MSR:
vmexit = nested_svm_exit_handled_msr(svm);
break;
case SVM_EXIT_IOIO:
vmexit = nested_svm_intercept_ioio(svm);
break;
case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
if (svm->nested.intercept_cr & bit)
vmexit = NESTED_EXIT_DONE;
break;
}
case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
if (svm->nested.intercept_dr & bit)
vmexit = NESTED_EXIT_DONE;
break;
}
case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
if (svm->nested.intercept_exceptions & excp_bits)
vmexit = NESTED_EXIT_DONE;
/* async page fault always cause vmexit */
else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
svm->apf_reason != 0)
vmexit = NESTED_EXIT_DONE;
break;
}
case SVM_EXIT_ERR: {
vmexit = NESTED_EXIT_DONE;
break;
}
default: {
u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
if (svm->nested.intercept & exit_bits)
vmexit = NESTED_EXIT_DONE;
}
}
return vmexit;
}
static int nested_svm_exit_handled(struct vcpu_svm *svm)
{
int vmexit;
vmexit = nested_svm_intercept(svm);
if (vmexit == NESTED_EXIT_DONE)
nested_svm_vmexit(svm);
return vmexit;
}
static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
{
struct vmcb_control_area *dst = &dst_vmcb->control;
struct vmcb_control_area *from = &from_vmcb->control;
dst->intercept_cr = from->intercept_cr;
dst->intercept_dr = from->intercept_dr;
dst->intercept_exceptions = from->intercept_exceptions;
dst->intercept = from->intercept;
dst->iopm_base_pa = from->iopm_base_pa;
dst->msrpm_base_pa = from->msrpm_base_pa;
dst->tsc_offset = from->tsc_offset;
dst->asid = from->asid;
dst->tlb_ctl = from->tlb_ctl;
dst->int_ctl = from->int_ctl;
dst->int_vector = from->int_vector;
dst->int_state = from->int_state;
dst->exit_code = from->exit_code;
dst->exit_code_hi = from->exit_code_hi;
dst->exit_info_1 = from->exit_info_1;
dst->exit_info_2 = from->exit_info_2;
dst->exit_int_info = from->exit_int_info;
dst->exit_int_info_err = from->exit_int_info_err;
dst->nested_ctl = from->nested_ctl;
dst->event_inj = from->event_inj;
dst->event_inj_err = from->event_inj_err;
dst->nested_cr3 = from->nested_cr3;
dst->lbr_ctl = from->lbr_ctl;
}
static int nested_svm_vmexit(struct vcpu_svm *svm)
{
struct vmcb *nested_vmcb;
struct vmcb *hsave = svm->nested.hsave;
struct vmcb *vmcb = svm->vmcb;
struct page *page;
trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
vmcb->control.exit_info_1,
vmcb->control.exit_info_2,
vmcb->control.exit_int_info,
vmcb->control.exit_int_info_err);
nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
if (!nested_vmcb)
return 1;
/* Exit Guest-Mode */
leave_guest_mode(&svm->vcpu);
svm->nested.vmcb = 0;
/* Give the current vmcb to the guest */
disable_gif(svm);
nested_vmcb->save.es = vmcb->save.es;
nested_vmcb->save.cs = vmcb->save.cs;
nested_vmcb->save.ss = vmcb->save.ss;
nested_vmcb->save.ds = vmcb->save.ds;
nested_vmcb->save.gdtr = vmcb->save.gdtr;
nested_vmcb->save.idtr = vmcb->save.idtr;
nested_vmcb->save.efer = svm->vcpu.arch.efer;
nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
nested_vmcb->save.cr2 = vmcb->save.cr2;
nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
nested_vmcb->save.rip = vmcb->save.rip;
nested_vmcb->save.rsp = vmcb->save.rsp;
nested_vmcb->save.rax = vmcb->save.rax;
nested_vmcb->save.dr7 = vmcb->save.dr7;
nested_vmcb->save.dr6 = vmcb->save.dr6;
nested_vmcb->save.cpl = vmcb->save.cpl;
nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
nested_vmcb->control.int_vector = vmcb->control.int_vector;
nested_vmcb->control.int_state = vmcb->control.int_state;
nested_vmcb->control.exit_code = vmcb->control.exit_code;
nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
nested_vmcb->control.next_rip = vmcb->control.next_rip;
/*
* If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
* to make sure that we do not lose injected events. So check event_inj
* here and copy it to exit_int_info if it is valid.
* Exit_int_info and event_inj can't be both valid because the case
* below only happens on a VMRUN instruction intercept which has
* no valid exit_int_info set.
*/
if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
struct vmcb_control_area *nc = &nested_vmcb->control;
nc->exit_int_info = vmcb->control.event_inj;
nc->exit_int_info_err = vmcb->control.event_inj_err;
}
nested_vmcb->control.tlb_ctl = 0;
nested_vmcb->control.event_inj = 0;
nested_vmcb->control.event_inj_err = 0;
/* We always set V_INTR_MASKING and remember the old value in hflags */
if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
/* Restore the original control entries */
copy_vmcb_control_area(vmcb, hsave);
kvm_clear_exception_queue(&svm->vcpu);
kvm_clear_interrupt_queue(&svm->vcpu);
svm->nested.nested_cr3 = 0;
/* Restore selected save entries */
svm->vmcb->save.es = hsave->save.es;
svm->vmcb->save.cs = hsave->save.cs;
svm->vmcb->save.ss = hsave->save.ss;
svm->vmcb->save.ds = hsave->save.ds;
svm->vmcb->save.gdtr = hsave->save.gdtr;
svm->vmcb->save.idtr = hsave->save.idtr;
kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
svm_set_efer(&svm->vcpu, hsave->save.efer);
svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
svm_set_cr4(&svm->vcpu, hsave->save.cr4);
if (npt_enabled) {
svm->vmcb->save.cr3 = hsave->save.cr3;
svm->vcpu.arch.cr3 = hsave->save.cr3;
} else {
(void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
}
kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
svm->vmcb->save.dr7 = 0;
svm->vmcb->save.cpl = 0;
svm->vmcb->control.exit_int_info = 0;
mark_all_dirty(svm->vmcb);
nested_svm_unmap(page);
nested_svm_uninit_mmu_context(&svm->vcpu);
kvm_mmu_reset_context(&svm->vcpu);
kvm_mmu_load(&svm->vcpu);
return 0;
}
static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
{
/*
* This function merges the msr permission bitmaps of kvm and the
* nested vmcb. It is omptimized in that it only merges the parts where
* the kvm msr permission bitmap may contain zero bits
*/
int i;
if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
return true;
for (i = 0; i < MSRPM_OFFSETS; i++) {
u32 value, p;
u64 offset;
if (msrpm_offsets[i] == 0xffffffff)
break;
p = msrpm_offsets[i];
offset = svm->nested.vmcb_msrpm + (p * 4);
if (kvm_read_guest(svm->vcpu.kvm, offset, &value, 4))
return false;
svm->nested.msrpm[p] = svm->msrpm[p] | value;
}
svm->vmcb->control.msrpm_base_pa = __pa(svm->nested.msrpm);
return true;
}
static bool nested_vmcb_checks(struct vmcb *vmcb)
{
if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
return false;
if (vmcb->control.asid == 0)
return false;
if (vmcb->control.nested_ctl && !npt_enabled)
return false;
return true;
}
static bool nested_svm_vmrun(struct vcpu_svm *svm)
{
struct vmcb *nested_vmcb;
struct vmcb *hsave = svm->nested.hsave;
struct vmcb *vmcb = svm->vmcb;
struct page *page;
u64 vmcb_gpa;
vmcb_gpa = svm->vmcb->save.rax;
nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
if (!nested_vmcb)
return false;
if (!nested_vmcb_checks(nested_vmcb)) {
nested_vmcb->control.exit_code = SVM_EXIT_ERR;
nested_vmcb->control.exit_code_hi = 0;
nested_vmcb->control.exit_info_1 = 0;
nested_vmcb->control.exit_info_2 = 0;
nested_svm_unmap(page);
return false;
}
trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
nested_vmcb->save.rip,
nested_vmcb->control.int_ctl,
nested_vmcb->control.event_inj,
nested_vmcb->control.nested_ctl);
trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
nested_vmcb->control.intercept_cr >> 16,
nested_vmcb->control.intercept_exceptions,
nested_vmcb->control.intercept);
/* Clear internal status */
kvm_clear_exception_queue(&svm->vcpu);
kvm_clear_interrupt_queue(&svm->vcpu);
/*
* Save the old vmcb, so we don't need to pick what we save, but can
* restore everything when a VMEXIT occurs
*/
hsave->save.es = vmcb->save.es;
hsave->save.cs = vmcb->save.cs;
hsave->save.ss = vmcb->save.ss;
hsave->save.ds = vmcb->save.ds;
hsave->save.gdtr = vmcb->save.gdtr;
hsave->save.idtr = vmcb->save.idtr;
hsave->save.efer = svm->vcpu.arch.efer;
hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
hsave->save.cr4 = svm->vcpu.arch.cr4;
hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
hsave->save.rip = kvm_rip_read(&svm->vcpu);
hsave->save.rsp = vmcb->save.rsp;
hsave->save.rax = vmcb->save.rax;
if (npt_enabled)
hsave->save.cr3 = vmcb->save.cr3;
else
hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
copy_vmcb_control_area(hsave, vmcb);
if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
svm->vcpu.arch.hflags |= HF_HIF_MASK;
else
svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
if (nested_vmcb->control.nested_ctl) {
kvm_mmu_unload(&svm->vcpu);
svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
nested_svm_init_mmu_context(&svm->vcpu);
}
/* Load the nested guest state */
svm->vmcb->save.es = nested_vmcb->save.es;
svm->vmcb->save.cs = nested_vmcb->save.cs;
svm->vmcb->save.ss = nested_vmcb->save.ss;
svm->vmcb->save.ds = nested_vmcb->save.ds;
svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
svm->vmcb->save.idtr = nested_vmcb->save.idtr;
kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
if (npt_enabled) {
svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
} else
(void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
/* Guest paging mode is active - reset mmu */
kvm_mmu_reset_context(&svm->vcpu);
svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
/* In case we don't even reach vcpu_run, the fields are not updated */
svm->vmcb->save.rax = nested_vmcb->save.rax;
svm->vmcb->save.rsp = nested_vmcb->save.rsp;
svm->vmcb->save.rip = nested_vmcb->save.rip;
svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
svm->vmcb->save.cpl = nested_vmcb->save.cpl;
svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
/* cache intercepts */
svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
svm->nested.intercept = nested_vmcb->control.intercept;
svm_flush_tlb(&svm->vcpu);
svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
svm->vcpu.arch.hflags |= HF_VINTR_MASK;
else
svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
/* We only want the cr8 intercept bits of the guest */
clr_cr_intercept(svm, INTERCEPT_CR8_READ);
clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
}
/* We don't want to see VMMCALLs from a nested guest */
clr_intercept(svm, INTERCEPT_VMMCALL);
svm->vmcb->control.lbr_ctl = nested_vmcb->control.lbr_ctl;
svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
svm->vmcb->control.int_state = nested_vmcb->control.int_state;
svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
nested_svm_unmap(page);
/* Enter Guest-Mode */
enter_guest_mode(&svm->vcpu);
/*
* Merge guest and host intercepts - must be called with vcpu in
* guest-mode to take affect here
*/
recalc_intercepts(svm);
svm->nested.vmcb = vmcb_gpa;
enable_gif(svm);
mark_all_dirty(svm->vmcb);
return true;
}
static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
{
to_vmcb->save.fs = from_vmcb->save.fs;
to_vmcb->save.gs = from_vmcb->save.gs;
to_vmcb->save.tr = from_vmcb->save.tr;
to_vmcb->save.ldtr = from_vmcb->save.ldtr;
to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
to_vmcb->save.star = from_vmcb->save.star;
to_vmcb->save.lstar = from_vmcb->save.lstar;
to_vmcb->save.cstar = from_vmcb->save.cstar;
to_vmcb->save.sfmask = from_vmcb->save.sfmask;
to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
}
static int vmload_interception(struct vcpu_svm *svm)
{
struct vmcb *nested_vmcb;
struct page *page;
if (nested_svm_check_permissions(svm))
return 1;
nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
if (!nested_vmcb)
return 1;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
nested_svm_unmap(page);
return 1;
}
static int vmsave_interception(struct vcpu_svm *svm)
{
struct vmcb *nested_vmcb;
struct page *page;
if (nested_svm_check_permissions(svm))
return 1;
nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
if (!nested_vmcb)
return 1;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
nested_svm_unmap(page);
return 1;
}
static int vmrun_interception(struct vcpu_svm *svm)
{
if (nested_svm_check_permissions(svm))
return 1;
/* Save rip after vmrun instruction */
kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
if (!nested_svm_vmrun(svm))
return 1;
if (!nested_svm_vmrun_msrpm(svm))
goto failed;
return 1;
failed:
svm->vmcb->control.exit_code = SVM_EXIT_ERR;
svm->vmcb->control.exit_code_hi = 0;
svm->vmcb->control.exit_info_1 = 0;
svm->vmcb->control.exit_info_2 = 0;
nested_svm_vmexit(svm);
return 1;
}
static int stgi_interception(struct vcpu_svm *svm)
{
if (nested_svm_check_permissions(svm))
return 1;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
enable_gif(svm);
return 1;
}
static int clgi_interception(struct vcpu_svm *svm)
{
if (nested_svm_check_permissions(svm))
return 1;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
disable_gif(svm);
/* After a CLGI no interrupts should come */
svm_clear_vintr(svm);
svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
mark_dirty(svm->vmcb, VMCB_INTR);
return 1;
}
static int invlpga_interception(struct vcpu_svm *svm)
{
struct kvm_vcpu *vcpu = &svm->vcpu;
trace_kvm_invlpga(svm->vmcb->save.rip, vcpu->arch.regs[VCPU_REGS_RCX],
vcpu->arch.regs[VCPU_REGS_RAX]);
/* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
kvm_mmu_invlpg(vcpu, vcpu->arch.regs[VCPU_REGS_RAX]);
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
return 1;
}
static int skinit_interception(struct vcpu_svm *svm)
{
trace_kvm_skinit(svm->vmcb->save.rip, svm->vcpu.arch.regs[VCPU_REGS_RAX]);
kvm_queue_exception(&svm->vcpu, UD_VECTOR);
return 1;
}
static int xsetbv_interception(struct vcpu_svm *svm)
{
u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
skip_emulated_instruction(&svm->vcpu);
}
return 1;
}
static int invalid_op_interception(struct vcpu_svm *svm)
{
kvm_queue_exception(&svm->vcpu, UD_VECTOR);
return 1;
}
static int task_switch_interception(struct vcpu_svm *svm)
{
u16 tss_selector;
int reason;
int int_type = svm->vmcb->control.exit_int_info &
SVM_EXITINTINFO_TYPE_MASK;
int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
uint32_t type =
svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
uint32_t idt_v =
svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
bool has_error_code = false;
u32 error_code = 0;
tss_selector = (u16)svm->vmcb->control.exit_info_1;
if (svm->vmcb->control.exit_info_2 &
(1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
reason = TASK_SWITCH_IRET;
else if (svm->vmcb->control.exit_info_2 &
(1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
reason = TASK_SWITCH_JMP;
else if (idt_v)
reason = TASK_SWITCH_GATE;
else
reason = TASK_SWITCH_CALL;
if (reason == TASK_SWITCH_GATE) {
switch (type) {
case SVM_EXITINTINFO_TYPE_NMI:
svm->vcpu.arch.nmi_injected = false;
break;
case SVM_EXITINTINFO_TYPE_EXEPT:
if (svm->vmcb->control.exit_info_2 &
(1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
has_error_code = true;
error_code =
(u32)svm->vmcb->control.exit_info_2;
}
kvm_clear_exception_queue(&svm->vcpu);
break;
case SVM_EXITINTINFO_TYPE_INTR:
kvm_clear_interrupt_queue(&svm->vcpu);
break;
default:
break;
}
}
if (reason != TASK_SWITCH_GATE ||
int_type == SVM_EXITINTINFO_TYPE_SOFT ||
(int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
(int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
skip_emulated_instruction(&svm->vcpu);
if (kvm_task_switch(&svm->vcpu, tss_selector, reason,
has_error_code, error_code) == EMULATE_FAIL) {
svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
svm->vcpu.run->internal.ndata = 0;
return 0;
}
return 1;
}
static int cpuid_interception(struct vcpu_svm *svm)
{
svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
kvm_emulate_cpuid(&svm->vcpu);
return 1;
}
static int iret_interception(struct vcpu_svm *svm)
{
++svm->vcpu.stat.nmi_window_exits;
clr_intercept(svm, INTERCEPT_IRET);
svm->vcpu.arch.hflags |= HF_IRET_MASK;
svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
return 1;
}
static int invlpg_interception(struct vcpu_svm *svm)
{
if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
skip_emulated_instruction(&svm->vcpu);
return 1;
}
static int emulate_on_interception(struct vcpu_svm *svm)
{
return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
}
bool check_selective_cr0_intercepted(struct vcpu_svm *svm, unsigned long val)
{
unsigned long cr0 = svm->vcpu.arch.cr0;
bool ret = false;
u64 intercept;
intercept = svm->nested.intercept;
if (!is_guest_mode(&svm->vcpu) ||
(!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
return false;
cr0 &= ~SVM_CR0_SELECTIVE_MASK;
val &= ~SVM_CR0_SELECTIVE_MASK;
if (cr0 ^ val) {
svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
}
return ret;
}
#define CR_VALID (1ULL << 63)
static int cr_interception(struct vcpu_svm *svm)
{
int reg, cr;
unsigned long val;
int err;
if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
return emulate_on_interception(svm);
if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
return emulate_on_interception(svm);
reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
err = 0;
if (cr >= 16) { /* mov to cr */
cr -= 16;
val = kvm_register_read(&svm->vcpu, reg);
switch (cr) {
case 0:
if (!check_selective_cr0_intercepted(svm, val))
err = kvm_set_cr0(&svm->vcpu, val);
else
return 1;
break;
case 3:
err = kvm_set_cr3(&svm->vcpu, val);
break;
case 4:
err = kvm_set_cr4(&svm->vcpu, val);
break;
case 8:
err = kvm_set_cr8(&svm->vcpu, val);
break;
default:
WARN(1, "unhandled write to CR%d", cr);
kvm_queue_exception(&svm->vcpu, UD_VECTOR);
return 1;
}
} else { /* mov from cr */
switch (cr) {
case 0:
val = kvm_read_cr0(&svm->vcpu);
break;
case 2:
val = svm->vcpu.arch.cr2;
break;
case 3:
val = kvm_read_cr3(&svm->vcpu);
break;
case 4:
val = kvm_read_cr4(&svm->vcpu);
break;
case 8:
val = kvm_get_cr8(&svm->vcpu);
break;
default:
WARN(1, "unhandled read from CR%d", cr);
kvm_queue_exception(&svm->vcpu, UD_VECTOR);
return 1;
}
kvm_register_write(&svm->vcpu, reg, val);
}
kvm_complete_insn_gp(&svm->vcpu, err);
return 1;
}
static int dr_interception(struct vcpu_svm *svm)
{
int reg, dr;
unsigned long val;
int err;
if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
return emulate_on_interception(svm);
reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
if (dr >= 16) { /* mov to DRn */
val = kvm_register_read(&svm->vcpu, reg);
kvm_set_dr(&svm->vcpu, dr - 16, val);
} else {
err = kvm_get_dr(&svm->vcpu, dr, &val);
if (!err)
kvm_register_write(&svm->vcpu, reg, val);
}
skip_emulated_instruction(&svm->vcpu);
return 1;
}
static int cr8_write_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
int r;
u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
/* instruction emulation calls kvm_set_cr8() */
r = cr_interception(svm);
if (irqchip_in_kernel(svm->vcpu.kvm)) {
clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
return r;
}
if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
return r;
kvm_run->exit_reason = KVM_EXIT_SET_TPR;
return 0;
}
static int svm_get_msr(struct kvm_vcpu *vcpu, unsigned ecx, u64 *data)
{
struct vcpu_svm *svm = to_svm(vcpu);
switch (ecx) {
case MSR_IA32_TSC: {
struct vmcb *vmcb = get_host_vmcb(svm);
*data = vmcb->control.tsc_offset +
svm_scale_tsc(vcpu, native_read_tsc());
break;
}
case MSR_STAR:
*data = svm->vmcb->save.star;
break;
#ifdef CONFIG_X86_64
case MSR_LSTAR:
*data = svm->vmcb->save.lstar;
break;
case MSR_CSTAR:
*data = svm->vmcb->save.cstar;
break;
case MSR_KERNEL_GS_BASE:
*data = svm->vmcb->save.kernel_gs_base;
break;
case MSR_SYSCALL_MASK:
*data = svm->vmcb->save.sfmask;
break;
#endif
case MSR_IA32_SYSENTER_CS:
*data = svm->vmcb->save.sysenter_cs;
break;
case MSR_IA32_SYSENTER_EIP:
*data = svm->sysenter_eip;
break;
case MSR_IA32_SYSENTER_ESP:
*data = svm->sysenter_esp;
break;
/*
* Nobody will change the following 5 values in the VMCB so we can
* safely return them on rdmsr. They will always be 0 until LBRV is
* implemented.
*/
case MSR_IA32_DEBUGCTLMSR:
*data = svm->vmcb->save.dbgctl;
break;
case MSR_IA32_LASTBRANCHFROMIP:
*data = svm->vmcb->save.br_from;
break;
case MSR_IA32_LASTBRANCHTOIP:
*data = svm->vmcb->save.br_to;
break;
case MSR_IA32_LASTINTFROMIP:
*data = svm->vmcb->save.last_excp_from;
break;
case MSR_IA32_LASTINTTOIP:
*data = svm->vmcb->save.last_excp_to;
break;
case MSR_VM_HSAVE_PA:
*data = svm->nested.hsave_msr;
break;
case MSR_VM_CR:
*data = svm->nested.vm_cr_msr;
break;
case MSR_IA32_UCODE_REV:
*data = 0x01000065;
break;
default:
return kvm_get_msr_common(vcpu, ecx, data);
}
return 0;
}
static int rdmsr_interception(struct vcpu_svm *svm)
{
u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
u64 data;
if (svm_get_msr(&svm->vcpu, ecx, &data)) {
trace_kvm_msr_read_ex(ecx);
kvm_inject_gp(&svm->vcpu, 0);
} else {
trace_kvm_msr_read(ecx, data);
svm->vcpu.arch.regs[VCPU_REGS_RAX] = data & 0xffffffff;
svm->vcpu.arch.regs[VCPU_REGS_RDX] = data >> 32;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
skip_emulated_instruction(&svm->vcpu);
}
return 1;
}
static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
{
struct vcpu_svm *svm = to_svm(vcpu);
int svm_dis, chg_mask;
if (data & ~SVM_VM_CR_VALID_MASK)
return 1;
chg_mask = SVM_VM_CR_VALID_MASK;
if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
svm->nested.vm_cr_msr &= ~chg_mask;
svm->nested.vm_cr_msr |= (data & chg_mask);
svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
/* check for svm_disable while efer.svme is set */
if (svm_dis && (vcpu->arch.efer & EFER_SVME))
return 1;
return 0;
}
static int svm_set_msr(struct kvm_vcpu *vcpu, unsigned ecx, u64 data)
{
struct vcpu_svm *svm = to_svm(vcpu);
switch (ecx) {
case MSR_IA32_TSC:
kvm_write_tsc(vcpu, data);
break;
case MSR_STAR:
svm->vmcb->save.star = data;
break;
#ifdef CONFIG_X86_64
case MSR_LSTAR:
svm->vmcb->save.lstar = data;
break;
case MSR_CSTAR:
svm->vmcb->save.cstar = data;
break;
case MSR_KERNEL_GS_BASE:
svm->vmcb->save.kernel_gs_base = data;
break;
case MSR_SYSCALL_MASK:
svm->vmcb->save.sfmask = data;
break;
#endif
case MSR_IA32_SYSENTER_CS:
svm->vmcb->save.sysenter_cs = data;
break;
case MSR_IA32_SYSENTER_EIP:
svm->sysenter_eip = data;
svm->vmcb->save.sysenter_eip = data;
break;
case MSR_IA32_SYSENTER_ESP:
svm->sysenter_esp = data;
svm->vmcb->save.sysenter_esp = data;
break;
case MSR_IA32_DEBUGCTLMSR:
if (!boot_cpu_has(X86_FEATURE_LBRV)) {
pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
__func__, data);
break;
}
if (data & DEBUGCTL_RESERVED_BITS)
return 1;
svm->vmcb->save.dbgctl = data;
mark_dirty(svm->vmcb, VMCB_LBR);
if (data & (1ULL<<0))
svm_enable_lbrv(svm);
else
svm_disable_lbrv(svm);
break;
case MSR_VM_HSAVE_PA:
svm->nested.hsave_msr = data;
break;
case MSR_VM_CR:
return svm_set_vm_cr(vcpu, data);
case MSR_VM_IGNNE:
pr_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
break;
default:
return kvm_set_msr_common(vcpu, ecx, data);
}
return 0;
}
static int wrmsr_interception(struct vcpu_svm *svm)
{
u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
u64 data = (svm->vcpu.arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(svm->vcpu.arch.regs[VCPU_REGS_RDX] & -1u) << 32);
svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
if (svm_set_msr(&svm->vcpu, ecx, data)) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(&svm->vcpu, 0);
} else {
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(&svm->vcpu);
}
return 1;
}
static int msr_interception(struct vcpu_svm *svm)
{
if (svm->vmcb->control.exit_info_1)
return wrmsr_interception(svm);
else
return rdmsr_interception(svm);
}
static int interrupt_window_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
svm_clear_vintr(svm);
svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
mark_dirty(svm->vmcb, VMCB_INTR);
/*
* If the user space waits to inject interrupts, exit as soon as
* possible
*/
if (!irqchip_in_kernel(svm->vcpu.kvm) &&
kvm_run->request_interrupt_window &&
!kvm_cpu_has_interrupt(&svm->vcpu)) {
++svm->vcpu.stat.irq_window_exits;
kvm_run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
return 0;
}
return 1;
}
static int pause_interception(struct vcpu_svm *svm)
{
kvm_vcpu_on_spin(&(svm->vcpu));
return 1;
}
static int (*svm_exit_handlers[])(struct vcpu_svm *svm) = {
[SVM_EXIT_READ_CR0] = cr_interception,
[SVM_EXIT_READ_CR3] = cr_interception,
[SVM_EXIT_READ_CR4] = cr_interception,
[SVM_EXIT_READ_CR8] = cr_interception,
[SVM_EXIT_CR0_SEL_WRITE] = emulate_on_interception,
[SVM_EXIT_WRITE_CR0] = cr_interception,
[SVM_EXIT_WRITE_CR3] = cr_interception,
[SVM_EXIT_WRITE_CR4] = cr_interception,
[SVM_EXIT_WRITE_CR8] = cr8_write_interception,
[SVM_EXIT_READ_DR0] = dr_interception,
[SVM_EXIT_READ_DR1] = dr_interception,
[SVM_EXIT_READ_DR2] = dr_interception,
[SVM_EXIT_READ_DR3] = dr_interception,
[SVM_EXIT_READ_DR4] = dr_interception,
[SVM_EXIT_READ_DR5] = dr_interception,
[SVM_EXIT_READ_DR6] = dr_interception,
[SVM_EXIT_READ_DR7] = dr_interception,
[SVM_EXIT_WRITE_DR0] = dr_interception,
[SVM_EXIT_WRITE_DR1] = dr_interception,
[SVM_EXIT_WRITE_DR2] = dr_interception,
[SVM_EXIT_WRITE_DR3] = dr_interception,
[SVM_EXIT_WRITE_DR4] = dr_interception,
[SVM_EXIT_WRITE_DR5] = dr_interception,
[SVM_EXIT_WRITE_DR6] = dr_interception,
[SVM_EXIT_WRITE_DR7] = dr_interception,
[SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
[SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
[SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
[SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
[SVM_EXIT_EXCP_BASE + NM_VECTOR] = nm_interception,
[SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
[SVM_EXIT_INTR] = intr_interception,
[SVM_EXIT_NMI] = nmi_interception,
[SVM_EXIT_SMI] = nop_on_interception,
[SVM_EXIT_INIT] = nop_on_interception,
[SVM_EXIT_VINTR] = interrupt_window_interception,
[SVM_EXIT_CPUID] = cpuid_interception,
[SVM_EXIT_IRET] = iret_interception,
[SVM_EXIT_INVD] = emulate_on_interception,
[SVM_EXIT_PAUSE] = pause_interception,
[SVM_EXIT_HLT] = halt_interception,
[SVM_EXIT_INVLPG] = invlpg_interception,
[SVM_EXIT_INVLPGA] = invlpga_interception,
[SVM_EXIT_IOIO] = io_interception,
[SVM_EXIT_MSR] = msr_interception,
[SVM_EXIT_TASK_SWITCH] = task_switch_interception,
[SVM_EXIT_SHUTDOWN] = shutdown_interception,
[SVM_EXIT_VMRUN] = vmrun_interception,
[SVM_EXIT_VMMCALL] = vmmcall_interception,
[SVM_EXIT_VMLOAD] = vmload_interception,
[SVM_EXIT_VMSAVE] = vmsave_interception,
[SVM_EXIT_STGI] = stgi_interception,
[SVM_EXIT_CLGI] = clgi_interception,
[SVM_EXIT_SKINIT] = skinit_interception,
[SVM_EXIT_WBINVD] = emulate_on_interception,
[SVM_EXIT_MONITOR] = invalid_op_interception,
[SVM_EXIT_MWAIT] = invalid_op_interception,
[SVM_EXIT_XSETBV] = xsetbv_interception,
[SVM_EXIT_NPF] = pf_interception,
};
static void dump_vmcb(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
pr_err("VMCB Control Area:\n");
pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
pr_err("%-20s%d\n", "asid:", control->asid);
pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
pr_err("%-20s%08x\n", "int_state:", control->int_state);
pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
pr_err("%-20s%lld\n", "lbr_ctl:", control->lbr_ctl);
pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
pr_err("VMCB State Save Area:\n");
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"es:",
save->es.selector, save->es.attrib,
save->es.limit, save->es.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"cs:",
save->cs.selector, save->cs.attrib,
save->cs.limit, save->cs.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"ss:",
save->ss.selector, save->ss.attrib,
save->ss.limit, save->ss.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"ds:",
save->ds.selector, save->ds.attrib,
save->ds.limit, save->ds.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"fs:",
save->fs.selector, save->fs.attrib,
save->fs.limit, save->fs.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"gs:",
save->gs.selector, save->gs.attrib,
save->gs.limit, save->gs.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"gdtr:",
save->gdtr.selector, save->gdtr.attrib,
save->gdtr.limit, save->gdtr.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"ldtr:",
save->ldtr.selector, save->ldtr.attrib,
save->ldtr.limit, save->ldtr.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"idtr:",
save->idtr.selector, save->idtr.attrib,
save->idtr.limit, save->idtr.base);
pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
"tr:",
save->tr.selector, save->tr.attrib,
save->tr.limit, save->tr.base);
pr_err("cpl: %d efer: %016llx\n",
save->cpl, save->efer);
pr_err("%-15s %016llx %-13s %016llx\n",
"cr0:", save->cr0, "cr2:", save->cr2);
pr_err("%-15s %016llx %-13s %016llx\n",
"cr3:", save->cr3, "cr4:", save->cr4);
pr_err("%-15s %016llx %-13s %016llx\n",
"dr6:", save->dr6, "dr7:", save->dr7);
pr_err("%-15s %016llx %-13s %016llx\n",
"rip:", save->rip, "rflags:", save->rflags);
pr_err("%-15s %016llx %-13s %016llx\n",
"rsp:", save->rsp, "rax:", save->rax);
pr_err("%-15s %016llx %-13s %016llx\n",
"star:", save->star, "lstar:", save->lstar);
pr_err("%-15s %016llx %-13s %016llx\n",
"cstar:", save->cstar, "sfmask:", save->sfmask);
pr_err("%-15s %016llx %-13s %016llx\n",
"kernel_gs_base:", save->kernel_gs_base,
"sysenter_cs:", save->sysenter_cs);
pr_err("%-15s %016llx %-13s %016llx\n",
"sysenter_esp:", save->sysenter_esp,
"sysenter_eip:", save->sysenter_eip);
pr_err("%-15s %016llx %-13s %016llx\n",
"gpat:", save->g_pat, "dbgctl:", save->dbgctl);
pr_err("%-15s %016llx %-13s %016llx\n",
"br_from:", save->br_from, "br_to:", save->br_to);
pr_err("%-15s %016llx %-13s %016llx\n",
"excp_from:", save->last_excp_from,
"excp_to:", save->last_excp_to);
}
static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
{
struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
*info1 = control->exit_info_1;
*info2 = control->exit_info_2;
}
static int handle_exit(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 exit_code = svm->vmcb->control.exit_code;
trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
vcpu->arch.cr0 = svm->vmcb->save.cr0;
if (npt_enabled)
vcpu->arch.cr3 = svm->vmcb->save.cr3;
if (unlikely(svm->nested.exit_required)) {
nested_svm_vmexit(svm);
svm->nested.exit_required = false;
return 1;
}
if (is_guest_mode(vcpu)) {
int vmexit;
trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
svm->vmcb->control.exit_info_1,
svm->vmcb->control.exit_info_2,
svm->vmcb->control.exit_int_info,
svm->vmcb->control.exit_int_info_err);
vmexit = nested_svm_exit_special(svm);
if (vmexit == NESTED_EXIT_CONTINUE)
vmexit = nested_svm_exit_handled(svm);
if (vmexit == NESTED_EXIT_DONE)
return 1;
}
svm_complete_interrupts(svm);
if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
kvm_run->fail_entry.hardware_entry_failure_reason
= svm->vmcb->control.exit_code;
pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
dump_vmcb(vcpu);
return 0;
}
if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
printk(KERN_ERR "%s: unexpected exit_ini_info 0x%x "
"exit_code 0x%x\n",
__func__, svm->vmcb->control.exit_int_info,
exit_code);
if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
|| !svm_exit_handlers[exit_code]) {
kvm_run->exit_reason = KVM_EXIT_UNKNOWN;
kvm_run->hw.hardware_exit_reason = exit_code;
return 0;
}
return svm_exit_handlers[exit_code](svm);
}
static void reload_tss(struct kvm_vcpu *vcpu)
{
int cpu = raw_smp_processor_id();
struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
sd->tss_desc->type = 9; /* available 32/64-bit TSS */
load_TR_desc();
}
static void pre_svm_run(struct vcpu_svm *svm)
{
int cpu = raw_smp_processor_id();
struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
/* FIXME: handle wraparound of asid_generation */
if (svm->asid_generation != sd->asid_generation)
new_asid(svm, sd);
}
static void svm_inject_nmi(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
vcpu->arch.hflags |= HF_NMI_MASK;
set_intercept(svm, INTERCEPT_IRET);
++vcpu->stat.nmi_injections;
}
static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
{
struct vmcb_control_area *control;
control = &svm->vmcb->control;
control->int_vector = irq;
control->int_ctl &= ~V_INTR_PRIO_MASK;
control->int_ctl |= V_IRQ_MASK |
((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
mark_dirty(svm->vmcb, VMCB_INTR);
}
static void svm_set_irq(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
BUG_ON(!(gif_set(svm)));
trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
++vcpu->stat.irq_injections;
svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
return;
if (irr == -1)
return;
if (tpr >= irr)
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
}
static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
struct vmcb *vmcb = svm->vmcb;
int ret;
ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
!(svm->vcpu.arch.hflags & HF_NMI_MASK);
ret = ret && gif_set(svm) && nested_svm_nmi(svm);
return ret;
}
static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
}
static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (masked) {
svm->vcpu.arch.hflags |= HF_NMI_MASK;
set_intercept(svm, INTERCEPT_IRET);
} else {
svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
clr_intercept(svm, INTERCEPT_IRET);
}
}
static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
struct vmcb *vmcb = svm->vmcb;
int ret;
if (!gif_set(svm) ||
(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
return 0;
ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
if (is_guest_mode(vcpu))
return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
return ret;
}
static void enable_irq_window(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
/*
* In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
* 1, because that's a separate STGI/VMRUN intercept. The next time we
* get that intercept, this function will be called again though and
* we'll get the vintr intercept.
*/
if (gif_set(svm) && nested_svm_intr(svm)) {
svm_set_vintr(svm);
svm_inject_irq(svm, 0x0);
}
}
static void enable_nmi_window(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
== HF_NMI_MASK)
return; /* IRET will cause a vm exit */
/*
* Something prevents NMI from been injected. Single step over possible
* problem (IRET or exception injection or interrupt shadow)
*/
svm->nmi_singlestep = true;
svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_intercept(vcpu);
}
static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
{
return 0;
}
static void svm_flush_tlb(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
else
svm->asid_generation--;
}
static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
{
}
static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
return;
if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
kvm_set_cr8(vcpu, cr8);
}
}
static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
u64 cr8;
if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
return;
cr8 = kvm_get_cr8(vcpu);
svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
}
static void svm_complete_interrupts(struct vcpu_svm *svm)
{
u8 vector;
int type;
u32 exitintinfo = svm->vmcb->control.exit_int_info;
unsigned int3_injected = svm->int3_injected;
svm->int3_injected = 0;
/*
* If we've made progress since setting HF_IRET_MASK, we've
* executed an IRET and can allow NMI injection.
*/
if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
&& kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
}
svm->vcpu.arch.nmi_injected = false;
kvm_clear_exception_queue(&svm->vcpu);
kvm_clear_interrupt_queue(&svm->vcpu);
if (!(exitintinfo & SVM_EXITINTINFO_VALID))
return;
kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
switch (type) {
case SVM_EXITINTINFO_TYPE_NMI:
svm->vcpu.arch.nmi_injected = true;
break;
case SVM_EXITINTINFO_TYPE_EXEPT:
/*
* In case of software exceptions, do not reinject the vector,
* but re-execute the instruction instead. Rewind RIP first
* if we emulated INT3 before.
*/
if (kvm_exception_is_soft(vector)) {
if (vector == BP_VECTOR && int3_injected &&
kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
kvm_rip_write(&svm->vcpu,
kvm_rip_read(&svm->vcpu) -
int3_injected);
break;
}
if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
u32 err = svm->vmcb->control.exit_int_info_err;
kvm_requeue_exception_e(&svm->vcpu, vector, err);
} else
kvm_requeue_exception(&svm->vcpu, vector);
break;
case SVM_EXITINTINFO_TYPE_INTR:
kvm_queue_interrupt(&svm->vcpu, vector, false);
break;
default:
break;
}
}
static void svm_cancel_injection(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
struct vmcb_control_area *control = &svm->vmcb->control;
control->exit_int_info = control->event_inj;
control->exit_int_info_err = control->event_inj_err;
control->event_inj = 0;
svm_complete_interrupts(svm);
}
#ifdef CONFIG_X86_64
#define R "r"
#else
#define R "e"
#endif
static void svm_vcpu_run(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
/*
* A vmexit emulation is required before the vcpu can be executed
* again.
*/
if (unlikely(svm->nested.exit_required))
return;
pre_svm_run(svm);
sync_lapic_to_cr8(vcpu);
svm->vmcb->save.cr2 = vcpu->arch.cr2;
clgi();
local_irq_enable();
asm volatile (
"push %%"R"bp; \n\t"
"mov %c[rbx](%[svm]), %%"R"bx \n\t"
"mov %c[rcx](%[svm]), %%"R"cx \n\t"
"mov %c[rdx](%[svm]), %%"R"dx \n\t"
"mov %c[rsi](%[svm]), %%"R"si \n\t"
"mov %c[rdi](%[svm]), %%"R"di \n\t"
"mov %c[rbp](%[svm]), %%"R"bp \n\t"
#ifdef CONFIG_X86_64
"mov %c[r8](%[svm]), %%r8 \n\t"
"mov %c[r9](%[svm]), %%r9 \n\t"
"mov %c[r10](%[svm]), %%r10 \n\t"
"mov %c[r11](%[svm]), %%r11 \n\t"
"mov %c[r12](%[svm]), %%r12 \n\t"
"mov %c[r13](%[svm]), %%r13 \n\t"
"mov %c[r14](%[svm]), %%r14 \n\t"
"mov %c[r15](%[svm]), %%r15 \n\t"
#endif
/* Enter guest mode */
"push %%"R"ax \n\t"
"mov %c[vmcb](%[svm]), %%"R"ax \n\t"
__ex(SVM_VMLOAD) "\n\t"
__ex(SVM_VMRUN) "\n\t"
__ex(SVM_VMSAVE) "\n\t"
"pop %%"R"ax \n\t"
/* Save guest registers, load host registers */
"mov %%"R"bx, %c[rbx](%[svm]) \n\t"
"mov %%"R"cx, %c[rcx](%[svm]) \n\t"
"mov %%"R"dx, %c[rdx](%[svm]) \n\t"
"mov %%"R"si, %c[rsi](%[svm]) \n\t"
"mov %%"R"di, %c[rdi](%[svm]) \n\t"
"mov %%"R"bp, %c[rbp](%[svm]) \n\t"
#ifdef CONFIG_X86_64
"mov %%r8, %c[r8](%[svm]) \n\t"
"mov %%r9, %c[r9](%[svm]) \n\t"
"mov %%r10, %c[r10](%[svm]) \n\t"
"mov %%r11, %c[r11](%[svm]) \n\t"
"mov %%r12, %c[r12](%[svm]) \n\t"
"mov %%r13, %c[r13](%[svm]) \n\t"
"mov %%r14, %c[r14](%[svm]) \n\t"
"mov %%r15, %c[r15](%[svm]) \n\t"
#endif
"pop %%"R"bp"
:
: [svm]"a"(svm),
[vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
[rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
[rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
[rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
[rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
[rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
[rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
#ifdef CONFIG_X86_64
, [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
[r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
[r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
[r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
[r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
[r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
[r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
[r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
#endif
: "cc", "memory"
, R"bx", R"cx", R"dx", R"si", R"di"
#ifdef CONFIG_X86_64
, "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
#endif
);
#ifdef CONFIG_X86_64
wrmsrl(MSR_GS_BASE, svm->host.gs_base);
#else
loadsegment(fs, svm->host.fs);
#ifndef CONFIG_X86_32_LAZY_GS
loadsegment(gs, svm->host.gs);
#endif
#endif
reload_tss(vcpu);
local_irq_disable();
vcpu->arch.cr2 = svm->vmcb->save.cr2;
vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
kvm_before_handle_nmi(&svm->vcpu);
stgi();
/* Any pending NMI will happen here */
if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
kvm_after_handle_nmi(&svm->vcpu);
sync_cr8_to_lapic(vcpu);
svm->next_rip = 0;
svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
/* if exit due to PF check for async PF */
if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
svm->apf_reason = kvm_read_and_reset_pf_reason();
if (npt_enabled) {
vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
}
/*
* We need to handle MC intercepts here before the vcpu has a chance to
* change the physical cpu
*/
if (unlikely(svm->vmcb->control.exit_code ==
SVM_EXIT_EXCP_BASE + MC_VECTOR))
svm_handle_mce(svm);
mark_all_clean(svm->vmcb);
}
#undef R
static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->save.cr3 = root;
mark_dirty(svm->vmcb, VMCB_CR);
svm_flush_tlb(vcpu);
}
static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
{
struct vcpu_svm *svm = to_svm(vcpu);
svm->vmcb->control.nested_cr3 = root;
mark_dirty(svm->vmcb, VMCB_NPT);
/* Also sync guest cr3 here in case we live migrate */
svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
mark_dirty(svm->vmcb, VMCB_CR);
svm_flush_tlb(vcpu);
}
static int is_disabled(void)
{
u64 vm_cr;
rdmsrl(MSR_VM_CR, vm_cr);
if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
return 1;
return 0;
}
static void
svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
{
/*
* Patch in the VMMCALL instruction:
*/
hypercall[0] = 0x0f;
hypercall[1] = 0x01;
hypercall[2] = 0xd9;
}
static void svm_check_processor_compat(void *rtn)
{
*(int *)rtn = 0;
}
static bool svm_cpu_has_accelerated_tpr(void)
{
return false;
}
static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
{
return 0;
}
static void svm_cpuid_update(struct kvm_vcpu *vcpu)
{
}
static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
{
switch (func) {
case 0x80000001:
if (nested)
entry->ecx |= (1 << 2); /* Set SVM bit */
break;
case 0x8000000A:
entry->eax = 1; /* SVM revision 1 */
entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
ASID emulation to nested SVM */
entry->ecx = 0; /* Reserved */
entry->edx = 0; /* Per default do not support any
additional features */
/* Support next_rip if host supports it */
if (boot_cpu_has(X86_FEATURE_NRIPS))
entry->edx |= SVM_FEATURE_NRIP;
/* Support NPT for the guest if enabled */
if (npt_enabled)
entry->edx |= SVM_FEATURE_NPT;
break;
}
}
static const struct trace_print_flags svm_exit_reasons_str[] = {
{ SVM_EXIT_READ_CR0, "read_cr0" },
{ SVM_EXIT_READ_CR3, "read_cr3" },
{ SVM_EXIT_READ_CR4, "read_cr4" },
{ SVM_EXIT_READ_CR8, "read_cr8" },
{ SVM_EXIT_WRITE_CR0, "write_cr0" },
{ SVM_EXIT_WRITE_CR3, "write_cr3" },
{ SVM_EXIT_WRITE_CR4, "write_cr4" },
{ SVM_EXIT_WRITE_CR8, "write_cr8" },
{ SVM_EXIT_READ_DR0, "read_dr0" },
{ SVM_EXIT_READ_DR1, "read_dr1" },
{ SVM_EXIT_READ_DR2, "read_dr2" },
{ SVM_EXIT_READ_DR3, "read_dr3" },
{ SVM_EXIT_WRITE_DR0, "write_dr0" },
{ SVM_EXIT_WRITE_DR1, "write_dr1" },
{ SVM_EXIT_WRITE_DR2, "write_dr2" },
{ SVM_EXIT_WRITE_DR3, "write_dr3" },
{ SVM_EXIT_WRITE_DR5, "write_dr5" },
{ SVM_EXIT_WRITE_DR7, "write_dr7" },
{ SVM_EXIT_EXCP_BASE + DB_VECTOR, "DB excp" },
{ SVM_EXIT_EXCP_BASE + BP_VECTOR, "BP excp" },
{ SVM_EXIT_EXCP_BASE + UD_VECTOR, "UD excp" },
{ SVM_EXIT_EXCP_BASE + PF_VECTOR, "PF excp" },
{ SVM_EXIT_EXCP_BASE + NM_VECTOR, "NM excp" },
{ SVM_EXIT_EXCP_BASE + MC_VECTOR, "MC excp" },
{ SVM_EXIT_INTR, "interrupt" },
{ SVM_EXIT_NMI, "nmi" },
{ SVM_EXIT_SMI, "smi" },
{ SVM_EXIT_INIT, "init" },
{ SVM_EXIT_VINTR, "vintr" },
{ SVM_EXIT_CPUID, "cpuid" },
{ SVM_EXIT_INVD, "invd" },
{ SVM_EXIT_HLT, "hlt" },
{ SVM_EXIT_INVLPG, "invlpg" },
{ SVM_EXIT_INVLPGA, "invlpga" },
{ SVM_EXIT_IOIO, "io" },
{ SVM_EXIT_MSR, "msr" },
{ SVM_EXIT_TASK_SWITCH, "task_switch" },
{ SVM_EXIT_SHUTDOWN, "shutdown" },
{ SVM_EXIT_VMRUN, "vmrun" },
{ SVM_EXIT_VMMCALL, "hypercall" },
{ SVM_EXIT_VMLOAD, "vmload" },
{ SVM_EXIT_VMSAVE, "vmsave" },
{ SVM_EXIT_STGI, "stgi" },
{ SVM_EXIT_CLGI, "clgi" },
{ SVM_EXIT_SKINIT, "skinit" },
{ SVM_EXIT_WBINVD, "wbinvd" },
{ SVM_EXIT_MONITOR, "monitor" },
{ SVM_EXIT_MWAIT, "mwait" },
{ SVM_EXIT_XSETBV, "xsetbv" },
{ SVM_EXIT_NPF, "npf" },
{ -1, NULL }
};
static int svm_get_lpage_level(void)
{
return PT_PDPE_LEVEL;
}
static bool svm_rdtscp_supported(void)
{
return false;
}
static bool svm_has_wbinvd_exit(void)
{
return true;
}
static void svm_fpu_deactivate(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
set_exception_intercept(svm, NM_VECTOR);
update_cr0_intercept(svm);
}
#define PRE_EX(exit) { .exit_code = (exit), \
.stage = X86_ICPT_PRE_EXCEPT, }
#define POST_EX(exit) { .exit_code = (exit), \
.stage = X86_ICPT_POST_EXCEPT, }
#define POST_MEM(exit) { .exit_code = (exit), \
.stage = X86_ICPT_POST_MEMACCESS, }
static struct __x86_intercept {
u32 exit_code;
enum x86_intercept_stage stage;
} x86_intercept_map[] = {
[x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
[x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
[x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
[x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
[x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
[x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
[x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
[x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
[x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
[x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
[x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
[x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
[x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
[x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
[x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
[x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
[x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
[x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
[x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
[x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
[x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
[x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
[x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
[x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
[x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
[x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
[x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
[x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
[x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
[x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
[x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
[x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
[x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
[x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
[x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
[x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
[x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
[x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
[x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
[x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
[x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
[x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
[x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
[x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
[x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
[x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
};
#undef PRE_EX
#undef POST_EX
#undef POST_MEM
static int svm_check_intercept(struct kvm_vcpu *vcpu,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
struct vcpu_svm *svm = to_svm(vcpu);
int vmexit, ret = X86EMUL_CONTINUE;
struct __x86_intercept icpt_info;
struct vmcb *vmcb = svm->vmcb;
if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
goto out;
icpt_info = x86_intercept_map[info->intercept];
if (stage != icpt_info.stage)
goto out;
switch (icpt_info.exit_code) {
case SVM_EXIT_READ_CR0:
if (info->intercept == x86_intercept_cr_read)
icpt_info.exit_code += info->modrm_reg;
break;
case SVM_EXIT_WRITE_CR0: {
unsigned long cr0, val;
u64 intercept;
if (info->intercept == x86_intercept_cr_write)
icpt_info.exit_code += info->modrm_reg;
if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0)
break;
intercept = svm->nested.intercept;
if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
break;
cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
if (info->intercept == x86_intercept_lmsw) {
cr0 &= 0xfUL;
val &= 0xfUL;
/* lmsw can't clear PE - catch this here */
if (cr0 & X86_CR0_PE)
val |= X86_CR0_PE;
}
if (cr0 ^ val)
icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
break;
}
case SVM_EXIT_READ_DR0:
case SVM_EXIT_WRITE_DR0:
icpt_info.exit_code += info->modrm_reg;
break;
case SVM_EXIT_MSR:
if (info->intercept == x86_intercept_wrmsr)
vmcb->control.exit_info_1 = 1;
else
vmcb->control.exit_info_1 = 0;
break;
case SVM_EXIT_PAUSE:
/*
* We get this for NOP only, but pause
* is rep not, check this here
*/
if (info->rep_prefix != REPE_PREFIX)
goto out;
case SVM_EXIT_IOIO: {
u64 exit_info;
u32 bytes;
exit_info = (vcpu->arch.regs[VCPU_REGS_RDX] & 0xffff) << 16;
if (info->intercept == x86_intercept_in ||
info->intercept == x86_intercept_ins) {
exit_info |= SVM_IOIO_TYPE_MASK;
bytes = info->src_bytes;
} else {
bytes = info->dst_bytes;
}
if (info->intercept == x86_intercept_outs ||
info->intercept == x86_intercept_ins)
exit_info |= SVM_IOIO_STR_MASK;
if (info->rep_prefix)
exit_info |= SVM_IOIO_REP_MASK;
bytes = min(bytes, 4u);
exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
vmcb->control.exit_info_1 = exit_info;
vmcb->control.exit_info_2 = info->next_rip;
break;
}
default:
break;
}
vmcb->control.next_rip = info->next_rip;
vmcb->control.exit_code = icpt_info.exit_code;
vmexit = nested_svm_exit_handled(svm);
ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
: X86EMUL_CONTINUE;
out:
return ret;
}
static struct kvm_x86_ops svm_x86_ops = {
.cpu_has_kvm_support = has_svm,
.disabled_by_bios = is_disabled,
.hardware_setup = svm_hardware_setup,
.hardware_unsetup = svm_hardware_unsetup,
.check_processor_compatibility = svm_check_processor_compat,
.hardware_enable = svm_hardware_enable,
.hardware_disable = svm_hardware_disable,
.cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
.vcpu_create = svm_create_vcpu,
.vcpu_free = svm_free_vcpu,
.vcpu_reset = svm_vcpu_reset,
.prepare_guest_switch = svm_prepare_guest_switch,
.vcpu_load = svm_vcpu_load,
.vcpu_put = svm_vcpu_put,
.set_guest_debug = svm_guest_debug,
.get_msr = svm_get_msr,
.set_msr = svm_set_msr,
.get_segment_base = svm_get_segment_base,
.get_segment = svm_get_segment,
.set_segment = svm_set_segment,
.get_cpl = svm_get_cpl,
.get_cs_db_l_bits = kvm_get_cs_db_l_bits,
.decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
.decache_cr3 = svm_decache_cr3,
.decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
.set_cr0 = svm_set_cr0,
.set_cr3 = svm_set_cr3,
.set_cr4 = svm_set_cr4,
.set_efer = svm_set_efer,
.get_idt = svm_get_idt,
.set_idt = svm_set_idt,
.get_gdt = svm_get_gdt,
.set_gdt = svm_set_gdt,
.set_dr7 = svm_set_dr7,
.cache_reg = svm_cache_reg,
.get_rflags = svm_get_rflags,
.set_rflags = svm_set_rflags,
.fpu_activate = svm_fpu_activate,
.fpu_deactivate = svm_fpu_deactivate,
.tlb_flush = svm_flush_tlb,
.run = svm_vcpu_run,
.handle_exit = handle_exit,
.skip_emulated_instruction = skip_emulated_instruction,
.set_interrupt_shadow = svm_set_interrupt_shadow,
.get_interrupt_shadow = svm_get_interrupt_shadow,
.patch_hypercall = svm_patch_hypercall,
.set_irq = svm_set_irq,
.set_nmi = svm_inject_nmi,
.queue_exception = svm_queue_exception,
.cancel_injection = svm_cancel_injection,
.interrupt_allowed = svm_interrupt_allowed,
.nmi_allowed = svm_nmi_allowed,
.get_nmi_mask = svm_get_nmi_mask,
.set_nmi_mask = svm_set_nmi_mask,
.enable_nmi_window = enable_nmi_window,
.enable_irq_window = enable_irq_window,
.update_cr8_intercept = update_cr8_intercept,
.set_tss_addr = svm_set_tss_addr,
.get_tdp_level = get_npt_level,
.get_mt_mask = svm_get_mt_mask,
.get_exit_info = svm_get_exit_info,
.exit_reasons_str = svm_exit_reasons_str,
.get_lpage_level = svm_get_lpage_level,
.cpuid_update = svm_cpuid_update,
.rdtscp_supported = svm_rdtscp_supported,
.set_supported_cpuid = svm_set_supported_cpuid,
.has_wbinvd_exit = svm_has_wbinvd_exit,
.set_tsc_khz = svm_set_tsc_khz,
.write_tsc_offset = svm_write_tsc_offset,
.adjust_tsc_offset = svm_adjust_tsc_offset,
.compute_tsc_offset = svm_compute_tsc_offset,
.set_tdp_cr3 = set_tdp_cr3,
.check_intercept = svm_check_intercept,
};
static int __init svm_init(void)
{
return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
__alignof__(struct vcpu_svm), THIS_MODULE);
}
static void __exit svm_exit(void)
{
kvm_exit();
}
module_init(svm_init)
module_exit(svm_exit)
| gpl-2.0 |
jdkernel/android-omap-tuna_3.0 | arch/s390/lib/delay.c | 2582 | 3037 | /*
* Precise Delay Loops for S390
*
* Copyright IBM Corp. 1999,2008
* Author(s): Martin Schwidefsky <schwidefsky@de.ibm.com>,
* Heiko Carstens <heiko.carstens@de.ibm.com>,
*/
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/timex.h>
#include <linux/module.h>
#include <linux/irqflags.h>
#include <linux/interrupt.h>
#include <asm/div64.h>
void __delay(unsigned long loops)
{
/*
* To end the bloody studid and useless discussion about the
* BogoMips number I took the liberty to define the __delay
* function in a way that that resulting BogoMips number will
* yield the megahertz number of the cpu. The important function
* is udelay and that is done using the tod clock. -- martin.
*/
asm volatile("0: brct %0,0b" : : "d" ((loops/2) + 1));
}
static void __udelay_disabled(unsigned long long usecs)
{
unsigned long mask, cr0, cr0_saved;
u64 clock_saved;
u64 end;
mask = psw_kernel_bits | PSW_MASK_WAIT | PSW_MASK_EXT;
end = get_clock() + (usecs << 12);
clock_saved = local_tick_disable();
__ctl_store(cr0_saved, 0, 0);
cr0 = (cr0_saved & 0xffff00e0) | 0x00000800;
__ctl_load(cr0 , 0, 0);
lockdep_off();
do {
set_clock_comparator(end);
trace_hardirqs_on();
__load_psw_mask(mask);
local_irq_disable();
} while (get_clock() < end);
lockdep_on();
__ctl_load(cr0_saved, 0, 0);
local_tick_enable(clock_saved);
}
static void __udelay_enabled(unsigned long long usecs)
{
unsigned long mask;
u64 clock_saved;
u64 end;
mask = psw_kernel_bits | PSW_MASK_WAIT | PSW_MASK_EXT | PSW_MASK_IO;
end = get_clock() + (usecs << 12);
do {
clock_saved = 0;
if (end < S390_lowcore.clock_comparator) {
clock_saved = local_tick_disable();
set_clock_comparator(end);
}
trace_hardirqs_on();
__load_psw_mask(mask);
local_irq_disable();
if (clock_saved)
local_tick_enable(clock_saved);
} while (get_clock() < end);
}
/*
* Waits for 'usecs' microseconds using the TOD clock comparator.
*/
void __udelay(unsigned long long usecs)
{
unsigned long flags;
preempt_disable();
local_irq_save(flags);
if (in_irq()) {
__udelay_disabled(usecs);
goto out;
}
if (in_softirq()) {
if (raw_irqs_disabled_flags(flags))
__udelay_disabled(usecs);
else
__udelay_enabled(usecs);
goto out;
}
if (raw_irqs_disabled_flags(flags)) {
local_bh_disable();
__udelay_disabled(usecs);
_local_bh_enable();
goto out;
}
__udelay_enabled(usecs);
out:
local_irq_restore(flags);
preempt_enable();
}
EXPORT_SYMBOL(__udelay);
/*
* Simple udelay variant. To be used on startup and reboot
* when the interrupt handler isn't working.
*/
void udelay_simple(unsigned long long usecs)
{
u64 end;
end = get_clock() + (usecs << 12);
while (get_clock() < end)
cpu_relax();
}
void __ndelay(unsigned long long nsecs)
{
u64 end;
nsecs <<= 9;
do_div(nsecs, 125);
end = get_clock() + nsecs;
if (nsecs & ~0xfffUL)
__udelay(nsecs >> 12);
while (get_clock() < end)
barrier();
}
EXPORT_SYMBOL(__ndelay);
| gpl-2.0 |
Entropy512/I9300_N8013_Changes | arch/sparc/mm/hugetlbpage.c | 2838 | 8502 | /*
* SPARC64 Huge TLB page support.
*
* Copyright (C) 2002, 2003, 2006 David S. Miller (davem@davemloft.net)
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/pagemap.h>
#include <linux/sysctl.h>
#include <asm/mman.h>
#include <asm/pgalloc.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/cacheflush.h>
#include <asm/mmu_context.h>
/* Slightly simplified from the non-hugepage variant because by
* definition we don't have to worry about any page coloring stuff
*/
#define VA_EXCLUDE_START (0x0000080000000000UL - (1UL << 32UL))
#define VA_EXCLUDE_END (0xfffff80000000000UL + (1UL << 32UL))
static unsigned long hugetlb_get_unmapped_area_bottomup(struct file *filp,
unsigned long addr,
unsigned long len,
unsigned long pgoff,
unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct * vma;
unsigned long task_size = TASK_SIZE;
unsigned long start_addr;
if (test_thread_flag(TIF_32BIT))
task_size = STACK_TOP32;
if (unlikely(len >= VA_EXCLUDE_START))
return -ENOMEM;
if (len > mm->cached_hole_size) {
start_addr = addr = mm->free_area_cache;
} else {
start_addr = addr = TASK_UNMAPPED_BASE;
mm->cached_hole_size = 0;
}
task_size -= len;
full_search:
addr = ALIGN(addr, HPAGE_SIZE);
for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
/* At this point: (!vma || addr < vma->vm_end). */
if (addr < VA_EXCLUDE_START &&
(addr + len) >= VA_EXCLUDE_START) {
addr = VA_EXCLUDE_END;
vma = find_vma(mm, VA_EXCLUDE_END);
}
if (unlikely(task_size < addr)) {
if (start_addr != TASK_UNMAPPED_BASE) {
start_addr = addr = TASK_UNMAPPED_BASE;
mm->cached_hole_size = 0;
goto full_search;
}
return -ENOMEM;
}
if (likely(!vma || addr + len <= vma->vm_start)) {
/*
* Remember the place where we stopped the search:
*/
mm->free_area_cache = addr + len;
return addr;
}
if (addr + mm->cached_hole_size < vma->vm_start)
mm->cached_hole_size = vma->vm_start - addr;
addr = ALIGN(vma->vm_end, HPAGE_SIZE);
}
}
static unsigned long
hugetlb_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
const unsigned long len,
const unsigned long pgoff,
const unsigned long flags)
{
struct vm_area_struct *vma;
struct mm_struct *mm = current->mm;
unsigned long addr = addr0;
/* This should only ever run for 32-bit processes. */
BUG_ON(!test_thread_flag(TIF_32BIT));
/* check if free_area_cache is useful for us */
if (len <= mm->cached_hole_size) {
mm->cached_hole_size = 0;
mm->free_area_cache = mm->mmap_base;
}
/* either no address requested or can't fit in requested address hole */
addr = mm->free_area_cache & HPAGE_MASK;
/* make sure it can fit in the remaining address space */
if (likely(addr > len)) {
vma = find_vma(mm, addr-len);
if (!vma || addr <= vma->vm_start) {
/* remember the address as a hint for next time */
return (mm->free_area_cache = addr-len);
}
}
if (unlikely(mm->mmap_base < len))
goto bottomup;
addr = (mm->mmap_base-len) & HPAGE_MASK;
do {
/*
* Lookup failure means no vma is above this address,
* else if new region fits below vma->vm_start,
* return with success:
*/
vma = find_vma(mm, addr);
if (likely(!vma || addr+len <= vma->vm_start)) {
/* remember the address as a hint for next time */
return (mm->free_area_cache = addr);
}
/* remember the largest hole we saw so far */
if (addr + mm->cached_hole_size < vma->vm_start)
mm->cached_hole_size = vma->vm_start - addr;
/* try just below the current vma->vm_start */
addr = (vma->vm_start-len) & HPAGE_MASK;
} while (likely(len < vma->vm_start));
bottomup:
/*
* A failed mmap() very likely causes application failure,
* so fall back to the bottom-up function here. This scenario
* can happen with large stack limits and large mmap()
* allocations.
*/
mm->cached_hole_size = ~0UL;
mm->free_area_cache = TASK_UNMAPPED_BASE;
addr = arch_get_unmapped_area(filp, addr0, len, pgoff, flags);
/*
* Restore the topdown base:
*/
mm->free_area_cache = mm->mmap_base;
mm->cached_hole_size = ~0UL;
return addr;
}
unsigned long
hugetlb_get_unmapped_area(struct file *file, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long task_size = TASK_SIZE;
if (test_thread_flag(TIF_32BIT))
task_size = STACK_TOP32;
if (len & ~HPAGE_MASK)
return -EINVAL;
if (len > task_size)
return -ENOMEM;
if (flags & MAP_FIXED) {
if (prepare_hugepage_range(file, addr, len))
return -EINVAL;
return addr;
}
if (addr) {
addr = ALIGN(addr, HPAGE_SIZE);
vma = find_vma(mm, addr);
if (task_size - len >= addr &&
(!vma || addr + len <= vma->vm_start))
return addr;
}
if (mm->get_unmapped_area == arch_get_unmapped_area)
return hugetlb_get_unmapped_area_bottomup(file, addr, len,
pgoff, flags);
else
return hugetlb_get_unmapped_area_topdown(file, addr, len,
pgoff, flags);
}
pte_t *huge_pte_alloc(struct mm_struct *mm,
unsigned long addr, unsigned long sz)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte = NULL;
/* We must align the address, because our caller will run
* set_huge_pte_at() on whatever we return, which writes out
* all of the sub-ptes for the hugepage range. So we have
* to give it the first such sub-pte.
*/
addr &= HPAGE_MASK;
pgd = pgd_offset(mm, addr);
pud = pud_alloc(mm, pgd, addr);
if (pud) {
pmd = pmd_alloc(mm, pud, addr);
if (pmd)
pte = pte_alloc_map(mm, NULL, pmd, addr);
}
return pte;
}
pte_t *huge_pte_offset(struct mm_struct *mm, unsigned long addr)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte = NULL;
addr &= HPAGE_MASK;
pgd = pgd_offset(mm, addr);
if (!pgd_none(*pgd)) {
pud = pud_offset(pgd, addr);
if (!pud_none(*pud)) {
pmd = pmd_offset(pud, addr);
if (!pmd_none(*pmd))
pte = pte_offset_map(pmd, addr);
}
}
return pte;
}
int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
{
return 0;
}
void set_huge_pte_at(struct mm_struct *mm, unsigned long addr,
pte_t *ptep, pte_t entry)
{
int i;
if (!pte_present(*ptep) && pte_present(entry))
mm->context.huge_pte_count++;
addr &= HPAGE_MASK;
for (i = 0; i < (1 << HUGETLB_PAGE_ORDER); i++) {
set_pte_at(mm, addr, ptep, entry);
ptep++;
addr += PAGE_SIZE;
pte_val(entry) += PAGE_SIZE;
}
}
pte_t huge_ptep_get_and_clear(struct mm_struct *mm, unsigned long addr,
pte_t *ptep)
{
pte_t entry;
int i;
entry = *ptep;
if (pte_present(entry))
mm->context.huge_pte_count--;
addr &= HPAGE_MASK;
for (i = 0; i < (1 << HUGETLB_PAGE_ORDER); i++) {
pte_clear(mm, addr, ptep);
addr += PAGE_SIZE;
ptep++;
}
return entry;
}
struct page *follow_huge_addr(struct mm_struct *mm,
unsigned long address, int write)
{
return ERR_PTR(-EINVAL);
}
int pmd_huge(pmd_t pmd)
{
return 0;
}
int pud_huge(pud_t pud)
{
return 0;
}
struct page *follow_huge_pmd(struct mm_struct *mm, unsigned long address,
pmd_t *pmd, int write)
{
return NULL;
}
static void context_reload(void *__data)
{
struct mm_struct *mm = __data;
if (mm == current->mm)
load_secondary_context(mm);
}
void hugetlb_prefault_arch_hook(struct mm_struct *mm)
{
struct tsb_config *tp = &mm->context.tsb_block[MM_TSB_HUGE];
if (likely(tp->tsb != NULL))
return;
tsb_grow(mm, MM_TSB_HUGE, 0);
tsb_context_switch(mm);
smp_tsb_sync(mm);
/* On UltraSPARC-III+ and later, configure the second half of
* the Data-TLB for huge pages.
*/
if (tlb_type == cheetah_plus) {
unsigned long ctx;
spin_lock(&ctx_alloc_lock);
ctx = mm->context.sparc64_ctx_val;
ctx &= ~CTX_PGSZ_MASK;
ctx |= CTX_PGSZ_BASE << CTX_PGSZ0_SHIFT;
ctx |= CTX_PGSZ_HUGE << CTX_PGSZ1_SHIFT;
if (ctx != mm->context.sparc64_ctx_val) {
/* When changing the page size fields, we
* must perform a context flush so that no
* stale entries match. This flush must
* occur with the original context register
* settings.
*/
do_flush_tlb_mm(mm);
/* Reload the context register of all processors
* also executing in this address space.
*/
mm->context.sparc64_ctx_val = ctx;
on_each_cpu(context_reload, mm, 0);
}
spin_unlock(&ctx_alloc_lock);
}
}
| gpl-2.0 |
kylon/AndromadusMod-New | drivers/media/rc/keymaps/rc-winfast-usbii-deluxe.c | 3094 | 2157 | /* winfast-usbii-deluxe.h - Keytable for winfast_usbii_deluxe Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
/* Leadtek Winfast TV USB II Deluxe remote
Magnus Alm <magnus.alm@gmail.com>
*/
static struct rc_map_table winfast_usbii_deluxe[] = {
{ 0x62, KEY_0},
{ 0x75, KEY_1},
{ 0x76, KEY_2},
{ 0x77, KEY_3},
{ 0x79, KEY_4},
{ 0x7a, KEY_5},
{ 0x7b, KEY_6},
{ 0x7d, KEY_7},
{ 0x7e, KEY_8},
{ 0x7f, KEY_9},
{ 0x38, KEY_CAMERA}, /* SNAPSHOT */
{ 0x37, KEY_RECORD}, /* RECORD */
{ 0x35, KEY_TIME}, /* TIMESHIFT */
{ 0x74, KEY_VOLUMEUP}, /* VOLUMEUP */
{ 0x78, KEY_VOLUMEDOWN}, /* VOLUMEDOWN */
{ 0x64, KEY_MUTE}, /* MUTE */
{ 0x21, KEY_CHANNEL}, /* SURF */
{ 0x7c, KEY_CHANNELUP}, /* CHANNELUP */
{ 0x60, KEY_CHANNELDOWN}, /* CHANNELDOWN */
{ 0x61, KEY_LAST}, /* LAST CHANNEL (RECALL) */
{ 0x72, KEY_VIDEO}, /* INPUT MODES (TV/FM) */
{ 0x70, KEY_POWER2}, /* TV ON/OFF */
{ 0x39, KEY_CYCLEWINDOWS}, /* MINIMIZE (BOSS) */
{ 0x3a, KEY_NEW}, /* PIP */
{ 0x73, KEY_ZOOM}, /* FULLSECREEN */
{ 0x66, KEY_INFO}, /* OSD (DISPLAY) */
{ 0x31, KEY_DOT}, /* '.' */
{ 0x63, KEY_ENTER}, /* ENTER */
};
static struct rc_map_list winfast_usbii_deluxe_map = {
.map = {
.scan = winfast_usbii_deluxe,
.size = ARRAY_SIZE(winfast_usbii_deluxe),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_WINFAST_USBII_DELUXE,
}
};
static int __init init_rc_map_winfast_usbii_deluxe(void)
{
return rc_map_register(&winfast_usbii_deluxe_map);
}
static void __exit exit_rc_map_winfast_usbii_deluxe(void)
{
rc_map_unregister(&winfast_usbii_deluxe_map);
}
module_init(init_rc_map_winfast_usbii_deluxe)
module_exit(exit_rc_map_winfast_usbii_deluxe)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Split-Screen/android_kernel_motorola_msm8960-common | drivers/media/rc/keymaps/rc-evga-indtube.c | 3094 | 1531 | /* evga-indtube.h - Keytable for evga_indtube Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
/* EVGA inDtube
Devin Heitmueller <devin.heitmueller@gmail.com>
*/
static struct rc_map_table evga_indtube[] = {
{ 0x12, KEY_POWER},
{ 0x02, KEY_MODE}, /* TV */
{ 0x14, KEY_MUTE},
{ 0x1a, KEY_CHANNELUP},
{ 0x16, KEY_TV2}, /* PIP */
{ 0x1d, KEY_VOLUMEUP},
{ 0x05, KEY_CHANNELDOWN},
{ 0x0f, KEY_PLAYPAUSE},
{ 0x19, KEY_VOLUMEDOWN},
{ 0x1c, KEY_REWIND},
{ 0x0d, KEY_RECORD},
{ 0x18, KEY_FORWARD},
{ 0x1e, KEY_PREVIOUS},
{ 0x1b, KEY_STOP},
{ 0x1f, KEY_NEXT},
{ 0x13, KEY_CAMERA},
};
static struct rc_map_list evga_indtube_map = {
.map = {
.scan = evga_indtube,
.size = ARRAY_SIZE(evga_indtube),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_EVGA_INDTUBE,
}
};
static int __init init_rc_map_evga_indtube(void)
{
return rc_map_register(&evga_indtube_map);
}
static void __exit exit_rc_map_evga_indtube(void)
{
rc_map_unregister(&evga_indtube_map);
}
module_init(init_rc_map_evga_indtube)
module_exit(exit_rc_map_evga_indtube)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Entropy512/kernel_motorola_falcon_reference | arch/arm/mach-pxa/smemc.c | 5654 | 1273 | /*
* Static Memory Controller
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/syscore_ops.h>
#include <mach/hardware.h>
#include <mach/smemc.h>
#ifdef CONFIG_PM
static unsigned long msc[2];
static unsigned long sxcnfg, memclkcfg;
static unsigned long csadrcfg[4];
static int pxa3xx_smemc_suspend(void)
{
msc[0] = __raw_readl(MSC0);
msc[1] = __raw_readl(MSC1);
sxcnfg = __raw_readl(SXCNFG);
memclkcfg = __raw_readl(MEMCLKCFG);
csadrcfg[0] = __raw_readl(CSADRCFG0);
csadrcfg[1] = __raw_readl(CSADRCFG1);
csadrcfg[2] = __raw_readl(CSADRCFG2);
csadrcfg[3] = __raw_readl(CSADRCFG3);
return 0;
}
static void pxa3xx_smemc_resume(void)
{
__raw_writel(msc[0], MSC0);
__raw_writel(msc[1], MSC1);
__raw_writel(sxcnfg, SXCNFG);
__raw_writel(memclkcfg, MEMCLKCFG);
__raw_writel(csadrcfg[0], CSADRCFG0);
__raw_writel(csadrcfg[1], CSADRCFG1);
__raw_writel(csadrcfg[2], CSADRCFG2);
__raw_writel(csadrcfg[3], CSADRCFG3);
}
static struct syscore_ops smemc_syscore_ops = {
.suspend = pxa3xx_smemc_suspend,
.resume = pxa3xx_smemc_resume,
};
static int __init smemc_init(void)
{
if (cpu_is_pxa3xx())
register_syscore_ops(&smemc_syscore_ops);
return 0;
}
subsys_initcall(smemc_init);
#endif
| gpl-2.0 |
naufragoweb/android_kernel_samsung_kyleopen | arch/m68k/platform/528x/gpio.c | 7446 | 12775 | /*
* Coldfire generic GPIO support
*
* (C) Copyright 2009, Steven King <sfking@fdwdc.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/coldfire.h>
#include <asm/mcfsim.h>
#include <asm/mcfgpio.h>
static struct mcf_gpio_chip mcf_gpio_chips[] = {
{
.gpio_chip = {
.label = "NQ",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value,
.base = 1,
.ngpio = 7,
},
.pddr = (void __iomem *)MCFEPORT_EPDDR,
.podr = (void __iomem *)MCFEPORT_EPDR,
.ppdr = (void __iomem *)MCFEPORT_EPPDR,
},
{
.gpio_chip = {
.label = "TA",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 8,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFGPTA_GPTDDR,
.podr = (void __iomem *)MCFGPTA_GPTPORT,
.ppdr = (void __iomem *)MCFGPTB_GPTPORT,
},
{
.gpio_chip = {
.label = "TB",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 16,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFGPTB_GPTDDR,
.podr = (void __iomem *)MCFGPTB_GPTPORT,
.ppdr = (void __iomem *)MCFGPTB_GPTPORT,
},
{
.gpio_chip = {
.label = "QA",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 24,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFQADC_DDRQA,
.podr = (void __iomem *)MCFQADC_PORTQA,
.ppdr = (void __iomem *)MCFQADC_PORTQA,
},
{
.gpio_chip = {
.label = "QB",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 32,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFQADC_DDRQB,
.podr = (void __iomem *)MCFQADC_PORTQB,
.ppdr = (void __iomem *)MCFQADC_PORTQB,
},
{
.gpio_chip = {
.label = "A",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 40,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRA,
.podr = (void __iomem *)MCFGPIO_PORTA,
.ppdr = (void __iomem *)MCFGPIO_PORTAP,
.setr = (void __iomem *)MCFGPIO_SETA,
.clrr = (void __iomem *)MCFGPIO_CLRA,
},
{
.gpio_chip = {
.label = "B",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 48,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRB,
.podr = (void __iomem *)MCFGPIO_PORTB,
.ppdr = (void __iomem *)MCFGPIO_PORTBP,
.setr = (void __iomem *)MCFGPIO_SETB,
.clrr = (void __iomem *)MCFGPIO_CLRB,
},
{
.gpio_chip = {
.label = "C",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 56,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRC,
.podr = (void __iomem *)MCFGPIO_PORTC,
.ppdr = (void __iomem *)MCFGPIO_PORTCP,
.setr = (void __iomem *)MCFGPIO_SETC,
.clrr = (void __iomem *)MCFGPIO_CLRC,
},
{
.gpio_chip = {
.label = "D",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 64,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRD,
.podr = (void __iomem *)MCFGPIO_PORTD,
.ppdr = (void __iomem *)MCFGPIO_PORTDP,
.setr = (void __iomem *)MCFGPIO_SETD,
.clrr = (void __iomem *)MCFGPIO_CLRD,
},
{
.gpio_chip = {
.label = "E",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 72,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRE,
.podr = (void __iomem *)MCFGPIO_PORTE,
.ppdr = (void __iomem *)MCFGPIO_PORTEP,
.setr = (void __iomem *)MCFGPIO_SETE,
.clrr = (void __iomem *)MCFGPIO_CLRE,
},
{
.gpio_chip = {
.label = "F",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 80,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRF,
.podr = (void __iomem *)MCFGPIO_PORTF,
.ppdr = (void __iomem *)MCFGPIO_PORTFP,
.setr = (void __iomem *)MCFGPIO_SETF,
.clrr = (void __iomem *)MCFGPIO_CLRF,
},
{
.gpio_chip = {
.label = "G",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 88,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRG,
.podr = (void __iomem *)MCFGPIO_PORTG,
.ppdr = (void __iomem *)MCFGPIO_PORTGP,
.setr = (void __iomem *)MCFGPIO_SETG,
.clrr = (void __iomem *)MCFGPIO_CLRG,
},
{
.gpio_chip = {
.label = "H",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 96,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRH,
.podr = (void __iomem *)MCFGPIO_PORTH,
.ppdr = (void __iomem *)MCFGPIO_PORTHP,
.setr = (void __iomem *)MCFGPIO_SETH,
.clrr = (void __iomem *)MCFGPIO_CLRH,
},
{
.gpio_chip = {
.label = "J",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 104,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRJ,
.podr = (void __iomem *)MCFGPIO_PORTJ,
.ppdr = (void __iomem *)MCFGPIO_PORTJP,
.setr = (void __iomem *)MCFGPIO_SETJ,
.clrr = (void __iomem *)MCFGPIO_CLRJ,
},
{
.gpio_chip = {
.label = "DD",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 112,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDRDD,
.podr = (void __iomem *)MCFGPIO_PORTDD,
.ppdr = (void __iomem *)MCFGPIO_PORTDDP,
.setr = (void __iomem *)MCFGPIO_SETDD,
.clrr = (void __iomem *)MCFGPIO_CLRDD,
},
{
.gpio_chip = {
.label = "EH",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 120,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDREH,
.podr = (void __iomem *)MCFGPIO_PORTEH,
.ppdr = (void __iomem *)MCFGPIO_PORTEHP,
.setr = (void __iomem *)MCFGPIO_SETEH,
.clrr = (void __iomem *)MCFGPIO_CLREH,
},
{
.gpio_chip = {
.label = "EL",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 128,
.ngpio = 8,
},
.pddr = (void __iomem *)MCFGPIO_DDREL,
.podr = (void __iomem *)MCFGPIO_PORTEL,
.ppdr = (void __iomem *)MCFGPIO_PORTELP,
.setr = (void __iomem *)MCFGPIO_SETEL,
.clrr = (void __iomem *)MCFGPIO_CLREL,
},
{
.gpio_chip = {
.label = "AS",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 136,
.ngpio = 6,
},
.pddr = (void __iomem *)MCFGPIO_DDRAS,
.podr = (void __iomem *)MCFGPIO_PORTAS,
.ppdr = (void __iomem *)MCFGPIO_PORTASP,
.setr = (void __iomem *)MCFGPIO_SETAS,
.clrr = (void __iomem *)MCFGPIO_CLRAS,
},
{
.gpio_chip = {
.label = "QS",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 144,
.ngpio = 7,
},
.pddr = (void __iomem *)MCFGPIO_DDRQS,
.podr = (void __iomem *)MCFGPIO_PORTQS,
.ppdr = (void __iomem *)MCFGPIO_PORTQSP,
.setr = (void __iomem *)MCFGPIO_SETQS,
.clrr = (void __iomem *)MCFGPIO_CLRQS,
},
{
.gpio_chip = {
.label = "SD",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 152,
.ngpio = 6,
},
.pddr = (void __iomem *)MCFGPIO_DDRSD,
.podr = (void __iomem *)MCFGPIO_PORTSD,
.ppdr = (void __iomem *)MCFGPIO_PORTSDP,
.setr = (void __iomem *)MCFGPIO_SETSD,
.clrr = (void __iomem *)MCFGPIO_CLRSD,
},
{
.gpio_chip = {
.label = "TC",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 160,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFGPIO_DDRTC,
.podr = (void __iomem *)MCFGPIO_PORTTC,
.ppdr = (void __iomem *)MCFGPIO_PORTTCP,
.setr = (void __iomem *)MCFGPIO_SETTC,
.clrr = (void __iomem *)MCFGPIO_CLRTC,
},
{
.gpio_chip = {
.label = "TD",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 168,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFGPIO_DDRTD,
.podr = (void __iomem *)MCFGPIO_PORTTD,
.ppdr = (void __iomem *)MCFGPIO_PORTTDP,
.setr = (void __iomem *)MCFGPIO_SETTD,
.clrr = (void __iomem *)MCFGPIO_CLRTD,
},
{
.gpio_chip = {
.label = "UA",
.request = mcf_gpio_request,
.free = mcf_gpio_free,
.direction_input = mcf_gpio_direction_input,
.direction_output = mcf_gpio_direction_output,
.get = mcf_gpio_get_value,
.set = mcf_gpio_set_value_fast,
.base = 176,
.ngpio = 4,
},
.pddr = (void __iomem *)MCFGPIO_DDRUA,
.podr = (void __iomem *)MCFGPIO_PORTUA,
.ppdr = (void __iomem *)MCFGPIO_PORTUAP,
.setr = (void __iomem *)MCFGPIO_SETUA,
.clrr = (void __iomem *)MCFGPIO_CLRUA,
},
};
static int __init mcf_gpio_init(void)
{
unsigned i = 0;
while (i < ARRAY_SIZE(mcf_gpio_chips))
(void)gpiochip_add((struct gpio_chip *)&mcf_gpio_chips[i++]);
return 0;
}
core_initcall(mcf_gpio_init);
| gpl-2.0 |
MasterPlexus/kernel_i8200 | fs/afs/cmservice.c | 11030 | 13555 | /* AFS Cache Manager Service
*
* Copyright (C) 2002 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/slab.h>
#include <linux/sched.h>
#include <linux/ip.h>
#include "internal.h"
#include "afs_cm.h"
#if 0
struct workqueue_struct *afs_cm_workqueue;
#endif /* 0 */
static int afs_deliver_cb_init_call_back_state(struct afs_call *,
struct sk_buff *, bool);
static int afs_deliver_cb_init_call_back_state3(struct afs_call *,
struct sk_buff *, bool);
static int afs_deliver_cb_probe(struct afs_call *, struct sk_buff *, bool);
static int afs_deliver_cb_callback(struct afs_call *, struct sk_buff *, bool);
static int afs_deliver_cb_probe_uuid(struct afs_call *, struct sk_buff *, bool);
static int afs_deliver_cb_tell_me_about_yourself(struct afs_call *,
struct sk_buff *, bool);
static void afs_cm_destructor(struct afs_call *);
/*
* CB.CallBack operation type
*/
static const struct afs_call_type afs_SRXCBCallBack = {
.name = "CB.CallBack",
.deliver = afs_deliver_cb_callback,
.abort_to_error = afs_abort_to_error,
.destructor = afs_cm_destructor,
};
/*
* CB.InitCallBackState operation type
*/
static const struct afs_call_type afs_SRXCBInitCallBackState = {
.name = "CB.InitCallBackState",
.deliver = afs_deliver_cb_init_call_back_state,
.abort_to_error = afs_abort_to_error,
.destructor = afs_cm_destructor,
};
/*
* CB.InitCallBackState3 operation type
*/
static const struct afs_call_type afs_SRXCBInitCallBackState3 = {
.name = "CB.InitCallBackState3",
.deliver = afs_deliver_cb_init_call_back_state3,
.abort_to_error = afs_abort_to_error,
.destructor = afs_cm_destructor,
};
/*
* CB.Probe operation type
*/
static const struct afs_call_type afs_SRXCBProbe = {
.name = "CB.Probe",
.deliver = afs_deliver_cb_probe,
.abort_to_error = afs_abort_to_error,
.destructor = afs_cm_destructor,
};
/*
* CB.ProbeUuid operation type
*/
static const struct afs_call_type afs_SRXCBProbeUuid = {
.name = "CB.ProbeUuid",
.deliver = afs_deliver_cb_probe_uuid,
.abort_to_error = afs_abort_to_error,
.destructor = afs_cm_destructor,
};
/*
* CB.TellMeAboutYourself operation type
*/
static const struct afs_call_type afs_SRXCBTellMeAboutYourself = {
.name = "CB.TellMeAboutYourself",
.deliver = afs_deliver_cb_tell_me_about_yourself,
.abort_to_error = afs_abort_to_error,
.destructor = afs_cm_destructor,
};
/*
* route an incoming cache manager call
* - return T if supported, F if not
*/
bool afs_cm_incoming_call(struct afs_call *call)
{
u32 operation_id = ntohl(call->operation_ID);
_enter("{CB.OP %u}", operation_id);
switch (operation_id) {
case CBCallBack:
call->type = &afs_SRXCBCallBack;
return true;
case CBInitCallBackState:
call->type = &afs_SRXCBInitCallBackState;
return true;
case CBInitCallBackState3:
call->type = &afs_SRXCBInitCallBackState3;
return true;
case CBProbe:
call->type = &afs_SRXCBProbe;
return true;
case CBTellMeAboutYourself:
call->type = &afs_SRXCBTellMeAboutYourself;
return true;
default:
return false;
}
}
/*
* clean up a cache manager call
*/
static void afs_cm_destructor(struct afs_call *call)
{
_enter("");
afs_put_server(call->server);
call->server = NULL;
kfree(call->buffer);
call->buffer = NULL;
}
/*
* allow the fileserver to see if the cache manager is still alive
*/
static void SRXAFSCB_CallBack(struct work_struct *work)
{
struct afs_call *call = container_of(work, struct afs_call, work);
_enter("");
/* be sure to send the reply *before* attempting to spam the AFS server
* with FSFetchStatus requests on the vnodes with broken callbacks lest
* the AFS server get into a vicious cycle of trying to break further
* callbacks because it hadn't received completion of the CBCallBack op
* yet */
afs_send_empty_reply(call);
afs_break_callbacks(call->server, call->count, call->request);
_leave("");
}
/*
* deliver request data to a CB.CallBack call
*/
static int afs_deliver_cb_callback(struct afs_call *call, struct sk_buff *skb,
bool last)
{
struct afs_callback *cb;
struct afs_server *server;
struct in_addr addr;
__be32 *bp;
u32 tmp;
int ret, loop;
_enter("{%u},{%u},%d", call->unmarshall, skb->len, last);
switch (call->unmarshall) {
case 0:
call->offset = 0;
call->unmarshall++;
/* extract the FID array and its count in two steps */
case 1:
_debug("extract FID count");
ret = afs_extract_data(call, skb, last, &call->tmp, 4);
switch (ret) {
case 0: break;
case -EAGAIN: return 0;
default: return ret;
}
call->count = ntohl(call->tmp);
_debug("FID count: %u", call->count);
if (call->count > AFSCBMAX)
return -EBADMSG;
call->buffer = kmalloc(call->count * 3 * 4, GFP_KERNEL);
if (!call->buffer)
return -ENOMEM;
call->offset = 0;
call->unmarshall++;
case 2:
_debug("extract FID array");
ret = afs_extract_data(call, skb, last, call->buffer,
call->count * 3 * 4);
switch (ret) {
case 0: break;
case -EAGAIN: return 0;
default: return ret;
}
_debug("unmarshall FID array");
call->request = kcalloc(call->count,
sizeof(struct afs_callback),
GFP_KERNEL);
if (!call->request)
return -ENOMEM;
cb = call->request;
bp = call->buffer;
for (loop = call->count; loop > 0; loop--, cb++) {
cb->fid.vid = ntohl(*bp++);
cb->fid.vnode = ntohl(*bp++);
cb->fid.unique = ntohl(*bp++);
cb->type = AFSCM_CB_UNTYPED;
}
call->offset = 0;
call->unmarshall++;
/* extract the callback array and its count in two steps */
case 3:
_debug("extract CB count");
ret = afs_extract_data(call, skb, last, &call->tmp, 4);
switch (ret) {
case 0: break;
case -EAGAIN: return 0;
default: return ret;
}
tmp = ntohl(call->tmp);
_debug("CB count: %u", tmp);
if (tmp != call->count && tmp != 0)
return -EBADMSG;
call->offset = 0;
call->unmarshall++;
if (tmp == 0)
goto empty_cb_array;
case 4:
_debug("extract CB array");
ret = afs_extract_data(call, skb, last, call->request,
call->count * 3 * 4);
switch (ret) {
case 0: break;
case -EAGAIN: return 0;
default: return ret;
}
_debug("unmarshall CB array");
cb = call->request;
bp = call->buffer;
for (loop = call->count; loop > 0; loop--, cb++) {
cb->version = ntohl(*bp++);
cb->expiry = ntohl(*bp++);
cb->type = ntohl(*bp++);
}
empty_cb_array:
call->offset = 0;
call->unmarshall++;
case 5:
_debug("trailer");
if (skb->len != 0)
return -EBADMSG;
break;
}
if (!last)
return 0;
call->state = AFS_CALL_REPLYING;
/* we'll need the file server record as that tells us which set of
* vnodes to operate upon */
memcpy(&addr, &ip_hdr(skb)->saddr, 4);
server = afs_find_server(&addr);
if (!server)
return -ENOTCONN;
call->server = server;
INIT_WORK(&call->work, SRXAFSCB_CallBack);
queue_work(afs_wq, &call->work);
return 0;
}
/*
* allow the fileserver to request callback state (re-)initialisation
*/
static void SRXAFSCB_InitCallBackState(struct work_struct *work)
{
struct afs_call *call = container_of(work, struct afs_call, work);
_enter("{%p}", call->server);
afs_init_callback_state(call->server);
afs_send_empty_reply(call);
_leave("");
}
/*
* deliver request data to a CB.InitCallBackState call
*/
static int afs_deliver_cb_init_call_back_state(struct afs_call *call,
struct sk_buff *skb,
bool last)
{
struct afs_server *server;
struct in_addr addr;
_enter(",{%u},%d", skb->len, last);
if (skb->len > 0)
return -EBADMSG;
if (!last)
return 0;
/* no unmarshalling required */
call->state = AFS_CALL_REPLYING;
/* we'll need the file server record as that tells us which set of
* vnodes to operate upon */
memcpy(&addr, &ip_hdr(skb)->saddr, 4);
server = afs_find_server(&addr);
if (!server)
return -ENOTCONN;
call->server = server;
INIT_WORK(&call->work, SRXAFSCB_InitCallBackState);
queue_work(afs_wq, &call->work);
return 0;
}
/*
* deliver request data to a CB.InitCallBackState3 call
*/
static int afs_deliver_cb_init_call_back_state3(struct afs_call *call,
struct sk_buff *skb,
bool last)
{
struct afs_server *server;
struct in_addr addr;
_enter(",{%u},%d", skb->len, last);
if (!last)
return 0;
/* no unmarshalling required */
call->state = AFS_CALL_REPLYING;
/* we'll need the file server record as that tells us which set of
* vnodes to operate upon */
memcpy(&addr, &ip_hdr(skb)->saddr, 4);
server = afs_find_server(&addr);
if (!server)
return -ENOTCONN;
call->server = server;
INIT_WORK(&call->work, SRXAFSCB_InitCallBackState);
queue_work(afs_wq, &call->work);
return 0;
}
/*
* allow the fileserver to see if the cache manager is still alive
*/
static void SRXAFSCB_Probe(struct work_struct *work)
{
struct afs_call *call = container_of(work, struct afs_call, work);
_enter("");
afs_send_empty_reply(call);
_leave("");
}
/*
* deliver request data to a CB.Probe call
*/
static int afs_deliver_cb_probe(struct afs_call *call, struct sk_buff *skb,
bool last)
{
_enter(",{%u},%d", skb->len, last);
if (skb->len > 0)
return -EBADMSG;
if (!last)
return 0;
/* no unmarshalling required */
call->state = AFS_CALL_REPLYING;
INIT_WORK(&call->work, SRXAFSCB_Probe);
queue_work(afs_wq, &call->work);
return 0;
}
/*
* allow the fileserver to quickly find out if the fileserver has been rebooted
*/
static void SRXAFSCB_ProbeUuid(struct work_struct *work)
{
struct afs_call *call = container_of(work, struct afs_call, work);
struct afs_uuid *r = call->request;
struct {
__be32 match;
} reply;
_enter("");
if (memcmp(r, &afs_uuid, sizeof(afs_uuid)) == 0)
reply.match = htonl(0);
else
reply.match = htonl(1);
afs_send_simple_reply(call, &reply, sizeof(reply));
_leave("");
}
/*
* deliver request data to a CB.ProbeUuid call
*/
static int afs_deliver_cb_probe_uuid(struct afs_call *call, struct sk_buff *skb,
bool last)
{
struct afs_uuid *r;
unsigned loop;
__be32 *b;
int ret;
_enter("{%u},{%u},%d", call->unmarshall, skb->len, last);
if (skb->len > 0)
return -EBADMSG;
if (!last)
return 0;
switch (call->unmarshall) {
case 0:
call->offset = 0;
call->buffer = kmalloc(11 * sizeof(__be32), GFP_KERNEL);
if (!call->buffer)
return -ENOMEM;
call->unmarshall++;
case 1:
_debug("extract UUID");
ret = afs_extract_data(call, skb, last, call->buffer,
11 * sizeof(__be32));
switch (ret) {
case 0: break;
case -EAGAIN: return 0;
default: return ret;
}
_debug("unmarshall UUID");
call->request = kmalloc(sizeof(struct afs_uuid), GFP_KERNEL);
if (!call->request)
return -ENOMEM;
b = call->buffer;
r = call->request;
r->time_low = ntohl(b[0]);
r->time_mid = ntohl(b[1]);
r->time_hi_and_version = ntohl(b[2]);
r->clock_seq_hi_and_reserved = ntohl(b[3]);
r->clock_seq_low = ntohl(b[4]);
for (loop = 0; loop < 6; loop++)
r->node[loop] = ntohl(b[loop + 5]);
call->offset = 0;
call->unmarshall++;
case 2:
_debug("trailer");
if (skb->len != 0)
return -EBADMSG;
break;
}
if (!last)
return 0;
call->state = AFS_CALL_REPLYING;
INIT_WORK(&call->work, SRXAFSCB_ProbeUuid);
queue_work(afs_wq, &call->work);
return 0;
}
/*
* allow the fileserver to ask about the cache manager's capabilities
*/
static void SRXAFSCB_TellMeAboutYourself(struct work_struct *work)
{
struct afs_interface *ifs;
struct afs_call *call = container_of(work, struct afs_call, work);
int loop, nifs;
struct {
struct /* InterfaceAddr */ {
__be32 nifs;
__be32 uuid[11];
__be32 ifaddr[32];
__be32 netmask[32];
__be32 mtu[32];
} ia;
struct /* Capabilities */ {
__be32 capcount;
__be32 caps[1];
} cap;
} reply;
_enter("");
nifs = 0;
ifs = kcalloc(32, sizeof(*ifs), GFP_KERNEL);
if (ifs) {
nifs = afs_get_ipv4_interfaces(ifs, 32, false);
if (nifs < 0) {
kfree(ifs);
ifs = NULL;
nifs = 0;
}
}
memset(&reply, 0, sizeof(reply));
reply.ia.nifs = htonl(nifs);
reply.ia.uuid[0] = htonl(afs_uuid.time_low);
reply.ia.uuid[1] = htonl(afs_uuid.time_mid);
reply.ia.uuid[2] = htonl(afs_uuid.time_hi_and_version);
reply.ia.uuid[3] = htonl((s8) afs_uuid.clock_seq_hi_and_reserved);
reply.ia.uuid[4] = htonl((s8) afs_uuid.clock_seq_low);
for (loop = 0; loop < 6; loop++)
reply.ia.uuid[loop + 5] = htonl((s8) afs_uuid.node[loop]);
if (ifs) {
for (loop = 0; loop < nifs; loop++) {
reply.ia.ifaddr[loop] = ifs[loop].address.s_addr;
reply.ia.netmask[loop] = ifs[loop].netmask.s_addr;
reply.ia.mtu[loop] = htonl(ifs[loop].mtu);
}
kfree(ifs);
}
reply.cap.capcount = htonl(1);
reply.cap.caps[0] = htonl(AFS_CAP_ERROR_TRANSLATION);
afs_send_simple_reply(call, &reply, sizeof(reply));
_leave("");
}
/*
* deliver request data to a CB.TellMeAboutYourself call
*/
static int afs_deliver_cb_tell_me_about_yourself(struct afs_call *call,
struct sk_buff *skb, bool last)
{
_enter(",{%u},%d", skb->len, last);
if (skb->len > 0)
return -EBADMSG;
if (!last)
return 0;
/* no unmarshalling required */
call->state = AFS_CALL_REPLYING;
INIT_WORK(&call->work, SRXAFSCB_TellMeAboutYourself);
queue_work(afs_wq, &call->work);
return 0;
}
| gpl-2.0 |
TroNit/BlackDome_New_supersonic | fs/nls/nls_cp866.c | 12566 | 12666 | /*
* linux/fs/nls/nls_cp866.c
*
* Charset cp866 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x0410, 0x0411, 0x0412, 0x0413,
0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041a, 0x041b,
0x041c, 0x041d, 0x041e, 0x041f,
/* 0x90*/
0x0420, 0x0421, 0x0422, 0x0423,
0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b,
0x042c, 0x042d, 0x042e, 0x042f,
/* 0xa0*/
0x0430, 0x0431, 0x0432, 0x0433,
0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0439, 0x043a, 0x043b,
0x043c, 0x043d, 0x043e, 0x043f,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557,
0x255d, 0x255c, 0x255b, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x2567,
/* 0xd0*/
0x2568, 0x2564, 0x2565, 0x2559,
0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588,
0x2584, 0x258c, 0x2590, 0x2580,
/* 0xe0*/
0x0440, 0x0441, 0x0442, 0x0443,
0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b,
0x044c, 0x044d, 0x044e, 0x044f,
/* 0xf0*/
0x0401, 0x0451, 0x0404, 0x0454,
0x0407, 0x0457, 0x040e, 0x045e,
0x00b0, 0x2219, 0x00b7, 0x221a,
0x2116, 0x00a4, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfa, /* 0xb0-0xb7 */
};
static const unsigned char page04[256] = {
0x00, 0xf0, 0x00, 0x00, 0xf2, 0x00, 0x00, 0xf4, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0x00, /* 0x08-0x0f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x10-0x17 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x18-0x1f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x20-0x27 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x28-0x2f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0x30-0x37 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0x38-0x3f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x40-0x47 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x48-0x4f */
0x00, 0xf1, 0x00, 0x00, 0xf3, 0x00, 0x00, 0xf5, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf7, 0x00, /* 0x58-0x5f */
};
static const unsigned char page21[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, /* 0x10-0x17 */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */
0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */
0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */
0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, NULL, NULL, NULL, page04, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, page21, page22, NULL, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0x80-0x87 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0x88-0x8f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x90-0x97 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf1, 0xf1, 0xf3, 0xf3, 0xf5, 0xf5, 0xf7, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0xa0-0xa7 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0xe0-0xe7 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0xe8-0xef */
0xf0, 0xf0, 0xf2, 0xf2, 0xf4, 0xf4, 0xf6, 0xf6, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp866",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp866(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp866(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp866)
module_exit(exit_nls_cp866)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
carvsdriver/msm8660-common_marla | fs/nls/nls_cp865.c | 12566 | 17508 | /*
* linux/fs/nls/nls_cp865.c
*
* Charset cp865 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x00c7, 0x00fc, 0x00e9, 0x00e2,
0x00e4, 0x00e0, 0x00e5, 0x00e7,
0x00ea, 0x00eb, 0x00e8, 0x00ef,
0x00ee, 0x00ec, 0x00c4, 0x00c5,
/* 0x90*/
0x00c9, 0x00e6, 0x00c6, 0x00f4,
0x00f6, 0x00f2, 0x00fb, 0x00f9,
0x00ff, 0x00d6, 0x00dc, 0x00f8,
0x00a3, 0x00d8, 0x20a7, 0x0192,
/* 0xa0*/
0x00e1, 0x00ed, 0x00f3, 0x00fa,
0x00f1, 0x00d1, 0x00aa, 0x00ba,
0x00bf, 0x2310, 0x00ac, 0x00bd,
0x00bc, 0x00a1, 0x00ab, 0x00a4,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557,
0x255d, 0x255c, 0x255b, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x2567,
/* 0xd0*/
0x2568, 0x2564, 0x2565, 0x2559,
0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588,
0x2584, 0x258c, 0x2590, 0x2580,
/* 0xe0*/
0x03b1, 0x00df, 0x0393, 0x03c0,
0x03a3, 0x03c3, 0x00b5, 0x03c4,
0x03a6, 0x0398, 0x03a9, 0x03b4,
0x221e, 0x03c6, 0x03b5, 0x2229,
/* 0xf0*/
0x2261, 0x00b1, 0x2265, 0x2264,
0x2320, 0x2321, 0x00f7, 0x2248,
0x00b0, 0x2219, 0x00b7, 0x221a,
0x207f, 0x00b2, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0xad, 0x00, 0x9c, 0xaf, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0xa6, 0xae, 0xaa, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0xf8, 0xf1, 0xfd, 0x00, 0x00, 0xe6, 0x00, 0xfa, /* 0xb0-0xb7 */
0x00, 0x00, 0xa7, 0x00, 0xac, 0xab, 0x00, 0xa8, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x8e, 0x8f, 0x92, 0x80, /* 0xc0-0xc7 */
0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0xa5, 0x00, 0x00, 0x00, 0x00, 0x99, 0x00, /* 0xd0-0xd7 */
0x9d, 0x00, 0x00, 0x00, 0x9a, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */
0x85, 0xa0, 0x83, 0x00, 0x84, 0x86, 0x91, 0x87, /* 0xe0-0xe7 */
0x8a, 0x82, 0x88, 0x89, 0x8d, 0xa1, 0x8c, 0x8b, /* 0xe8-0xef */
0x00, 0xa4, 0x95, 0xa2, 0x93, 0x00, 0x94, 0xf6, /* 0xf0-0xf7 */
0x9b, 0x97, 0xa3, 0x96, 0x81, 0x00, 0x00, 0x98, /* 0xf8-0xff */
};
static const unsigned char page01[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
};
static const unsigned char page03[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0xe9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0xe8, 0x00, /* 0xa0-0xa7 */
0x00, 0xea, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0xe0, 0x00, 0x00, 0xeb, 0xee, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0xe3, 0x00, 0x00, 0xe5, 0xe7, 0x00, 0xed, 0x00, /* 0xc0-0xc7 */
};
static const unsigned char page20[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9e, /* 0xa0-0xa7 */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0xec, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0xf0, 0x00, 0x00, 0xf3, 0xf2, 0x00, 0x00, /* 0x60-0x67 */
};
static const unsigned char page23[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0xf4, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */
0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */
0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */
0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, page01, NULL, page03, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
page20, NULL, page22, page23, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x84, 0x86, /* 0x88-0x8f */
0x82, 0x91, 0x91, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x94, 0x81, 0x9b, 0x9c, 0x9b, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa4, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0x00, 0xe3, 0xe5, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xed, 0x00, 0x00, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x9a, 0x90, 0x00, 0x8e, 0x00, 0x8f, 0x80, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x92, 0x92, 0x00, 0x99, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x99, 0x9a, 0x9d, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0xa5, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0x00, 0xe1, 0xe2, 0x00, 0xe4, 0xe4, 0x00, 0x00, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0x00, 0xec, 0xe8, 0x00, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp865",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp865(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp865(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp865)
module_exit(exit_nls_cp865)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
TeamOrion-Devices/Orion_kernel_motorola_msm8226 | fs/nls/nls_cp863.c | 12566 | 17182 | /*
* linux/fs/nls/nls_cp863.c
*
* Charset cp863 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x00c7, 0x00fc, 0x00e9, 0x00e2,
0x00c2, 0x00e0, 0x00b6, 0x00e7,
0x00ea, 0x00eb, 0x00e8, 0x00ef,
0x00ee, 0x2017, 0x00c0, 0x00a7,
/* 0x90*/
0x00c9, 0x00c8, 0x00ca, 0x00f4,
0x00cb, 0x00cf, 0x00fb, 0x00f9,
0x00a4, 0x00d4, 0x00dc, 0x00a2,
0x00a3, 0x00d9, 0x00db, 0x0192,
/* 0xa0*/
0x00a6, 0x00b4, 0x00f3, 0x00fa,
0x00a8, 0x00b8, 0x00b3, 0x00af,
0x00ce, 0x2310, 0x00ac, 0x00bd,
0x00bc, 0x00be, 0x00ab, 0x00bb,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557,
0x255d, 0x255c, 0x255b, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x2567,
/* 0xd0*/
0x2568, 0x2564, 0x2565, 0x2559,
0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588,
0x2584, 0x258c, 0x2590, 0x2580,
/* 0xe0*/
0x03b1, 0x00df, 0x0393, 0x03c0,
0x03a3, 0x03c3, 0x00b5, 0x03c4,
0x03a6, 0x0398, 0x03a9, 0x03b4,
0x221e, 0x03c6, 0x03b5, 0x2229,
/* 0xf0*/
0x2261, 0x00b1, 0x2265, 0x2264,
0x2320, 0x2321, 0x00f7, 0x2248,
0x00b0, 0x2219, 0x00b7, 0x221a,
0x207f, 0x00b2, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0x00, 0x9b, 0x9c, 0x98, 0x00, 0xa0, 0x8f, /* 0xa0-0xa7 */
0xa4, 0x00, 0x00, 0xae, 0xaa, 0x00, 0x00, 0xa7, /* 0xa8-0xaf */
0xf8, 0xf1, 0xfd, 0xa6, 0xa1, 0xe6, 0x86, 0xfa, /* 0xb0-0xb7 */
0xa5, 0x00, 0x00, 0xaf, 0xac, 0xab, 0xad, 0x00, /* 0xb8-0xbf */
0x8e, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x80, /* 0xc0-0xc7 */
0x91, 0x90, 0x92, 0x94, 0x00, 0x00, 0xa8, 0x95, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x9d, 0x00, 0x9e, 0x9a, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */
0x85, 0x00, 0x83, 0x00, 0x00, 0x00, 0x00, 0x87, /* 0xe0-0xe7 */
0x8a, 0x82, 0x88, 0x89, 0x00, 0x00, 0x8c, 0x8b, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0xa2, 0x93, 0x00, 0x00, 0xf6, /* 0xf0-0xf7 */
0x00, 0x97, 0xa3, 0x96, 0x81, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page01[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
};
static const unsigned char page03[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0xe9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0xe8, 0x00, /* 0xa0-0xa7 */
0x00, 0xea, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0xe0, 0x00, 0x00, 0xeb, 0xee, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0xe3, 0x00, 0x00, 0xe5, 0xe7, 0x00, 0xed, 0x00, /* 0xc0-0xc7 */
};
static const unsigned char page20[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8d, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, /* 0x78-0x7f */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0xec, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0xf0, 0x00, 0x00, 0xf3, 0xf2, 0x00, 0x00, /* 0x60-0x67 */
};
static const unsigned char page23[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0xf4, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */
0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */
0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */
0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, page01, NULL, page03, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
page20, NULL, page22, page23, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x87, 0x81, 0x82, 0x83, 0x83, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x85, 0x8f, /* 0x88-0x8f */
0x82, 0x8a, 0x88, 0x93, 0x89, 0x8b, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x93, 0x81, 0x9b, 0x9c, 0x97, 0x96, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0x8c, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0x00, 0xe3, 0xe5, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xed, 0x00, 0x00, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x9a, 0x90, 0x84, 0x84, 0x8e, 0x86, 0x80, /* 0x80-0x87 */
0x92, 0x94, 0x91, 0x95, 0xa8, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x99, 0x94, 0x95, 0x9e, 0x9d, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */
0xa0, 0xa1, 0x00, 0x00, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0x00, 0xe1, 0xe2, 0x00, 0xe4, 0xe4, 0x00, 0x00, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0x00, 0xec, 0xe8, 0x00, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp863",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp863(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp863(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp863)
module_exit(exit_nls_cp863)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
Tim1928/DBK-3.0-4.2 | fs/nls/nls_cp862.c | 12566 | 19506 | /*
* linux/fs/nls/nls_cp862.c
*
* Charset cp862 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x05d0, 0x05d1, 0x05d2, 0x05d3,
0x05d4, 0x05d5, 0x05d6, 0x05d7,
0x05d8, 0x05d9, 0x05da, 0x05db,
0x05dc, 0x05dd, 0x05de, 0x05df,
/* 0x90*/
0x05e0, 0x05e1, 0x05e2, 0x05e3,
0x05e4, 0x05e5, 0x05e6, 0x05e7,
0x05e8, 0x05e9, 0x05ea, 0x00a2,
0x00a3, 0x00a5, 0x20a7, 0x0192,
/* 0xa0*/
0x00e1, 0x00ed, 0x00f3, 0x00fa,
0x00f1, 0x00d1, 0x00aa, 0x00ba,
0x00bf, 0x2310, 0x00ac, 0x00bd,
0x00bc, 0x00a1, 0x00ab, 0x00bb,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557,
0x255d, 0x255c, 0x255b, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x2567,
/* 0xd0*/
0x2568, 0x2564, 0x2565, 0x2559,
0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588,
0x2584, 0x258c, 0x2590, 0x2580,
/* 0xe0*/
0x03b1, 0x00df, 0x0393, 0x03c0,
0x03a3, 0x03c3, 0x00b5, 0x03c4,
0x03a6, 0x0398, 0x03a9, 0x03b4,
0x221e, 0x03c6, 0x03b5, 0x2229,
/* 0xf0*/
0x2261, 0x00b1, 0x2265, 0x2264,
0x2320, 0x2321, 0x00f7, 0x2248,
0x00b0, 0x2219, 0x00b7, 0x221a,
0x207f, 0x00b2, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0xad, 0x9b, 0x9c, 0x00, 0x9d, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0xa6, 0xae, 0xaa, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0xf8, 0xf1, 0xfd, 0x00, 0x00, 0xe6, 0x00, 0xfa, /* 0xb0-0xb7 */
0x00, 0x00, 0xa7, 0xaf, 0xac, 0xab, 0x00, 0xa8, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0xa5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */
0x00, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0xa1, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0xa4, 0x00, 0xa2, 0x00, 0x00, 0x00, 0xf6, /* 0xf0-0xf7 */
0x00, 0x00, 0xa3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page01[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
};
static const unsigned char page03[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0xe9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0xe8, 0x00, /* 0xa0-0xa7 */
0x00, 0xea, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0xe0, 0x00, 0x00, 0xeb, 0xee, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0xe3, 0x00, 0x00, 0xe5, 0xe7, 0x00, 0xed, 0x00, /* 0xc0-0xc7 */
};
static const unsigned char page05[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0xd0-0xd7 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0xd8-0xdf */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0xe0-0xe7 */
0x98, 0x99, 0x9a, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
};
static const unsigned char page20[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9e, /* 0xa0-0xa7 */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0xec, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0xf0, 0x00, 0x00, 0xf3, 0xf2, 0x00, 0x00, /* 0x60-0x67 */
};
static const unsigned char page23[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0xf4, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */
0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */
0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */
0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, page01, NULL, page03, NULL, page05, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
page20, NULL, page22, page23, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa4, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0x00, 0xe3, 0xe5, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xed, 0x00, 0x00, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0xa5, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0x00, 0xe1, 0xe2, 0x00, 0xe4, 0xe4, 0x00, 0x00, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0x00, 0xec, 0xe8, 0x00, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp862",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp862(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp862(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp862)
module_exit(exit_nls_cp862)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
ktoonsez/KTSGS6 | fs/nls/nls_cp866.c | 12566 | 12666 | /*
* linux/fs/nls/nls_cp866.c
*
* Charset cp866 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x0410, 0x0411, 0x0412, 0x0413,
0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041a, 0x041b,
0x041c, 0x041d, 0x041e, 0x041f,
/* 0x90*/
0x0420, 0x0421, 0x0422, 0x0423,
0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b,
0x042c, 0x042d, 0x042e, 0x042f,
/* 0xa0*/
0x0430, 0x0431, 0x0432, 0x0433,
0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0439, 0x043a, 0x043b,
0x043c, 0x043d, 0x043e, 0x043f,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557,
0x255d, 0x255c, 0x255b, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x2567,
/* 0xd0*/
0x2568, 0x2564, 0x2565, 0x2559,
0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588,
0x2584, 0x258c, 0x2590, 0x2580,
/* 0xe0*/
0x0440, 0x0441, 0x0442, 0x0443,
0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b,
0x044c, 0x044d, 0x044e, 0x044f,
/* 0xf0*/
0x0401, 0x0451, 0x0404, 0x0454,
0x0407, 0x0457, 0x040e, 0x045e,
0x00b0, 0x2219, 0x00b7, 0x221a,
0x2116, 0x00a4, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfa, /* 0xb0-0xb7 */
};
static const unsigned char page04[256] = {
0x00, 0xf0, 0x00, 0x00, 0xf2, 0x00, 0x00, 0xf4, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0x00, /* 0x08-0x0f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x10-0x17 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x18-0x1f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x20-0x27 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x28-0x2f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0x30-0x37 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0x38-0x3f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x40-0x47 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x48-0x4f */
0x00, 0xf1, 0x00, 0x00, 0xf3, 0x00, 0x00, 0xf5, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf7, 0x00, /* 0x58-0x5f */
};
static const unsigned char page21[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, /* 0x10-0x17 */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */
0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */
0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */
0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, NULL, NULL, NULL, page04, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, page21, page22, NULL, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0x80-0x87 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0x88-0x8f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x90-0x97 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf1, 0xf1, 0xf3, 0xf3, 0xf5, 0xf5, 0xf7, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0xa0-0xa7 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0xe0-0xe7 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0xe8-0xef */
0xf0, 0xf0, 0xf2, 0xf2, 0xf4, 0xf4, 0xf6, 0xf6, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp866",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp866(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp866(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp866)
module_exit(exit_nls_cp866)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
n00by0815/v30C_kernel | fs/nls/nls_iso8859-3.c | 12566 | 13181 | /*
* linux/fs/nls/nls_iso8859-3.c
*
* Charset iso8859-3 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x0080, 0x0081, 0x0082, 0x0083,
0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b,
0x008c, 0x008d, 0x008e, 0x008f,
/* 0x90*/
0x0090, 0x0091, 0x0092, 0x0093,
0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b,
0x009c, 0x009d, 0x009e, 0x009f,
/* 0xa0*/
0x00a0, 0x0126, 0x02d8, 0x00a3,
0x00a4, 0x0000, 0x0124, 0x00a7,
0x00a8, 0x0130, 0x015e, 0x011e,
0x0134, 0x00ad, 0x0000, 0x017b,
/* 0xb0*/
0x00b0, 0x0127, 0x00b2, 0x00b3,
0x00b4, 0x00b5, 0x0125, 0x00b7,
0x00b8, 0x0131, 0x015f, 0x011f,
0x0135, 0x00bd, 0x0000, 0x017c,
/* 0xc0*/
0x00c0, 0x00c1, 0x00c2, 0x0000,
0x00c4, 0x010a, 0x0108, 0x00c7,
0x00c8, 0x00c9, 0x00ca, 0x00cb,
0x00cc, 0x00cd, 0x00ce, 0x00cf,
/* 0xd0*/
0x0000, 0x00d1, 0x00d2, 0x00d3,
0x00d4, 0x0120, 0x00d6, 0x00d7,
0x011c, 0x00d9, 0x00da, 0x00db,
0x00dc, 0x016c, 0x015c, 0x00df,
/* 0xe0*/
0x00e0, 0x00e1, 0x00e2, 0x0000,
0x00e4, 0x010b, 0x0109, 0x00e7,
0x00e8, 0x00e9, 0x00ea, 0x00eb,
0x00ec, 0x00ed, 0x00ee, 0x00ef,
/* 0xf0*/
0x0000, 0x00f1, 0x00f2, 0x00f3,
0x00f4, 0x0121, 0x00f6, 0x00f7,
0x011d, 0x00f9, 0x00fa, 0x00fb,
0x00fc, 0x016d, 0x015d, 0x02d9,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0x00, 0x00, 0xa3, 0xa4, 0x00, 0x00, 0xa7, /* 0xa0-0xa7 */
0xa8, 0x00, 0x00, 0x00, 0x00, 0xad, 0x00, 0x00, /* 0xa8-0xaf */
0xb0, 0x00, 0xb2, 0xb3, 0xb4, 0xb5, 0x00, 0xb7, /* 0xb0-0xb7 */
0xb8, 0x00, 0x00, 0x00, 0x00, 0xbd, 0x00, 0x00, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0x00, 0xc4, 0x00, 0x00, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0x00, 0xd1, 0xd2, 0xd3, 0xd4, 0x00, 0xd6, 0xd7, /* 0xd0-0xd7 */
0x00, 0xd9, 0xda, 0xdb, 0xdc, 0x00, 0x00, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0x00, 0xe4, 0x00, 0x00, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0x00, 0xf1, 0xf2, 0xf3, 0xf4, 0x00, 0xf6, 0xf7, /* 0xf0-0xf7 */
0x00, 0xf9, 0xfa, 0xfb, 0xfc, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page01[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0xc6, 0xe6, 0xc5, 0xe5, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0xd8, 0xf8, 0xab, 0xbb, /* 0x18-0x1f */
0xd5, 0xf5, 0x00, 0x00, 0xa6, 0xb6, 0xa1, 0xb1, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0xa9, 0xb9, 0x00, 0x00, 0xac, 0xbc, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0xde, 0xfe, 0xaa, 0xba, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0xdd, 0xfd, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0xaf, 0xbf, 0x00, 0x00, 0x00, /* 0x78-0x7f */
};
static const unsigned char page02[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0xa2, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
};
static const unsigned char *const page_uni2charset[256] = {
page00, page01, page02, NULL, NULL, NULL, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xb1, 0xa2, 0xa3, 0xa4, 0x00, 0xb6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0x69, 0xba, 0xbb, 0xbc, 0xad, 0x00, 0xbf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0x00, 0xbf, /* 0xb8-0xbf */
0xe0, 0xe1, 0xe2, 0x00, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xc0-0xc7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xc8-0xcf */
0x00, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xd7, /* 0xd0-0xd7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0x00, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0x00, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0x00, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0x00, 0xaf, /* 0xa8-0xaf */
0xb0, 0xa1, 0xb2, 0xb3, 0xb4, 0x00, 0xa6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0x49, 0xaa, 0xab, 0xac, 0xbd, 0x00, 0xaf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0x00, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0x00, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xc0, 0xc1, 0xc2, 0x00, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xe0-0xe7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xe8-0xef */
0x00, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xf7, /* 0xf0-0xf7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "iso8859-3",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_iso8859_3(void)
{
return register_nls(&table);
}
static void __exit exit_nls_iso8859_3(void)
{
unregister_nls(&table);
}
module_init(init_nls_iso8859_3)
module_exit(exit_nls_iso8859_3)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
knone1/Pinaslang-Kernel | fs/nls/nls_cp866.c | 12566 | 12666 | /*
* linux/fs/nls/nls_cp866.c
*
* Charset cp866 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x0410, 0x0411, 0x0412, 0x0413,
0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041a, 0x041b,
0x041c, 0x041d, 0x041e, 0x041f,
/* 0x90*/
0x0420, 0x0421, 0x0422, 0x0423,
0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b,
0x042c, 0x042d, 0x042e, 0x042f,
/* 0xa0*/
0x0430, 0x0431, 0x0432, 0x0433,
0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0439, 0x043a, 0x043b,
0x043c, 0x043d, 0x043e, 0x043f,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557,
0x255d, 0x255c, 0x255b, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x2567,
/* 0xd0*/
0x2568, 0x2564, 0x2565, 0x2559,
0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588,
0x2584, 0x258c, 0x2590, 0x2580,
/* 0xe0*/
0x0440, 0x0441, 0x0442, 0x0443,
0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b,
0x044c, 0x044d, 0x044e, 0x044f,
/* 0xf0*/
0x0401, 0x0451, 0x0404, 0x0454,
0x0407, 0x0457, 0x040e, 0x045e,
0x00b0, 0x2219, 0x00b7, 0x221a,
0x2116, 0x00a4, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfa, /* 0xb0-0xb7 */
};
static const unsigned char page04[256] = {
0x00, 0xf0, 0x00, 0x00, 0xf2, 0x00, 0x00, 0xf4, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0x00, /* 0x08-0x0f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x10-0x17 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x18-0x1f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x20-0x27 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x28-0x2f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0x30-0x37 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0x38-0x3f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x40-0x47 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x48-0x4f */
0x00, 0xf1, 0x00, 0x00, 0xf3, 0x00, 0x00, 0xf5, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf7, 0x00, /* 0x58-0x5f */
};
static const unsigned char page21[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, /* 0x10-0x17 */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */
0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */
0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */
0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, NULL, NULL, NULL, page04, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, page21, page22, NULL, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0x80-0x87 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0x88-0x8f */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0x90-0x97 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf1, 0xf1, 0xf3, 0xf3, 0xf5, 0xf5, 0xf7, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0xa0-0xa7 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0xe0-0xe7 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0xe8-0xef */
0xf0, 0xf0, 0xf2, 0xf2, 0xf4, 0xf4, 0xf6, 0xf6, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp866",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp866(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp866(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp866)
module_exit(exit_nls_cp866)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
cphelps76/kernel_google_msm | net/netfilter/xt_CONNSECMARK.c | 13590 | 3666 | /*
* This module is used to copy security markings from packets
* to connections, and restore security markings from connections
* back to packets. This would normally be performed in conjunction
* with the SECMARK target and state match.
*
* Based somewhat on CONNMARK:
* Copyright (C) 2002,2004 MARA Systems AB <http://www.marasystems.com>
* by Henrik Nordstrom <hno@marasystems.com>
*
* (C) 2006,2008 Red Hat, Inc., James Morris <jmorris@redhat.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.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_CONNSECMARK.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_ecache.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Morris <jmorris@redhat.com>");
MODULE_DESCRIPTION("Xtables: target for copying between connection and security mark");
MODULE_ALIAS("ipt_CONNSECMARK");
MODULE_ALIAS("ip6t_CONNSECMARK");
/*
* If the packet has a security mark and the connection does not, copy
* the security mark from the packet to the connection.
*/
static void secmark_save(const struct sk_buff *skb)
{
if (skb->secmark) {
struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
ct = nf_ct_get(skb, &ctinfo);
if (ct && !ct->secmark) {
ct->secmark = skb->secmark;
nf_conntrack_event_cache(IPCT_SECMARK, ct);
}
}
}
/*
* If packet has no security mark, and the connection does, restore the
* security mark from the connection to the packet.
*/
static void secmark_restore(struct sk_buff *skb)
{
if (!skb->secmark) {
const struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
ct = nf_ct_get(skb, &ctinfo);
if (ct && ct->secmark)
skb->secmark = ct->secmark;
}
}
static unsigned int
connsecmark_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_connsecmark_target_info *info = par->targinfo;
switch (info->mode) {
case CONNSECMARK_SAVE:
secmark_save(skb);
break;
case CONNSECMARK_RESTORE:
secmark_restore(skb);
break;
default:
BUG();
}
return XT_CONTINUE;
}
static int connsecmark_tg_check(const struct xt_tgchk_param *par)
{
const struct xt_connsecmark_target_info *info = par->targinfo;
int ret;
if (strcmp(par->table, "mangle") != 0 &&
strcmp(par->table, "security") != 0) {
pr_info("target only valid in the \'mangle\' "
"or \'security\' tables, not \'%s\'.\n", par->table);
return -EINVAL;
}
switch (info->mode) {
case CONNSECMARK_SAVE:
case CONNSECMARK_RESTORE:
break;
default:
pr_info("invalid mode: %hu\n", info->mode);
return -EINVAL;
}
ret = nf_ct_l3proto_try_module_get(par->family);
if (ret < 0)
pr_info("cannot load conntrack support for proto=%u\n",
par->family);
return ret;
}
static void connsecmark_tg_destroy(const struct xt_tgdtor_param *par)
{
nf_ct_l3proto_module_put(par->family);
}
static struct xt_target connsecmark_tg_reg __read_mostly = {
.name = "CONNSECMARK",
.revision = 0,
.family = NFPROTO_UNSPEC,
.checkentry = connsecmark_tg_check,
.destroy = connsecmark_tg_destroy,
.target = connsecmark_tg,
.targetsize = sizeof(struct xt_connsecmark_target_info),
.me = THIS_MODULE,
};
static int __init connsecmark_tg_init(void)
{
return xt_register_target(&connsecmark_tg_reg);
}
static void __exit connsecmark_tg_exit(void)
{
xt_unregister_target(&connsecmark_tg_reg);
}
module_init(connsecmark_tg_init);
module_exit(connsecmark_tg_exit);
| gpl-2.0 |
MoKee/android_kernel_htc_msm7x30 | net/netfilter/xt_CONNSECMARK.c | 13590 | 3666 | /*
* This module is used to copy security markings from packets
* to connections, and restore security markings from connections
* back to packets. This would normally be performed in conjunction
* with the SECMARK target and state match.
*
* Based somewhat on CONNMARK:
* Copyright (C) 2002,2004 MARA Systems AB <http://www.marasystems.com>
* by Henrik Nordstrom <hno@marasystems.com>
*
* (C) 2006,2008 Red Hat, Inc., James Morris <jmorris@redhat.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.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_CONNSECMARK.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_ecache.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Morris <jmorris@redhat.com>");
MODULE_DESCRIPTION("Xtables: target for copying between connection and security mark");
MODULE_ALIAS("ipt_CONNSECMARK");
MODULE_ALIAS("ip6t_CONNSECMARK");
/*
* If the packet has a security mark and the connection does not, copy
* the security mark from the packet to the connection.
*/
static void secmark_save(const struct sk_buff *skb)
{
if (skb->secmark) {
struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
ct = nf_ct_get(skb, &ctinfo);
if (ct && !ct->secmark) {
ct->secmark = skb->secmark;
nf_conntrack_event_cache(IPCT_SECMARK, ct);
}
}
}
/*
* If packet has no security mark, and the connection does, restore the
* security mark from the connection to the packet.
*/
static void secmark_restore(struct sk_buff *skb)
{
if (!skb->secmark) {
const struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
ct = nf_ct_get(skb, &ctinfo);
if (ct && ct->secmark)
skb->secmark = ct->secmark;
}
}
static unsigned int
connsecmark_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_connsecmark_target_info *info = par->targinfo;
switch (info->mode) {
case CONNSECMARK_SAVE:
secmark_save(skb);
break;
case CONNSECMARK_RESTORE:
secmark_restore(skb);
break;
default:
BUG();
}
return XT_CONTINUE;
}
static int connsecmark_tg_check(const struct xt_tgchk_param *par)
{
const struct xt_connsecmark_target_info *info = par->targinfo;
int ret;
if (strcmp(par->table, "mangle") != 0 &&
strcmp(par->table, "security") != 0) {
pr_info("target only valid in the \'mangle\' "
"or \'security\' tables, not \'%s\'.\n", par->table);
return -EINVAL;
}
switch (info->mode) {
case CONNSECMARK_SAVE:
case CONNSECMARK_RESTORE:
break;
default:
pr_info("invalid mode: %hu\n", info->mode);
return -EINVAL;
}
ret = nf_ct_l3proto_try_module_get(par->family);
if (ret < 0)
pr_info("cannot load conntrack support for proto=%u\n",
par->family);
return ret;
}
static void connsecmark_tg_destroy(const struct xt_tgdtor_param *par)
{
nf_ct_l3proto_module_put(par->family);
}
static struct xt_target connsecmark_tg_reg __read_mostly = {
.name = "CONNSECMARK",
.revision = 0,
.family = NFPROTO_UNSPEC,
.checkentry = connsecmark_tg_check,
.destroy = connsecmark_tg_destroy,
.target = connsecmark_tg,
.targetsize = sizeof(struct xt_connsecmark_target_info),
.me = THIS_MODULE,
};
static int __init connsecmark_tg_init(void)
{
return xt_register_target(&connsecmark_tg_reg);
}
static void __exit connsecmark_tg_exit(void)
{
xt_unregister_target(&connsecmark_tg_reg);
}
module_init(connsecmark_tg_init);
module_exit(connsecmark_tg_exit);
| gpl-2.0 |
ali-filth/android_kernel_samsung_msm8226 | drivers/usb/dwc3/dwc3_otg.c | 23 | 28678 | /**
* dwc3_otg.c - DesignWare USB3 DRD Controller OTG
*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>
#include "core.h"
#include "dwc3_otg.h"
#include "io.h"
#include "xhci.h"
#define VBUS_REG_CHECK_DELAY (msecs_to_jiffies(1000))
#define MAX_INVALID_CHRGR_RETRY 3
static int max_chgr_retry_count = MAX_INVALID_CHRGR_RETRY;
module_param(max_chgr_retry_count, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(max_chgr_retry_count, "Max invalid charger retry count");
static void dwc3_otg_reset(struct dwc3_otg *dotg);
static void dwc3_otg_notify_host_mode(struct usb_otg *otg, int host_mode);
static void dwc3_otg_reset(struct dwc3_otg *dotg);
/**
* dwc3_otg_set_host_regs - reset dwc3 otg registers to host operation.
*
* This function sets the OTG registers to work in A-Device host mode.
* This function should be called just before entering to A-Device mode.
*
* @w: Pointer to the dwc3 otg struct
*/
static void dwc3_otg_set_host_regs(struct dwc3_otg *dotg)
{
u32 reg;
struct dwc3 *dwc = dotg->dwc;
struct dwc3_ext_xceiv *ext_xceiv = dotg->ext_xceiv;
if (ext_xceiv && !ext_xceiv->otg_capability) {
/* Set OCTL[6](PeriMode) to 0 (host) */
reg = dwc3_readl(dotg->regs, DWC3_OCTL);
reg &= ~DWC3_OTG_OCTL_PERIMODE;
dwc3_writel(dotg->regs, DWC3_OCTL, reg);
} else {
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg &= ~(DWC3_GCTL_PRTCAPDIR(DWC3_GCTL_PRTCAP_OTG));
reg |= DWC3_GCTL_PRTCAPDIR(DWC3_GCTL_PRTCAP_HOST);
/*
* Allow ITP generated off of ref clk based counter instead
* of UTMI/ULPI clk based counter, when superspeed only is
* active so that UTMI/ULPI can be suspened.
*/
reg |= DWC3_GCTL_SOFITPSYNC;
/*
* Set this bit so that device attempts three more times at SS,
* even if it failed previously to operate in SS mode.
*/
reg |= DWC3_GCTL_U2RSTECN;
reg &= ~(DWC3_GCTL_PWRDNSCALEMASK);
reg |= DWC3_GCTL_PWRDNSCALE(2);
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
}
}
static int dwc3_otg_set_suspend(struct usb_phy *phy, int suspend)
{
struct usb_otg *otg = phy->otg;
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
if (dotg->host_bus_suspend == suspend)
return 0;
dotg->host_bus_suspend = suspend;
if (suspend) {
pm_runtime_put_sync(phy->dev);
} else {
pm_runtime_get_noresume(phy->dev);
pm_runtime_resume(phy->dev);
}
return 0;
}
/**
* dwc3_otg_set_host_power - Enable port power control for host operation
*
* This function enables the OTG Port Power required to operate in Host mode
* This function should be called only after XHCI driver has set the port
* power in PORTSC register.
*
* @w: Pointer to the dwc3 otg struct
*/
void dwc3_otg_set_host_power(struct dwc3_otg *dotg)
{
u32 osts;
osts = dwc3_readl(dotg->regs, DWC3_OSTS);
if (!(osts & 0x8))
dev_err(dotg->dwc->dev, "%s: xHCIPrtPower not set\n", __func__);
dwc3_writel(dotg->regs, DWC3_OCTL, DWC3_OTG_OCTL_PRTPWRCTL);
}
/**
* dwc3_otg_set_peripheral_regs - reset dwc3 otg registers to peripheral operation.
*
* This function sets the OTG registers to work in B-Device peripheral mode.
* This function should be called just before entering to B-Device mode.
*
* @w: Pointer to the dwc3 otg workqueue.
*/
static void dwc3_otg_set_peripheral_regs(struct dwc3_otg *dotg)
{
u32 reg;
struct dwc3 *dwc = dotg->dwc;
struct dwc3_ext_xceiv *ext_xceiv = dotg->ext_xceiv;
if (ext_xceiv && !ext_xceiv->otg_capability) {
/* Set OCTL[6](PeriMode) to 1 (peripheral) */
reg = dwc3_readl(dotg->regs, DWC3_OCTL);
reg |= DWC3_OTG_OCTL_PERIMODE;
dwc3_writel(dotg->regs, DWC3_OCTL, reg);
/*
* TODO: add more OTG registers writes for PERIPHERAL mode here,
* see figure 12-19 B-device flow in dwc3 Synopsis spec
*/
} else {
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg &= ~(DWC3_GCTL_PRTCAPDIR(DWC3_GCTL_PRTCAP_OTG));
reg |= DWC3_GCTL_PRTCAPDIR(DWC3_GCTL_PRTCAP_DEVICE);
/*
* Set this bit so that device attempts three more times at SS,
* even if it failed previously to operate in SS mode.
*/
reg |= DWC3_GCTL_U2RSTECN;
reg &= ~(DWC3_GCTL_PWRDNSCALEMASK);
reg |= DWC3_GCTL_PWRDNSCALE(2);
reg &= ~(DWC3_GCTL_SOFITPSYNC);
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
}
}
/**
* dwc3_otg_start_host - helper function for starting/stoping the host controller driver.
*
* @otg: Pointer to the otg_transceiver structure.
* @on: start / stop the host controller driver.
*
* Returns 0 on success otherwise negative errno.
*/
static int dwc3_otg_start_host(struct usb_otg *otg, int on)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
struct dwc3_ext_xceiv *ext_xceiv = dotg->ext_xceiv;
struct dwc3 *dwc = dotg->dwc;
int ret = 0;
if (!dwc->xhci)
return -EINVAL;
if (!dotg->vbus_otg) {
dotg->vbus_otg = devm_regulator_get(dwc->dev->parent,
"vbus_dwc3");
if (IS_ERR(dotg->vbus_otg)) {
dev_err(dwc->dev, "Failed to get vbus regulator\n");
ret = PTR_ERR(dotg->vbus_otg);
dotg->vbus_otg = 0;
return ret;
}
}
if (on) {
dev_dbg(otg->phy->dev, "%s: turn on host\n", __func__);
/*
* This should be revisited for more testing post-silicon.
* In worst case we may need to disconnect the root hub
* before stopping the controller so that it does not
* interfere with runtime pm/system pm.
* We can also consider registering and unregistering xhci
* platform device. It is almost similar to add_hcd and
* remove_hcd, But we may not use standard set_host method
* anymore.
*/
dwc3_otg_set_host_regs(dotg);
/*
* FIXME If micro A cable is disconnected during system suspend,
* xhci platform device will be removed before runtime pm is
* enabled for xhci device. Due to this, disable_depth becomes
* greater than one and runtimepm is not enabled for next microA
* connect. Fix this by calling pm_runtime_init for xhci device.
*/
pm_runtime_init(&dwc->xhci->dev);
ret = platform_device_add(dwc->xhci);
if (ret) {
dev_err(otg->phy->dev,
"%s: failed to add XHCI pdev ret=%d\n",
__func__, ret);
return ret;
}
dwc3_otg_notify_host_mode(otg, on);
ret = regulator_enable(dotg->vbus_otg);
if (ret) {
dev_err(otg->phy->dev, "unable to enable vbus_otg\n");
platform_device_del(dwc->xhci);
return ret;
}
/* re-init OTG EVTEN register as XHCI reset clears it */
if (ext_xceiv && !ext_xceiv->otg_capability)
dwc3_otg_reset(dotg);
} else {
dev_dbg(otg->phy->dev, "%s: turn off host\n", __func__);
ret = regulator_disable(dotg->vbus_otg);
if (ret) {
dev_err(otg->phy->dev, "unable to disable vbus_otg\n");
return ret;
}
dwc3_otg_notify_host_mode(otg, on);
platform_device_del(dwc->xhci);
/*
* Perform USB hardware RESET (both core reset and DBM reset)
* when moving from host to peripheral. This is required for
* peripheral mode to work.
*/
if (ext_xceiv && ext_xceiv->otg_capability &&
ext_xceiv->ext_block_reset)
ext_xceiv->ext_block_reset(ext_xceiv, true);
dwc3_otg_set_peripheral_regs(dotg);
/* re-init core and OTG registers as block reset clears these */
dwc3_post_host_reset_core_init(dwc);
if (ext_xceiv && !ext_xceiv->otg_capability)
dwc3_otg_reset(dotg);
}
return 0;
}
/**
* dwc3_otg_set_host - bind/unbind the host controller driver.
*
* @otg: Pointer to the otg_transceiver structure.
* @host: Pointer to the usb_bus structure.
*
* Returns 0 on success otherwise negative errno.
*/
static int dwc3_otg_set_host(struct usb_otg *otg, struct usb_bus *host)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
if (host) {
dev_dbg(otg->phy->dev, "%s: set host %s, portpower\n",
__func__, host->bus_name);
otg->host = host;
/*
* Though XHCI power would be set by now, but some delay is
* required for XHCI controller before setting OTG Port Power
* TODO: Tune this delay
*/
msleep(300);
dwc3_otg_set_host_power(dotg);
} else {
otg->host = NULL;
}
return 0;
}
/**
* dwc3_otg_start_peripheral - bind/unbind the peripheral controller.
*
* @otg: Pointer to the otg_transceiver structure.
* @gadget: pointer to the usb_gadget structure.
*
* Returns 0 on success otherwise negative errno.
*/
static int dwc3_otg_start_peripheral(struct usb_otg *otg, int on)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
struct dwc3_ext_xceiv *ext_xceiv = dotg->ext_xceiv;
if (!otg->gadget)
return -EINVAL;
if (on) {
dev_dbg(otg->phy->dev, "%s: turn on gadget %s\n",
__func__, otg->gadget->name);
/* Core reset is not required during start peripheral. Only
* DBM reset is required, hence perform only DBM reset here */
if (ext_xceiv && ext_xceiv->otg_capability &&
ext_xceiv->ext_block_reset)
ext_xceiv->ext_block_reset(ext_xceiv, false);
dwc3_otg_set_peripheral_regs(dotg);
usb_gadget_vbus_connect(otg->gadget);
} else {
dev_dbg(otg->phy->dev, "%s: turn off gadget %s\n",
__func__, otg->gadget->name);
usb_gadget_vbus_disconnect(otg->gadget);
}
return 0;
}
/**
* dwc3_otg_set_peripheral - bind/unbind the peripheral controller driver.
*
* @otg: Pointer to the otg_transceiver structure.
* @gadget: pointer to the usb_gadget structure.
*
* Returns 0 on success otherwise negative errno.
*/
static int dwc3_otg_set_peripheral(struct usb_otg *otg,
struct usb_gadget *gadget)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
if (gadget) {
dev_dbg(otg->phy->dev, "%s: set gadget %s\n",
__func__, gadget->name);
otg->gadget = gadget;
queue_delayed_work(system_nrt_wq, &dotg->sm_work, 0);
} else {
if (otg->phy->state == OTG_STATE_B_PERIPHERAL) {
dwc3_otg_start_peripheral(otg, 0);
otg->gadget = NULL;
otg->phy->state = OTG_STATE_UNDEFINED;
queue_delayed_work(system_nrt_wq, &dotg->sm_work, 0);
} else {
otg->gadget = NULL;
}
}
return 0;
}
/**
* dwc3_ext_chg_det_done - callback to handle charger detection completion
* @otg: Pointer to the otg transceiver structure
* @charger: Pointer to the external charger structure
*
* Returns 0 on success
*/
static void dwc3_ext_chg_det_done(struct usb_otg *otg, struct dwc3_charger *chg)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
/*
* Ignore chg_detection notification if BSV has gone off by this time.
* STOP chg_det as part of !BSV handling would reset the chg_det flags
*/
if (test_bit(B_SESS_VLD, &dotg->inputs))
queue_delayed_work(system_nrt_wq, &dotg->sm_work, 0);
}
/**
* dwc3_set_charger - bind/unbind external charger driver
* @otg: Pointer to the otg transceiver structure
* @charger: Pointer to the external charger structure
*
* Returns 0 on success
*/
int dwc3_set_charger(struct usb_otg *otg, struct dwc3_charger *charger)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
dotg->charger = charger;
if (charger)
charger->notify_detection_complete = dwc3_ext_chg_det_done;
return 0;
}
/**
* dwc3_ext_event_notify - callback to handle events from external transceiver
* @otg: Pointer to the otg transceiver structure
* @event: Event reported by transceiver
*
* Returns 0 on success
*/
static void dwc3_ext_event_notify(struct usb_otg *otg,
enum dwc3_ext_events event)
{
static bool init;
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
struct dwc3_ext_xceiv *ext_xceiv = dotg->ext_xceiv;
struct usb_phy *phy = dotg->otg.phy;
int ret = 0;
/* Flush processing any pending events before handling new ones */
if (init)
flush_delayed_work(&dotg->sm_work);
if (event == DWC3_EVENT_PHY_RESUME) {
if (!pm_runtime_status_suspended(phy->dev)) {
dev_warn(phy->dev, "PHY_RESUME event out of LPM!!!!\n");
} else {
dev_dbg(phy->dev, "ext PHY_RESUME event received\n");
/* ext_xceiver would have taken h/w out of LPM by now */
ret = pm_runtime_get(phy->dev);
if ((phy->state == OTG_STATE_A_HOST) &&
dotg->host_bus_suspend)
dotg->host_bus_suspend = 0;
if (ret == -EACCES) {
/* pm_runtime_get may fail during system
resume with -EACCES error */
pm_runtime_disable(phy->dev);
pm_runtime_set_active(phy->dev);
pm_runtime_enable(phy->dev);
} else if (ret < 0) {
dev_warn(phy->dev, "pm_runtime_get failed!\n");
}
}
} else if (event == DWC3_EVENT_XCEIV_STATE) {
if (pm_runtime_status_suspended(phy->dev)) {
dev_warn(phy->dev, "PHY_STATE event in LPM!!!!\n");
ret = pm_runtime_get(phy->dev);
if (ret < 0)
dev_warn(phy->dev, "pm_runtime_get failed!!\n");
}
if (ext_xceiv->id == DWC3_ID_FLOAT) {
dev_dbg(phy->dev, "XCVR: ID set\n");
set_bit(ID, &dotg->inputs);
} else {
dev_dbg(phy->dev, "XCVR: ID clear\n");
clear_bit(ID, &dotg->inputs);
}
if (ext_xceiv->bsv) {
dev_dbg(phy->dev, "XCVR: BSV set\n");
set_bit(B_SESS_VLD, &dotg->inputs);
} else {
dev_dbg(phy->dev, "XCVR: BSV clear\n");
clear_bit(B_SESS_VLD, &dotg->inputs);
}
if (!init) {
init = true;
if (!work_busy(&dotg->sm_work.work))
queue_delayed_work(system_nrt_wq,
&dotg->sm_work, 0);
complete(&dotg->dwc3_xcvr_vbus_init);
dev_dbg(phy->dev, "XCVR: BSV init complete\n");
return;
}
queue_delayed_work(system_nrt_wq, &dotg->sm_work, 0);
}
}
/**
* dwc3_set_ext_xceiv - bind/unbind external transceiver driver
* @otg: Pointer to the otg transceiver structure
* @ext_xceiv: Pointer to the external transceiver struccture
*
* Returns 0 on success
*/
int dwc3_set_ext_xceiv(struct usb_otg *otg, struct dwc3_ext_xceiv *ext_xceiv)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
dotg->ext_xceiv = ext_xceiv;
if (ext_xceiv)
ext_xceiv->notify_ext_events = dwc3_ext_event_notify;
return 0;
}
static void dwc3_otg_notify_host_mode(struct usb_otg *otg, int host_mode)
{
struct dwc3_otg *dotg = container_of(otg, struct dwc3_otg, otg);
if (!dotg->psy) {
dev_err(otg->phy->dev, "no usb power supply registered\n");
return;
}
if (host_mode)
power_supply_set_scope(dotg->psy, POWER_SUPPLY_SCOPE_SYSTEM);
else
power_supply_set_scope(dotg->psy, POWER_SUPPLY_SCOPE_DEVICE);
}
static int dwc3_otg_set_power(struct usb_phy *phy, unsigned mA)
{
static int power_supply_type;
struct dwc3_otg *dotg = container_of(phy->otg, struct dwc3_otg, otg);
if (!dotg->psy || !dotg->charger) {
dev_err(phy->dev, "no usb power supply/charger registered\n");
return 0;
}
if (dotg->charger->charging_disabled)
return 0;
if (dotg->charger->chg_type == DWC3_SDP_CHARGER)
power_supply_type = POWER_SUPPLY_TYPE_USB;
else if (dotg->charger->chg_type == DWC3_CDP_CHARGER)
power_supply_type = POWER_SUPPLY_TYPE_USB_CDP;
else if (dotg->charger->chg_type == DWC3_DCP_CHARGER ||
dotg->charger->chg_type == DWC3_PROPRIETARY_CHARGER)
power_supply_type = POWER_SUPPLY_TYPE_USB_DCP;
else
power_supply_type = POWER_SUPPLY_TYPE_BATTERY;
power_supply_set_supply_type(dotg->psy, power_supply_type);
if (dotg->charger->chg_type == DWC3_CDP_CHARGER)
mA = DWC3_IDEV_CHG_MAX;
if (dotg->charger->max_power == mA)
return 0;
dev_info(phy->dev, "Avail curr from USB = %u\n", mA);
if (dotg->charger->max_power <= 2 && mA > 2) {
/* Enable charging */
if (power_supply_set_online(dotg->psy, true))
goto psy_error;
if (power_supply_set_current_limit(dotg->psy, 1000*mA))
goto psy_error;
} else if (dotg->charger->max_power > 0 && (mA == 0 || mA == 2)) {
/* Disable charging */
if (power_supply_set_online(dotg->psy, false))
goto psy_error;
/* Set max current limit */
if (power_supply_set_current_limit(dotg->psy, 0))
goto psy_error;
}
power_supply_changed(dotg->psy);
dotg->charger->max_power = mA;
return 0;
psy_error:
dev_dbg(phy->dev, "power supply error when setting property\n");
return -ENXIO;
}
/* IRQs which OTG driver is interested in handling */
#define DWC3_OEVT_MASK (DWC3_OEVTEN_OTGCONIDSTSCHNGEVNT | \
DWC3_OEVTEN_OTGBDEVVBUSCHNGEVNT)
/**
* dwc3_otg_interrupt - interrupt handler for dwc3 otg events.
* @_dotg: Pointer to out controller context structure
*
* Returns IRQ_HANDLED on success otherwise IRQ_NONE.
*/
static irqreturn_t dwc3_otg_interrupt(int irq, void *_dotg)
{
struct dwc3_otg *dotg = (struct dwc3_otg *)_dotg;
u32 osts, oevt_reg;
int ret = IRQ_NONE;
int handled_irqs = 0;
struct usb_phy *phy = dotg->otg.phy;
oevt_reg = dwc3_readl(dotg->regs, DWC3_OEVT);
if (!(oevt_reg & DWC3_OEVT_MASK))
return IRQ_NONE;
osts = dwc3_readl(dotg->regs, DWC3_OSTS);
if ((oevt_reg & DWC3_OEVTEN_OTGCONIDSTSCHNGEVNT) ||
(oevt_reg & DWC3_OEVTEN_OTGBDEVVBUSCHNGEVNT)) {
/*
* ID sts has changed, set inputs later, in the workqueue
* function, switch from A to B or from B to A.
*/
if (oevt_reg & DWC3_OEVTEN_OTGCONIDSTSCHNGEVNT) {
if (osts & DWC3_OTG_OSTS_CONIDSTS) {
dev_dbg(phy->dev, "ID set\n");
set_bit(ID, &dotg->inputs);
} else {
dev_dbg(phy->dev, "ID clear\n");
clear_bit(ID, &dotg->inputs);
}
handled_irqs |= DWC3_OEVTEN_OTGCONIDSTSCHNGEVNT;
}
if (oevt_reg & DWC3_OEVTEN_OTGBDEVVBUSCHNGEVNT) {
if (osts & DWC3_OTG_OSTS_BSESVALID) {
dev_dbg(phy->dev, "BSV set\n");
set_bit(B_SESS_VLD, &dotg->inputs);
} else {
dev_dbg(phy->dev, "BSV clear\n");
clear_bit(B_SESS_VLD, &dotg->inputs);
}
handled_irqs |= DWC3_OEVTEN_OTGBDEVVBUSCHNGEVNT;
}
queue_delayed_work(system_nrt_wq, &dotg->sm_work, 0);
ret = IRQ_HANDLED;
/* Clear the interrupts we handled */
dwc3_writel(dotg->regs, DWC3_OEVT, handled_irqs);
}
return ret;
}
/**
* dwc3_otg_init_sm - initialize OTG statemachine input
* @dotg: Pointer to the dwc3_otg structure
*
*/
void dwc3_otg_init_sm(struct dwc3_otg *dotg)
{
u32 osts = dwc3_readl(dotg->regs, DWC3_OSTS);
struct usb_phy *phy = dotg->otg.phy;
struct dwc3_ext_xceiv *ext_xceiv;
int ret;
dev_dbg(phy->dev, "Initialize OTG inputs, osts: 0x%x\n", osts);
/*
* VBUS initial state is reported after PMIC
* driver initialization. Wait for it.
*/
ret = wait_for_completion_timeout(&dotg->dwc3_xcvr_vbus_init, HZ * 5);
if (!ret) {
dev_err(phy->dev, "%s: completion timeout\n", __func__);
/* We can safely assume no cable connected */
set_bit(ID, &dotg->inputs);
}
ext_xceiv = dotg->ext_xceiv;
dwc3_otg_reset(dotg);
if (ext_xceiv && !ext_xceiv->otg_capability) {
if (osts & DWC3_OTG_OSTS_CONIDSTS)
set_bit(ID, &dotg->inputs);
else
clear_bit(ID, &dotg->inputs);
if (osts & DWC3_OTG_OSTS_BSESVALID)
set_bit(B_SESS_VLD, &dotg->inputs);
else
clear_bit(B_SESS_VLD, &dotg->inputs);
}
}
/**
* dwc3_otg_sm_work - workqueue function.
*
* @w: Pointer to the dwc3 otg workqueue
*
* NOTE: After any change in phy->state,
* we must reschdule the state machine.
*/
static void dwc3_otg_sm_work(struct work_struct *w)
{
struct dwc3_otg *dotg = container_of(w, struct dwc3_otg, sm_work.work);
struct usb_phy *phy = dotg->otg.phy;
struct dwc3_charger *charger = dotg->charger;
bool work = 0;
int ret = 0;
unsigned long delay = 0;
pm_runtime_resume(phy->dev);
dev_dbg(phy->dev, "%s state\n", otg_state_string(phy->state));
/* Check OTG state */
switch (phy->state) {
case OTG_STATE_UNDEFINED:
dwc3_otg_init_sm(dotg);
if (!dotg->psy) {
dotg->psy = power_supply_get_by_name("usb");
if (!dotg->psy)
dev_err(phy->dev,
"couldn't get usb power supply\n");
}
/* Switch to A or B-Device according to ID / BSV */
if (!test_bit(ID, &dotg->inputs)) {
dev_dbg(phy->dev, "!id\n");
phy->state = OTG_STATE_A_IDLE;
work = 1;
} else if (test_bit(B_SESS_VLD, &dotg->inputs)) {
dev_dbg(phy->dev, "b_sess_vld\n");
phy->state = OTG_STATE_B_IDLE;
work = 1;
} else {
phy->state = OTG_STATE_B_IDLE;
dev_dbg(phy->dev, "No device, trying to suspend\n");
pm_runtime_put_sync(phy->dev);
}
break;
case OTG_STATE_B_IDLE:
if (!test_bit(ID, &dotg->inputs)) {
dev_dbg(phy->dev, "!id\n");
phy->state = OTG_STATE_A_IDLE;
work = 1;
dotg->charger_retry_count = 0;
if (charger) {
if (charger->chg_type == DWC3_INVALID_CHARGER)
charger->start_detection(dotg->charger,
false);
else
charger->chg_type =
DWC3_INVALID_CHARGER;
}
} else if (test_bit(B_SESS_VLD, &dotg->inputs)) {
dev_dbg(phy->dev, "b_sess_vld\n");
if (charger) {
/* Has charger been detected? If no detect it */
switch (charger->chg_type) {
case DWC3_DCP_CHARGER:
case DWC3_PROPRIETARY_CHARGER:
dev_dbg(phy->dev, "lpm, DCP charger\n");
dwc3_otg_set_power(phy,
DWC3_IDEV_CHG_MAX);
pm_runtime_put_sync(phy->dev);
break;
case DWC3_CDP_CHARGER:
dwc3_otg_set_power(phy,
DWC3_IDEV_CHG_MAX);
dwc3_otg_start_peripheral(&dotg->otg,
1);
phy->state = OTG_STATE_B_PERIPHERAL;
work = 1;
break;
case DWC3_SDP_CHARGER:
dwc3_otg_start_peripheral(&dotg->otg,
1);
phy->state = OTG_STATE_B_PERIPHERAL;
work = 1;
break;
case DWC3_FLOATED_CHARGER:
if (dotg->charger_retry_count <
max_chgr_retry_count)
dotg->charger_retry_count++;
/*
* In case of floating charger, if
* retry count equal to max retry count
* notify PMIC about floating charger
* and put Hw in low power mode. Else
* perform charger detection again by
* calling start_detection() with false
* and then with true argument.
*/
if (dotg->charger_retry_count ==
max_chgr_retry_count) {
dwc3_otg_set_power(phy, 0);
pm_runtime_put_sync(phy->dev);
break;
}
charger->start_detection(dotg->charger,
false);
default:
dev_dbg(phy->dev, "chg_det started\n");
charger->start_detection(charger, true);
break;
}
} else {
/* no charger registered, start peripheral */
if (dwc3_otg_start_peripheral(&dotg->otg, 1)) {
/*
* Probably set_peripheral not called
* yet. We will re-try as soon as it
* will be called
*/
dev_err(phy->dev, "enter lpm as\n"
"unable to start B-device\n");
phy->state = OTG_STATE_UNDEFINED;
pm_runtime_put_sync(phy->dev);
return;
}
}
} else {
if (charger)
charger->start_detection(dotg->charger, false);
dotg->charger_retry_count = 0;
dwc3_otg_set_power(phy, 0);
dev_dbg(phy->dev, "No device, trying to suspend\n");
pm_runtime_put_sync(phy->dev);
}
break;
case OTG_STATE_B_PERIPHERAL:
if (!test_bit(B_SESS_VLD, &dotg->inputs) ||
!test_bit(ID, &dotg->inputs)) {
dev_dbg(phy->dev, "!id || !bsv\n");
dwc3_otg_start_peripheral(&dotg->otg, 0);
phy->state = OTG_STATE_B_IDLE;
if (charger)
charger->chg_type = DWC3_INVALID_CHARGER;
work = 1;
}
break;
case OTG_STATE_A_IDLE:
/* Switch to A-Device*/
if (test_bit(ID, &dotg->inputs)) {
dev_dbg(phy->dev, "id\n");
phy->state = OTG_STATE_B_IDLE;
dotg->vbus_retry_count = 0;
work = 1;
} else {
phy->state = OTG_STATE_A_HOST;
ret = dwc3_otg_start_host(&dotg->otg, 1);
if ((ret == -EPROBE_DEFER) &&
dotg->vbus_retry_count < 3) {
/*
* Get regulator failed as regulator driver is
* not up yet. Will try to start host after 1sec
*/
phy->state = OTG_STATE_A_IDLE;
dev_dbg(phy->dev, "Unable to get vbus regulator. Retrying...\n");
delay = VBUS_REG_CHECK_DELAY;
work = 1;
dotg->vbus_retry_count++;
} else if (ret) {
/*
* Probably set_host was not called yet.
* We will re-try as soon as it will be called
*/
dev_dbg(phy->dev, "enter lpm as\n"
"unable to start A-device\n");
phy->state = OTG_STATE_A_IDLE;
pm_runtime_put_sync(phy->dev);
return;
}
}
break;
case OTG_STATE_A_HOST:
if (test_bit(ID, &dotg->inputs)) {
dev_dbg(phy->dev, "id\n");
dwc3_otg_start_host(&dotg->otg, 0);
phy->state = OTG_STATE_B_IDLE;
dotg->vbus_retry_count = 0;
work = 1;
}
break;
default:
dev_err(phy->dev, "%s: invalid otg-state\n", __func__);
}
if (work)
queue_delayed_work(system_nrt_wq, &dotg->sm_work, delay);
}
/**
* dwc3_otg_reset - reset dwc3 otg registers.
*
* @w: Pointer to the dwc3 otg workqueue
*/
static void dwc3_otg_reset(struct dwc3_otg *dotg)
{
static int once;
struct dwc3_ext_xceiv *ext_xceiv = dotg->ext_xceiv;
/*
* OCFG[2] - OTG-Version = 1
* OCFG[1] - HNPCap = 0
* OCFG[0] - SRPCap = 0
*/
if (ext_xceiv && !ext_xceiv->otg_capability)
dwc3_writel(dotg->regs, DWC3_OCFG, 0x4);
/*
* OCTL[6] - PeriMode = 1
* OCTL[5] - PrtPwrCtl = 0
* OCTL[4] - HNPReq = 0
* OCTL[3] - SesReq = 0
* OCTL[2] - TermSelDLPulse = 0
* OCTL[1] - DevSetHNPEn = 0
* OCTL[0] - HstSetHNPEn = 0
*/
if (!once) {
if (ext_xceiv && !ext_xceiv->otg_capability)
dwc3_writel(dotg->regs, DWC3_OCTL, 0x40);
once++;
}
/* Clear all otg events (interrupts) indications */
dwc3_writel(dotg->regs, DWC3_OEVT, 0xFFFF);
/* Enable ID/BSV StsChngEn event*/
if (ext_xceiv && !ext_xceiv->otg_capability)
dwc3_writel(dotg->regs, DWC3_OEVTEN,
DWC3_OEVTEN_OTGCONIDSTSCHNGEVNT |
DWC3_OEVTEN_OTGBDEVVBUSCHNGEVNT);
}
/**
* dwc3_otg_init - Initializes otg related registers
* @dwc: Pointer to out controller context structure
*
* Returns 0 on success otherwise negative errno.
*/
int dwc3_otg_init(struct dwc3 *dwc)
{
u32 reg;
int ret = 0;
struct dwc3_otg *dotg;
dev_dbg(dwc->dev, "dwc3_otg_init\n");
/*
* GHWPARAMS6[10] bit is SRPSupport.
* This bit also reflects DWC_USB3_EN_OTG
*/
reg = dwc3_readl(dwc->regs, DWC3_GHWPARAMS6);
if (!(reg & DWC3_GHWPARAMS6_SRP_SUPPORT)) {
/*
* No OTG support in the HW core.
* We return 0 to indicate no error, since this is acceptable
* situation, just continue probe the dwc3 driver without otg.
*/
dev_dbg(dwc->dev, "dwc3_otg address space is not supported\n");
return 0;
}
/* Allocate and init otg instance */
dotg = kzalloc(sizeof(struct dwc3_otg), GFP_KERNEL);
if (!dotg) {
dev_err(dwc->dev, "unable to allocate dwc3_otg\n");
return -ENOMEM;
}
/* DWC3 has separate IRQ line for OTG events (ID/BSV etc.) */
dotg->irq = platform_get_irq_byname(to_platform_device(dwc->dev),
"otg_irq");
if (dotg->irq < 0) {
dev_err(dwc->dev, "%s: missing OTG IRQ\n", __func__);
ret = -ENODEV;
goto err1;
}
dotg->regs = dwc->regs;
dotg->otg.set_peripheral = dwc3_otg_set_peripheral;
dotg->otg.set_host = dwc3_otg_set_host;
/* This reference is used by dwc3 modules for checking otg existance */
dwc->dotg = dotg;
dotg->otg.phy = kzalloc(sizeof(struct usb_phy), GFP_KERNEL);
if (!dotg->otg.phy) {
dev_err(dwc->dev, "unable to allocate dwc3_otg.phy\n");
ret = -ENOMEM;
goto err1;
}
dotg->dwc = dwc;
dotg->otg.phy->otg = &dotg->otg;
dotg->otg.phy->dev = dwc->dev;
dotg->otg.phy->set_power = dwc3_otg_set_power;
dotg->otg.phy->set_suspend = dwc3_otg_set_suspend;
ret = usb_set_transceiver(dotg->otg.phy);
if (ret) {
dev_err(dotg->otg.phy->dev,
"%s: failed to set transceiver, already exists\n",
__func__);
goto err2;
}
dotg->otg.phy->state = OTG_STATE_UNDEFINED;
init_completion(&dotg->dwc3_xcvr_vbus_init);
INIT_DELAYED_WORK(&dotg->sm_work, dwc3_otg_sm_work);
ret = request_irq(dotg->irq, dwc3_otg_interrupt, IRQF_SHARED,
"dwc3_otg", dotg);
if (ret) {
dev_err(dotg->otg.phy->dev, "failed to request irq #%d --> %d\n",
dotg->irq, ret);
goto err3;
}
pm_runtime_get(dwc->dev);
return 0;
err3:
cancel_delayed_work_sync(&dotg->sm_work);
usb_set_transceiver(NULL);
err2:
kfree(dotg->otg.phy);
err1:
dwc->dotg = NULL;
kfree(dotg);
return ret;
}
/**
* dwc3_otg_exit
* @dwc: Pointer to out controller context structure
*
* Returns 0 on success otherwise negative errno.
*/
void dwc3_otg_exit(struct dwc3 *dwc)
{
struct dwc3_otg *dotg = dwc->dotg;
/* dotg is null when GHWPARAMS6[10]=SRPSupport=0, see dwc3_otg_init */
if (dotg) {
if (dotg->charger)
dotg->charger->start_detection(dotg->charger, false);
cancel_delayed_work_sync(&dotg->sm_work);
usb_set_transceiver(NULL);
pm_runtime_put(dwc->dev);
free_irq(dotg->irq, dotg);
kfree(dotg->otg.phy);
kfree(dotg);
dwc->dotg = NULL;
}
}
| gpl-2.0 |
anupdw/android-bluez.kernel-backports | drivers/net/wireless/orinoco/fw.c | 23 | 9866 | /* Firmware file reading and download helpers
*
* See copyright notice in main.c
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/firmware.h>
#include <linux/device.h>
#include <linux/module.h>
#include "hermes.h"
#include "hermes_dld.h"
#include "orinoco.h"
#include "fw.h"
/* End markers (for Symbol firmware only) */
#define TEXT_END 0x1A /* End of text header */
struct fw_info {
char *pri_fw;
char *sta_fw;
char *ap_fw;
u32 pda_addr;
u16 pda_size;
};
static const struct fw_info orinoco_fw[] = {
{ NULL, "agere_sta_fw.bin", "agere_ap_fw.bin", 0x00390000, 1000 },
{ NULL, "prism_sta_fw.bin", "prism_ap_fw.bin", 0, 1024 },
{ "symbol_sp24t_prim_fw", "symbol_sp24t_sec_fw", NULL, 0x00003100, 512 }
};
MODULE_FIRMWARE("agere_sta_fw.bin");
MODULE_FIRMWARE("agere_ap_fw.bin");
MODULE_FIRMWARE("prism_sta_fw.bin");
MODULE_FIRMWARE("prism_ap_fw.bin");
MODULE_FIRMWARE("symbol_sp24t_prim_fw");
MODULE_FIRMWARE("symbol_sp24t_sec_fw");
/* Structure used to access fields in FW
* Make sure LE decoding macros are used
*/
struct orinoco_fw_header {
char hdr_vers[6]; /* ASCII string for header version */
__le16 headersize; /* Total length of header */
__le32 entry_point; /* NIC entry point */
__le32 blocks; /* Number of blocks to program */
__le32 block_offset; /* Offset of block data from eof header */
__le32 pdr_offset; /* Offset to PDR data from eof header */
__le32 pri_offset; /* Offset to primary plug data */
__le32 compat_offset; /* Offset to compatibility data*/
char signature[0]; /* FW signature length headersize-20 */
} __packed;
/* Check the range of various header entries. Return a pointer to a
* description of the problem, or NULL if everything checks out. */
static const char *validate_fw(const struct orinoco_fw_header *hdr, size_t len)
{
u16 hdrsize;
if (len < sizeof(*hdr))
return "image too small";
if (memcmp(hdr->hdr_vers, "HFW", 3) != 0)
return "format not recognised";
hdrsize = le16_to_cpu(hdr->headersize);
if (hdrsize > len)
return "bad headersize";
if ((hdrsize + le32_to_cpu(hdr->block_offset)) > len)
return "bad block offset";
if ((hdrsize + le32_to_cpu(hdr->pdr_offset)) > len)
return "bad PDR offset";
if ((hdrsize + le32_to_cpu(hdr->pri_offset)) > len)
return "bad PRI offset";
if ((hdrsize + le32_to_cpu(hdr->compat_offset)) > len)
return "bad compat offset";
/* TODO: consider adding a checksum or CRC to the firmware format */
return NULL;
}
#if defined(CPTCFG_HERMES_CACHE_FW_ON_INIT) || defined(CONFIG_PM_SLEEP)
static inline const struct firmware *
orinoco_cached_fw_get(struct orinoco_private *priv, bool primary)
{
if (primary)
return priv->cached_pri_fw;
else
return priv->cached_fw;
}
#else
#define orinoco_cached_fw_get(priv, primary) (NULL)
#endif
/* Download either STA or AP firmware into the card. */
static int
orinoco_dl_firmware(struct orinoco_private *priv,
const struct fw_info *fw,
int ap)
{
/* Plug Data Area (PDA) */
__le16 *pda;
struct hermes *hw = &priv->hw;
const struct firmware *fw_entry;
const struct orinoco_fw_header *hdr;
const unsigned char *first_block;
const void *end;
const char *firmware;
const char *fw_err;
struct device *dev = priv->dev;
int err = 0;
pda = kzalloc(fw->pda_size, GFP_KERNEL);
if (!pda)
return -ENOMEM;
if (ap)
firmware = fw->ap_fw;
else
firmware = fw->sta_fw;
dev_dbg(dev, "Attempting to download firmware %s\n", firmware);
/* Read current plug data */
err = hw->ops->read_pda(hw, pda, fw->pda_addr, fw->pda_size);
dev_dbg(dev, "Read PDA returned %d\n", err);
if (err)
goto free;
if (!orinoco_cached_fw_get(priv, false)) {
err = request_firmware(&fw_entry, firmware, priv->dev);
if (err) {
dev_err(dev, "Cannot find firmware %s\n", firmware);
err = -ENOENT;
goto free;
}
} else
fw_entry = orinoco_cached_fw_get(priv, false);
hdr = (const struct orinoco_fw_header *) fw_entry->data;
fw_err = validate_fw(hdr, fw_entry->size);
if (fw_err) {
dev_warn(dev, "Invalid firmware image detected (%s). "
"Aborting download\n", fw_err);
err = -EINVAL;
goto abort;
}
/* Enable aux port to allow programming */
err = hw->ops->program_init(hw, le32_to_cpu(hdr->entry_point));
dev_dbg(dev, "Program init returned %d\n", err);
if (err != 0)
goto abort;
/* Program data */
first_block = (fw_entry->data +
le16_to_cpu(hdr->headersize) +
le32_to_cpu(hdr->block_offset));
end = fw_entry->data + fw_entry->size;
err = hermes_program(hw, first_block, end);
dev_dbg(dev, "Program returned %d\n", err);
if (err != 0)
goto abort;
/* Update production data */
first_block = (fw_entry->data +
le16_to_cpu(hdr->headersize) +
le32_to_cpu(hdr->pdr_offset));
err = hermes_apply_pda_with_defaults(hw, first_block, end, pda,
&pda[fw->pda_size / sizeof(*pda)]);
dev_dbg(dev, "Apply PDA returned %d\n", err);
if (err)
goto abort;
/* Tell card we've finished */
err = hw->ops->program_end(hw);
dev_dbg(dev, "Program end returned %d\n", err);
if (err != 0)
goto abort;
/* Check if we're running */
dev_dbg(dev, "hermes_present returned %d\n", hermes_present(hw));
abort:
/* If we requested the firmware, release it. */
if (!orinoco_cached_fw_get(priv, false))
release_firmware(fw_entry);
free:
kfree(pda);
return err;
}
/*
* Process a firmware image - stop the card, load the firmware, reset
* the card and make sure it responds. For the secondary firmware take
* care of the PDA - read it and then write it on top of the firmware.
*/
static int
symbol_dl_image(struct orinoco_private *priv, const struct fw_info *fw,
const unsigned char *image, const void *end,
int secondary)
{
struct hermes *hw = &priv->hw;
int ret = 0;
const unsigned char *ptr;
const unsigned char *first_block;
/* Plug Data Area (PDA) */
__le16 *pda = NULL;
/* Binary block begins after the 0x1A marker */
ptr = image;
while (*ptr++ != TEXT_END);
first_block = ptr;
/* Read the PDA from EEPROM */
if (secondary) {
pda = kzalloc(fw->pda_size, GFP_KERNEL);
if (!pda)
return -ENOMEM;
ret = hw->ops->read_pda(hw, pda, fw->pda_addr, fw->pda_size);
if (ret)
goto free;
}
/* Stop the firmware, so that it can be safely rewritten */
if (priv->stop_fw) {
ret = priv->stop_fw(priv, 1);
if (ret)
goto free;
}
/* Program the adapter with new firmware */
ret = hermes_program(hw, first_block, end);
if (ret)
goto free;
/* Write the PDA to the adapter */
if (secondary) {
size_t len = hermes_blocks_length(first_block, end);
ptr = first_block + len;
ret = hermes_apply_pda(hw, ptr, end, pda,
&pda[fw->pda_size / sizeof(*pda)]);
kfree(pda);
if (ret)
return ret;
}
/* Run the firmware */
if (priv->stop_fw) {
ret = priv->stop_fw(priv, 0);
if (ret)
return ret;
}
/* Reset hermes chip and make sure it responds */
ret = hw->ops->init(hw);
/* hermes_reset() should return 0 with the secondary firmware */
if (secondary && ret != 0)
return -ENODEV;
/* And this should work with any firmware */
if (!hermes_present(hw))
return -ENODEV;
return 0;
free:
kfree(pda);
return ret;
}
/*
* Download the firmware into the card, this also does a PCMCIA soft
* reset on the card, to make sure it's in a sane state.
*/
static int
symbol_dl_firmware(struct orinoco_private *priv,
const struct fw_info *fw)
{
struct device *dev = priv->dev;
int ret;
const struct firmware *fw_entry;
if (!orinoco_cached_fw_get(priv, true)) {
if (request_firmware(&fw_entry, fw->pri_fw, priv->dev) != 0) {
dev_err(dev, "Cannot find firmware: %s\n", fw->pri_fw);
return -ENOENT;
}
} else
fw_entry = orinoco_cached_fw_get(priv, true);
/* Load primary firmware */
ret = symbol_dl_image(priv, fw, fw_entry->data,
fw_entry->data + fw_entry->size, 0);
if (!orinoco_cached_fw_get(priv, true))
release_firmware(fw_entry);
if (ret) {
dev_err(dev, "Primary firmware download failed\n");
return ret;
}
if (!orinoco_cached_fw_get(priv, false)) {
if (request_firmware(&fw_entry, fw->sta_fw, priv->dev) != 0) {
dev_err(dev, "Cannot find firmware: %s\n", fw->sta_fw);
return -ENOENT;
}
} else
fw_entry = orinoco_cached_fw_get(priv, false);
/* Load secondary firmware */
ret = symbol_dl_image(priv, fw, fw_entry->data,
fw_entry->data + fw_entry->size, 1);
if (!orinoco_cached_fw_get(priv, false))
release_firmware(fw_entry);
if (ret)
dev_err(dev, "Secondary firmware download failed\n");
return ret;
}
int orinoco_download(struct orinoco_private *priv)
{
int err = 0;
/* Reload firmware */
switch (priv->firmware_type) {
case FIRMWARE_TYPE_AGERE:
/* case FIRMWARE_TYPE_INTERSIL: */
err = orinoco_dl_firmware(priv,
&orinoco_fw[priv->firmware_type], 0);
break;
case FIRMWARE_TYPE_SYMBOL:
err = symbol_dl_firmware(priv,
&orinoco_fw[priv->firmware_type]);
break;
case FIRMWARE_TYPE_INTERSIL:
break;
}
/* TODO: if we fail we probably need to reinitialise
* the driver */
return err;
}
#if defined(CPTCFG_HERMES_CACHE_FW_ON_INIT) || defined(CONFIG_PM_SLEEP)
void orinoco_cache_fw(struct orinoco_private *priv, int ap)
{
const struct firmware *fw_entry = NULL;
const char *pri_fw;
const char *fw;
pri_fw = orinoco_fw[priv->firmware_type].pri_fw;
if (ap)
fw = orinoco_fw[priv->firmware_type].ap_fw;
else
fw = orinoco_fw[priv->firmware_type].sta_fw;
if (pri_fw) {
if (request_firmware(&fw_entry, pri_fw, priv->dev) == 0)
priv->cached_pri_fw = fw_entry;
}
if (fw) {
if (request_firmware(&fw_entry, fw, priv->dev) == 0)
priv->cached_fw = fw_entry;
}
}
void orinoco_uncache_fw(struct orinoco_private *priv)
{
release_firmware(priv->cached_pri_fw);
release_firmware(priv->cached_fw);
priv->cached_pri_fw = NULL;
priv->cached_fw = NULL;
}
#endif
| gpl-2.0 |
hoholee12/util-linux | login-utils/utmpdump.c | 23 | 9517 | /*
* utmpdump
*
* Simple program to dump UTMP and WTMP files in raw format, so they can be
* examined.
*
* Based on utmpdump dump from sysvinit suite.
*
* Copyright (C) 1991-2000 Miquel van Smoorenburg <miquels@cistron.nl>
*
* Copyright (C) 1998 Danek Duvall <duvall@alumni.princeton.edu>
* Copyright (C) 2012 Karel Zak <kzak@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.
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utmp.h>
#include <time.h>
#include <ctype.h>
#include <getopt.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#ifdef HAVE_INOTIFY_INIT
#include <sys/inotify.h>
#endif
#include "c.h"
#include "nls.h"
#include "xalloc.h"
#include "closestream.h"
static char *timetostr(const time_t time)
{
static char s[29]; /* [Sun Sep 01 00:00:00 1998 PST] */
struct tm *tmp;
if (time != 0 && (tmp = localtime(&time)))
strftime(s, 29, "%a %b %d %T %Y %Z", tmp);
else
s[0] = '\0';
return s;
}
static time_t strtotime(const char *s_time)
{
struct tm tm;
memset(&tm, '\0', sizeof(struct tm));
if (s_time[0] == ' ' || s_time[0] == '\0')
return (time_t)0;
strptime(s_time, "%a %b %d %T %Y", &tm);
/* Cheesy way of checking for DST */
if (s_time[26] == 'D')
tm.tm_isdst = 1;
return mktime(&tm);
}
#define cleanse(x) xcleanse(x, sizeof(x))
static void xcleanse(char *s, int len)
{
for ( ; *s && len-- > 0; s++)
if (!isprint(*s) || *s == '[' || *s == ']')
*s = '?';
}
static void print_utline(struct utmp *ut, FILE *out)
{
const char *addr_string, *time_string;
char buffer[INET6_ADDRSTRLEN];
if (ut->ut_addr_v6[1] || ut->ut_addr_v6[2] || ut->ut_addr_v6[3])
addr_string = inet_ntop(AF_INET6, &(ut->ut_addr_v6), buffer, sizeof(buffer));
else
addr_string = inet_ntop(AF_INET, &(ut->ut_addr_v6), buffer, sizeof(buffer));
#if defined(_HAVE_UT_TV)
time_string = timetostr(ut->ut_tv.tv_sec);
#else
time_string = timetostr((time_t)ut->ut_time); /* ut_time is not always a time_t */
#endif
cleanse(ut->ut_id);
cleanse(ut->ut_user);
cleanse(ut->ut_line);
cleanse(ut->ut_host);
/* pid id user line host addr time */
fprintf(out, "[%d] [%05d] [%-4.4s] [%-*.*s] [%-*.*s] [%-*.*s] [%-15s] [%-28.28s]\n",
ut->ut_type, ut->ut_pid, ut->ut_id, 8, UT_NAMESIZE, ut->ut_user,
12, UT_LINESIZE, ut->ut_line, 20, UT_HOSTSIZE, ut->ut_host,
addr_string, time_string);
}
#ifdef HAVE_INOTIFY_INIT
#define EVENTS (IN_MODIFY|IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT)
#define NEVENTS 4
static void roll_file(const char *filename, off_t *size, FILE *out)
{
FILE *in;
struct stat st;
struct utmp ut;
off_t pos;
if (!(in = fopen(filename, "r")))
err(EXIT_FAILURE, _("cannot open %s"), filename);
if (fstat(fileno(in), &st) == -1)
err(EXIT_FAILURE, _("stat of %s failed"), filename);
if (st.st_size == *size)
goto done;
if (fseek(in, *size, SEEK_SET) != (off_t) -1) {
while (fread(&ut, sizeof(ut), 1, in) == 1)
print_utline(&ut, out);
}
pos = ftello(in);
/* If we've successfully read something, use the file position, this
* avoids data duplication. If we read nothing or hit an error,
* reset to the reported size, this handles truncated files.
*/
*size = (pos != -1 && pos != *size) ? pos : st.st_size;
done:
fclose(in);
}
static int follow_by_inotify(FILE *in, const char *filename, FILE *out)
{
char buf[NEVENTS * sizeof(struct inotify_event)];
int fd, wd, event;
ssize_t length;
off_t size;
fd = inotify_init();
if (fd == -1)
return -1; /* probably reached any limit ... */
size = ftello(in);
fclose(in);
wd = inotify_add_watch(fd, filename, EVENTS);
if (wd == -1)
err(EXIT_FAILURE, _("%s: cannot add inotify watch."), filename);
while (wd >= 0) {
errno = 0;
length = read(fd, buf, sizeof(buf));
if (length < 0 && (errno == EINTR || errno == EAGAIN))
continue;
if (length < 0)
err(EXIT_FAILURE, _("%s: cannot read inotify events"),
filename);
for (event = 0; event < length;) {
struct inotify_event *ev =
(struct inotify_event *) &buf[event];
if (ev->mask & IN_MODIFY)
roll_file(filename, &size, out);
else {
close(wd);
wd = -1;
break;
}
event += sizeof(struct inotify_event) + ev->len;
}
}
close(fd);
return 0;
}
#endif /* HAVE_INOTIFY_INIT */
static FILE *dump(FILE *in, const char *filename, int follow, FILE *out)
{
struct utmp ut;
if (follow)
ignore_result( fseek(in, -10 * sizeof(ut), SEEK_END) );
while (fread(&ut, sizeof(ut), 1, in) == 1)
print_utline(&ut, out);
if (!follow)
return in;
#ifdef HAVE_INOTIFY_INIT
if (follow_by_inotify(in, filename, out) == 0)
return NULL; /* file already closed */
else
#endif
/* fallback for systems without inotify or with non-free
* inotify instances */
for (;;) {
while (fread(&ut, sizeof(ut), 1, in) == 1)
print_utline(&ut, out);
sleep(1);
}
return in;
}
/* This function won't work properly if there's a ']' or a ' ' in the real
* token. Thankfully, this should never happen. */
static int gettok(char *line, char *dest, int size, int eatspace)
{
int bpos, epos, eaten;
bpos = strchr(line, '[') - line;
if (bpos < 0)
errx(EXIT_FAILURE, _("Extraneous newline in file. Exiting."));
line += 1 + bpos;
epos = strchr(line, ']') - line;
if (epos < 0)
errx(EXIT_FAILURE, _("Extraneous newline in file. Exiting."));
line[epos] = '\0';
eaten = bpos + epos + 1;
if (eatspace) {
char *t;
if ((t = strchr(line, ' ')))
*t = 0;
}
strncpy(dest, line, size);
return eaten + 1;
}
static void undump(FILE *in, FILE *out)
{
struct utmp ut;
char s_addr[INET6_ADDRSTRLEN + 1], s_time[29], *linestart, *line;
int count = 0;
linestart = xmalloc(1024 * sizeof(*linestart));
s_time[28] = 0;
while (fgets(linestart, 1023, in)) {
line = linestart;
memset(&ut, '\0', sizeof(ut));
sscanf(line, "[%hd] [%d] [%4c] ", &ut.ut_type, &ut.ut_pid, ut.ut_id);
line += 19;
line += gettok(line, ut.ut_user, sizeof(ut.ut_user), 1);
line += gettok(line, ut.ut_line, sizeof(ut.ut_line), 1);
line += gettok(line, ut.ut_host, sizeof(ut.ut_host), 1);
line += gettok(line, s_addr, sizeof(s_addr) - 1, 1);
gettok(line, s_time, sizeof(s_time) - 1, 0);
if (strchr(s_addr, '.'))
inet_pton(AF_INET, s_addr, &(ut.ut_addr_v6));
else
inet_pton(AF_INET6, s_addr, &(ut.ut_addr_v6));
#if defined(_HAVE_UT_TV)
ut.ut_tv.tv_sec = strtotime(s_time);
#else
ut.ut_time = strtotime(s_time);
#endif
ignore_result( fwrite(&ut, sizeof(ut), 1, out) );
++count;
}
free(linestart);
}
static void __attribute__((__noreturn__)) usage(FILE *out)
{
fputs(USAGE_HEADER, out);
fprintf(out,
_(" %s [options] [filename]\n"), program_invocation_short_name);
fputs(USAGE_SEPARATOR, out);
fputs(_("Dump UTMP and WTMP files in raw format.\n"), out);
fputs(USAGE_OPTIONS, out);
fputs(_(" -f, --follow output appended data as the file grows\n"), out);
fputs(_(" -r, --reverse write back dumped data into utmp file\n"), out);
fputs(_(" -o, --output <file> write to file instead of standard output\n"), out);
fputs(USAGE_HELP, out);
fputs(USAGE_VERSION, out);
fprintf(out, USAGE_MAN_TAIL("utmpdump(1)"));
exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}
int main(int argc, char **argv)
{
int c;
FILE *in = NULL, *out = NULL;
int reverse = 0, follow = 0;
const char *filename = NULL;
static const struct option longopts[] = {
{ "follow", 0, 0, 'f' },
{ "reverse", 0, 0, 'r' },
{ "output", required_argument, 0, 'o' },
{ "help", 0, 0, 'h' },
{ "version", 0, 0, 'V' },
{ NULL, 0, 0, 0 }
};
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
atexit(close_stdout);
while ((c = getopt_long(argc, argv, "fro:hV", longopts, NULL)) != -1) {
switch (c) {
case 'r':
reverse = 1;
break;
case 'f':
follow = 1;
break;
case 'o':
out = fopen(optarg, "w");
if (!out)
err(EXIT_FAILURE, _("cannot open %s"),
optarg);
break;
case 'h':
usage(stdout);
break;
case 'V':
printf(UTIL_LINUX_VERSION);
return EXIT_SUCCESS;
default:
usage(stderr);
}
}
if (!out)
out = stdout;
if (optind < argc) {
filename = argv[optind];
in = fopen(filename, "r");
if (!in)
err(EXIT_FAILURE, _("cannot open %s"), filename);
} else {
if (follow)
errx(EXIT_FAILURE, _("following standard input is unsupported"));
filename = "/dev/stdin";
in = stdin;
}
if (reverse) {
fprintf(stderr, _("Utmp undump of %s\n"), filename);
undump(in, out);
} else {
fprintf(stderr, _("Utmp dump of %s\n"), filename);
in = dump(in, filename, follow, out);
}
if (out != stdout)
if (close_stream(out))
err(EXIT_FAILURE, _("write failed"));
if (in && in != stdin)
fclose(in);
return EXIT_SUCCESS;
}
| gpl-2.0 |
Jairus980/kernel_hltexx | drivers/usb/gadget/f_acm.c | 279 | 31499 | /*
* f_acm.c -- USB CDC serial (ACM) function driver
*
* Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
* Copyright (C) 2008 by David Brownell
* Copyright (C) 2008 by Nokia Corporation
* Copyright (C) 2009 by Samsung Electronics
* Copyright (c) 2011 The Linux Foundation. All rights reserved.
* Author: Michal Nazarewicz (mina86@mina86.com)
*
* This software is distributed under the terms of the GNU General
* Public License ("GPL") as published by the Free Software Foundation,
* either version 2 of that License or (at your option) any later version.
*/
/* #define VERBOSE_DEBUG */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
#include <linux/usb/android_composite.h>
#include <mach/usb_gadget_xport.h>
#endif
#include "u_serial.h"
#include "gadget_chips.h"
/*
* This CDC ACM function support just wraps control functions and
* notifications around the generic serial-over-usb code.
*
* Because CDC ACM is standardized by the USB-IF, many host operating
* systems have drivers for it. Accordingly, ACM is the preferred
* interop solution for serial-port type connections. The control
* models are often not necessary, and in any case don't do much in
* this bare-bones implementation.
*
* Note that even MS-Windows has some support for ACM. However, that
* support is somewhat broken because when you use ACM in a composite
* device, having multiple interfaces confuses the poor OS. It doesn't
* seem to understand CDC Union descriptors. The new "association"
* descriptors (roughly equivalent to CDC Unions) may sometimes help.
*/
struct f_acm {
struct gserial port;
u8 ctrl_id, data_id;
u8 port_num;
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
enum transport_type transport;
#endif
u8 pending;
/* lock is mostly for pending and notify_req ... they get accessed
* by callbacks both from tty (open/close/break) under its spinlock,
* and notify_req.complete() which can't use that lock.
*/
spinlock_t lock;
struct usb_ep *notify;
struct usb_request *notify_req;
struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
/* SetControlLineState request -- CDC 1.1 section 6.2.14 (INPUT) */
u16 port_handshake_bits;
#define ACM_CTRL_RTS (1 << 1) /* unused with full duplex */
#define ACM_CTRL_DTR (1 << 0) /* host is ready for data r/w */
/* SerialState notification -- CDC 1.1 section 6.3.5 (OUTPUT) */
u16 serial_state;
#define ACM_CTRL_OVERRUN (1 << 6)
#define ACM_CTRL_PARITY (1 << 5)
#define ACM_CTRL_FRAMING (1 << 4)
#define ACM_CTRL_RI (1 << 3)
#define ACM_CTRL_BRK (1 << 2)
#define ACM_CTRL_DSR (1 << 1)
#define ACM_CTRL_DCD (1 << 0)
};
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
static unsigned int no_acm_tty_ports;
static unsigned int no_acm_sdio_ports;
static unsigned int no_acm_smd_ports;
static unsigned int nr_acm_ports;
static unsigned int no_acm_hsic_sports;
static struct acm_port_info {
enum transport_type transport;
unsigned port_num;
unsigned client_port_num;
} gacm_ports[GSERIAL_NO_PORTS];
#endif
static inline struct f_acm *func_to_acm(struct usb_function *f)
{
return container_of(f, struct f_acm, port.func);
}
static inline struct f_acm *port_to_acm(struct gserial *p)
{
return container_of(p, struct f_acm, port);
}
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
static int acm_port_setup(struct usb_configuration *c)
{
int ret = 0;
int port_idx=0;
int i=0;
pr_debug("%s: no_acm_tty_ports:%u no_acm_sdio_ports: %u nr_acm_ports:%u\n",
__func__, no_acm_tty_ports, no_acm_sdio_ports,
nr_acm_ports);
if (no_acm_tty_ports)
ret = gserial_setup(c->cdev->gadget, no_acm_tty_ports);
if (no_acm_sdio_ports)
ret = gsdio_setup(c->cdev->gadget, no_acm_sdio_ports);
if (no_acm_smd_ports)
ret = gsmd_setup(c->cdev->gadget, no_acm_smd_ports);
if (no_acm_hsic_sports) {
port_idx = ghsic_data_setup(no_acm_hsic_sports,
USB_GADGET_SERIAL);
if (port_idx < 0)
return port_idx;
for (i = 0; i < nr_acm_ports; i++) {
if (gacm_ports[i].transport ==
USB_GADGET_XPORT_HSIC) {
gacm_ports[i].client_port_num = port_idx;
port_idx++;
}
}
/*clinet port num is same for data setup and ctrl setup*/
ret = ghsic_ctrl_setup(no_acm_hsic_sports, USB_GADGET_SERIAL);
if (ret < 0)
return ret;
return 0;
}
return ret;
}
static int acm_port_connect(struct f_acm *acm)
{
unsigned port_num;
int ret=0;
port_num = gacm_ports[acm->port_num].client_port_num;
pr_debug("%s: transport:%s f_acm:%p gserial:%p port_num:%d cl_port_no:%d\n",
__func__, xport_to_str(acm->transport),
acm, &acm->port, acm->port_num, port_num);
switch (acm->transport) {
case USB_GADGET_XPORT_TTY:
gserial_connect(&acm->port, port_num);
break;
case USB_GADGET_XPORT_SDIO:
gsdio_connect(&acm->port, port_num);
break;
case USB_GADGET_XPORT_SMD:
gsmd_connect(&acm->port, port_num);
break;
case USB_GADGET_XPORT_HSIC:
ret = ghsic_ctrl_connect(&acm->port, port_num);
if (ret) {
pr_err("%s: ghsic_ctrl_connect failed: err:%d\n",
__func__, ret);
return ret;
}
ret = ghsic_data_connect(&acm->port, port_num);
if (ret) {
pr_err("%s: ghsic_data_connect failed: err:%d\n",
__func__, ret);
ghsic_ctrl_disconnect(&acm->port, port_num);
return ret;
}
break;
default:
pr_err("%s: Un-supported transport: %s\n", __func__,
xport_to_str(acm->transport));
return -ENODEV;
}
return 0;
}
static int acm_port_disconnect(struct f_acm *acm)
{
unsigned port_num;
port_num = gacm_ports[acm->port_num].client_port_num;
pr_debug("%s: transport:%s f_acm:%p gserial:%p port_num:%d cl_pno:%d\n",
__func__, xport_to_str(acm->transport),
acm, &acm->port, acm->port_num, port_num);
switch (acm->transport) {
case USB_GADGET_XPORT_TTY:
gserial_disconnect(&acm->port);
break;
case USB_GADGET_XPORT_SDIO:
gsdio_disconnect(&acm->port, port_num);
break;
case USB_GADGET_XPORT_SMD:
gsmd_disconnect(&acm->port, port_num);
break;
case USB_GADGET_XPORT_HSIC:
ghsic_ctrl_disconnect(&acm->port, port_num);
ghsic_data_disconnect(&acm->port, port_num);
break;
default:
pr_err("%s: Un-supported transport:%s\n", __func__,
xport_to_str(acm->transport));
return -ENODEV;
}
return 0;
}
#endif
/*-------------------------------------------------------------------------*/
/* notification endpoint uses smallish and infrequent fixed-size messages */
#define GS_LOG2_NOTIFY_INTERVAL 5 /* 1 << 5 == 32 msec */
#define GS_NOTIFY_MAXPACKET 10 /* notification + 2 bytes */
/* interface and class descriptors: */
static struct usb_interface_assoc_descriptor
acm_iad_descriptor = {
.bLength = sizeof acm_iad_descriptor,
.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
/* .bFirstInterface = DYNAMIC, */
.bInterfaceCount = 2, // control + data
.bFunctionClass = USB_CLASS_COMM,
.bFunctionSubClass = USB_CDC_SUBCLASS_ACM,
.bFunctionProtocol = USB_CDC_ACM_PROTO_AT_V25TER,
/* .iFunction = DYNAMIC */
};
static struct usb_interface_descriptor acm_control_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
.bInterfaceProtocol = USB_CDC_ACM_PROTO_AT_V25TER,
/* .iInterface = DYNAMIC */
};
static struct usb_interface_descriptor acm_data_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
static struct usb_cdc_header_desc acm_header_desc = {
.bLength = sizeof(acm_header_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static struct usb_cdc_call_mgmt_descriptor
acm_call_mgmt_descriptor = {
.bLength = sizeof(acm_call_mgmt_descriptor),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
.bmCapabilities = 0,
/* .bDataInterface = DYNAMIC */
};
static struct usb_cdc_acm_descriptor acm_descriptor = {
.bLength = sizeof(acm_descriptor),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ACM_TYPE,
.bmCapabilities = USB_CDC_CAP_LINE,
};
static struct usb_cdc_union_desc acm_union_desc = {
.bLength = sizeof(acm_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor acm_fs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(GS_NOTIFY_MAXPACKET),
.bInterval = 1 << GS_LOG2_NOTIFY_INTERVAL,
};
static struct usb_endpoint_descriptor acm_fs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor acm_fs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *acm_fs_function[] = {
(struct usb_descriptor_header *) &acm_iad_descriptor,
(struct usb_descriptor_header *) &acm_control_interface_desc,
(struct usb_descriptor_header *) &acm_header_desc,
(struct usb_descriptor_header *) &acm_call_mgmt_descriptor,
(struct usb_descriptor_header *) &acm_descriptor,
(struct usb_descriptor_header *) &acm_union_desc,
(struct usb_descriptor_header *) &acm_fs_notify_desc,
(struct usb_descriptor_header *) &acm_data_interface_desc,
(struct usb_descriptor_header *) &acm_fs_in_desc,
(struct usb_descriptor_header *) &acm_fs_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor acm_hs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(GS_NOTIFY_MAXPACKET),
.bInterval = GS_LOG2_NOTIFY_INTERVAL+4,
};
static struct usb_endpoint_descriptor acm_hs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor acm_hs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *acm_hs_function[] = {
(struct usb_descriptor_header *) &acm_iad_descriptor,
(struct usb_descriptor_header *) &acm_control_interface_desc,
(struct usb_descriptor_header *) &acm_header_desc,
(struct usb_descriptor_header *) &acm_call_mgmt_descriptor,
(struct usb_descriptor_header *) &acm_descriptor,
(struct usb_descriptor_header *) &acm_union_desc,
(struct usb_descriptor_header *) &acm_hs_notify_desc,
(struct usb_descriptor_header *) &acm_data_interface_desc,
(struct usb_descriptor_header *) &acm_hs_in_desc,
(struct usb_descriptor_header *) &acm_hs_out_desc,
NULL,
};
static struct usb_endpoint_descriptor acm_ss_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_endpoint_descriptor acm_ss_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_ss_ep_comp_descriptor acm_ss_bulk_comp_desc = {
.bLength = sizeof acm_ss_bulk_comp_desc,
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
};
static struct usb_descriptor_header *acm_ss_function[] = {
(struct usb_descriptor_header *) &acm_iad_descriptor,
(struct usb_descriptor_header *) &acm_control_interface_desc,
(struct usb_descriptor_header *) &acm_header_desc,
(struct usb_descriptor_header *) &acm_call_mgmt_descriptor,
(struct usb_descriptor_header *) &acm_descriptor,
(struct usb_descriptor_header *) &acm_union_desc,
(struct usb_descriptor_header *) &acm_hs_notify_desc,
(struct usb_descriptor_header *) &acm_ss_bulk_comp_desc,
(struct usb_descriptor_header *) &acm_data_interface_desc,
(struct usb_descriptor_header *) &acm_ss_in_desc,
(struct usb_descriptor_header *) &acm_ss_bulk_comp_desc,
(struct usb_descriptor_header *) &acm_ss_out_desc,
(struct usb_descriptor_header *) &acm_ss_bulk_comp_desc,
NULL,
};
/* string descriptors: */
#define ACM_CTRL_IDX 0
#define ACM_DATA_IDX 1
#define ACM_IAD_IDX 2
/* static strings, in UTF-8 */
static struct usb_string acm_string_defs[] = {
[ACM_CTRL_IDX].s = "CDC Abstract Control Model (ACM)",
[ACM_DATA_IDX].s = "CDC ACM Data",
[ACM_IAD_IDX ].s = "CDC Serial",
{ /* ZEROES END LIST */ },
};
static struct usb_gadget_strings acm_string_table = {
.language = 0x0409, /* en-us */
.strings = acm_string_defs,
};
static struct usb_gadget_strings *acm_strings[] = {
&acm_string_table,
NULL,
};
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
static int acm_notify_serial_state(struct f_acm *acm);
#endif
/*-------------------------------------------------------------------------*/
/* ACM control ... data handling is delegated to tty library code.
* The main task of this function is to activate and deactivate
* that code based on device state; track parameters like line
* speed, handshake state, and so on; and issue notifications.
*/
static void acm_complete_set_line_coding(struct usb_ep *ep,
struct usb_request *req)
{
struct f_acm *acm = ep->driver_data;
struct usb_composite_dev *cdev = acm->port.func.config->cdev;
if (req->status != 0) {
DBG(cdev, "acm ttyGS%d completion, err %d\n",
acm->port_num, req->status);
return;
}
/* normal completion */
if (req->actual != sizeof(acm->port_line_coding)) {
DBG(cdev, "acm ttyGS%d short resp, len %d\n",
acm->port_num, req->actual);
usb_ep_set_halt(ep);
} else {
struct usb_cdc_line_coding *value = req->buf;
/* REVISIT: we currently just remember this data.
* If we change that, (a) validate it first, then
* (b) update whatever hardware needs updating,
* (c) worry about locking. This is information on
* the order of 9600-8-N-1 ... most of which means
* nothing unless we control a real RS232 line.
*/
acm->port_line_coding = *value;
}
}
static int acm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_acm *acm = func_to_acm(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything except
* CDC class messages; interface activation uses set_alt().
*
* Note CDC spec table 4 lists the ACM request profile. It requires
* encapsulated command support ... we don't handle any, and respond
* to them by stalling. Options include get/set/clear comm features
* (not that useful) and SEND_BREAK.
*/
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
/* SET_LINE_CODING ... just read and save what the host sends */
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_REQ_SET_LINE_CODING:
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
if (w_length != sizeof(struct usb_cdc_line_coding))
#else
if (w_length != sizeof(struct usb_cdc_line_coding)
|| w_index != acm->ctrl_id)
#endif
goto invalid;
value = w_length;
cdev->gadget->ep0->driver_data = acm;
req->complete = acm_complete_set_line_coding;
break;
/* GET_LINE_CODING ... return what host sent, or initial value */
case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_REQ_GET_LINE_CODING:
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
if (w_index != acm->ctrl_id)
goto invalid;
#endif
value = min_t(unsigned, w_length,
sizeof(struct usb_cdc_line_coding));
memcpy(req->buf, &acm->port_line_coding, value);
break;
/* SET_CONTROL_LINE_STATE ... save what the host sent */
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_REQ_SET_CONTROL_LINE_STATE:
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
if (w_index != acm->ctrl_id)
goto invalid;
#endif
value = 0;
/* FIXME we should not allow data to flow until the
* host sets the ACM_CTRL_DTR bit; and when it clears
* that bit, we should return to that no-flow state.
*/
acm->port_handshake_bits = w_value;
#ifdef CONFIG_USB_DUN_SUPPORT
notify_control_line_state((unsigned long)w_value);
#endif
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
if (acm->port.notify_modem) {
unsigned port_num =
gacm_ports[acm->port_num].client_port_num;
acm->port.notify_modem(&acm->port, port_num, w_value);
}
#endif
break;
default:
invalid:
VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "acm ttyGS%d req%02x.%02x v%04x i%04x l%d\n",
acm->port_num, ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = 0;
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "acm response on ttyGS%d, err %d\n",
acm->port_num, value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int acm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_acm *acm = func_to_acm(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* we know alt == 0, so this is an activation or a reset */
if (intf == acm->ctrl_id) {
if (acm->notify->driver_data) {
VDBG(cdev, "reset acm control interface %d\n", intf);
usb_ep_disable(acm->notify);
} else {
VDBG(cdev, "init acm ctrl interface %d\n", intf);
}
if (config_ep_by_speed(cdev->gadget, f, acm->notify))
return -EINVAL;
usb_ep_enable(acm->notify);
acm->notify->driver_data = acm;
} else if (intf == acm->data_id) {
if (acm->port.in->driver_data) {
DBG(cdev, "reset acm ttyGS%d\n", acm->port_num);
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
gserial_disconnect(&acm->port);
#else
acm_port_disconnect(acm);
#endif
}
if (!acm->port.in->desc || !acm->port.out->desc) {
DBG(cdev, "activate acm ttyGS%d\n", acm->port_num);
if (config_ep_by_speed(cdev->gadget, f,
acm->port.in) ||
config_ep_by_speed(cdev->gadget, f,
acm->port.out)) {
acm->port.in->desc = NULL;
acm->port.out->desc = NULL;
return -EINVAL;
}
}
if (config_ep_by_speed(cdev->gadget, f,
acm->port.in) ||
config_ep_by_speed(cdev->gadget, f,
acm->port.out)) {
acm->port.in->desc = NULL;
acm->port.out->desc = NULL;
return -EINVAL;
}
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
gserial_connect(&acm->port, acm->port_num);
#else
acm_port_connect(acm);
#endif
} else
return -EINVAL;
return 0;
}
static void acm_disable(struct usb_function *f)
{
struct f_acm *acm = func_to_acm(f);
struct usb_composite_dev *cdev = f->config->cdev;
DBG(cdev, "acm ttyGS%d deactivated\n", acm->port_num);
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
gserial_disconnect(&acm->port);
#else
acm_port_disconnect(acm);
#endif
usb_ep_disable(acm->notify);
acm->notify->driver_data = NULL;
}
/*-------------------------------------------------------------------------*/
/**
* acm_cdc_notify - issue CDC notification to host
* @acm: wraps host to be notified
* @type: notification type
* @value: Refer to cdc specs, wValue field.
* @data: data to be sent
* @length: size of data
* Context: irqs blocked, acm->lock held, acm_notify_req non-null
*
* Returns zero on success or a negative errno.
*
* See section 6.3.5 of the CDC 1.1 specification for information
* about the only notification we issue: SerialState change.
*/
static int acm_cdc_notify(struct f_acm *acm, u8 type, u16 value,
void *data, unsigned length)
{
struct usb_ep *ep = acm->notify;
struct usb_request *req;
struct usb_cdc_notification *notify;
const unsigned len = sizeof(*notify) + length;
void *buf;
int status;
unsigned char noti_buf[GS_NOTIFY_MAXPACKET];
memset(noti_buf, 0, GS_NOTIFY_MAXPACKET);
req = acm->notify_req;
acm->notify_req = NULL;
acm->pending = false;
req->length = len;
notify = req->buf;
buf = notify + 1;
notify->bmRequestType = USB_DIR_IN | USB_TYPE_CLASS
| USB_RECIP_INTERFACE;
notify->bNotificationType = type;
notify->wValue = cpu_to_le16(value);
notify->wIndex = cpu_to_le16(acm->ctrl_id);
notify->wLength = cpu_to_le16(length);
memcpy(noti_buf, data, length);
memcpy(buf, noti_buf, GS_NOTIFY_MAXPACKET);
memcpy(buf, data, length);
/* ep_queue() can complete immediately if it fills the fifo... */
spin_unlock(&acm->lock);
status = usb_ep_queue(ep, req, GFP_ATOMIC);
spin_lock(&acm->lock);
if (status < 0) {
ERROR(acm->port.func.config->cdev,
"acm ttyGS%d can't notify serial state, %d\n",
acm->port_num, status);
acm->notify_req = req;
}
return status;
}
static int acm_notify_serial_state(struct f_acm *acm)
{
struct usb_composite_dev *cdev = acm->port.func.config->cdev;
int status;
unsigned long flags;
spin_lock_irqsave(&acm->lock, flags);
if (acm->notify_req) {
DBG(cdev, "acm ttyGS%d serial state %04x\n",
acm->port_num, acm->serial_state);
printk(KERN_DEBUG "acm ttyGS%d serial state %04x\n",
acm->port_num, acm->serial_state);
status = acm_cdc_notify(acm, USB_CDC_NOTIFY_SERIAL_STATE,
0, &acm->serial_state, sizeof(acm->serial_state));
} else {
acm->pending = true;
status = 0;
}
spin_unlock_irqrestore(&acm->lock, flags);
return status;
}
static void acm_cdc_notify_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_acm *acm = req->context;
u8 doit = false;
unsigned long flags;
/* on this call path we do NOT hold the port spinlock,
* which is why ACM needs its own spinlock
*/
spin_lock_irqsave(&acm->lock, flags);
if (req->status != -ESHUTDOWN)
doit = acm->pending;
acm->notify_req = req;
spin_unlock_irqrestore(&acm->lock, flags);
if (doit)
acm_notify_serial_state(acm);
}
#ifdef CONFIG_USB_DUN_SUPPORT
void acm_notify(void *dev, u16 state)
{
struct f_acm *acm = (struct f_acm *)dev;
if (acm) {
acm->serial_state = state;
acm_notify_serial_state(acm);
}
}
#endif
/* connect == the TTY link is open */
static void acm_connect(struct gserial *port)
{
struct f_acm *acm = port_to_acm(port);
acm->serial_state |= ACM_CTRL_DSR | ACM_CTRL_DCD;
acm_notify_serial_state(acm);
}
static void acm_disconnect(struct gserial *port)
{
struct f_acm *acm = port_to_acm(port);
acm->serial_state &= ~(ACM_CTRL_DSR | ACM_CTRL_DCD);
acm_notify_serial_state(acm);
}
static int acm_send_break(struct gserial *port, int duration)
{
struct f_acm *acm = port_to_acm(port);
u16 state;
state = acm->serial_state;
state &= ~ACM_CTRL_BRK;
if (duration)
state |= ACM_CTRL_BRK;
acm->serial_state = state;
return acm_notify_serial_state(acm);
}
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
static int acm_send_modem_ctrl_bits(struct gserial *port, int ctrl_bits)
{
struct f_acm *acm = port_to_acm(port);
acm->serial_state = ctrl_bits;
return acm_notify_serial_state(acm);
}
#endif
/*-------------------------------------------------------------------------*/
/* ACM function driver setup/binding */
static int
acm_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_acm *acm = func_to_acm(f);
int status;
struct usb_ep *ep;
/* allocate instance-specific interface IDs, and patch descriptors */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
acm->ctrl_id = status;
acm_iad_descriptor.bFirstInterface = status;
acm_control_interface_desc.bInterfaceNumber = status;
acm_union_desc .bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
acm->data_id = status;
acm_data_interface_desc.bInterfaceNumber = status;
acm_union_desc.bSlaveInterface0 = status;
acm_call_mgmt_descriptor.bDataInterface = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_in_desc);
if (!ep)
goto fail;
acm->port.in = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_out_desc);
if (!ep)
goto fail;
acm->port.out = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_notify_desc);
if (!ep)
goto fail;
acm->notify = ep;
ep->driver_data = cdev; /* claim */
/* allocate notification */
acm->notify_req = gs_alloc_req(ep,
sizeof(struct usb_cdc_notification) + 2,
GFP_KERNEL);
if (!acm->notify_req)
goto fail;
acm->notify_req->complete = acm_cdc_notify_complete;
acm->notify_req->context = acm;
/* copy descriptors */
f->descriptors = usb_copy_descriptors(acm_fs_function);
if (!f->descriptors)
goto fail;
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
if (gadget_is_dualspeed(c->cdev->gadget)) {
acm_hs_in_desc.bEndpointAddress =
acm_fs_in_desc.bEndpointAddress;
acm_hs_out_desc.bEndpointAddress =
acm_fs_out_desc.bEndpointAddress;
acm_hs_notify_desc.bEndpointAddress =
acm_fs_notify_desc.bEndpointAddress;
/* copy descriptors */
f->hs_descriptors = usb_copy_descriptors(acm_hs_function);
if (!f->hs_descriptors)
goto fail;
}
if (gadget_is_superspeed(c->cdev->gadget)) {
acm_ss_in_desc.bEndpointAddress =
acm_fs_in_desc.bEndpointAddress;
acm_ss_out_desc.bEndpointAddress =
acm_fs_out_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->ss_descriptors = usb_copy_descriptors(acm_ss_function);
if (!f->ss_descriptors)
goto fail;
}
DBG(cdev, "acm ttyGS%d: %s speed IN/%s OUT/%s NOTIFY/%s\n",
acm->port_num,
gadget_is_superspeed(c->cdev->gadget) ? "super" :
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
acm->port.in->name, acm->port.out->name,
acm->notify->name);
/* To notify serial state by datarouter*/
#ifdef CONFIG_USB_DUN_SUPPORT
modem_register(acm);
#endif
return 0;
fail:
if (f->hs_descriptors)
usb_free_descriptors(f->hs_descriptors);
if (f->descriptors)
usb_free_descriptors(f->descriptors);
if (acm->notify_req)
gs_free_req(acm->notify, acm->notify_req);
/* we might as well release our claims on endpoints */
if (acm->notify)
acm->notify->driver_data = NULL;
if (acm->port.out)
acm->port.out->driver_data = NULL;
if (acm->port.in)
acm->port.in->driver_data = NULL;
ERROR(cdev, "%s/%p: can't bind, err %d\n", f->name, f, status);
return status;
}
static void
acm_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_acm *acm = func_to_acm(f);
#ifdef CONFIG_USB_DUN_SUPPORT
modem_unregister();
#endif
if (gadget_is_dualspeed(c->cdev->gadget))
usb_free_descriptors(f->hs_descriptors);
if (gadget_is_superspeed(c->cdev->gadget))
usb_free_descriptors(f->ss_descriptors);
usb_free_descriptors(f->descriptors);
gs_free_req(acm->notify, acm->notify_req);
kfree(acm->port.func.name);
kfree(acm);
}
/* Some controllers can't support CDC ACM ... */
static inline bool can_support_cdc(struct usb_configuration *c)
{
/* everything else is *probably* fine ... */
return true;
}
/**
* acm_bind_config - add a CDC ACM function to a configuration
* @c: the configuration to support the CDC ACM instance
* @port_num: /dev/ttyGS* port this interface will use
* Context: single threaded during gadget setup
*
* Returns zero on success, else negative errno.
*
* Caller must have called @gserial_setup() with enough ports to
* handle all the ones it binds. Caller is also responsible
* for calling @gserial_cleanup() before module unload.
*/
int acm_bind_config(struct usb_configuration *c, u8 port_num)
{
struct f_acm *acm;
int status;
if (!can_support_cdc(c))
return -EINVAL;
/* REVISIT might want instance-specific strings to help
* distinguish instances ...
*/
/* maybe allocate device-global string IDs, and patch descriptors */
if (acm_string_defs[ACM_CTRL_IDX].id == 0) {
status = usb_string_id(c->cdev);
if (status < 0)
return status;
acm_string_defs[ACM_CTRL_IDX].id = status;
acm_control_interface_desc.iInterface = status;
status = usb_string_id(c->cdev);
if (status < 0)
return status;
acm_string_defs[ACM_DATA_IDX].id = status;
acm_data_interface_desc.iInterface = status;
status = usb_string_id(c->cdev);
if (status < 0)
return status;
acm_string_defs[ACM_IAD_IDX].id = status;
acm_iad_descriptor.iFunction = status;
}
/* allocate and initialize one new instance */
acm = kzalloc(sizeof *acm, GFP_KERNEL);
if (!acm)
return -ENOMEM;
spin_lock_init(&acm->lock);
acm->port_num = port_num;
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
acm->transport = gacm_ports[port_num].transport;
#endif
acm->port.connect = acm_connect;
acm->port.disconnect = acm_disconnect;
acm->port.send_break = acm_send_break;
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
acm->port.send_modem_ctrl_bits = acm_send_modem_ctrl_bits;
#endif
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
acm->port.func.name = kasprintf(GFP_KERNEL, "acm%u", port_num);
#else
acm->port.func.name = kasprintf(GFP_KERNEL, "acm%u", port_num + 1);
#endif
if (!acm->port.func.name) {
kfree(acm);
return -ENOMEM;
}
acm->port.func.strings = acm_strings;
/* descriptors are per-instance copies */
acm->port.func.bind = acm_bind;
acm->port.func.unbind = acm_unbind;
acm->port.func.set_alt = acm_set_alt;
acm->port.func.setup = acm_setup;
acm->port.func.disable = acm_disable;
status = usb_add_function(c, &acm->port.func);
if (status)
kfree(acm);
return status;
}
#ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
/**
* acm_init_port - bind a acm_port to its transport
*/
static int acm_init_port(int port_num, const char *name)
{
enum transport_type transport;
if (port_num >= GSERIAL_NO_PORTS)
return -ENODEV;
transport = str_to_xport(name);
pr_debug("%s, port:%d, transport:%s\n", __func__,
port_num, xport_to_str(transport));
gacm_ports[port_num].transport = transport;
gacm_ports[port_num].port_num = port_num;
switch (transport) {
case USB_GADGET_XPORT_TTY:
gacm_ports[port_num].client_port_num = no_acm_tty_ports;
no_acm_tty_ports++;
break;
case USB_GADGET_XPORT_SDIO:
gacm_ports[port_num].client_port_num = no_acm_sdio_ports;
no_acm_sdio_ports++;
break;
case USB_GADGET_XPORT_SMD:
gacm_ports[port_num].client_port_num = no_acm_smd_ports;
no_acm_smd_ports++;
break;
case USB_GADGET_XPORT_HSIC:
/*client port number will be updated in acm_port_setup*/
no_acm_hsic_sports++;
break;
default:
pr_err("%s: Un-supported transport transport: %u\n",
__func__, gacm_ports[port_num].transport);
return -ENODEV;
}
nr_acm_ports++;
return 0;
}
#endif
| gpl-2.0 |
jpiolho/portalclassic | dep/ACE_wrappers/ace/ATM_QoS.cpp | 535 | 22397 | // $Id: ATM_QoS.cpp 91286 2010-08-05 09:04:31Z johnnyw $
#include "ace/ATM_QoS.h"
#if defined (ACE_HAS_ATM)
#if !defined (__ACE_INLINE__)
#include "ace/ATM_QoS.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2)
#define BHLI_MAGIC "FORE_ATM"
// This is line rate in cells/s for an OC-3 MM interface.
const long ACE_ATM_QoS::LINE_RATE = 353207;
const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0x1;
const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0x2;
const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x99;
const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 8192;
#elif defined (ACE_HAS_LINUX_ATM)
//pbrandao:for Linux:
//pbrandao:for now stick with current definitions
//pbrandao:see if later need to change
const long ACE_ATM_QoS::LINE_RATE = 353207;
const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0x1;
const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0x2;
const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x99;
const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 8192;
#else
const long ACE_ATM_QoS::LINE_RATE = 0L;
const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0;
const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0;
const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x0;
const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 0;
#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */
ACE_ALLOC_HOOK_DEFINE(ACE_ATM_QoS)
ACE_ATM_QoS::ACE_ATM_QoS (int pktSize)
{
ACE_TRACE ("ACE_ATM_QoS::ACE_ATM_QoS");
#if defined (ACE_HAS_LINUX_ATM)
ACE_OS::memset(&qos_, 0, sizeof(qos_));
qos_.aal = ATM_PROTOCOL_DEFAULT;
qos_.rxtp.traffic_class = ATM_ANYCLASS;
qos_.rxtp.max_sdu = pktSize;
qos_.txtp.traffic_class = ATM_ANYCLASS;
qos_.txtp.max_sdu = pktSize;
#else
ACE_UNUSED_ARG (pktSize);
#endif /* ACE_HAS_LINUX_ATM */
}
ACE_ATM_QoS::ACE_ATM_QoS(int rate,
int pktSize)
{
ACE_TRACE( "ACE_ATM_QoS::ACE_ATM_QoS" );
#if defined (ACE_HAS_FORE_ATM_WS2)
AAL_PARAMETERS_IE ie_aalparams;
ATM_TRAFFIC_DESCRIPTOR_IE ie_td;
ATM_BROADBAND_BEARER_CAPABILITY_IE ie_bbc;
ATM_QOS_CLASS_IE ie_qos;
Q2931_IE *ie_ptr;
int size;
// Setting up cbr parameters ...
ie_aalparams.AALType = AALTYPE_5;
ie_aalparams.AALSpecificParameters.AAL5Parameters.ForwardMaxCPCSSDUSize
= pktSize; // was 1516;
ie_aalparams.AALSpecificParameters.AAL5Parameters.BackwardMaxCPCSSDUSize
= pktSize; // was 1516;
ie_aalparams.AALSpecificParameters.AAL5Parameters.Mode = AAL5_MODE_MESSAGE;
ie_aalparams.AALSpecificParameters.AAL5Parameters.SSCSType = AAL5_SSCS_NULL;
size = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(AAL_PARAMETERS_IE);
ie_td.Forward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Forward.PeakCellRate_CLP01 = rate;
ie_td.Forward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Forward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT;
ie_td.Forward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT;
ie_td.Forward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT;
ie_td.Forward.Tagging = SAP_FIELD_ABSENT;
ie_td.Backward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Backward.PeakCellRate_CLP01 = rate;
ie_td.Backward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Backward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT;
ie_td.Backward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT;
ie_td.Backward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT;
ie_td.Backward.Tagging = SAP_FIELD_ABSENT;
ie_td.BestEffort = 0; // Note: this must be set to zero for CBR.
size += sizeof( Q2931_IE_TYPE )
+ sizeof( ULONG )
+ sizeof( ATM_TRAFFIC_DESCRIPTOR_IE );
ie_bbc.BearerClass = BCOB_X;
ie_bbc.TrafficType = TT_CBR;
ie_bbc.TimingRequirements = TR_END_TO_END;
ie_bbc.ClippingSusceptability = CLIP_NOT;
ie_bbc.UserPlaneConnectionConfig = UP_P2P;
size += sizeof( Q2931_IE_TYPE )
+ sizeof( ULONG )
+ sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE );
ie_qos.QOSClassForward = QOS_CLASS1;
ie_qos.QOSClassBackward = QOS_CLASS1; // This may not be really used
// since we do only simplex data xfer.
size += sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(ATM_QOS_CLASS_IE);
qos_.ProviderSpecific.buf = (char *) ACE_OS::malloc(size);
if (qos_.ProviderSpecific.buf == 0) {
ACE_ERROR((LM_ERROR,
ACE_TEXT ("ACE_ATM_QoS::ACE_ATM_QoS: Unable to allocate %d bytes for qos_.ProviderSpecific.buf\n"),
size));
return;
}
qos_.ProviderSpecific.len = size;
ACE_OS::memset(qos_.ProviderSpecific.buf, 0, size);
ie_ptr = (Q2931_IE *) qos_.ProviderSpecific.buf;
ie_ptr->IEType = IE_AALParameters;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE )
+ sizeof( ULONG )
+ sizeof( AAL_PARAMETERS_IE );
ACE_OS::memcpy(ie_ptr->IE, &ie_aalparams, sizeof(AAL_PARAMETERS_IE));
ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength);
ie_ptr->IEType = IE_TrafficDescriptor;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE )
+ sizeof( ULONG )
+ sizeof( ATM_TRAFFIC_DESCRIPTOR_IE );
ACE_OS::memcpy(ie_ptr->IE, &ie_td, sizeof(ATM_TRAFFIC_DESCRIPTOR_IE));
ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength);
ie_ptr->IEType = IE_BroadbandBearerCapability;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE )
+ sizeof( ULONG )
+ sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE );
ACE_OS::memcpy(ie_ptr->IE,
&ie_bbc,
sizeof(ATM_BROADBAND_BEARER_CAPABILITY_IE));
ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength);
ie_ptr->IEType = IE_QOSClass;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE )
+ sizeof( ULONG )
+ sizeof( ATM_QOS_CLASS_IE );
ACE_OS::memcpy(ie_ptr->IE, &ie_qos, sizeof(ATM_QOS_CLASS_IE));
// qos_.SendingFlowspec.TokenRate = 0xffffffff;
// qos_.SendingFlowspec.TokenBucketSize = 0xffffffff;
// qos_.SendingFlowspec.PeakBandwidth = 0xffffffff;
// qos_.SendingFlowspec.Latency = 0xffffffff;
// qos_.SendingFlowspec.DelayVariation = 0xffffffff;
// qos_.SendingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT;
// This will most probably be ignored by the service provider.
// qos_.SendingFlowspec.MaxSduSize = 0xffffffff;
// qos_.SendingFlowspec.MinimumPolicedSize = 0xffffffff;
// qos_.ReceivingFlowspec.TokenRate = 0xffffffff;
// qos_.ReceivingFlowspec.TokenBucketSize = 0xffffffff;
// qos_.ReceivingFlowspec.PeakBandwidth = 0xffffffff;
// qos_.ReceivingFlowspec.Latency = 0xffffffff;
// qos_.ReceivingFlowspec.DelayVariation = 0xffffffff;
// qos_.ReceivingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT;
// This will most probably be ignored by the service provider.
// qos_.ReceivingFlowspec.MaxSduSize = 0xffffffff;
// qos_.ReceivingFlowspec.MinimumPolicedSize = 0;
ACE_Flow_Spec send_fspec( 0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
SERVICETYPE_BESTEFFORT,
// This will most probably ignored by SP.
0xffffffff,
0xffffffff,
15,
ACE_DEFAULT_THREAD_PRIORITY ),
recv_fspec( 0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
SERVICETYPE_BESTEFFORT,
// This will most probably ignored by SP.
0xffffffff,
0,
15,
ACE_DEFAULT_THREAD_PRIORITY );
qos_.sending_flowspec (send_fspec);
qos_.receiving_flowspec (recv_fspec);
#elif defined (ACE_HAS_FORE_ATM_XTI)
ACE_UNUSED_ARG (rate);
ACE_UNUSED_ARG (pktSize);
#elif defined (ACE_HAS_LINUX_ATM)
ACE_OS::memset(&qos_,
0,
sizeof(qos_));
qos_.aal = ATM_PROTOCOL_DEFAULT;
qos_.rxtp.max_sdu = pktSize;
if (rate > 0) {
qos_.rxtp.pcr = rate;
qos_.rxtp.traffic_class = ATM_CBR;
qos_.txtp.traffic_class = ATM_CBR;
qos_.txtp.pcr = rate;
}
else {
qos_.rxtp.traffic_class = ATM_UBR;
qos_.txtp.traffic_class = ATM_UBR;
}
qos_.txtp.max_sdu = pktSize;
#else
ACE_UNUSED_ARG (rate);
#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */
}
void
ACE_ATM_QoS::set_cbr_rate (int rate,
int pktSize)
{
ACE_TRACE ("ACE_ATM_QoS::set_cbr_rate");
#if defined (ACE_HAS_FORE_ATM_WS2)
/*
AAL_PARAMETERS_IE ie_aalparams;
ATM_TRAFFIC_DESCRIPTOR_IE ie_td;
ATM_BROADBAND_BEARER_CAPABILITY_IE ie_bbc;
ATM_QOS_CLASS_IE ie_qos;
Q2931_IE *ie_ptr;
int size;
*/
ACE_OS::printf( "ATM_QoS(set_cbr_rate): set rate to %d c/s\n", rate );
// Setting up cbr parameters ...
/*
FORE has changed this - we no longer specify QoS this way
ie_aalparams.AALType = AALTYPE_5;
ie_aalparams.AALSpecificParameters.AAL5Parameters.ForwardMaxCPCSSDUSize
= pktSize; // was 1516;
ie_aalparams.AALSpecificParameters.AAL5Parameters.BackwardMaxCPCSSDUSize
= pktSize; // was 1516;
ie_aalparams.AALSpecificParameters.AAL5Parameters.Mode = AAL5_MODE_MESSAGE;
ie_aalparams.AALSpecificParameters.AAL5Parameters.SSCSType = AAL5_SSCS_NULL;
size = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(AAL_PARAMETERS_IE);
ie_td.Forward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Forward.PeakCellRate_CLP01 = rate;
ie_td.Forward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Forward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT;
ie_td.Forward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT;
ie_td.Forward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT;
ie_td.Forward.Tagging = SAP_FIELD_ABSENT;
ie_td.Backward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Backward.PeakCellRate_CLP01 = rate;
ie_td.Backward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT;
ie_td.Backward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT;
ie_td.Backward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT;
ie_td.Backward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT;
ie_td.Backward.Tagging = SAP_FIELD_ABSENT;
ie_td.BestEffort = 0; // Note: this must be set to zero for CBR.
size += sizeof( Q2931_IE_TYPE ) +
sizeof( ULONG ) +
sizeof( ATM_TRAFFIC_DESCRIPTOR_IE );
ie_bbc.BearerClass = BCOB_X;
ie_bbc.TrafficType = TT_CBR;
ie_bbc.TimingRequirements = TR_END_TO_END;
ie_bbc.ClippingSusceptability = CLIP_NOT;
ie_bbc.UserPlaneConnectionConfig = UP_P2P;
size += sizeof(Q2931_IE_TYPE) +
sizeof(ULONG) +
sizeof(ATM_BROADBAND_BEARER_CAPABILITY_IE);
ie_qos.QOSClassForward = QOS_CLASS1;
ie_qos.QOSClassBackward = QOS_CLASS1; // This may not be really used
// since we only simplex data xfer.
size += sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(ATM_QOS_CLASS_IE);
qos_.ProviderSpecific.buf = (char *) ACE_OS::malloc(size);
if (qos_.ProviderSpecific.buf == 0) {
ACE_ERROR((LM_ERROR,
ACE_TEXT ("ACE_ATM_QoS::ACE_ATM_QoS: Unable to allocate %d bytes for qos_.ProviderSpecific.buf\n"),
size));
return;
}
qos_.ProviderSpecific.len = size;
ACE_OS::memset(qos_.ProviderSpecific.buf, 0, size);
ie_ptr = (Q2931_IE *) qos_.ProviderSpecific.buf;
ie_ptr->IEType = IE_AALParameters;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) +
sizeof( ULONG ) +
sizeof( AAL_PARAMETERS_IE );
ACE_OS::memcpy(ie_ptr->IE, &ie_aalparams, sizeof(AAL_PARAMETERS_IE));
ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength);
ie_ptr->IEType = IE_TrafficDescriptor;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) +
sizeof( ULONG ) +
sizeof( ATM_TRAFFIC_DESCRIPTOR_IE );
ACE_OS::memcpy(ie_ptr->IE, &ie_td, sizeof(ATM_TRAFFIC_DESCRIPTOR_IE));
ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength);
ie_ptr->IEType = IE_BroadbandBearerCapability;
ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) +
sizeof( ULONG ) +
sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE );
ACE_OS::memcpy( ie_ptr->IE,
&ie_bbc,
sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ));
ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength);
ie_ptr->IEType = IE_QOSClass;
ie_ptr->IELength = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) +
sizeof(ATM_QOS_CLASS_IE);
ACE_OS::memcpy(ie_ptr->IE, &ie_qos, sizeof(ATM_QOS_CLASS_IE));
*/
const int BYTES_PER_ATM_CELL = 53;
ACE_OS::memset(&qos_, 0, sizeof(ATM_QoS));
// Setting the token rate sets the minimum rate. 3 Mbits/sec seems too high.
// Certainly for Vaudeville audio, we only need about 1000 c/s which is
// 424000 bits/sec which is 53000 bytes/sec.
//qos_.SendingFlowspec.TokenRate = 3*(1024*128); // 3Mbits/sec
qos_.SendingFlowspec.TokenRate = 53000; // 1000 cells/sec
qos_.SendingFlowspec.TokenBucketSize = 32*1024; // our block size
//ourQos.SendingFlowspec.PeakBandwidth = ourQos.SendingFlowspec.TokenRate;
qos_.SendingFlowspec.ServiceType = SERVICETYPE_GUARANTEED;
// Peak bandwidth is in bytes/sec. The rate is specified in cells/sec so
// we need to convert from cells/sec to bytes/sec (i.e., multiply by 53).
qos_.SendingFlowspec.PeakBandwidth = rate * BYTES_PER_ATM_CELL;
qos_.SendingFlowspec.Latency = -1; // we don't care too much
qos_.SendingFlowspec.DelayVariation = -1; // we don't care too much
// no provider-specific data allowed on ATM
qos_.ProviderSpecific.buf=0;
qos_.ProviderSpecific.len=0;
// unidirectional P2MP; we don't need to setup the Receiving flowspec
//qos_.SendingFlowspec.TokenRate = 0xffffffff;
//qos_.SendingFlowspec.TokenBucketSize = 0xffffffff;
//qos_.SendingFlowspec.PeakBandwidth = 0xffffffff;
//qos_.SendingFlowspec.Latency = 0xffffffff;
//qos_.SendingFlowspec.DelayVariation = 0xffffffff;
//qos_.SendingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT;
// This will most probably be ignored by the service provider.
//qos_.SendingFlowspec.MaxSduSize = 0xffffffff;
//qos_.SendingFlowspec.MinimumPolicedSize = 0xffffffff;
//qos_.ReceivingFlowspec.TokenRate = 0xffffffff;
//qos_.ReceivingFlowspec.TokenBucketSize = 0xffffffff;
//qos_.ReceivingFlowspec.PeakBandwidth = 0xffffffff;
//qos_.ReceivingFlowspec.Latency = 0xffffffff;
//qos_.ReceivingFlowspec.DelayVariation = 0xffffffff;
//qos_.ReceivingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT;
// This will most probably be ignored by the service provider.
//qos_.ReceivingFlowspec.MaxSduSize = 0xffffffff;
//qos_.ReceivingFlowspec.MinimumPolicedSize = 0;
/*
ACE_Flow_Spec send_fspec( 0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
SERVICETYPE_BESTEFFORT,
// This will most probably ignored by SP.
0xffffffff,
0xffffffff,
15,
ACE_DEFAULT_THREAD_PRIORITY ),
recv_fspec( 0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
SERVICETYPE_BESTEFFORT,
// This will most probably ignored by SP.
0xffffffff,
0,
15,
ACE_DEFAULT_THREAD_PRIORITY );
qos_.sending_flowspec( send_fspec );
qos_.receiving_flowspec( recv_fspec );
*/
#elif defined (ACE_HAS_FORE_ATM_XTI)
ACE_UNUSED_ARG (rate);
ACE_UNUSED_ARG (pktSize);
#elif defined (ACE_HAS_LINUX_ATM)
ACE_UNUSED_ARG (pktSize);
qos_.rxtp.traffic_class = ATM_CBR;
qos_.rxtp.pcr = rate;
qos_.txtp.traffic_class = ATM_CBR;
qos_.txtp.pcr = rate;
#else
ACE_UNUSED_ARG (rate);
#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */
}
void
ACE_ATM_QoS::set_rate (ACE_HANDLE fd,
int rate,
int flags)
{
ACE_TRACE ("ACE_ATM_QoS::set_rate");
#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM)
set_cbr_rate( rate );
ACE_UNUSED_ARG( fd );
ACE_UNUSED_ARG( flags );
#elif defined (ACE_HAS_FORE_ATM_XTI)
long optlen = 0;
qos_.buf = construct_options(fd,
rate,
flags,
&optlen);
qos_.len = optlen;
#else
ACE_UNUSED_ARG (rate);
#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM || ACE_HAS_FORE_ATM_XTI */
}
char*
ACE_ATM_QoS::construct_options (ACE_HANDLE fd,
int rate,
int flags,
long *len)
{
#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM)
ACE_UNUSED_ARG (fd);
ACE_UNUSED_ARG (rate);
ACE_UNUSED_ARG (flags);
ACE_UNUSED_ARG (len);
return 0;
#elif defined (ACE_HAS_FORE_ATM_XTI)
struct t_opthdr *popt;
char *buf;
int qos_cells;
struct t_info info;
if (ACE_OS::t_getinfo (fd, &info) == -1)
{
ACE_OS::t_error ("t_getinfo");
return 0;
}
buf = (char *) ACE_OS::malloc (info.options);
if (buf == 0)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("Unable to allocate %d bytes for options\n"),
info.options),
0);
popt = (struct t_opthdr *) buf;
if (flags & OPT_FLAGS_CPID)
{
// This constructs the T_ATM_ORIG_ADDR option, which is used to
// signal the UNI 3.1 Calling Party ID Information Element.
t_atm_addr *source_addr;
popt->len = sizeof (struct t_opthdr) + sizeof (t_atm_addr);
popt->level = T_ATM_SIGNALING;
popt->name = T_ATM_ORIG_ADDR;
popt->status = 0;
source_addr =
(t_atm_addr *)((char *) popt + sizeof (struct t_opthdr));
source_addr->address_format = T_ATM_ENDSYS_ADDR;
source_addr->address_length = ATMNSAP_ADDR_LEN;
ATMSAPAddress local_addr;
struct t_bind boundaddr;
boundaddr.addr.maxlen = sizeof(local_addr);
boundaddr.addr.buf = (char *) &local_addr;
//if (ACE_OS::t_getprotaddr(fd, &boundaddr, 0) < 0) {
if (ACE_OS::t_getname(fd,
&boundaddr.addr,
LOCALNAME) < 0)
{
ACE_OS::t_error("t_getname (local_address)");
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("Can't get local address!\n")));
ACE_OS::free (buf);
return 0;
}
ACE_OS::memcpy(source_addr->address,
local_addr.sap.t_atm_sap_addr.address,
ATMNSAP_ADDR_LEN);
popt = T_OPT_NEXTHDR (buf, info.options , popt);
}
// This constructs all options necessary (bearer cap., QoS, and
// Traffic Descriptor) to signal for a CBR connection with the
// specified QoS in kbit/sec., and/or specify a PMP connection.
// For FORE 200e cards, the adapter shapes traffic to CBR with rate
// equal to PCR CLP=0+1 (traffic.forward.PCR_all_traffic)
qos_cells = (rate * 1000) / (48*8);
if ((qos_cells > 0 && qos_cells < LINE_RATE)
|| (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP)))
{
struct t_atm_bearer *bearer;
struct t_atm_traffic *traffic;
// T_ATM_BEARER_CAP: Broadband bearer capability
popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_bearer);
popt->level = T_ATM_SIGNALING;
popt->name = T_ATM_BEARER_CAP;
popt->status = 0;
bearer = (struct t_atm_bearer *)((char *) popt +
sizeof (struct t_opthdr));
bearer->bearer_class = T_ATM_CLASS_X;
if (qos_cells)
{
bearer->traffic_type = T_ATM_CBR;
bearer->timing_requirements = T_ATM_END_TO_END;
}
else
{
bearer->traffic_type = 0; // UBR
bearer->timing_requirements = 0;
}
bearer->clipping_susceptibility = T_ATM_NULL;
if (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP))
bearer->connection_configuration = T_ATM_1_TO_MANY;
else
bearer->connection_configuration = T_ATM_1_TO_1;
popt = T_OPT_NEXTHDR (buf, info.options, popt);
// T_ATM_TRAFFIC: traffic descriptor
popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_traffic);
popt->level = T_ATM_SIGNALING;
popt->name = T_ATM_TRAFFIC;
popt->status = 0;
traffic = (struct t_atm_traffic *)((char *) popt +
sizeof (struct t_opthdr));
traffic->forward.PCR_high_priority = T_ATM_ABSENT;
traffic->forward.PCR_all_traffic = qos_cells ? qos_cells : LINE_RATE;
traffic->forward.SCR_high_priority = T_ATM_ABSENT;
traffic->forward.SCR_all_traffic = T_ATM_ABSENT;
traffic->forward.MBS_high_priority = T_ATM_ABSENT;
traffic->forward.MBS_all_traffic = T_ATM_ABSENT;
traffic->forward.tagging = T_NO;
traffic->backward.PCR_high_priority = T_ATM_ABSENT;
traffic->backward.PCR_all_traffic =
(ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP))
? 0 : qos_cells ? qos_cells : LINE_RATE;
traffic->backward.SCR_high_priority = T_ATM_ABSENT;
traffic->backward.SCR_all_traffic = T_ATM_ABSENT;
traffic->backward.MBS_high_priority = T_ATM_ABSENT;
traffic->backward.MBS_all_traffic = T_ATM_ABSENT;
traffic->backward.tagging = T_NO;
traffic->best_effort = qos_cells ? T_NO : T_YES;
popt = T_OPT_NEXTHDR (buf,
info.options,
popt);
}
if (qos_cells > 0 && qos_cells < LINE_RATE)
{
struct t_atm_qos *qos;
// T_ATM_QOS: Quality of Service
popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_qos);
popt->level = T_ATM_SIGNALING;
popt->name = T_ATM_QOS;
popt->status = 0;
qos = (struct t_atm_qos *)((char *) popt + sizeof (struct t_opthdr));
qos->coding_standard = T_ATM_ITU_CODING;
qos->forward.qos_class = T_ATM_QOS_CLASS_1;
qos->backward.qos_class = T_ATM_QOS_CLASS_1;
popt = T_OPT_NEXTHDR (buf, info.options, popt);
}
// Return actual size of options and option buffer to user.
*len = (char *) popt - buf;
return buf;
#else
ACE_UNUSED_ARG (fd);
ACE_UNUSED_ARG (rate);
ACE_UNUSED_ARG (flag);
ACE_UNUSED_ARG (len);
return 0;
#endif /* ACE_HAS_FORE_ATM_WS2 */
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_HAS_ATM */
| gpl-2.0 |
pablocrossa/trinitycore-portable | dep/acelite/ace/Malloc.cpp | 535 | 5596 | // $Id: Malloc.cpp 91368 2010-08-16 13:03:34Z mhengstmengel $
#include "ace/Malloc.h"
#if !defined (__ACE_INLINE__)
#include "ace/Malloc.inl"
#endif /* __ACE_INLINE__ */
#include "ace/Object_Manager.h"
#include "ace/Malloc_Base.h"
#include "ace/OS_NS_string.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
// Process-wide ACE_Allocator.
ACE_Allocator *ACE_Allocator::allocator_ = 0;
// Controls whether the Allocator is deleted when we shut down (we can
// only delete it safely if we created it!) This is no longer used;
// see ACE_Allocator::instance (void).
int ACE_Allocator::delete_allocator_ = 0;
void
ACE_Control_Block::ACE_Malloc_Header::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Control_Block::ACE_Malloc_Header::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_block = %@"), (ACE_Malloc_Header *) this->next_block_));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize = %d\n"), this->size_));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
void
ACE_Control_Block::print_alignment_info (void)
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Control_Block::print_alignment_info");
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Start ---> ACE_Control_Block::print_alignment_info:\n")));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("Sizeof ptr: %d\n")
ACE_TEXT ("Sizeof size_t: %d\n")
ACE_TEXT ("Sizeof long: %d\n")
ACE_TEXT ("Sizeof double: %d\n")
ACE_TEXT ("Sizeof ACE_MALLOC_ALIGN: %d\n")
ACE_TEXT ("Sizeof ACE_MALLOC_PADDING: %d\n")
ACE_TEXT ("Sizeof ACE_MALLOC_HEADER_SIZE: %d\n")
ACE_TEXT ("Sizeof ACE_MALLOC_PADDING_SIZE: %d\n")
ACE_TEXT ("Sizeof ACE_CONTROL_BLOCK_SIZE: %d\n")
ACE_TEXT ("Sizeof ACE_CONTROL_BLOCK_ALIGN_BYTES: %d\n")
ACE_TEXT ("Sizeof (MALLOC_HEADER): %d\n")
ACE_TEXT ("Sizeof (CONTROL_BLOCK): %d\n"),
sizeof (char *),
sizeof (size_t),
sizeof (long),
sizeof (double),
ACE_MALLOC_ALIGN,
ACE_MALLOC_PADDING,
ACE_MALLOC_HEADER_SIZE,
ACE_MALLOC_PADDING_SIZE,
ACE_CONTROL_BLOCK_SIZE,
ACE_CONTROL_BLOCK_ALIGN_BYTES,
sizeof (ACE_Malloc_Header),
sizeof (ACE_Control_Block)
));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("End <--- ACE_Control_Block::print_alignment_info:\n")));
#endif /* ACE_HAS_DUMP */
}
void
ACE_Control_Block::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Control_Block::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Name Node:\n")));
for (ACE_Name_Node *nextn = this->name_head_;
nextn != 0;
nextn = nextn->next_)
nextn->dump ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("freep_ = %@"), (ACE_Malloc_Header *) this->freep_));
this->base_.dump ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nMalloc Header:\n")));
for (ACE_Malloc_Header *nexth = ((ACE_Malloc_Header *)this->freep_)->next_block_;
nexth != 0 && nexth != &this->base_;
nexth = nexth->next_block_)
nexth->dump ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n")));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
ACE_Control_Block::ACE_Name_Node::ACE_Name_Node (void)
{
ACE_TRACE ("ACE_Control_Block::ACE_Name_Node::ACE_Name_Node");
}
ACE_Control_Block::ACE_Name_Node::ACE_Name_Node (const char *name,
char *name_ptr,
char *pointer,
ACE_Name_Node *next)
: name_ (name_ptr),
pointer_ (pointer),
next_ (next),
prev_ (0)
{
ACE_TRACE ("ACE_Control_Block::ACE_Name_Node::ACE_Name_Node");
char *n = this->name_;
ACE_OS::strcpy (n, name);
if (next != 0)
next->prev_ = this;
}
const char *
ACE_Control_Block::ACE_Name_Node::name (void) const
{
return this->name_;
}
ACE_Control_Block::ACE_Malloc_Header::ACE_Malloc_Header (void)
: next_block_ (0),
size_ (0)
{
}
void
ACE_Control_Block::ACE_Name_Node::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Control_Block::ACE_Name_Node::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("pointer = %@"), (const char *) this->pointer_));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %@"), (ACE_Name_Node *) this->next_));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("\nname_ = (%@, %C)\n"),
(const char *) this->name_,
(const char *) this->name_));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
#if defined (ACE_HAS_MALLOC_STATS)
ACE_Malloc_Stats::ACE_Malloc_Stats (void)
: nchunks_ (0),
nblocks_ (0),
ninuse_ (0)
{
ACE_TRACE ("ACE_Malloc_Stats::ACE_Malloc_Stats");
}
void
ACE_Malloc_Stats::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Malloc_Stats::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
int const nblocks = this->nblocks_.value ();
int const ninuse = this->ninuse_.value ();
int const nchunks = this->nchunks_.value ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT("nblocks = %d"), nblocks));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT("\nninuse = %d"), ninuse));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT("\nnchunks = %d"), nchunks));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT("\n")));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
#endif /*ACE_HAS_MALLOC_STATS*/
ACE_END_VERSIONED_NAMESPACE_DECL
| gpl-2.0 |
kamarush/Xperia-2011-KRsH-Kernel-2.6.32.9-ICS | drivers/watchdog/cpu5wdt.c | 791 | 6940 | /*
* sma cpu5 watchdog driver
*
* Copyright (C) 2003 Heiko Ronsdorf <hero@ihg.uni-duisburg.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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/timer.h>
#include <linux/completion.h>
#include <linux/jiffies.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/watchdog.h>
/* adjustable parameters */
static int verbose;
static int port = 0x91;
static int ticks = 10000;
static spinlock_t cpu5wdt_lock;
#define PFX "cpu5wdt: "
#define CPU5WDT_EXTENT 0x0A
#define CPU5WDT_STATUS_REG 0x00
#define CPU5WDT_TIME_A_REG 0x02
#define CPU5WDT_TIME_B_REG 0x03
#define CPU5WDT_MODE_REG 0x04
#define CPU5WDT_TRIGGER_REG 0x07
#define CPU5WDT_ENABLE_REG 0x08
#define CPU5WDT_RESET_REG 0x09
#define CPU5WDT_INTERVAL (HZ/10+1)
/* some device data */
static struct {
struct completion stop;
int running;
struct timer_list timer;
int queue;
int default_ticks;
unsigned long inuse;
} cpu5wdt_device;
/* generic helper functions */
static void cpu5wdt_trigger(unsigned long unused)
{
if (verbose > 2)
printk(KERN_DEBUG PFX "trigger at %i ticks\n", ticks);
if (cpu5wdt_device.running)
ticks--;
spin_lock(&cpu5wdt_lock);
/* keep watchdog alive */
outb(1, port + CPU5WDT_TRIGGER_REG);
/* requeue?? */
if (cpu5wdt_device.queue && ticks)
mod_timer(&cpu5wdt_device.timer, jiffies + CPU5WDT_INTERVAL);
else {
/* ticks doesn't matter anyway */
complete(&cpu5wdt_device.stop);
}
spin_unlock(&cpu5wdt_lock);
}
static void cpu5wdt_reset(void)
{
ticks = cpu5wdt_device.default_ticks;
if (verbose)
printk(KERN_DEBUG PFX "reset (%i ticks)\n", (int) ticks);
}
static void cpu5wdt_start(void)
{
unsigned long flags;
spin_lock_irqsave(&cpu5wdt_lock, flags);
if (!cpu5wdt_device.queue) {
cpu5wdt_device.queue = 1;
outb(0, port + CPU5WDT_TIME_A_REG);
outb(0, port + CPU5WDT_TIME_B_REG);
outb(1, port + CPU5WDT_MODE_REG);
outb(0, port + CPU5WDT_RESET_REG);
outb(0, port + CPU5WDT_ENABLE_REG);
mod_timer(&cpu5wdt_device.timer, jiffies + CPU5WDT_INTERVAL);
}
/* if process dies, counter is not decremented */
cpu5wdt_device.running++;
spin_unlock_irqrestore(&cpu5wdt_lock, flags);
}
static int cpu5wdt_stop(void)
{
unsigned long flags;
spin_lock_irqsave(&cpu5wdt_lock, flags);
if (cpu5wdt_device.running)
cpu5wdt_device.running = 0;
ticks = cpu5wdt_device.default_ticks;
spin_unlock_irqrestore(&cpu5wdt_lock, flags);
if (verbose)
printk(KERN_CRIT PFX "stop not possible\n");
return -EIO;
}
/* filesystem operations */
static int cpu5wdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &cpu5wdt_device.inuse))
return -EBUSY;
return nonseekable_open(inode, file);
}
static int cpu5wdt_release(struct inode *inode, struct file *file)
{
clear_bit(0, &cpu5wdt_device.inuse);
return 0;
}
static long cpu5wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = argp;
unsigned int value;
static struct watchdog_info ident = {
.options = WDIOF_CARDRESET,
.identity = "CPU5 WDT",
};
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &ident, sizeof(ident)))
return -EFAULT;
break;
case WDIOC_GETSTATUS:
value = inb(port + CPU5WDT_STATUS_REG);
value = (value >> 2) & 1;
return put_user(value, p);
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_SETOPTIONS:
if (get_user(value, p))
return -EFAULT;
if (value & WDIOS_ENABLECARD)
cpu5wdt_start();
if (value & WDIOS_DISABLECARD)
cpu5wdt_stop();
break;
case WDIOC_KEEPALIVE:
cpu5wdt_reset();
break;
default:
return -ENOTTY;
}
return 0;
}
static ssize_t cpu5wdt_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
if (!count)
return -EIO;
cpu5wdt_reset();
return count;
}
static const struct file_operations cpu5wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.unlocked_ioctl = cpu5wdt_ioctl,
.open = cpu5wdt_open,
.write = cpu5wdt_write,
.release = cpu5wdt_release,
};
static struct miscdevice cpu5wdt_misc = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &cpu5wdt_fops,
};
/* init/exit function */
static int __devinit cpu5wdt_init(void)
{
unsigned int val;
int err;
if (verbose)
printk(KERN_DEBUG PFX
"port=0x%x, verbose=%i\n", port, verbose);
init_completion(&cpu5wdt_device.stop);
spin_lock_init(&cpu5wdt_lock);
cpu5wdt_device.queue = 0;
setup_timer(&cpu5wdt_device.timer, cpu5wdt_trigger, 0);
cpu5wdt_device.default_ticks = ticks;
if (!request_region(port, CPU5WDT_EXTENT, PFX)) {
printk(KERN_ERR PFX "request_region failed\n");
err = -EBUSY;
goto no_port;
}
/* watchdog reboot? */
val = inb(port + CPU5WDT_STATUS_REG);
val = (val >> 2) & 1;
if (!val)
printk(KERN_INFO PFX "sorry, was my fault\n");
err = misc_register(&cpu5wdt_misc);
if (err < 0) {
printk(KERN_ERR PFX "misc_register failed\n");
goto no_misc;
}
printk(KERN_INFO PFX "init success\n");
return 0;
no_misc:
release_region(port, CPU5WDT_EXTENT);
no_port:
return err;
}
static int __devinit cpu5wdt_init_module(void)
{
return cpu5wdt_init();
}
static void __devexit cpu5wdt_exit(void)
{
if (cpu5wdt_device.queue) {
cpu5wdt_device.queue = 0;
wait_for_completion(&cpu5wdt_device.stop);
}
misc_deregister(&cpu5wdt_misc);
release_region(port, CPU5WDT_EXTENT);
}
static void __devexit cpu5wdt_exit_module(void)
{
cpu5wdt_exit();
}
/* module entry points */
module_init(cpu5wdt_init_module);
module_exit(cpu5wdt_exit_module);
MODULE_AUTHOR("Heiko Ronsdorf <hero@ihg.uni-duisburg.de>");
MODULE_DESCRIPTION("sma cpu5 watchdog driver");
MODULE_SUPPORTED_DEVICE("sma cpu5 watchdog");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
module_param(port, int, 0);
MODULE_PARM_DESC(port, "base address of watchdog card, default is 0x91");
module_param(verbose, int, 0);
MODULE_PARM_DESC(verbose, "be verbose, default is 0 (no)");
module_param(ticks, int, 0);
MODULE_PARM_DESC(ticks, "count down ticks, default is 10000");
| gpl-2.0 |
iamyuiwong/linux-2.6.28_6410 | drivers/input/gameport/emu10k1-gp.c | 791 | 3297 | /*
* Copyright (c) 2001 Vojtech Pavlik
*/
/*
* EMU10k1 - SB Live / Audigy - gameport driver for Linux
*/
/*
* 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
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <asm/io.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/gameport.h>
#include <linux/slab.h>
#include <linux/pci.h>
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION("EMU10k1 gameport driver");
MODULE_LICENSE("GPL");
struct emu {
struct pci_dev *dev;
struct gameport *gameport;
int io;
int size;
};
static struct pci_device_id emu_tbl[] = {
{ 0x1102, 0x7002, PCI_ANY_ID, PCI_ANY_ID }, /* SB Live gameport */
{ 0x1102, 0x7003, PCI_ANY_ID, PCI_ANY_ID }, /* Audigy gameport */
{ 0x1102, 0x7004, PCI_ANY_ID, PCI_ANY_ID }, /* Dell SB Live */
{ 0x1102, 0x7005, PCI_ANY_ID, PCI_ANY_ID }, /* Audigy LS gameport */
{ 0, }
};
MODULE_DEVICE_TABLE(pci, emu_tbl);
static int __devinit emu_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int ioport, iolen;
struct emu *emu;
struct gameport *port;
if (pci_enable_device(pdev))
return -EBUSY;
ioport = pci_resource_start(pdev, 0);
iolen = pci_resource_len(pdev, 0);
if (!request_region(ioport, iolen, "emu10k1-gp"))
return -EBUSY;
emu = kzalloc(sizeof(struct emu), GFP_KERNEL);
port = gameport_allocate_port();
if (!emu || !port) {
printk(KERN_ERR "emu10k1-gp: Memory allocation failed\n");
release_region(ioport, iolen);
kfree(emu);
gameport_free_port(port);
return -ENOMEM;
}
emu->io = ioport;
emu->size = iolen;
emu->dev = pdev;
emu->gameport = port;
gameport_set_name(port, "EMU10K1");
gameport_set_phys(port, "pci%s/gameport0", pci_name(pdev));
port->dev.parent = &pdev->dev;
port->io = ioport;
pci_set_drvdata(pdev, emu);
gameport_register_port(port);
return 0;
}
static void __devexit emu_remove(struct pci_dev *pdev)
{
struct emu *emu = pci_get_drvdata(pdev);
gameport_unregister_port(emu->gameport);
release_region(emu->io, emu->size);
kfree(emu);
}
static struct pci_driver emu_driver = {
.name = "Emu10k1_gameport",
.id_table = emu_tbl,
.probe = emu_probe,
.remove = __devexit_p(emu_remove),
};
static int __init emu_init(void)
{
return pci_register_driver(&emu_driver);
}
static void __exit emu_exit(void)
{
pci_unregister_driver(&emu_driver);
}
module_init(emu_init);
module_exit(emu_exit);
| gpl-2.0 |
artefvck/android_kernel_asus_T00F | drivers/net/wireless/iwlwifi/iwl-6000.c | 1815 | 13361 | /******************************************************************************
*
* Copyright(c) 2008 - 2013 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* 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/module.h>
#include <linux/stringify.h>
#include "iwl-config.h"
#include "iwl-agn-hw.h"
#include "dvm/commands.h" /* needed for BT for now */
/* Highest firmware API version supported */
#define IWL6000_UCODE_API_MAX 6
#define IWL6050_UCODE_API_MAX 5
#define IWL6000G2_UCODE_API_MAX 6
#define IWL6035_UCODE_API_MAX 6
/* Oldest version we won't warn about */
#define IWL6000_UCODE_API_OK 4
#define IWL6000G2_UCODE_API_OK 5
#define IWL6050_UCODE_API_OK 5
#define IWL6000G2B_UCODE_API_OK 6
#define IWL6035_UCODE_API_OK 6
/* Lowest firmware API version supported */
#define IWL6000_UCODE_API_MIN 4
#define IWL6050_UCODE_API_MIN 4
#define IWL6000G2_UCODE_API_MIN 5
#define IWL6035_UCODE_API_MIN 6
/* EEPROM versions */
#define EEPROM_6000_TX_POWER_VERSION (4)
#define EEPROM_6000_EEPROM_VERSION (0x423)
#define EEPROM_6050_TX_POWER_VERSION (4)
#define EEPROM_6050_EEPROM_VERSION (0x532)
#define EEPROM_6150_TX_POWER_VERSION (6)
#define EEPROM_6150_EEPROM_VERSION (0x553)
#define EEPROM_6005_TX_POWER_VERSION (6)
#define EEPROM_6005_EEPROM_VERSION (0x709)
#define EEPROM_6030_TX_POWER_VERSION (6)
#define EEPROM_6030_EEPROM_VERSION (0x709)
#define EEPROM_6035_TX_POWER_VERSION (6)
#define EEPROM_6035_EEPROM_VERSION (0x753)
#define IWL6000_FW_PRE "iwlwifi-6000-"
#define IWL6000_MODULE_FIRMWARE(api) IWL6000_FW_PRE __stringify(api) ".ucode"
#define IWL6050_FW_PRE "iwlwifi-6050-"
#define IWL6050_MODULE_FIRMWARE(api) IWL6050_FW_PRE __stringify(api) ".ucode"
#define IWL6005_FW_PRE "iwlwifi-6000g2a-"
#define IWL6005_MODULE_FIRMWARE(api) IWL6005_FW_PRE __stringify(api) ".ucode"
#define IWL6030_FW_PRE "iwlwifi-6000g2b-"
#define IWL6030_MODULE_FIRMWARE(api) IWL6030_FW_PRE __stringify(api) ".ucode"
static const struct iwl_base_params iwl6000_base_params = {
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.num_of_queues = IWLAGN_NUM_QUEUES,
.pll_cfg_val = 0,
.max_ll_items = OTP_MAX_LL_ITEMS_6x00,
.shadow_ram_support = true,
.led_compensation = 51,
.adv_thermal_throttle = true,
.support_ct_kill_exit = true,
.plcp_delta_threshold = IWL_MAX_PLCP_ERR_THRESHOLD_DEF,
.chain_noise_scale = 1000,
.wd_timeout = IWL_DEF_WD_TIMEOUT,
.max_event_log_size = 512,
.shadow_reg_enable = false, /* TODO: fix bugs using this feature */
};
static const struct iwl_base_params iwl6050_base_params = {
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.num_of_queues = IWLAGN_NUM_QUEUES,
.pll_cfg_val = 0,
.max_ll_items = OTP_MAX_LL_ITEMS_6x50,
.shadow_ram_support = true,
.led_compensation = 51,
.adv_thermal_throttle = true,
.support_ct_kill_exit = true,
.plcp_delta_threshold = IWL_MAX_PLCP_ERR_THRESHOLD_DEF,
.chain_noise_scale = 1500,
.wd_timeout = IWL_DEF_WD_TIMEOUT,
.max_event_log_size = 1024,
.shadow_reg_enable = false, /* TODO: fix bugs using this feature */
};
static const struct iwl_base_params iwl6000_g2_base_params = {
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.num_of_queues = IWLAGN_NUM_QUEUES,
.pll_cfg_val = 0,
.max_ll_items = OTP_MAX_LL_ITEMS_6x00,
.shadow_ram_support = true,
.led_compensation = 57,
.adv_thermal_throttle = true,
.support_ct_kill_exit = true,
.plcp_delta_threshold = IWL_MAX_PLCP_ERR_THRESHOLD_DEF,
.chain_noise_scale = 1000,
.wd_timeout = IWL_LONG_WD_TIMEOUT,
.max_event_log_size = 512,
.shadow_reg_enable = false, /* TODO: fix bugs using this feature */
};
static const struct iwl_ht_params iwl6000_ht_params = {
.ht_greenfield_support = true,
.use_rts_for_aggregation = true, /* use rts/cts protection */
.ht40_bands = BIT(IEEE80211_BAND_2GHZ) | BIT(IEEE80211_BAND_5GHZ),
};
static const struct iwl_bt_params iwl6000_bt_params = {
/* Due to bluetooth, we transmit 2.4 GHz probes only on antenna A */
.advanced_bt_coexist = true,
.agg_time_limit = BT_AGG_THRESHOLD_DEF,
.bt_init_traffic_load = IWL_BT_COEX_TRAFFIC_LOAD_NONE,
.bt_prio_boost = IWLAGN_BT_PRIO_BOOST_DEFAULT,
.bt_sco_disable = true,
};
static const struct iwl_eeprom_params iwl6000_eeprom_params = {
.regulatory_bands = {
EEPROM_REG_BAND_1_CHANNELS,
EEPROM_REG_BAND_2_CHANNELS,
EEPROM_REG_BAND_3_CHANNELS,
EEPROM_REG_BAND_4_CHANNELS,
EEPROM_REG_BAND_5_CHANNELS,
EEPROM_6000_REG_BAND_24_HT40_CHANNELS,
EEPROM_REG_BAND_52_HT40_CHANNELS
},
.enhanced_txpower = true,
};
#define IWL_DEVICE_6005 \
.fw_name_pre = IWL6005_FW_PRE, \
.ucode_api_max = IWL6000G2_UCODE_API_MAX, \
.ucode_api_ok = IWL6000G2_UCODE_API_OK, \
.ucode_api_min = IWL6000G2_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_6005, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_6005_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_6005_TX_POWER_VERSION, \
.base_params = &iwl6000_g2_base_params, \
.eeprom_params = &iwl6000_eeprom_params, \
.need_temp_offset_calib = true, \
.led_mode = IWL_LED_RF_STATE
const struct iwl_cfg iwl6005_2agn_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6205 AGN",
IWL_DEVICE_6005,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6005_2abg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6205 ABG",
IWL_DEVICE_6005,
};
const struct iwl_cfg iwl6005_2bg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6205 BG",
IWL_DEVICE_6005,
};
const struct iwl_cfg iwl6005_2agn_sff_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6205S AGN",
IWL_DEVICE_6005,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6005_2agn_d_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6205D AGN",
IWL_DEVICE_6005,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6005_2agn_mow1_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6206 AGN",
IWL_DEVICE_6005,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6005_2agn_mow2_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6207 AGN",
IWL_DEVICE_6005,
.ht_params = &iwl6000_ht_params,
};
#define IWL_DEVICE_6030 \
.fw_name_pre = IWL6030_FW_PRE, \
.ucode_api_max = IWL6000G2_UCODE_API_MAX, \
.ucode_api_ok = IWL6000G2B_UCODE_API_OK, \
.ucode_api_min = IWL6000G2_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_6030, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_6030_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_6030_TX_POWER_VERSION, \
.base_params = &iwl6000_g2_base_params, \
.bt_params = &iwl6000_bt_params, \
.eeprom_params = &iwl6000_eeprom_params, \
.need_temp_offset_calib = true, \
.led_mode = IWL_LED_RF_STATE, \
.adv_pm = true \
const struct iwl_cfg iwl6030_2agn_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6230 AGN",
IWL_DEVICE_6030,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6030_2abg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6230 ABG",
IWL_DEVICE_6030,
};
const struct iwl_cfg iwl6030_2bgn_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6230 BGN",
IWL_DEVICE_6030,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6030_2bg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6230 BG",
IWL_DEVICE_6030,
};
#define IWL_DEVICE_6035 \
.fw_name_pre = IWL6030_FW_PRE, \
.ucode_api_max = IWL6035_UCODE_API_MAX, \
.ucode_api_ok = IWL6035_UCODE_API_OK, \
.ucode_api_min = IWL6035_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_6030, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_6030_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_6030_TX_POWER_VERSION, \
.base_params = &iwl6000_g2_base_params, \
.bt_params = &iwl6000_bt_params, \
.eeprom_params = &iwl6000_eeprom_params, \
.need_temp_offset_calib = true, \
.led_mode = IWL_LED_RF_STATE, \
.adv_pm = true
const struct iwl_cfg iwl6035_2agn_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6235 AGN",
IWL_DEVICE_6035,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6035_2agn_sff_cfg = {
.name = "Intel(R) Centrino(R) Ultimate-N 6235 AGN",
IWL_DEVICE_6035,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl1030_bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 1030 BGN",
IWL_DEVICE_6030,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl1030_bg_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 1030 BG",
IWL_DEVICE_6030,
};
const struct iwl_cfg iwl130_bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 130 BGN",
IWL_DEVICE_6030,
.ht_params = &iwl6000_ht_params,
.rx_with_siso_diversity = true,
};
const struct iwl_cfg iwl130_bg_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 130 BG",
IWL_DEVICE_6030,
.rx_with_siso_diversity = true,
};
/*
* "i": Internal configuration, use internal Power Amplifier
*/
#define IWL_DEVICE_6000i \
.fw_name_pre = IWL6000_FW_PRE, \
.ucode_api_max = IWL6000_UCODE_API_MAX, \
.ucode_api_ok = IWL6000_UCODE_API_OK, \
.ucode_api_min = IWL6000_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_6000i, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.valid_tx_ant = ANT_BC, /* .cfg overwrite */ \
.valid_rx_ant = ANT_BC, /* .cfg overwrite */ \
.nvm_ver = EEPROM_6000_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_6000_TX_POWER_VERSION, \
.base_params = &iwl6000_base_params, \
.eeprom_params = &iwl6000_eeprom_params, \
.led_mode = IWL_LED_BLINK
const struct iwl_cfg iwl6000i_2agn_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6200 AGN",
IWL_DEVICE_6000i,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6000i_2abg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6200 ABG",
IWL_DEVICE_6000i,
};
const struct iwl_cfg iwl6000i_2bg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N 6200 BG",
IWL_DEVICE_6000i,
};
#define IWL_DEVICE_6050 \
.fw_name_pre = IWL6050_FW_PRE, \
.ucode_api_max = IWL6050_UCODE_API_MAX, \
.ucode_api_min = IWL6050_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_6050, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.valid_tx_ant = ANT_AB, /* .cfg overwrite */ \
.valid_rx_ant = ANT_AB, /* .cfg overwrite */ \
.nvm_ver = EEPROM_6050_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_6050_TX_POWER_VERSION, \
.base_params = &iwl6050_base_params, \
.eeprom_params = &iwl6000_eeprom_params, \
.led_mode = IWL_LED_BLINK, \
.internal_wimax_coex = true
const struct iwl_cfg iwl6050_2agn_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N + WiMAX 6250 AGN",
IWL_DEVICE_6050,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6050_2abg_cfg = {
.name = "Intel(R) Centrino(R) Advanced-N + WiMAX 6250 ABG",
IWL_DEVICE_6050,
};
#define IWL_DEVICE_6150 \
.fw_name_pre = IWL6050_FW_PRE, \
.ucode_api_max = IWL6050_UCODE_API_MAX, \
.ucode_api_min = IWL6050_UCODE_API_MIN, \
.device_family = IWL_DEVICE_FAMILY_6150, \
.max_inst_size = IWL60_RTC_INST_SIZE, \
.max_data_size = IWL60_RTC_DATA_SIZE, \
.nvm_ver = EEPROM_6150_EEPROM_VERSION, \
.nvm_calib_ver = EEPROM_6150_TX_POWER_VERSION, \
.base_params = &iwl6050_base_params, \
.eeprom_params = &iwl6000_eeprom_params, \
.led_mode = IWL_LED_BLINK, \
.internal_wimax_coex = true
const struct iwl_cfg iwl6150_bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N + WiMAX 6150 BGN",
IWL_DEVICE_6150,
.ht_params = &iwl6000_ht_params,
};
const struct iwl_cfg iwl6150_bg_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N + WiMAX 6150 BG",
IWL_DEVICE_6150,
};
const struct iwl_cfg iwl6000_3agn_cfg = {
.name = "Intel(R) Centrino(R) Ultimate-N 6300 AGN",
.fw_name_pre = IWL6000_FW_PRE,
.ucode_api_max = IWL6000_UCODE_API_MAX,
.ucode_api_ok = IWL6000_UCODE_API_OK,
.ucode_api_min = IWL6000_UCODE_API_MIN,
.device_family = IWL_DEVICE_FAMILY_6000,
.max_inst_size = IWL60_RTC_INST_SIZE,
.max_data_size = IWL60_RTC_DATA_SIZE,
.nvm_ver = EEPROM_6000_EEPROM_VERSION,
.nvm_calib_ver = EEPROM_6000_TX_POWER_VERSION,
.base_params = &iwl6000_base_params,
.eeprom_params = &iwl6000_eeprom_params,
.ht_params = &iwl6000_ht_params,
.led_mode = IWL_LED_BLINK,
};
MODULE_FIRMWARE(IWL6000_MODULE_FIRMWARE(IWL6000_UCODE_API_OK));
MODULE_FIRMWARE(IWL6050_MODULE_FIRMWARE(IWL6050_UCODE_API_OK));
MODULE_FIRMWARE(IWL6005_MODULE_FIRMWARE(IWL6000G2_UCODE_API_OK));
MODULE_FIRMWARE(IWL6030_MODULE_FIRMWARE(IWL6000G2B_UCODE_API_OK));
| gpl-2.0 |
skywalker01/galaxy-nexus-kernel | drivers/acpi/scan.c | 2071 | 40141 | /*
* scan.c - support for transforming the ACPI namespace into individual objects
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/acpi.h>
#include <linux/signal.h>
#include <linux/kthread.h>
#include <linux/dmi.h>
#include <acpi/acpi_drivers.h>
#include "internal.h"
#define _COMPONENT ACPI_BUS_COMPONENT
ACPI_MODULE_NAME("scan");
#define STRUCT_TO_INT(s) (*((int*)&s))
extern struct acpi_device *acpi_root;
#define ACPI_BUS_CLASS "system_bus"
#define ACPI_BUS_HID "LNXSYBUS"
#define ACPI_BUS_DEVICE_NAME "System Bus"
#define ACPI_IS_ROOT_DEVICE(device) (!(device)->parent)
static const char *dummy_hid = "device";
static LIST_HEAD(acpi_device_list);
static LIST_HEAD(acpi_bus_id_list);
DEFINE_MUTEX(acpi_device_lock);
LIST_HEAD(acpi_wakeup_device_list);
struct acpi_device_bus_id{
char bus_id[15];
unsigned int instance_no;
struct list_head node;
};
/*
* Creates hid/cid(s) string needed for modalias and uevent
* e.g. on a device with hid:IBM0001 and cid:ACPI0001 you get:
* char *modalias: "acpi:IBM0001:ACPI0001"
*/
static int create_modalias(struct acpi_device *acpi_dev, char *modalias,
int size)
{
int len;
int count;
struct acpi_hardware_id *id;
if (list_empty(&acpi_dev->pnp.ids))
return 0;
len = snprintf(modalias, size, "acpi:");
size -= len;
list_for_each_entry(id, &acpi_dev->pnp.ids, list) {
count = snprintf(&modalias[len], size, "%s:", id->id);
if (count < 0 || count >= size)
return -EINVAL;
len += count;
size -= count;
}
modalias[len] = '\0';
return len;
}
static ssize_t
acpi_device_modalias_show(struct device *dev, struct device_attribute *attr, char *buf) {
struct acpi_device *acpi_dev = to_acpi_device(dev);
int len;
/* Device has no HID and no CID or string is >1024 */
len = create_modalias(acpi_dev, buf, 1024);
if (len <= 0)
return 0;
buf[len++] = '\n';
return len;
}
static DEVICE_ATTR(modalias, 0444, acpi_device_modalias_show, NULL);
static void acpi_bus_hot_remove_device(void *context)
{
struct acpi_device *device;
acpi_handle handle = context;
struct acpi_object_list arg_list;
union acpi_object arg;
acpi_status status = AE_OK;
if (acpi_bus_get_device(handle, &device))
return;
if (!device)
return;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Hot-removing device %s...\n", dev_name(&device->dev)));
if (acpi_bus_trim(device, 1)) {
printk(KERN_ERR PREFIX
"Removing device failed\n");
return;
}
/* power off device */
status = acpi_evaluate_object(handle, "_PS3", NULL, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND)
printk(KERN_WARNING PREFIX
"Power-off device failed\n");
if (device->flags.lockable) {
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = 0;
acpi_evaluate_object(handle, "_LCK", &arg_list, NULL);
}
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = 1;
/*
* TBD: _EJD support.
*/
status = acpi_evaluate_object(handle, "_EJ0", &arg_list, NULL);
if (ACPI_FAILURE(status))
printk(KERN_WARNING PREFIX
"Eject device failed\n");
return;
}
static ssize_t
acpi_eject_store(struct device *d, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret = count;
acpi_status status;
acpi_object_type type = 0;
struct acpi_device *acpi_device = to_acpi_device(d);
if ((!count) || (buf[0] != '1')) {
return -EINVAL;
}
#ifndef FORCE_EJECT
if (acpi_device->driver == NULL) {
ret = -ENODEV;
goto err;
}
#endif
status = acpi_get_type(acpi_device->handle, &type);
if (ACPI_FAILURE(status) || (!acpi_device->flags.ejectable)) {
ret = -ENODEV;
goto err;
}
acpi_os_hotplug_execute(acpi_bus_hot_remove_device, acpi_device->handle);
err:
return ret;
}
static DEVICE_ATTR(eject, 0200, NULL, acpi_eject_store);
static ssize_t
acpi_device_hid_show(struct device *dev, struct device_attribute *attr, char *buf) {
struct acpi_device *acpi_dev = to_acpi_device(dev);
return sprintf(buf, "%s\n", acpi_device_hid(acpi_dev));
}
static DEVICE_ATTR(hid, 0444, acpi_device_hid_show, NULL);
static ssize_t
acpi_device_path_show(struct device *dev, struct device_attribute *attr, char *buf) {
struct acpi_device *acpi_dev = to_acpi_device(dev);
struct acpi_buffer path = {ACPI_ALLOCATE_BUFFER, NULL};
int result;
result = acpi_get_name(acpi_dev->handle, ACPI_FULL_PATHNAME, &path);
if (result)
goto end;
result = sprintf(buf, "%s\n", (char*)path.pointer);
kfree(path.pointer);
end:
return result;
}
static DEVICE_ATTR(path, 0444, acpi_device_path_show, NULL);
static int acpi_device_setup_files(struct acpi_device *dev)
{
acpi_status status;
acpi_handle temp;
int result = 0;
/*
* Devices gotten from FADT don't have a "path" attribute
*/
if (dev->handle) {
result = device_create_file(&dev->dev, &dev_attr_path);
if (result)
goto end;
}
if (!list_empty(&dev->pnp.ids)) {
result = device_create_file(&dev->dev, &dev_attr_hid);
if (result)
goto end;
result = device_create_file(&dev->dev, &dev_attr_modalias);
if (result)
goto end;
}
/*
* If device has _EJ0, 'eject' file is created that is used to trigger
* hot-removal function from userland.
*/
status = acpi_get_handle(dev->handle, "_EJ0", &temp);
if (ACPI_SUCCESS(status))
result = device_create_file(&dev->dev, &dev_attr_eject);
end:
return result;
}
static void acpi_device_remove_files(struct acpi_device *dev)
{
acpi_status status;
acpi_handle temp;
/*
* If device has _EJ0, 'eject' file is created that is used to trigger
* hot-removal function from userland.
*/
status = acpi_get_handle(dev->handle, "_EJ0", &temp);
if (ACPI_SUCCESS(status))
device_remove_file(&dev->dev, &dev_attr_eject);
device_remove_file(&dev->dev, &dev_attr_modalias);
device_remove_file(&dev->dev, &dev_attr_hid);
if (dev->handle)
device_remove_file(&dev->dev, &dev_attr_path);
}
/* --------------------------------------------------------------------------
ACPI Bus operations
-------------------------------------------------------------------------- */
int acpi_match_device_ids(struct acpi_device *device,
const struct acpi_device_id *ids)
{
const struct acpi_device_id *id;
struct acpi_hardware_id *hwid;
/*
* If the device is not present, it is unnecessary to load device
* driver for it.
*/
if (!device->status.present)
return -ENODEV;
for (id = ids; id->id[0]; id++)
list_for_each_entry(hwid, &device->pnp.ids, list)
if (!strcmp((char *) id->id, hwid->id))
return 0;
return -ENOENT;
}
EXPORT_SYMBOL(acpi_match_device_ids);
static void acpi_free_ids(struct acpi_device *device)
{
struct acpi_hardware_id *id, *tmp;
list_for_each_entry_safe(id, tmp, &device->pnp.ids, list) {
kfree(id->id);
kfree(id);
}
}
static void acpi_device_release(struct device *dev)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
acpi_free_ids(acpi_dev);
kfree(acpi_dev);
}
static int acpi_device_suspend(struct device *dev, pm_message_t state)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
struct acpi_driver *acpi_drv = acpi_dev->driver;
if (acpi_drv && acpi_drv->ops.suspend)
return acpi_drv->ops.suspend(acpi_dev, state);
return 0;
}
static int acpi_device_resume(struct device *dev)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
struct acpi_driver *acpi_drv = acpi_dev->driver;
if (acpi_drv && acpi_drv->ops.resume)
return acpi_drv->ops.resume(acpi_dev);
return 0;
}
static int acpi_bus_match(struct device *dev, struct device_driver *drv)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
struct acpi_driver *acpi_drv = to_acpi_driver(drv);
return !acpi_match_device_ids(acpi_dev, acpi_drv->ids);
}
static int acpi_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
int len;
if (list_empty(&acpi_dev->pnp.ids))
return 0;
if (add_uevent_var(env, "MODALIAS="))
return -ENOMEM;
len = create_modalias(acpi_dev, &env->buf[env->buflen - 1],
sizeof(env->buf) - env->buflen);
if (len >= (sizeof(env->buf) - env->buflen))
return -ENOMEM;
env->buflen += len;
return 0;
}
static void acpi_device_notify(acpi_handle handle, u32 event, void *data)
{
struct acpi_device *device = data;
device->driver->ops.notify(device, event);
}
static acpi_status acpi_device_notify_fixed(void *data)
{
struct acpi_device *device = data;
/* Fixed hardware devices have no handles */
acpi_device_notify(NULL, ACPI_FIXED_HARDWARE_EVENT, device);
return AE_OK;
}
static int acpi_device_install_notify_handler(struct acpi_device *device)
{
acpi_status status;
if (device->device_type == ACPI_BUS_TYPE_POWER_BUTTON)
status =
acpi_install_fixed_event_handler(ACPI_EVENT_POWER_BUTTON,
acpi_device_notify_fixed,
device);
else if (device->device_type == ACPI_BUS_TYPE_SLEEP_BUTTON)
status =
acpi_install_fixed_event_handler(ACPI_EVENT_SLEEP_BUTTON,
acpi_device_notify_fixed,
device);
else
status = acpi_install_notify_handler(device->handle,
ACPI_DEVICE_NOTIFY,
acpi_device_notify,
device);
if (ACPI_FAILURE(status))
return -EINVAL;
return 0;
}
static void acpi_device_remove_notify_handler(struct acpi_device *device)
{
if (device->device_type == ACPI_BUS_TYPE_POWER_BUTTON)
acpi_remove_fixed_event_handler(ACPI_EVENT_POWER_BUTTON,
acpi_device_notify_fixed);
else if (device->device_type == ACPI_BUS_TYPE_SLEEP_BUTTON)
acpi_remove_fixed_event_handler(ACPI_EVENT_SLEEP_BUTTON,
acpi_device_notify_fixed);
else
acpi_remove_notify_handler(device->handle, ACPI_DEVICE_NOTIFY,
acpi_device_notify);
}
static int acpi_bus_driver_init(struct acpi_device *, struct acpi_driver *);
static int acpi_start_single_object(struct acpi_device *);
static int acpi_device_probe(struct device * dev)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
struct acpi_driver *acpi_drv = to_acpi_driver(dev->driver);
int ret;
ret = acpi_bus_driver_init(acpi_dev, acpi_drv);
if (!ret) {
if (acpi_dev->bus_ops.acpi_op_start)
acpi_start_single_object(acpi_dev);
if (acpi_drv->ops.notify) {
ret = acpi_device_install_notify_handler(acpi_dev);
if (ret) {
if (acpi_drv->ops.remove)
acpi_drv->ops.remove(acpi_dev,
acpi_dev->removal_type);
return ret;
}
}
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Found driver [%s] for device [%s]\n",
acpi_drv->name, acpi_dev->pnp.bus_id));
get_device(dev);
}
return ret;
}
static int acpi_device_remove(struct device * dev)
{
struct acpi_device *acpi_dev = to_acpi_device(dev);
struct acpi_driver *acpi_drv = acpi_dev->driver;
if (acpi_drv) {
if (acpi_drv->ops.notify)
acpi_device_remove_notify_handler(acpi_dev);
if (acpi_drv->ops.remove)
acpi_drv->ops.remove(acpi_dev, acpi_dev->removal_type);
}
acpi_dev->driver = NULL;
acpi_dev->driver_data = NULL;
put_device(dev);
return 0;
}
struct bus_type acpi_bus_type = {
.name = "acpi",
.suspend = acpi_device_suspend,
.resume = acpi_device_resume,
.match = acpi_bus_match,
.probe = acpi_device_probe,
.remove = acpi_device_remove,
.uevent = acpi_device_uevent,
};
static int acpi_device_register(struct acpi_device *device)
{
int result;
struct acpi_device_bus_id *acpi_device_bus_id, *new_bus_id;
int found = 0;
/*
* Linkage
* -------
* Link this device to its parent and siblings.
*/
INIT_LIST_HEAD(&device->children);
INIT_LIST_HEAD(&device->node);
INIT_LIST_HEAD(&device->wakeup_list);
new_bus_id = kzalloc(sizeof(struct acpi_device_bus_id), GFP_KERNEL);
if (!new_bus_id) {
printk(KERN_ERR PREFIX "Memory allocation error\n");
return -ENOMEM;
}
mutex_lock(&acpi_device_lock);
/*
* Find suitable bus_id and instance number in acpi_bus_id_list
* If failed, create one and link it into acpi_bus_id_list
*/
list_for_each_entry(acpi_device_bus_id, &acpi_bus_id_list, node) {
if (!strcmp(acpi_device_bus_id->bus_id,
acpi_device_hid(device))) {
acpi_device_bus_id->instance_no++;
found = 1;
kfree(new_bus_id);
break;
}
}
if (!found) {
acpi_device_bus_id = new_bus_id;
strcpy(acpi_device_bus_id->bus_id, acpi_device_hid(device));
acpi_device_bus_id->instance_no = 0;
list_add_tail(&acpi_device_bus_id->node, &acpi_bus_id_list);
}
dev_set_name(&device->dev, "%s:%02x", acpi_device_bus_id->bus_id, acpi_device_bus_id->instance_no);
if (device->parent)
list_add_tail(&device->node, &device->parent->children);
if (device->wakeup.flags.valid)
list_add_tail(&device->wakeup_list, &acpi_wakeup_device_list);
mutex_unlock(&acpi_device_lock);
if (device->parent)
device->dev.parent = &device->parent->dev;
device->dev.bus = &acpi_bus_type;
device->dev.release = &acpi_device_release;
result = device_register(&device->dev);
if (result) {
dev_err(&device->dev, "Error registering device\n");
goto end;
}
result = acpi_device_setup_files(device);
if (result)
printk(KERN_ERR PREFIX "Error creating sysfs interface for device %s\n",
dev_name(&device->dev));
device->removal_type = ACPI_BUS_REMOVAL_NORMAL;
return 0;
end:
mutex_lock(&acpi_device_lock);
if (device->parent)
list_del(&device->node);
list_del(&device->wakeup_list);
mutex_unlock(&acpi_device_lock);
return result;
}
static void acpi_device_unregister(struct acpi_device *device, int type)
{
mutex_lock(&acpi_device_lock);
if (device->parent)
list_del(&device->node);
list_del(&device->wakeup_list);
mutex_unlock(&acpi_device_lock);
acpi_detach_data(device->handle, acpi_bus_data_handler);
acpi_device_remove_files(device);
device_unregister(&device->dev);
}
/* --------------------------------------------------------------------------
Driver Management
-------------------------------------------------------------------------- */
/**
* acpi_bus_driver_init - add a device to a driver
* @device: the device to add and initialize
* @driver: driver for the device
*
* Used to initialize a device via its device driver. Called whenever a
* driver is bound to a device. Invokes the driver's add() ops.
*/
static int
acpi_bus_driver_init(struct acpi_device *device, struct acpi_driver *driver)
{
int result = 0;
if (!device || !driver)
return -EINVAL;
if (!driver->ops.add)
return -ENOSYS;
result = driver->ops.add(device);
if (result) {
device->driver = NULL;
device->driver_data = NULL;
return result;
}
device->driver = driver;
/*
* TBD - Configuration Management: Assign resources to device based
* upon possible configuration and currently allocated resources.
*/
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Driver successfully bound to device\n"));
return 0;
}
static int acpi_start_single_object(struct acpi_device *device)
{
int result = 0;
struct acpi_driver *driver;
if (!(driver = device->driver))
return 0;
if (driver->ops.start) {
result = driver->ops.start(device);
if (result && driver->ops.remove)
driver->ops.remove(device, ACPI_BUS_REMOVAL_NORMAL);
}
return result;
}
/**
* acpi_bus_register_driver - register a driver with the ACPI bus
* @driver: driver being registered
*
* Registers a driver with the ACPI bus. Searches the namespace for all
* devices that match the driver's criteria and binds. Returns zero for
* success or a negative error status for failure.
*/
int acpi_bus_register_driver(struct acpi_driver *driver)
{
int ret;
if (acpi_disabled)
return -ENODEV;
driver->drv.name = driver->name;
driver->drv.bus = &acpi_bus_type;
driver->drv.owner = driver->owner;
ret = driver_register(&driver->drv);
return ret;
}
EXPORT_SYMBOL(acpi_bus_register_driver);
/**
* acpi_bus_unregister_driver - unregisters a driver with the APIC bus
* @driver: driver to unregister
*
* Unregisters a driver with the ACPI bus. Searches the namespace for all
* devices that match the driver's criteria and unbinds.
*/
void acpi_bus_unregister_driver(struct acpi_driver *driver)
{
driver_unregister(&driver->drv);
}
EXPORT_SYMBOL(acpi_bus_unregister_driver);
/* --------------------------------------------------------------------------
Device Enumeration
-------------------------------------------------------------------------- */
static struct acpi_device *acpi_bus_get_parent(acpi_handle handle)
{
acpi_status status;
int ret;
struct acpi_device *device;
/*
* Fixed hardware devices do not appear in the namespace and do not
* have handles, but we fabricate acpi_devices for them, so we have
* to deal with them specially.
*/
if (handle == NULL)
return acpi_root;
do {
status = acpi_get_parent(handle, &handle);
if (status == AE_NULL_ENTRY)
return NULL;
if (ACPI_FAILURE(status))
return acpi_root;
ret = acpi_bus_get_device(handle, &device);
if (ret == 0)
return device;
} while (1);
}
acpi_status
acpi_bus_get_ejd(acpi_handle handle, acpi_handle *ejd)
{
acpi_status status;
acpi_handle tmp;
struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
union acpi_object *obj;
status = acpi_get_handle(handle, "_EJD", &tmp);
if (ACPI_FAILURE(status))
return status;
status = acpi_evaluate_object(handle, "_EJD", NULL, &buffer);
if (ACPI_SUCCESS(status)) {
obj = buffer.pointer;
status = acpi_get_handle(ACPI_ROOT_OBJECT, obj->string.pointer,
ejd);
kfree(buffer.pointer);
}
return status;
}
EXPORT_SYMBOL_GPL(acpi_bus_get_ejd);
void acpi_bus_data_handler(acpi_handle handle, void *context)
{
/* TBD */
return;
}
static int acpi_bus_get_perf_flags(struct acpi_device *device)
{
device->performance.state = ACPI_STATE_UNKNOWN;
return 0;
}
static acpi_status
acpi_bus_extract_wakeup_device_power_package(acpi_handle handle,
struct acpi_device_wakeup *wakeup)
{
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *package = NULL;
union acpi_object *element = NULL;
acpi_status status;
int i = 0;
if (!wakeup)
return AE_BAD_PARAMETER;
/* _PRW */
status = acpi_evaluate_object(handle, "_PRW", NULL, &buffer);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status, "Evaluating _PRW"));
return status;
}
package = (union acpi_object *)buffer.pointer;
if (!package || (package->package.count < 2)) {
status = AE_BAD_DATA;
goto out;
}
element = &(package->package.elements[0]);
if (!element) {
status = AE_BAD_DATA;
goto out;
}
if (element->type == ACPI_TYPE_PACKAGE) {
if ((element->package.count < 2) ||
(element->package.elements[0].type !=
ACPI_TYPE_LOCAL_REFERENCE)
|| (element->package.elements[1].type != ACPI_TYPE_INTEGER)) {
status = AE_BAD_DATA;
goto out;
}
wakeup->gpe_device =
element->package.elements[0].reference.handle;
wakeup->gpe_number =
(u32) element->package.elements[1].integer.value;
} else if (element->type == ACPI_TYPE_INTEGER) {
wakeup->gpe_device = NULL;
wakeup->gpe_number = element->integer.value;
} else {
status = AE_BAD_DATA;
goto out;
}
element = &(package->package.elements[1]);
if (element->type != ACPI_TYPE_INTEGER) {
status = AE_BAD_DATA;
goto out;
}
wakeup->sleep_state = element->integer.value;
if ((package->package.count - 2) > ACPI_MAX_HANDLES) {
status = AE_NO_MEMORY;
goto out;
}
wakeup->resources.count = package->package.count - 2;
for (i = 0; i < wakeup->resources.count; i++) {
element = &(package->package.elements[i + 2]);
if (element->type != ACPI_TYPE_LOCAL_REFERENCE) {
status = AE_BAD_DATA;
goto out;
}
wakeup->resources.handles[i] = element->reference.handle;
}
acpi_setup_gpe_for_wake(handle, wakeup->gpe_device, wakeup->gpe_number);
out:
kfree(buffer.pointer);
return status;
}
static void acpi_bus_set_run_wake_flags(struct acpi_device *device)
{
struct acpi_device_id button_device_ids[] = {
{"PNP0C0D", 0},
{"PNP0C0C", 0},
{"PNP0C0E", 0},
{"", 0},
};
acpi_status status;
acpi_event_status event_status;
device->wakeup.flags.notifier_present = 0;
/* Power button, Lid switch always enable wakeup */
if (!acpi_match_device_ids(device, button_device_ids)) {
device->wakeup.flags.run_wake = 1;
device_set_wakeup_capable(&device->dev, true);
return;
}
status = acpi_get_gpe_status(device->wakeup.gpe_device,
device->wakeup.gpe_number,
&event_status);
if (status == AE_OK)
device->wakeup.flags.run_wake =
!!(event_status & ACPI_EVENT_FLAG_HANDLE);
}
static void acpi_bus_get_wakeup_device_flags(struct acpi_device *device)
{
acpi_handle temp;
acpi_status status = 0;
int psw_error;
/* Presence of _PRW indicates wake capable */
status = acpi_get_handle(device->handle, "_PRW", &temp);
if (ACPI_FAILURE(status))
return;
status = acpi_bus_extract_wakeup_device_power_package(device->handle,
&device->wakeup);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status, "Extracting _PRW package"));
return;
}
device->wakeup.flags.valid = 1;
device->wakeup.prepare_count = 0;
acpi_bus_set_run_wake_flags(device);
/* Call _PSW/_DSW object to disable its ability to wake the sleeping
* system for the ACPI device with the _PRW object.
* The _PSW object is depreciated in ACPI 3.0 and is replaced by _DSW.
* So it is necessary to call _DSW object first. Only when it is not
* present will the _PSW object used.
*/
psw_error = acpi_device_sleep_wake(device, 0, 0, 0);
if (psw_error)
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"error in _DSW or _PSW evaluation\n"));
}
static void acpi_bus_add_power_resource(acpi_handle handle);
static int acpi_bus_get_power_flags(struct acpi_device *device)
{
acpi_status status = 0;
acpi_handle handle = NULL;
u32 i = 0;
/*
* Power Management Flags
*/
status = acpi_get_handle(device->handle, "_PSC", &handle);
if (ACPI_SUCCESS(status))
device->power.flags.explicit_get = 1;
status = acpi_get_handle(device->handle, "_IRC", &handle);
if (ACPI_SUCCESS(status))
device->power.flags.inrush_current = 1;
/*
* Enumerate supported power management states
*/
for (i = ACPI_STATE_D0; i <= ACPI_STATE_D3; i++) {
struct acpi_device_power_state *ps = &device->power.states[i];
char object_name[5] = { '_', 'P', 'R', '0' + i, '\0' };
/* Evaluate "_PRx" to se if power resources are referenced */
acpi_evaluate_reference(device->handle, object_name, NULL,
&ps->resources);
if (ps->resources.count) {
int j;
device->power.flags.power_resources = 1;
ps->flags.valid = 1;
for (j = 0; j < ps->resources.count; j++)
acpi_bus_add_power_resource(ps->resources.handles[j]);
}
/* Evaluate "_PSx" to see if we can do explicit sets */
object_name[2] = 'S';
status = acpi_get_handle(device->handle, object_name, &handle);
if (ACPI_SUCCESS(status)) {
ps->flags.explicit_set = 1;
ps->flags.valid = 1;
}
/* State is valid if we have some power control */
if (ps->resources.count || ps->flags.explicit_set)
ps->flags.valid = 1;
ps->power = -1; /* Unknown - driver assigned */
ps->latency = -1; /* Unknown - driver assigned */
}
/* Set defaults for D0 and D3 states (always valid) */
device->power.states[ACPI_STATE_D0].flags.valid = 1;
device->power.states[ACPI_STATE_D0].power = 100;
device->power.states[ACPI_STATE_D3].flags.valid = 1;
device->power.states[ACPI_STATE_D3].power = 0;
acpi_bus_init_power(device);
return 0;
}
static int acpi_bus_get_flags(struct acpi_device *device)
{
acpi_status status = AE_OK;
acpi_handle temp = NULL;
/* Presence of _STA indicates 'dynamic_status' */
status = acpi_get_handle(device->handle, "_STA", &temp);
if (ACPI_SUCCESS(status))
device->flags.dynamic_status = 1;
/* Presence of _RMV indicates 'removable' */
status = acpi_get_handle(device->handle, "_RMV", &temp);
if (ACPI_SUCCESS(status))
device->flags.removable = 1;
/* Presence of _EJD|_EJ0 indicates 'ejectable' */
status = acpi_get_handle(device->handle, "_EJD", &temp);
if (ACPI_SUCCESS(status))
device->flags.ejectable = 1;
else {
status = acpi_get_handle(device->handle, "_EJ0", &temp);
if (ACPI_SUCCESS(status))
device->flags.ejectable = 1;
}
/* Presence of _LCK indicates 'lockable' */
status = acpi_get_handle(device->handle, "_LCK", &temp);
if (ACPI_SUCCESS(status))
device->flags.lockable = 1;
/* Power resources cannot be power manageable. */
if (device->device_type == ACPI_BUS_TYPE_POWER)
return 0;
/* Presence of _PS0|_PR0 indicates 'power manageable' */
status = acpi_get_handle(device->handle, "_PS0", &temp);
if (ACPI_FAILURE(status))
status = acpi_get_handle(device->handle, "_PR0", &temp);
if (ACPI_SUCCESS(status))
device->flags.power_manageable = 1;
/* TBD: Performance management */
return 0;
}
static void acpi_device_get_busid(struct acpi_device *device)
{
char bus_id[5] = { '?', 0 };
struct acpi_buffer buffer = { sizeof(bus_id), bus_id };
int i = 0;
/*
* Bus ID
* ------
* The device's Bus ID is simply the object name.
* TBD: Shouldn't this value be unique (within the ACPI namespace)?
*/
if (ACPI_IS_ROOT_DEVICE(device)) {
strcpy(device->pnp.bus_id, "ACPI");
return;
}
switch (device->device_type) {
case ACPI_BUS_TYPE_POWER_BUTTON:
strcpy(device->pnp.bus_id, "PWRF");
break;
case ACPI_BUS_TYPE_SLEEP_BUTTON:
strcpy(device->pnp.bus_id, "SLPF");
break;
default:
acpi_get_name(device->handle, ACPI_SINGLE_NAME, &buffer);
/* Clean up trailing underscores (if any) */
for (i = 3; i > 1; i--) {
if (bus_id[i] == '_')
bus_id[i] = '\0';
else
break;
}
strcpy(device->pnp.bus_id, bus_id);
break;
}
}
/*
* acpi_bay_match - see if a device is an ejectable driver bay
*
* If an acpi object is ejectable and has one of the ACPI ATA methods defined,
* then we can safely call it an ejectable drive bay
*/
static int acpi_bay_match(struct acpi_device *device){
acpi_status status;
acpi_handle handle;
acpi_handle tmp;
acpi_handle phandle;
handle = device->handle;
status = acpi_get_handle(handle, "_EJ0", &tmp);
if (ACPI_FAILURE(status))
return -ENODEV;
if ((ACPI_SUCCESS(acpi_get_handle(handle, "_GTF", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_GTM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_STM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_SDD", &tmp))))
return 0;
if (acpi_get_parent(handle, &phandle))
return -ENODEV;
if ((ACPI_SUCCESS(acpi_get_handle(phandle, "_GTF", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(phandle, "_GTM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(phandle, "_STM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(phandle, "_SDD", &tmp))))
return 0;
return -ENODEV;
}
/*
* acpi_dock_match - see if a device has a _DCK method
*/
static int acpi_dock_match(struct acpi_device *device)
{
acpi_handle tmp;
return acpi_get_handle(device->handle, "_DCK", &tmp);
}
const char *acpi_device_hid(struct acpi_device *device)
{
struct acpi_hardware_id *hid;
if (list_empty(&device->pnp.ids))
return dummy_hid;
hid = list_first_entry(&device->pnp.ids, struct acpi_hardware_id, list);
return hid->id;
}
EXPORT_SYMBOL(acpi_device_hid);
static void acpi_add_id(struct acpi_device *device, const char *dev_id)
{
struct acpi_hardware_id *id;
id = kmalloc(sizeof(*id), GFP_KERNEL);
if (!id)
return;
id->id = kmalloc(strlen(dev_id) + 1, GFP_KERNEL);
if (!id->id) {
kfree(id);
return;
}
strcpy(id->id, dev_id);
list_add_tail(&id->list, &device->pnp.ids);
}
/*
* Old IBM workstations have a DSDT bug wherein the SMBus object
* lacks the SMBUS01 HID and the methods do not have the necessary "_"
* prefix. Work around this.
*/
static int acpi_ibm_smbus_match(struct acpi_device *device)
{
acpi_handle h_dummy;
struct acpi_buffer path = {ACPI_ALLOCATE_BUFFER, NULL};
int result;
if (!dmi_name_in_vendors("IBM"))
return -ENODEV;
/* Look for SMBS object */
result = acpi_get_name(device->handle, ACPI_SINGLE_NAME, &path);
if (result)
return result;
if (strcmp("SMBS", path.pointer)) {
result = -ENODEV;
goto out;
}
/* Does it have the necessary (but misnamed) methods? */
result = -ENODEV;
if (ACPI_SUCCESS(acpi_get_handle(device->handle, "SBI", &h_dummy)) &&
ACPI_SUCCESS(acpi_get_handle(device->handle, "SBR", &h_dummy)) &&
ACPI_SUCCESS(acpi_get_handle(device->handle, "SBW", &h_dummy)))
result = 0;
out:
kfree(path.pointer);
return result;
}
static void acpi_device_set_id(struct acpi_device *device)
{
acpi_status status;
struct acpi_device_info *info;
struct acpica_device_id_list *cid_list;
int i;
switch (device->device_type) {
case ACPI_BUS_TYPE_DEVICE:
if (ACPI_IS_ROOT_DEVICE(device)) {
acpi_add_id(device, ACPI_SYSTEM_HID);
break;
}
status = acpi_get_object_info(device->handle, &info);
if (ACPI_FAILURE(status)) {
printk(KERN_ERR PREFIX "%s: Error reading device info\n", __func__);
return;
}
if (info->valid & ACPI_VALID_HID)
acpi_add_id(device, info->hardware_id.string);
if (info->valid & ACPI_VALID_CID) {
cid_list = &info->compatible_id_list;
for (i = 0; i < cid_list->count; i++)
acpi_add_id(device, cid_list->ids[i].string);
}
if (info->valid & ACPI_VALID_ADR) {
device->pnp.bus_address = info->address;
device->flags.bus_address = 1;
}
kfree(info);
/*
* Some devices don't reliably have _HIDs & _CIDs, so add
* synthetic HIDs to make sure drivers can find them.
*/
if (acpi_is_video_device(device))
acpi_add_id(device, ACPI_VIDEO_HID);
else if (ACPI_SUCCESS(acpi_bay_match(device)))
acpi_add_id(device, ACPI_BAY_HID);
else if (ACPI_SUCCESS(acpi_dock_match(device)))
acpi_add_id(device, ACPI_DOCK_HID);
else if (!acpi_ibm_smbus_match(device))
acpi_add_id(device, ACPI_SMBUS_IBM_HID);
else if (!acpi_device_hid(device) &&
ACPI_IS_ROOT_DEVICE(device->parent)) {
acpi_add_id(device, ACPI_BUS_HID); /* \_SB, LNXSYBUS */
strcpy(device->pnp.device_name, ACPI_BUS_DEVICE_NAME);
strcpy(device->pnp.device_class, ACPI_BUS_CLASS);
}
break;
case ACPI_BUS_TYPE_POWER:
acpi_add_id(device, ACPI_POWER_HID);
break;
case ACPI_BUS_TYPE_PROCESSOR:
acpi_add_id(device, ACPI_PROCESSOR_OBJECT_HID);
break;
case ACPI_BUS_TYPE_THERMAL:
acpi_add_id(device, ACPI_THERMAL_HID);
break;
case ACPI_BUS_TYPE_POWER_BUTTON:
acpi_add_id(device, ACPI_BUTTON_HID_POWERF);
break;
case ACPI_BUS_TYPE_SLEEP_BUTTON:
acpi_add_id(device, ACPI_BUTTON_HID_SLEEPF);
break;
}
}
static int acpi_device_set_context(struct acpi_device *device)
{
acpi_status status;
/*
* Context
* -------
* Attach this 'struct acpi_device' to the ACPI object. This makes
* resolutions from handle->device very efficient. Fixed hardware
* devices have no handles, so we skip them.
*/
if (!device->handle)
return 0;
status = acpi_attach_data(device->handle,
acpi_bus_data_handler, device);
if (ACPI_SUCCESS(status))
return 0;
printk(KERN_ERR PREFIX "Error attaching device data\n");
return -ENODEV;
}
static int acpi_bus_remove(struct acpi_device *dev, int rmdevice)
{
if (!dev)
return -EINVAL;
dev->removal_type = ACPI_BUS_REMOVAL_EJECT;
device_release_driver(&dev->dev);
if (!rmdevice)
return 0;
/*
* unbind _ADR-Based Devices when hot removal
*/
if (dev->flags.bus_address) {
if ((dev->parent) && (dev->parent->ops.unbind))
dev->parent->ops.unbind(dev);
}
acpi_device_unregister(dev, ACPI_BUS_REMOVAL_EJECT);
return 0;
}
static int acpi_add_single_object(struct acpi_device **child,
acpi_handle handle, int type,
unsigned long long sta,
struct acpi_bus_ops *ops)
{
int result;
struct acpi_device *device;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
device = kzalloc(sizeof(struct acpi_device), GFP_KERNEL);
if (!device) {
printk(KERN_ERR PREFIX "Memory allocation error\n");
return -ENOMEM;
}
INIT_LIST_HEAD(&device->pnp.ids);
device->device_type = type;
device->handle = handle;
device->parent = acpi_bus_get_parent(handle);
device->bus_ops = *ops; /* workround for not call .start */
STRUCT_TO_INT(device->status) = sta;
acpi_device_get_busid(device);
/*
* Flags
* -----
* Note that we only look for object handles -- cannot evaluate objects
* until we know the device is present and properly initialized.
*/
result = acpi_bus_get_flags(device);
if (result)
goto end;
/*
* Initialize Device
* -----------------
* TBD: Synch with Core's enumeration/initialization process.
*/
acpi_device_set_id(device);
/*
* Power Management
* ----------------
*/
if (device->flags.power_manageable) {
result = acpi_bus_get_power_flags(device);
if (result)
goto end;
}
/*
* Wakeup device management
*-----------------------
*/
acpi_bus_get_wakeup_device_flags(device);
/*
* Performance Management
* ----------------------
*/
if (device->flags.performance_manageable) {
result = acpi_bus_get_perf_flags(device);
if (result)
goto end;
}
if ((result = acpi_device_set_context(device)))
goto end;
result = acpi_device_register(device);
/*
* Bind _ADR-Based Devices when hot add
*/
if (device->flags.bus_address) {
if (device->parent && device->parent->ops.bind)
device->parent->ops.bind(device);
}
end:
if (!result) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer);
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Adding %s [%s] parent %s\n", dev_name(&device->dev),
(char *) buffer.pointer,
device->parent ? dev_name(&device->parent->dev) :
"(null)"));
kfree(buffer.pointer);
*child = device;
} else
acpi_device_release(&device->dev);
return result;
}
#define ACPI_STA_DEFAULT (ACPI_STA_DEVICE_PRESENT | ACPI_STA_DEVICE_ENABLED | \
ACPI_STA_DEVICE_UI | ACPI_STA_DEVICE_FUNCTIONING)
static void acpi_bus_add_power_resource(acpi_handle handle)
{
struct acpi_bus_ops ops = {
.acpi_op_add = 1,
.acpi_op_start = 1,
};
struct acpi_device *device = NULL;
acpi_bus_get_device(handle, &device);
if (!device)
acpi_add_single_object(&device, handle, ACPI_BUS_TYPE_POWER,
ACPI_STA_DEFAULT, &ops);
}
static int acpi_bus_type_and_status(acpi_handle handle, int *type,
unsigned long long *sta)
{
acpi_status status;
acpi_object_type acpi_type;
status = acpi_get_type(handle, &acpi_type);
if (ACPI_FAILURE(status))
return -ENODEV;
switch (acpi_type) {
case ACPI_TYPE_ANY: /* for ACPI_ROOT_OBJECT */
case ACPI_TYPE_DEVICE:
*type = ACPI_BUS_TYPE_DEVICE;
status = acpi_bus_get_status_handle(handle, sta);
if (ACPI_FAILURE(status))
return -ENODEV;
break;
case ACPI_TYPE_PROCESSOR:
*type = ACPI_BUS_TYPE_PROCESSOR;
status = acpi_bus_get_status_handle(handle, sta);
if (ACPI_FAILURE(status))
return -ENODEV;
break;
case ACPI_TYPE_THERMAL:
*type = ACPI_BUS_TYPE_THERMAL;
*sta = ACPI_STA_DEFAULT;
break;
case ACPI_TYPE_POWER:
*type = ACPI_BUS_TYPE_POWER;
*sta = ACPI_STA_DEFAULT;
break;
default:
return -ENODEV;
}
return 0;
}
static acpi_status acpi_bus_check_add(acpi_handle handle, u32 lvl,
void *context, void **return_value)
{
struct acpi_bus_ops *ops = context;
int type;
unsigned long long sta;
struct acpi_device *device;
acpi_status status;
int result;
result = acpi_bus_type_and_status(handle, &type, &sta);
if (result)
return AE_OK;
if (!(sta & ACPI_STA_DEVICE_PRESENT) &&
!(sta & ACPI_STA_DEVICE_FUNCTIONING)) {
struct acpi_device_wakeup wakeup;
acpi_handle temp;
status = acpi_get_handle(handle, "_PRW", &temp);
if (ACPI_SUCCESS(status))
acpi_bus_extract_wakeup_device_power_package(handle,
&wakeup);
return AE_CTRL_DEPTH;
}
/*
* We may already have an acpi_device from a previous enumeration. If
* so, we needn't add it again, but we may still have to start it.
*/
device = NULL;
acpi_bus_get_device(handle, &device);
if (ops->acpi_op_add && !device)
acpi_add_single_object(&device, handle, type, sta, ops);
if (!device)
return AE_CTRL_DEPTH;
if (ops->acpi_op_start && !(ops->acpi_op_add)) {
status = acpi_start_single_object(device);
if (ACPI_FAILURE(status))
return AE_CTRL_DEPTH;
}
if (!*return_value)
*return_value = device;
return AE_OK;
}
static int acpi_bus_scan(acpi_handle handle, struct acpi_bus_ops *ops,
struct acpi_device **child)
{
acpi_status status;
void *device = NULL;
status = acpi_bus_check_add(handle, 0, ops, &device);
if (ACPI_SUCCESS(status))
acpi_walk_namespace(ACPI_TYPE_ANY, handle, ACPI_UINT32_MAX,
acpi_bus_check_add, NULL, ops, &device);
if (child)
*child = device;
if (device)
return 0;
else
return -ENODEV;
}
/*
* acpi_bus_add and acpi_bus_start
*
* scan a given ACPI tree and (probably recently hot-plugged)
* create and add or starts found devices.
*
* If no devices were found -ENODEV is returned which does not
* mean that this is a real error, there just have been no suitable
* ACPI objects in the table trunk from which the kernel could create
* a device and add/start an appropriate driver.
*/
int
acpi_bus_add(struct acpi_device **child,
struct acpi_device *parent, acpi_handle handle, int type)
{
struct acpi_bus_ops ops;
memset(&ops, 0, sizeof(ops));
ops.acpi_op_add = 1;
return acpi_bus_scan(handle, &ops, child);
}
EXPORT_SYMBOL(acpi_bus_add);
int acpi_bus_start(struct acpi_device *device)
{
struct acpi_bus_ops ops;
int result;
if (!device)
return -EINVAL;
memset(&ops, 0, sizeof(ops));
ops.acpi_op_start = 1;
result = acpi_bus_scan(device->handle, &ops, NULL);
acpi_update_all_gpes();
return result;
}
EXPORT_SYMBOL(acpi_bus_start);
int acpi_bus_trim(struct acpi_device *start, int rmdevice)
{
acpi_status status;
struct acpi_device *parent, *child;
acpi_handle phandle, chandle;
acpi_object_type type;
u32 level = 1;
int err = 0;
parent = start;
phandle = start->handle;
child = chandle = NULL;
while ((level > 0) && parent && (!err)) {
status = acpi_get_next_object(ACPI_TYPE_ANY, phandle,
chandle, &chandle);
/*
* If this scope is exhausted then move our way back up.
*/
if (ACPI_FAILURE(status)) {
level--;
chandle = phandle;
acpi_get_parent(phandle, &phandle);
child = parent;
parent = parent->parent;
if (level == 0)
err = acpi_bus_remove(child, rmdevice);
else
err = acpi_bus_remove(child, 1);
continue;
}
status = acpi_get_type(chandle, &type);
if (ACPI_FAILURE(status)) {
continue;
}
/*
* If there is a device corresponding to chandle then
* parse it (depth-first).
*/
if (acpi_bus_get_device(chandle, &child) == 0) {
level++;
phandle = chandle;
chandle = NULL;
parent = child;
}
continue;
}
return err;
}
EXPORT_SYMBOL_GPL(acpi_bus_trim);
static int acpi_bus_scan_fixed(void)
{
int result = 0;
struct acpi_device *device = NULL;
struct acpi_bus_ops ops;
memset(&ops, 0, sizeof(ops));
ops.acpi_op_add = 1;
ops.acpi_op_start = 1;
/*
* Enumerate all fixed-feature devices.
*/
if ((acpi_gbl_FADT.flags & ACPI_FADT_POWER_BUTTON) == 0) {
result = acpi_add_single_object(&device, NULL,
ACPI_BUS_TYPE_POWER_BUTTON,
ACPI_STA_DEFAULT,
&ops);
}
if ((acpi_gbl_FADT.flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
result = acpi_add_single_object(&device, NULL,
ACPI_BUS_TYPE_SLEEP_BUTTON,
ACPI_STA_DEFAULT,
&ops);
}
return result;
}
int __init acpi_scan_init(void)
{
int result;
struct acpi_bus_ops ops;
memset(&ops, 0, sizeof(ops));
ops.acpi_op_add = 1;
ops.acpi_op_start = 1;
result = bus_register(&acpi_bus_type);
if (result) {
/* We don't want to quit even if we failed to add suspend/resume */
printk(KERN_ERR PREFIX "Could not register bus type\n");
}
acpi_power_init();
/*
* Enumerate devices in the ACPI namespace.
*/
result = acpi_bus_scan(ACPI_ROOT_OBJECT, &ops, &acpi_root);
if (!result)
result = acpi_bus_scan_fixed();
if (result)
acpi_device_unregister(acpi_root, ACPI_BUS_REMOVAL_NORMAL);
else
acpi_update_all_gpes();
return result;
}
| gpl-2.0 |
MoKee/android_kernel_htc_flounder | arch/x86/kernel/machine_kexec_64.c | 2327 | 6793 | /*
* handle transition of Linux booting another kernel
* Copyright (C) 2002-2005 Eric Biederman <ebiederm@xmission.com>
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/mm.h>
#include <linux/kexec.h>
#include <linux/string.h>
#include <linux/gfp.h>
#include <linux/reboot.h>
#include <linux/numa.h>
#include <linux/ftrace.h>
#include <linux/io.h>
#include <linux/suspend.h>
#include <asm/init.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include <asm/mmu_context.h>
#include <asm/debugreg.h>
static void free_transition_pgtable(struct kimage *image)
{
free_page((unsigned long)image->arch.pud);
free_page((unsigned long)image->arch.pmd);
free_page((unsigned long)image->arch.pte);
}
static int init_transition_pgtable(struct kimage *image, pgd_t *pgd)
{
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
unsigned long vaddr, paddr;
int result = -ENOMEM;
vaddr = (unsigned long)relocate_kernel;
paddr = __pa(page_address(image->control_code_page)+PAGE_SIZE);
pgd += pgd_index(vaddr);
if (!pgd_present(*pgd)) {
pud = (pud_t *)get_zeroed_page(GFP_KERNEL);
if (!pud)
goto err;
image->arch.pud = pud;
set_pgd(pgd, __pgd(__pa(pud) | _KERNPG_TABLE));
}
pud = pud_offset(pgd, vaddr);
if (!pud_present(*pud)) {
pmd = (pmd_t *)get_zeroed_page(GFP_KERNEL);
if (!pmd)
goto err;
image->arch.pmd = pmd;
set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE));
}
pmd = pmd_offset(pud, vaddr);
if (!pmd_present(*pmd)) {
pte = (pte_t *)get_zeroed_page(GFP_KERNEL);
if (!pte)
goto err;
image->arch.pte = pte;
set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE));
}
pte = pte_offset_kernel(pmd, vaddr);
set_pte(pte, pfn_pte(paddr >> PAGE_SHIFT, PAGE_KERNEL_EXEC));
return 0;
err:
free_transition_pgtable(image);
return result;
}
static void *alloc_pgt_page(void *data)
{
struct kimage *image = (struct kimage *)data;
struct page *page;
void *p = NULL;
page = kimage_alloc_control_pages(image, 0);
if (page) {
p = page_address(page);
clear_page(p);
}
return p;
}
static int init_pgtable(struct kimage *image, unsigned long start_pgtable)
{
struct x86_mapping_info info = {
.alloc_pgt_page = alloc_pgt_page,
.context = image,
.pmd_flag = __PAGE_KERNEL_LARGE_EXEC,
};
unsigned long mstart, mend;
pgd_t *level4p;
int result;
int i;
level4p = (pgd_t *)__va(start_pgtable);
clear_page(level4p);
for (i = 0; i < nr_pfn_mapped; i++) {
mstart = pfn_mapped[i].start << PAGE_SHIFT;
mend = pfn_mapped[i].end << PAGE_SHIFT;
result = kernel_ident_mapping_init(&info,
level4p, mstart, mend);
if (result)
return result;
}
/*
* segments's mem ranges could be outside 0 ~ max_pfn,
* for example when jump back to original kernel from kexeced kernel.
* or first kernel is booted with user mem map, and second kernel
* could be loaded out of that range.
*/
for (i = 0; i < image->nr_segments; i++) {
mstart = image->segment[i].mem;
mend = mstart + image->segment[i].memsz;
result = kernel_ident_mapping_init(&info,
level4p, mstart, mend);
if (result)
return result;
}
return init_transition_pgtable(image, level4p);
}
static void set_idt(void *newidt, u16 limit)
{
struct desc_ptr curidt;
/* x86-64 supports unaliged loads & stores */
curidt.size = limit;
curidt.address = (unsigned long)newidt;
__asm__ __volatile__ (
"lidtq %0\n"
: : "m" (curidt)
);
};
static void set_gdt(void *newgdt, u16 limit)
{
struct desc_ptr curgdt;
/* x86-64 supports unaligned loads & stores */
curgdt.size = limit;
curgdt.address = (unsigned long)newgdt;
__asm__ __volatile__ (
"lgdtq %0\n"
: : "m" (curgdt)
);
};
static void load_segments(void)
{
__asm__ __volatile__ (
"\tmovl %0,%%ds\n"
"\tmovl %0,%%es\n"
"\tmovl %0,%%ss\n"
"\tmovl %0,%%fs\n"
"\tmovl %0,%%gs\n"
: : "a" (__KERNEL_DS) : "memory"
);
}
int machine_kexec_prepare(struct kimage *image)
{
unsigned long start_pgtable;
int result;
/* Calculate the offsets */
start_pgtable = page_to_pfn(image->control_code_page) << PAGE_SHIFT;
/* Setup the identity mapped 64bit page table */
result = init_pgtable(image, start_pgtable);
if (result)
return result;
return 0;
}
void machine_kexec_cleanup(struct kimage *image)
{
free_transition_pgtable(image);
}
/*
* Do not allocate memory (or fail in any way) in machine_kexec().
* We are past the point of no return, committed to rebooting now.
*/
void machine_kexec(struct kimage *image)
{
unsigned long page_list[PAGES_NR];
void *control_page;
int save_ftrace_enabled;
#ifdef CONFIG_KEXEC_JUMP
if (image->preserve_context)
save_processor_state();
#endif
save_ftrace_enabled = __ftrace_enabled_save();
/* Interrupts aren't acceptable while we reboot */
local_irq_disable();
hw_breakpoint_disable();
if (image->preserve_context) {
#ifdef CONFIG_X86_IO_APIC
/*
* We need to put APICs in legacy mode so that we can
* get timer interrupts in second kernel. kexec/kdump
* paths already have calls to disable_IO_APIC() in
* one form or other. kexec jump path also need
* one.
*/
disable_IO_APIC();
#endif
}
control_page = page_address(image->control_code_page) + PAGE_SIZE;
memcpy(control_page, relocate_kernel, KEXEC_CONTROL_CODE_MAX_SIZE);
page_list[PA_CONTROL_PAGE] = virt_to_phys(control_page);
page_list[VA_CONTROL_PAGE] = (unsigned long)control_page;
page_list[PA_TABLE_PAGE] =
(unsigned long)__pa(page_address(image->control_code_page));
if (image->type == KEXEC_TYPE_DEFAULT)
page_list[PA_SWAP_PAGE] = (page_to_pfn(image->swap_page)
<< PAGE_SHIFT);
/*
* The segment registers are funny things, they have both a
* visible and an invisible part. Whenever the visible part is
* set to a specific selector, the invisible part is loaded
* with from a table in memory. At no other time is the
* descriptor table in memory accessed.
*
* I take advantage of this here by force loading the
* segments, before I zap the gdt with an invalid value.
*/
load_segments();
/*
* The gdt & idt are now invalid.
* If you want to load them you must set up your own idt & gdt.
*/
set_gdt(phys_to_virt(0), 0);
set_idt(phys_to_virt(0), 0);
/* now call it */
image->start = relocate_kernel((unsigned long)image->head,
(unsigned long)page_list,
image->start,
image->preserve_context);
#ifdef CONFIG_KEXEC_JUMP
if (image->preserve_context)
restore_processor_state();
#endif
__ftrace_enabled_restore(save_ftrace_enabled);
}
void arch_crash_save_vmcoreinfo(void)
{
VMCOREINFO_SYMBOL(phys_base);
VMCOREINFO_SYMBOL(init_level4_pgt);
#ifdef CONFIG_NUMA
VMCOREINFO_SYMBOL(node_data);
VMCOREINFO_LENGTH(node_data, MAX_NUMNODES);
#endif
}
| gpl-2.0 |
rutvik95/android_kernel_frostbite | drivers/net/wireless/b43legacy/rfkill.c | 2583 | 2664 | /*
Broadcom B43 wireless driver
RFKILL support
Copyright (c) 2007 Michael Buesch <mb@bu3sch.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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "radio.h"
#include "b43legacy.h"
/* Returns TRUE, if the radio is enabled in hardware. */
bool b43legacy_is_hw_radio_enabled(struct b43legacy_wldev *dev)
{
if (dev->dev->id.revision >= 3) {
if (!(b43legacy_read32(dev, B43legacy_MMIO_RADIO_HWENABLED_HI)
& B43legacy_MMIO_RADIO_HWENABLED_HI_MASK))
return 1;
} else {
/* To prevent CPU fault on PPC, do not read a register
* unless the interface is started; however, on resume
* for hibernation, this routine is entered early. When
* that happens, unconditionally return TRUE.
*/
if (b43legacy_status(dev) < B43legacy_STAT_STARTED)
return 1;
if (b43legacy_read16(dev, B43legacy_MMIO_RADIO_HWENABLED_LO)
& B43legacy_MMIO_RADIO_HWENABLED_LO_MASK)
return 1;
}
return 0;
}
/* The poll callback for the hardware button. */
void b43legacy_rfkill_poll(struct ieee80211_hw *hw)
{
struct b43legacy_wl *wl = hw_to_b43legacy_wl(hw);
struct b43legacy_wldev *dev = wl->current_dev;
struct ssb_bus *bus = dev->dev->bus;
bool enabled;
bool brought_up = false;
mutex_lock(&wl->mutex);
if (unlikely(b43legacy_status(dev) < B43legacy_STAT_INITIALIZED)) {
if (ssb_bus_powerup(bus, 0)) {
mutex_unlock(&wl->mutex);
return;
}
ssb_device_enable(dev->dev, 0);
brought_up = true;
}
enabled = b43legacy_is_hw_radio_enabled(dev);
if (unlikely(enabled != dev->radio_hw_enable)) {
dev->radio_hw_enable = enabled;
b43legacyinfo(wl, "Radio hardware status changed to %s\n",
enabled ? "ENABLED" : "DISABLED");
wiphy_rfkill_set_hw_state(hw->wiphy, !enabled);
if (enabled != dev->phy.radio_on) {
if (enabled)
b43legacy_radio_turn_on(dev);
else
b43legacy_radio_turn_off(dev, 0);
}
}
if (brought_up) {
ssb_device_disable(dev->dev, 0);
ssb_bus_may_powerdown(bus);
}
mutex_unlock(&wl->mutex);
}
| gpl-2.0 |
STS-Dev-Team/kernel_mapphone_kexec | arch/mn10300/kernel/smp.c | 2839 | 28219 | /* SMP support routines.
*
* Copyright (C) 2006-2008 Panasonic Corporation
* 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 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/cpumask.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/profile.h>
#include <linux/smp.h>
#include <asm/tlbflush.h>
#include <asm/system.h>
#include <asm/bitops.h>
#include <asm/processor.h>
#include <asm/bug.h>
#include <asm/exceptions.h>
#include <asm/hardirq.h>
#include <asm/fpu.h>
#include <asm/mmu_context.h>
#include <asm/thread_info.h>
#include <asm/cpu-regs.h>
#include <asm/intctl-regs.h>
#include "internal.h"
#ifdef CONFIG_HOTPLUG_CPU
#include <linux/cpu.h>
#include <asm/cacheflush.h>
static unsigned long sleep_mode[NR_CPUS];
static void run_sleep_cpu(unsigned int cpu);
static void run_wakeup_cpu(unsigned int cpu);
#endif /* CONFIG_HOTPLUG_CPU */
/*
* Debug Message function
*/
#undef DEBUG_SMP
#ifdef DEBUG_SMP
#define Dprintk(fmt, ...) printk(KERN_DEBUG fmt, ##__VA_ARGS__)
#else
#define Dprintk(fmt, ...) no_printk(KERN_DEBUG fmt, ##__VA_ARGS__)
#endif
/* timeout value in msec for smp_nmi_call_function. zero is no timeout. */
#define CALL_FUNCTION_NMI_IPI_TIMEOUT 0
/*
* Structure and data for smp_nmi_call_function().
*/
struct nmi_call_data_struct {
smp_call_func_t func;
void *info;
cpumask_t started;
cpumask_t finished;
int wait;
char size_alignment[0]
__attribute__ ((__aligned__(SMP_CACHE_BYTES)));
} __attribute__ ((__aligned__(SMP_CACHE_BYTES)));
static DEFINE_SPINLOCK(smp_nmi_call_lock);
static struct nmi_call_data_struct *nmi_call_data;
/*
* Data structures and variables
*/
static cpumask_t cpu_callin_map; /* Bitmask of callin CPUs */
static cpumask_t cpu_callout_map; /* Bitmask of callout CPUs */
cpumask_t cpu_boot_map; /* Bitmask of boot APs */
unsigned long start_stack[NR_CPUS - 1];
/*
* Per CPU parameters
*/
struct mn10300_cpuinfo cpu_data[NR_CPUS] __cacheline_aligned;
static int cpucount; /* The count of boot CPUs */
static cpumask_t smp_commenced_mask;
cpumask_t cpu_initialized __initdata = CPU_MASK_NONE;
/*
* Function Prototypes
*/
static int do_boot_cpu(int);
static void smp_show_cpu_info(int cpu_id);
static void smp_callin(void);
static void smp_online(void);
static void smp_store_cpu_info(int);
static void smp_cpu_init(void);
static void smp_tune_scheduling(void);
static void send_IPI_mask(const cpumask_t *cpumask, int irq);
static void init_ipi(void);
/*
* IPI Initialization interrupt definitions
*/
static void mn10300_ipi_disable(unsigned int irq);
static void mn10300_ipi_enable(unsigned int irq);
static void mn10300_ipi_chip_disable(struct irq_data *d);
static void mn10300_ipi_chip_enable(struct irq_data *d);
static void mn10300_ipi_ack(struct irq_data *d);
static void mn10300_ipi_nop(struct irq_data *d);
static struct irq_chip mn10300_ipi_type = {
.name = "cpu_ipi",
.irq_disable = mn10300_ipi_chip_disable,
.irq_enable = mn10300_ipi_chip_enable,
.irq_ack = mn10300_ipi_ack,
.irq_eoi = mn10300_ipi_nop
};
static irqreturn_t smp_reschedule_interrupt(int irq, void *dev_id);
static irqreturn_t smp_call_function_interrupt(int irq, void *dev_id);
static struct irqaction reschedule_ipi = {
.handler = smp_reschedule_interrupt,
.name = "smp reschedule IPI"
};
static struct irqaction call_function_ipi = {
.handler = smp_call_function_interrupt,
.name = "smp call function IPI"
};
#if !defined(CONFIG_GENERIC_CLOCKEVENTS) || defined(CONFIG_GENERIC_CLOCKEVENTS_BROADCAST)
static irqreturn_t smp_ipi_timer_interrupt(int irq, void *dev_id);
static struct irqaction local_timer_ipi = {
.handler = smp_ipi_timer_interrupt,
.flags = IRQF_DISABLED,
.name = "smp local timer IPI"
};
#endif
/**
* init_ipi - Initialise the IPI mechanism
*/
static void init_ipi(void)
{
unsigned long flags;
u16 tmp16;
/* set up the reschedule IPI */
irq_set_chip_and_handler(RESCHEDULE_IPI, &mn10300_ipi_type,
handle_percpu_irq);
setup_irq(RESCHEDULE_IPI, &reschedule_ipi);
set_intr_level(RESCHEDULE_IPI, RESCHEDULE_GxICR_LV);
mn10300_ipi_enable(RESCHEDULE_IPI);
/* set up the call function IPI */
irq_set_chip_and_handler(CALL_FUNC_SINGLE_IPI, &mn10300_ipi_type,
handle_percpu_irq);
setup_irq(CALL_FUNC_SINGLE_IPI, &call_function_ipi);
set_intr_level(CALL_FUNC_SINGLE_IPI, CALL_FUNCTION_GxICR_LV);
mn10300_ipi_enable(CALL_FUNC_SINGLE_IPI);
/* set up the local timer IPI */
#if !defined(CONFIG_GENERIC_CLOCKEVENTS) || \
defined(CONFIG_GENERIC_CLOCKEVENTS_BROADCAST)
irq_set_chip_and_handler(LOCAL_TIMER_IPI, &mn10300_ipi_type,
handle_percpu_irq);
setup_irq(LOCAL_TIMER_IPI, &local_timer_ipi);
set_intr_level(LOCAL_TIMER_IPI, LOCAL_TIMER_GxICR_LV);
mn10300_ipi_enable(LOCAL_TIMER_IPI);
#endif
#ifdef CONFIG_MN10300_CACHE_ENABLED
/* set up the cache flush IPI */
flags = arch_local_cli_save();
__set_intr_stub(NUM2EXCEP_IRQ_LEVEL(FLUSH_CACHE_GxICR_LV),
mn10300_low_ipi_handler);
GxICR(FLUSH_CACHE_IPI) = FLUSH_CACHE_GxICR_LV | GxICR_DETECT;
mn10300_ipi_enable(FLUSH_CACHE_IPI);
arch_local_irq_restore(flags);
#endif
/* set up the NMI call function IPI */
flags = arch_local_cli_save();
GxICR(CALL_FUNCTION_NMI_IPI) = GxICR_NMI | GxICR_ENABLE | GxICR_DETECT;
tmp16 = GxICR(CALL_FUNCTION_NMI_IPI);
arch_local_irq_restore(flags);
/* set up the SMP boot IPI */
flags = arch_local_cli_save();
__set_intr_stub(NUM2EXCEP_IRQ_LEVEL(SMP_BOOT_GxICR_LV),
mn10300_low_ipi_handler);
arch_local_irq_restore(flags);
}
/**
* mn10300_ipi_shutdown - Shut down handling of an IPI
* @irq: The IPI to be shut down.
*/
static void mn10300_ipi_shutdown(unsigned int irq)
{
unsigned long flags;
u16 tmp;
flags = arch_local_cli_save();
tmp = GxICR(irq);
GxICR(irq) = (tmp & GxICR_LEVEL) | GxICR_DETECT;
tmp = GxICR(irq);
arch_local_irq_restore(flags);
}
/**
* mn10300_ipi_enable - Enable an IPI
* @irq: The IPI to be enabled.
*/
static void mn10300_ipi_enable(unsigned int irq)
{
unsigned long flags;
u16 tmp;
flags = arch_local_cli_save();
tmp = GxICR(irq);
GxICR(irq) = (tmp & GxICR_LEVEL) | GxICR_ENABLE;
tmp = GxICR(irq);
arch_local_irq_restore(flags);
}
static void mn10300_ipi_chip_enable(struct irq_data *d)
{
mn10300_ipi_enable(d->irq);
}
/**
* mn10300_ipi_disable - Disable an IPI
* @irq: The IPI to be disabled.
*/
static void mn10300_ipi_disable(unsigned int irq)
{
unsigned long flags;
u16 tmp;
flags = arch_local_cli_save();
tmp = GxICR(irq);
GxICR(irq) = tmp & GxICR_LEVEL;
tmp = GxICR(irq);
arch_local_irq_restore(flags);
}
static void mn10300_ipi_chip_disable(struct irq_data *d)
{
mn10300_ipi_disable(d->irq);
}
/**
* mn10300_ipi_ack - Acknowledge an IPI interrupt in the PIC
* @irq: The IPI to be acknowledged.
*
* Clear the interrupt detection flag for the IPI on the appropriate interrupt
* channel in the PIC.
*/
static void mn10300_ipi_ack(struct irq_data *d)
{
unsigned int irq = d->irq;
unsigned long flags;
u16 tmp;
flags = arch_local_cli_save();
GxICR_u8(irq) = GxICR_DETECT;
tmp = GxICR(irq);
arch_local_irq_restore(flags);
}
/**
* mn10300_ipi_nop - Dummy IPI action
* @irq: The IPI to be acted upon.
*/
static void mn10300_ipi_nop(struct irq_data *d)
{
}
/**
* send_IPI_mask - Send IPIs to all CPUs in list
* @cpumask: The list of CPUs to target.
* @irq: The IPI request to be sent.
*
* Send the specified IPI to all the CPUs in the list, not waiting for them to
* finish before returning. The caller is responsible for synchronisation if
* that is needed.
*/
static void send_IPI_mask(const cpumask_t *cpumask, int irq)
{
int i;
u16 tmp;
for (i = 0; i < NR_CPUS; i++) {
if (cpumask_test_cpu(i, cpumask)) {
/* send IPI */
tmp = CROSS_GxICR(irq, i);
CROSS_GxICR(irq, i) =
tmp | GxICR_REQUEST | GxICR_DETECT;
tmp = CROSS_GxICR(irq, i); /* flush write buffer */
}
}
}
/**
* send_IPI_self - Send an IPI to this CPU.
* @irq: The IPI request to be sent.
*
* Send the specified IPI to the current CPU.
*/
void send_IPI_self(int irq)
{
send_IPI_mask(cpumask_of(smp_processor_id()), irq);
}
/**
* send_IPI_allbutself - Send IPIs to all the other CPUs.
* @irq: The IPI request to be sent.
*
* Send the specified IPI to all CPUs in the system barring the current one,
* not waiting for them to finish before returning. The caller is responsible
* for synchronisation if that is needed.
*/
void send_IPI_allbutself(int irq)
{
cpumask_t cpumask;
cpumask_copy(&cpumask, cpu_online_mask);
cpumask_clear_cpu(smp_processor_id(), &cpumask);
send_IPI_mask(&cpumask, irq);
}
void arch_send_call_function_ipi_mask(const struct cpumask *mask)
{
BUG();
/*send_IPI_mask(mask, CALL_FUNCTION_IPI);*/
}
void arch_send_call_function_single_ipi(int cpu)
{
send_IPI_mask(cpumask_of(cpu), CALL_FUNC_SINGLE_IPI);
}
/**
* smp_send_reschedule - Send reschedule IPI to a CPU
* @cpu: The CPU to target.
*/
void smp_send_reschedule(int cpu)
{
send_IPI_mask(cpumask_of(cpu), RESCHEDULE_IPI);
}
/**
* smp_nmi_call_function - Send a call function NMI IPI to all CPUs
* @func: The function to ask to be run.
* @info: The context data to pass to that function.
* @wait: If true, wait (atomically) until function is run on all CPUs.
*
* Send a non-maskable request to all CPUs in the system, requesting them to
* run the specified function with the given context data, and, potentially, to
* wait for completion of that function on all CPUs.
*
* Returns 0 if successful, -ETIMEDOUT if we were asked to wait, but hit the
* timeout.
*/
int smp_nmi_call_function(smp_call_func_t func, void *info, int wait)
{
struct nmi_call_data_struct data;
unsigned long flags;
unsigned int cnt;
int cpus, ret = 0;
cpus = num_online_cpus() - 1;
if (cpus < 1)
return 0;
data.func = func;
data.info = info;
cpumask_copy(&data.started, cpu_online_mask);
cpumask_clear_cpu(smp_processor_id(), &data.started);
data.wait = wait;
if (wait)
data.finished = data.started;
spin_lock_irqsave(&smp_nmi_call_lock, flags);
nmi_call_data = &data;
smp_mb();
/* Send a message to all other CPUs and wait for them to respond */
send_IPI_allbutself(CALL_FUNCTION_NMI_IPI);
/* Wait for response */
if (CALL_FUNCTION_NMI_IPI_TIMEOUT > 0) {
for (cnt = 0;
cnt < CALL_FUNCTION_NMI_IPI_TIMEOUT &&
!cpumask_empty(&data.started);
cnt++)
mdelay(1);
if (wait && cnt < CALL_FUNCTION_NMI_IPI_TIMEOUT) {
for (cnt = 0;
cnt < CALL_FUNCTION_NMI_IPI_TIMEOUT &&
!cpumask_empty(&data.finished);
cnt++)
mdelay(1);
}
if (cnt >= CALL_FUNCTION_NMI_IPI_TIMEOUT)
ret = -ETIMEDOUT;
} else {
/* If timeout value is zero, wait until cpumask has been
* cleared */
while (!cpumask_empty(&data.started))
barrier();
if (wait)
while (!cpumask_empty(&data.finished))
barrier();
}
spin_unlock_irqrestore(&smp_nmi_call_lock, flags);
return ret;
}
/**
* smp_jump_to_debugger - Make other CPUs enter the debugger by sending an IPI
*
* Send a non-maskable request to all other CPUs in the system, instructing
* them to jump into the debugger. The caller is responsible for checking that
* the other CPUs responded to the instruction.
*
* The caller should make sure that this CPU's debugger IPI is disabled.
*/
void smp_jump_to_debugger(void)
{
if (num_online_cpus() > 1)
/* Send a message to all other CPUs */
send_IPI_allbutself(DEBUGGER_NMI_IPI);
}
/**
* stop_this_cpu - Callback to stop a CPU.
* @unused: Callback context (ignored).
*/
void stop_this_cpu(void *unused)
{
static volatile int stopflag;
unsigned long flags;
#ifdef CONFIG_GDBSTUB
/* In case of single stepping smp_send_stop by other CPU,
* clear procindebug to avoid deadlock.
*/
atomic_set(&procindebug[smp_processor_id()], 0);
#endif /* CONFIG_GDBSTUB */
flags = arch_local_cli_save();
set_cpu_online(smp_processor_id(), false);
while (!stopflag)
cpu_relax();
set_cpu_online(smp_processor_id(), true);
arch_local_irq_restore(flags);
}
/**
* smp_send_stop - Send a stop request to all CPUs.
*/
void smp_send_stop(void)
{
smp_nmi_call_function(stop_this_cpu, NULL, 0);
}
/**
* smp_reschedule_interrupt - Reschedule IPI handler
* @irq: The interrupt number.
* @dev_id: The device ID.
*
* Returns IRQ_HANDLED to indicate we handled the interrupt successfully.
*/
static irqreturn_t smp_reschedule_interrupt(int irq, void *dev_id)
{
scheduler_ipi();
return IRQ_HANDLED;
}
/**
* smp_call_function_interrupt - Call function IPI handler
* @irq: The interrupt number.
* @dev_id: The device ID.
*
* Returns IRQ_HANDLED to indicate we handled the interrupt successfully.
*/
static irqreturn_t smp_call_function_interrupt(int irq, void *dev_id)
{
/* generic_smp_call_function_interrupt(); */
generic_smp_call_function_single_interrupt();
return IRQ_HANDLED;
}
/**
* smp_nmi_call_function_interrupt - Non-maskable call function IPI handler
*/
void smp_nmi_call_function_interrupt(void)
{
smp_call_func_t func = nmi_call_data->func;
void *info = nmi_call_data->info;
int wait = nmi_call_data->wait;
/* Notify the initiating CPU that I've grabbed the data and am about to
* execute the function
*/
smp_mb();
cpumask_clear_cpu(smp_processor_id(), &nmi_call_data->started);
(*func)(info);
if (wait) {
smp_mb();
cpumask_clear_cpu(smp_processor_id(),
&nmi_call_data->finished);
}
}
#if !defined(CONFIG_GENERIC_CLOCKEVENTS) || \
defined(CONFIG_GENERIC_CLOCKEVENTS_BROADCAST)
/**
* smp_ipi_timer_interrupt - Local timer IPI handler
* @irq: The interrupt number.
* @dev_id: The device ID.
*
* Returns IRQ_HANDLED to indicate we handled the interrupt successfully.
*/
static irqreturn_t smp_ipi_timer_interrupt(int irq, void *dev_id)
{
return local_timer_interrupt();
}
#endif
void __init smp_init_cpus(void)
{
int i;
for (i = 0; i < NR_CPUS; i++) {
set_cpu_possible(i, true);
set_cpu_present(i, true);
}
}
/**
* smp_cpu_init - Initialise AP in start_secondary.
*
* For this Application Processor, set up init_mm, initialise FPU and set
* interrupt level 0-6 setting.
*/
static void __init smp_cpu_init(void)
{
unsigned long flags;
int cpu_id = smp_processor_id();
u16 tmp16;
if (test_and_set_bit(cpu_id, &cpu_initialized)) {
printk(KERN_WARNING "CPU#%d already initialized!\n", cpu_id);
for (;;)
local_irq_enable();
}
printk(KERN_INFO "Initializing CPU#%d\n", cpu_id);
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
BUG_ON(current->mm);
enter_lazy_tlb(&init_mm, current);
/* Force FPU initialization */
clear_using_fpu(current);
GxICR(CALL_FUNC_SINGLE_IPI) = CALL_FUNCTION_GxICR_LV | GxICR_DETECT;
mn10300_ipi_enable(CALL_FUNC_SINGLE_IPI);
GxICR(LOCAL_TIMER_IPI) = LOCAL_TIMER_GxICR_LV | GxICR_DETECT;
mn10300_ipi_enable(LOCAL_TIMER_IPI);
GxICR(RESCHEDULE_IPI) = RESCHEDULE_GxICR_LV | GxICR_DETECT;
mn10300_ipi_enable(RESCHEDULE_IPI);
#ifdef CONFIG_MN10300_CACHE_ENABLED
GxICR(FLUSH_CACHE_IPI) = FLUSH_CACHE_GxICR_LV | GxICR_DETECT;
mn10300_ipi_enable(FLUSH_CACHE_IPI);
#endif
mn10300_ipi_shutdown(SMP_BOOT_IRQ);
/* Set up the non-maskable call function IPI */
flags = arch_local_cli_save();
GxICR(CALL_FUNCTION_NMI_IPI) = GxICR_NMI | GxICR_ENABLE | GxICR_DETECT;
tmp16 = GxICR(CALL_FUNCTION_NMI_IPI);
arch_local_irq_restore(flags);
}
/**
* smp_prepare_cpu_init - Initialise CPU in startup_secondary
*
* Set interrupt level 0-6 setting and init ICR of the kernel debugger.
*/
void smp_prepare_cpu_init(void)
{
int loop;
/* Set the interrupt vector registers */
IVAR0 = EXCEP_IRQ_LEVEL0;
IVAR1 = EXCEP_IRQ_LEVEL1;
IVAR2 = EXCEP_IRQ_LEVEL2;
IVAR3 = EXCEP_IRQ_LEVEL3;
IVAR4 = EXCEP_IRQ_LEVEL4;
IVAR5 = EXCEP_IRQ_LEVEL5;
IVAR6 = EXCEP_IRQ_LEVEL6;
/* Disable all interrupts and set to priority 6 (lowest) */
for (loop = 0; loop < GxICR_NUM_IRQS; loop++)
GxICR(loop) = GxICR_LEVEL_6 | GxICR_DETECT;
#ifdef CONFIG_KERNEL_DEBUGGER
/* initialise the kernel debugger interrupt */
do {
unsigned long flags;
u16 tmp16;
flags = arch_local_cli_save();
GxICR(DEBUGGER_NMI_IPI) = GxICR_NMI | GxICR_ENABLE | GxICR_DETECT;
tmp16 = GxICR(DEBUGGER_NMI_IPI);
arch_local_irq_restore(flags);
} while (0);
#endif
}
/**
* start_secondary - Activate a secondary CPU (AP)
* @unused: Thread parameter (ignored).
*/
int __init start_secondary(void *unused)
{
smp_cpu_init();
smp_callin();
while (!cpumask_test_cpu(smp_processor_id(), &smp_commenced_mask))
cpu_relax();
local_flush_tlb();
preempt_disable();
smp_online();
#ifdef CONFIG_GENERIC_CLOCKEVENTS
init_clockevents();
#endif
cpu_idle();
return 0;
}
/**
* smp_prepare_cpus - Boot up secondary CPUs (APs)
* @max_cpus: Maximum number of CPUs to boot.
*
* Call do_boot_cpu, and boot up APs.
*/
void __init smp_prepare_cpus(unsigned int max_cpus)
{
int phy_id;
/* Setup boot CPU information */
smp_store_cpu_info(0);
smp_tune_scheduling();
init_ipi();
/* If SMP should be disabled, then finish */
if (max_cpus == 0) {
printk(KERN_INFO "SMP mode deactivated.\n");
goto smp_done;
}
/* Boot secondary CPUs (for which phy_id > 0) */
for (phy_id = 0; phy_id < NR_CPUS; phy_id++) {
/* Don't boot primary CPU */
if (max_cpus <= cpucount + 1)
continue;
if (phy_id != 0)
do_boot_cpu(phy_id);
set_cpu_possible(phy_id, true);
smp_show_cpu_info(phy_id);
}
smp_done:
Dprintk("Boot done.\n");
}
/**
* smp_store_cpu_info - Save a CPU's information
* @cpu: The CPU to save for.
*
* Save boot_cpu_data and jiffy for the specified CPU.
*/
static void __init smp_store_cpu_info(int cpu)
{
struct mn10300_cpuinfo *ci = &cpu_data[cpu];
*ci = boot_cpu_data;
ci->loops_per_jiffy = loops_per_jiffy;
ci->type = CPUREV;
}
/**
* smp_tune_scheduling - Set time slice value
*
* Nothing to do here.
*/
static void __init smp_tune_scheduling(void)
{
}
/**
* do_boot_cpu: Boot up one CPU
* @phy_id: Physical ID of CPU to boot.
*
* Send an IPI to a secondary CPU to boot it. Returns 0 on success, 1
* otherwise.
*/
static int __init do_boot_cpu(int phy_id)
{
struct task_struct *idle;
unsigned long send_status, callin_status;
int timeout, cpu_id;
send_status = GxICR_REQUEST;
callin_status = 0;
timeout = 0;
cpu_id = phy_id;
cpucount++;
/* Create idle thread for this CPU */
idle = fork_idle(cpu_id);
if (IS_ERR(idle))
panic("Failed fork for CPU#%d.", cpu_id);
idle->thread.pc = (unsigned long)start_secondary;
printk(KERN_NOTICE "Booting CPU#%d\n", cpu_id);
start_stack[cpu_id - 1] = idle->thread.sp;
task_thread_info(idle)->cpu = cpu_id;
/* Send boot IPI to AP */
send_IPI_mask(cpumask_of(phy_id), SMP_BOOT_IRQ);
Dprintk("Waiting for send to finish...\n");
/* Wait for AP's IPI receive in 100[ms] */
do {
udelay(1000);
send_status =
CROSS_GxICR(SMP_BOOT_IRQ, phy_id) & GxICR_REQUEST;
} while (send_status == GxICR_REQUEST && timeout++ < 100);
Dprintk("Waiting for cpu_callin_map.\n");
if (send_status == 0) {
/* Allow AP to start initializing */
cpumask_set_cpu(cpu_id, &cpu_callout_map);
/* Wait for setting cpu_callin_map */
timeout = 0;
do {
udelay(1000);
callin_status = cpumask_test_cpu(cpu_id,
&cpu_callin_map);
} while (callin_status == 0 && timeout++ < 5000);
if (callin_status == 0)
Dprintk("Not responding.\n");
} else {
printk(KERN_WARNING "IPI not delivered.\n");
}
if (send_status == GxICR_REQUEST || callin_status == 0) {
cpumask_clear_cpu(cpu_id, &cpu_callout_map);
cpumask_clear_cpu(cpu_id, &cpu_callin_map);
cpumask_clear_cpu(cpu_id, &cpu_initialized);
cpucount--;
return 1;
}
return 0;
}
/**
* smp_show_cpu_info - Show SMP CPU information
* @cpu: The CPU of interest.
*/
static void __init smp_show_cpu_info(int cpu)
{
struct mn10300_cpuinfo *ci = &cpu_data[cpu];
printk(KERN_INFO
"CPU#%d : ioclk speed: %lu.%02luMHz : bogomips : %lu.%02lu\n",
cpu,
MN10300_IOCLK / 1000000,
(MN10300_IOCLK / 10000) % 100,
ci->loops_per_jiffy / (500000 / HZ),
(ci->loops_per_jiffy / (5000 / HZ)) % 100);
}
/**
* smp_callin - Set cpu_callin_map of the current CPU ID
*/
static void __init smp_callin(void)
{
unsigned long timeout;
int cpu;
cpu = smp_processor_id();
timeout = jiffies + (2 * HZ);
if (cpumask_test_cpu(cpu, &cpu_callin_map)) {
printk(KERN_ERR "CPU#%d already present.\n", cpu);
BUG();
}
Dprintk("CPU#%d waiting for CALLOUT\n", cpu);
/* Wait for AP startup 2s total */
while (time_before(jiffies, timeout)) {
if (cpumask_test_cpu(cpu, &cpu_callout_map))
break;
cpu_relax();
}
if (!time_before(jiffies, timeout)) {
printk(KERN_ERR
"BUG: CPU#%d started up but did not get a callout!\n",
cpu);
BUG();
}
#ifdef CONFIG_CALIBRATE_DELAY
calibrate_delay(); /* Get our bogomips */
#endif
/* Save our processor parameters */
smp_store_cpu_info(cpu);
/* Allow the boot processor to continue */
cpumask_set_cpu(cpu, &cpu_callin_map);
}
/**
* smp_online - Set cpu_online_mask
*/
static void __init smp_online(void)
{
int cpu;
cpu = smp_processor_id();
local_irq_enable();
set_cpu_online(cpu, true);
smp_wmb();
}
/**
* smp_cpus_done -
* @max_cpus: Maximum CPU count.
*
* Do nothing.
*/
void __init smp_cpus_done(unsigned int max_cpus)
{
}
/*
* smp_prepare_boot_cpu - Set up stuff for the boot processor.
*
* Set up the cpu_online_mask, cpu_callout_map and cpu_callin_map of the boot
* processor (CPU 0).
*/
void __devinit smp_prepare_boot_cpu(void)
{
cpumask_set_cpu(0, &cpu_callout_map);
cpumask_set_cpu(0, &cpu_callin_map);
current_thread_info()->cpu = 0;
}
/*
* initialize_secondary - Initialise a secondary CPU (Application Processor).
*
* Set SP register and jump to thread's PC address.
*/
void initialize_secondary(void)
{
asm volatile (
"mov %0,sp \n"
"jmp (%1) \n"
:
: "a"(current->thread.sp), "a"(current->thread.pc));
}
/**
* __cpu_up - Set smp_commenced_mask for the nominated CPU
* @cpu: The target CPU.
*/
int __devinit __cpu_up(unsigned int cpu)
{
int timeout;
#ifdef CONFIG_HOTPLUG_CPU
if (num_online_cpus() == 1)
disable_hlt();
if (sleep_mode[cpu])
run_wakeup_cpu(cpu);
#endif /* CONFIG_HOTPLUG_CPU */
cpumask_set_cpu(cpu, &smp_commenced_mask);
/* Wait 5s total for a response */
for (timeout = 0 ; timeout < 5000 ; timeout++) {
if (cpu_online(cpu))
break;
udelay(1000);
}
BUG_ON(!cpu_online(cpu));
return 0;
}
/**
* setup_profiling_timer - Set up the profiling timer
* @multiplier - The frequency multiplier to use
*
* The frequency of the profiling timer can be changed by writing a multiplier
* value into /proc/profile.
*/
int setup_profiling_timer(unsigned int multiplier)
{
return -EINVAL;
}
/*
* CPU hotplug routines
*/
#ifdef CONFIG_HOTPLUG_CPU
static DEFINE_PER_CPU(struct cpu, cpu_devices);
static int __init topology_init(void)
{
int cpu, ret;
for_each_cpu(cpu) {
ret = register_cpu(&per_cpu(cpu_devices, cpu), cpu, NULL);
if (ret)
printk(KERN_WARNING
"topology_init: register_cpu %d failed (%d)\n",
cpu, ret);
}
return 0;
}
subsys_initcall(topology_init);
int __cpu_disable(void)
{
int cpu = smp_processor_id();
if (cpu == 0)
return -EBUSY;
migrate_irqs();
cpumask_clear_cpu(cpu, &mm_cpumask(current->active_mm));
return 0;
}
void __cpu_die(unsigned int cpu)
{
run_sleep_cpu(cpu);
if (num_online_cpus() == 1)
enable_hlt();
}
#ifdef CONFIG_MN10300_CACHE_ENABLED
static inline void hotplug_cpu_disable_cache(void)
{
int tmp;
asm volatile(
" movhu (%1),%0 \n"
" and %2,%0 \n"
" movhu %0,(%1) \n"
"1: movhu (%1),%0 \n"
" btst %3,%0 \n"
" bne 1b \n"
: "=&r"(tmp)
: "a"(&CHCTR),
"i"(~(CHCTR_ICEN | CHCTR_DCEN)),
"i"(CHCTR_ICBUSY | CHCTR_DCBUSY)
: "memory", "cc");
}
static inline void hotplug_cpu_enable_cache(void)
{
int tmp;
asm volatile(
"movhu (%1),%0 \n"
"or %2,%0 \n"
"movhu %0,(%1) \n"
: "=&r"(tmp)
: "a"(&CHCTR),
"i"(CHCTR_ICEN | CHCTR_DCEN)
: "memory", "cc");
}
static inline void hotplug_cpu_invalidate_cache(void)
{
int tmp;
asm volatile (
"movhu (%1),%0 \n"
"or %2,%0 \n"
"movhu %0,(%1) \n"
: "=&r"(tmp)
: "a"(&CHCTR),
"i"(CHCTR_ICINV | CHCTR_DCINV)
: "cc");
}
#else /* CONFIG_MN10300_CACHE_ENABLED */
#define hotplug_cpu_disable_cache() do {} while (0)
#define hotplug_cpu_enable_cache() do {} while (0)
#define hotplug_cpu_invalidate_cache() do {} while (0)
#endif /* CONFIG_MN10300_CACHE_ENABLED */
/**
* hotplug_cpu_nmi_call_function - Call a function on other CPUs for hotplug
* @cpumask: List of target CPUs.
* @func: The function to call on those CPUs.
* @info: The context data for the function to be called.
* @wait: Whether to wait for the calls to complete.
*
* Non-maskably call a function on another CPU for hotplug purposes.
*
* This function must be called with maskable interrupts disabled.
*/
static int hotplug_cpu_nmi_call_function(cpumask_t cpumask,
smp_call_func_t func, void *info,
int wait)
{
/*
* The address and the size of nmi_call_func_mask_data
* need to be aligned on L1_CACHE_BYTES.
*/
static struct nmi_call_data_struct nmi_call_func_mask_data
__cacheline_aligned;
unsigned long start, end;
start = (unsigned long)&nmi_call_func_mask_data;
end = start + sizeof(struct nmi_call_data_struct);
nmi_call_func_mask_data.func = func;
nmi_call_func_mask_data.info = info;
nmi_call_func_mask_data.started = cpumask;
nmi_call_func_mask_data.wait = wait;
if (wait)
nmi_call_func_mask_data.finished = cpumask;
spin_lock(&smp_nmi_call_lock);
nmi_call_data = &nmi_call_func_mask_data;
mn10300_local_dcache_flush_range(start, end);
smp_wmb();
send_IPI_mask(cpumask, CALL_FUNCTION_NMI_IPI);
do {
mn10300_local_dcache_inv_range(start, end);
barrier();
} while (!cpumask_empty(&nmi_call_func_mask_data.started));
if (wait) {
do {
mn10300_local_dcache_inv_range(start, end);
barrier();
} while (!cpumask_empty(&nmi_call_func_mask_data.finished));
}
spin_unlock(&smp_nmi_call_lock);
return 0;
}
static void restart_wakeup_cpu(void)
{
unsigned int cpu = smp_processor_id();
cpumask_set_cpu(cpu, &cpu_callin_map);
local_flush_tlb();
set_cpu_online(cpu, true);
smp_wmb();
}
static void prepare_sleep_cpu(void *unused)
{
sleep_mode[smp_processor_id()] = 1;
smp_mb();
mn10300_local_dcache_flush_inv();
hotplug_cpu_disable_cache();
hotplug_cpu_invalidate_cache();
}
/* when this function called, IE=0, NMID=0. */
static void sleep_cpu(void *unused)
{
unsigned int cpu_id = smp_processor_id();
/*
* CALL_FUNCTION_NMI_IPI for wakeup_cpu() shall not be requested,
* before this cpu goes in SLEEP mode.
*/
do {
smp_mb();
__sleep_cpu();
} while (sleep_mode[cpu_id]);
restart_wakeup_cpu();
}
static void run_sleep_cpu(unsigned int cpu)
{
unsigned long flags;
cpumask_t cpumask;
cpumask_copy(&cpumask, &cpumask_of(cpu));
flags = arch_local_cli_save();
hotplug_cpu_nmi_call_function(cpumask, prepare_sleep_cpu, NULL, 1);
hotplug_cpu_nmi_call_function(cpumask, sleep_cpu, NULL, 0);
udelay(1); /* delay for the cpu to sleep. */
arch_local_irq_restore(flags);
}
static void wakeup_cpu(void)
{
hotplug_cpu_invalidate_cache();
hotplug_cpu_enable_cache();
smp_mb();
sleep_mode[smp_processor_id()] = 0;
}
static void run_wakeup_cpu(unsigned int cpu)
{
unsigned long flags;
flags = arch_local_cli_save();
#if NR_CPUS == 2
mn10300_local_dcache_flush_inv();
#else
/*
* Before waking up the cpu,
* all online cpus should stop and flush D-Cache for global data.
*/
#error not support NR_CPUS > 2, when CONFIG_HOTPLUG_CPU=y.
#endif
hotplug_cpu_nmi_call_function(cpumask_of(cpu), wakeup_cpu, NULL, 1);
arch_local_irq_restore(flags);
}
#endif /* CONFIG_HOTPLUG_CPU */
| gpl-2.0 |
bestmjh47/android_kernel_A780L-stock | drivers/char/hw_random/pasemi-rng.c | 3095 | 4129 | /*
* Copyright (C) 2006-2007 PA Semi, Inc
*
* Maintained by: Olof Johansson <olof@lixom.net>
*
* Driver for the PWRficient onchip rng
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/hw_random.h>
#include <linux/delay.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#define SDCRNG_CTL_REG 0x00
#define SDCRNG_CTL_FVLD_M 0x0000f000
#define SDCRNG_CTL_FVLD_S 12
#define SDCRNG_CTL_KSZ 0x00000800
#define SDCRNG_CTL_RSRC_CRG 0x00000010
#define SDCRNG_CTL_RSRC_RRG 0x00000000
#define SDCRNG_CTL_CE 0x00000004
#define SDCRNG_CTL_RE 0x00000002
#define SDCRNG_CTL_DR 0x00000001
#define SDCRNG_CTL_SELECT_RRG_RNG (SDCRNG_CTL_RE | SDCRNG_CTL_RSRC_RRG)
#define SDCRNG_CTL_SELECT_CRG_RNG (SDCRNG_CTL_CE | SDCRNG_CTL_RSRC_CRG)
#define SDCRNG_VAL_REG 0x20
#define MODULE_NAME "pasemi_rng"
static int pasemi_rng_data_present(struct hwrng *rng, int wait)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
int data, i;
for (i = 0; i < 20; i++) {
data = (in_le32(rng_regs + SDCRNG_CTL_REG)
& SDCRNG_CTL_FVLD_M) ? 1 : 0;
if (data || !wait)
break;
udelay(10);
}
return data;
}
static int pasemi_rng_data_read(struct hwrng *rng, u32 *data)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
*data = in_le32(rng_regs + SDCRNG_VAL_REG);
return 4;
}
static int pasemi_rng_init(struct hwrng *rng)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
u32 ctl;
ctl = SDCRNG_CTL_DR | SDCRNG_CTL_SELECT_RRG_RNG | SDCRNG_CTL_KSZ;
out_le32(rng_regs + SDCRNG_CTL_REG, ctl);
out_le32(rng_regs + SDCRNG_CTL_REG, ctl & ~SDCRNG_CTL_DR);
return 0;
}
static void pasemi_rng_cleanup(struct hwrng *rng)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
u32 ctl;
ctl = SDCRNG_CTL_RE | SDCRNG_CTL_CE;
out_le32(rng_regs + SDCRNG_CTL_REG,
in_le32(rng_regs + SDCRNG_CTL_REG) & ~ctl);
}
static struct hwrng pasemi_rng = {
.name = MODULE_NAME,
.init = pasemi_rng_init,
.cleanup = pasemi_rng_cleanup,
.data_present = pasemi_rng_data_present,
.data_read = pasemi_rng_data_read,
};
static int __devinit rng_probe(struct platform_device *ofdev)
{
void __iomem *rng_regs;
struct device_node *rng_np = ofdev->dev.of_node;
struct resource res;
int err = 0;
err = of_address_to_resource(rng_np, 0, &res);
if (err)
return -ENODEV;
rng_regs = ioremap(res.start, 0x100);
if (!rng_regs)
return -ENOMEM;
pasemi_rng.priv = (unsigned long)rng_regs;
printk(KERN_INFO "Registering PA Semi RNG\n");
err = hwrng_register(&pasemi_rng);
if (err)
iounmap(rng_regs);
return err;
}
static int __devexit rng_remove(struct platform_device *dev)
{
void __iomem *rng_regs = (void __iomem *)pasemi_rng.priv;
hwrng_unregister(&pasemi_rng);
iounmap(rng_regs);
return 0;
}
static struct of_device_id rng_match[] = {
{ .compatible = "1682m-rng", },
{ .compatible = "pasemi,pwrficient-rng", },
{ },
};
static struct platform_driver rng_driver = {
.driver = {
.name = "pasemi-rng",
.owner = THIS_MODULE,
.of_match_table = rng_match,
},
.probe = rng_probe,
.remove = rng_remove,
};
static int __init rng_init(void)
{
return platform_driver_register(&rng_driver);
}
module_init(rng_init);
static void __exit rng_exit(void)
{
platform_driver_unregister(&rng_driver);
}
module_exit(rng_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Egor Martovetsky <egor@pasemi.com>");
MODULE_DESCRIPTION("H/W RNG driver for PA Semi processor");
| gpl-2.0 |
binarybishop/android_kernel_msm8660-common | drivers/char/hw_random/pasemi-rng.c | 3095 | 4129 | /*
* Copyright (C) 2006-2007 PA Semi, Inc
*
* Maintained by: Olof Johansson <olof@lixom.net>
*
* Driver for the PWRficient onchip rng
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/hw_random.h>
#include <linux/delay.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#define SDCRNG_CTL_REG 0x00
#define SDCRNG_CTL_FVLD_M 0x0000f000
#define SDCRNG_CTL_FVLD_S 12
#define SDCRNG_CTL_KSZ 0x00000800
#define SDCRNG_CTL_RSRC_CRG 0x00000010
#define SDCRNG_CTL_RSRC_RRG 0x00000000
#define SDCRNG_CTL_CE 0x00000004
#define SDCRNG_CTL_RE 0x00000002
#define SDCRNG_CTL_DR 0x00000001
#define SDCRNG_CTL_SELECT_RRG_RNG (SDCRNG_CTL_RE | SDCRNG_CTL_RSRC_RRG)
#define SDCRNG_CTL_SELECT_CRG_RNG (SDCRNG_CTL_CE | SDCRNG_CTL_RSRC_CRG)
#define SDCRNG_VAL_REG 0x20
#define MODULE_NAME "pasemi_rng"
static int pasemi_rng_data_present(struct hwrng *rng, int wait)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
int data, i;
for (i = 0; i < 20; i++) {
data = (in_le32(rng_regs + SDCRNG_CTL_REG)
& SDCRNG_CTL_FVLD_M) ? 1 : 0;
if (data || !wait)
break;
udelay(10);
}
return data;
}
static int pasemi_rng_data_read(struct hwrng *rng, u32 *data)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
*data = in_le32(rng_regs + SDCRNG_VAL_REG);
return 4;
}
static int pasemi_rng_init(struct hwrng *rng)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
u32 ctl;
ctl = SDCRNG_CTL_DR | SDCRNG_CTL_SELECT_RRG_RNG | SDCRNG_CTL_KSZ;
out_le32(rng_regs + SDCRNG_CTL_REG, ctl);
out_le32(rng_regs + SDCRNG_CTL_REG, ctl & ~SDCRNG_CTL_DR);
return 0;
}
static void pasemi_rng_cleanup(struct hwrng *rng)
{
void __iomem *rng_regs = (void __iomem *)rng->priv;
u32 ctl;
ctl = SDCRNG_CTL_RE | SDCRNG_CTL_CE;
out_le32(rng_regs + SDCRNG_CTL_REG,
in_le32(rng_regs + SDCRNG_CTL_REG) & ~ctl);
}
static struct hwrng pasemi_rng = {
.name = MODULE_NAME,
.init = pasemi_rng_init,
.cleanup = pasemi_rng_cleanup,
.data_present = pasemi_rng_data_present,
.data_read = pasemi_rng_data_read,
};
static int __devinit rng_probe(struct platform_device *ofdev)
{
void __iomem *rng_regs;
struct device_node *rng_np = ofdev->dev.of_node;
struct resource res;
int err = 0;
err = of_address_to_resource(rng_np, 0, &res);
if (err)
return -ENODEV;
rng_regs = ioremap(res.start, 0x100);
if (!rng_regs)
return -ENOMEM;
pasemi_rng.priv = (unsigned long)rng_regs;
printk(KERN_INFO "Registering PA Semi RNG\n");
err = hwrng_register(&pasemi_rng);
if (err)
iounmap(rng_regs);
return err;
}
static int __devexit rng_remove(struct platform_device *dev)
{
void __iomem *rng_regs = (void __iomem *)pasemi_rng.priv;
hwrng_unregister(&pasemi_rng);
iounmap(rng_regs);
return 0;
}
static struct of_device_id rng_match[] = {
{ .compatible = "1682m-rng", },
{ .compatible = "pasemi,pwrficient-rng", },
{ },
};
static struct platform_driver rng_driver = {
.driver = {
.name = "pasemi-rng",
.owner = THIS_MODULE,
.of_match_table = rng_match,
},
.probe = rng_probe,
.remove = rng_remove,
};
static int __init rng_init(void)
{
return platform_driver_register(&rng_driver);
}
module_init(rng_init);
static void __exit rng_exit(void)
{
platform_driver_unregister(&rng_driver);
}
module_exit(rng_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Egor Martovetsky <egor@pasemi.com>");
MODULE_DESCRIPTION("H/W RNG driver for PA Semi processor");
| gpl-2.0 |
android-armv7a-belalang-tempur/Android_SpeedKernel | drivers/media/rc/keymaps/rc-tt-1500.c | 3095 | 2074 | /* tt-1500.h - Keytable for tt_1500 Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
/* for the Technotrend 1500 bundled remotes (grey and black): */
static struct rc_map_table tt_1500[] = {
{ 0x1501, KEY_POWER },
{ 0x1502, KEY_SHUFFLE }, /* ? double-arrow key */
{ 0x1503, KEY_1 },
{ 0x1504, KEY_2 },
{ 0x1505, KEY_3 },
{ 0x1506, KEY_4 },
{ 0x1507, KEY_5 },
{ 0x1508, KEY_6 },
{ 0x1509, KEY_7 },
{ 0x150a, KEY_8 },
{ 0x150b, KEY_9 },
{ 0x150c, KEY_0 },
{ 0x150d, KEY_UP },
{ 0x150e, KEY_LEFT },
{ 0x150f, KEY_OK },
{ 0x1510, KEY_RIGHT },
{ 0x1511, KEY_DOWN },
{ 0x1512, KEY_INFO },
{ 0x1513, KEY_EXIT },
{ 0x1514, KEY_RED },
{ 0x1515, KEY_GREEN },
{ 0x1516, KEY_YELLOW },
{ 0x1517, KEY_BLUE },
{ 0x1518, KEY_MUTE },
{ 0x1519, KEY_TEXT },
{ 0x151a, KEY_MODE }, /* ? TV/Radio */
{ 0x1521, KEY_OPTION },
{ 0x1522, KEY_EPG },
{ 0x1523, KEY_CHANNELUP },
{ 0x1524, KEY_CHANNELDOWN },
{ 0x1525, KEY_VOLUMEUP },
{ 0x1526, KEY_VOLUMEDOWN },
{ 0x1527, KEY_SETUP },
{ 0x153a, KEY_RECORD }, /* these keys are only in the black remote */
{ 0x153b, KEY_PLAY },
{ 0x153c, KEY_STOP },
{ 0x153d, KEY_REWIND },
{ 0x153e, KEY_PAUSE },
{ 0x153f, KEY_FORWARD },
};
static struct rc_map_list tt_1500_map = {
.map = {
.scan = tt_1500,
.size = ARRAY_SIZE(tt_1500),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_TT_1500,
}
};
static int __init init_rc_map_tt_1500(void)
{
return rc_map_register(&tt_1500_map);
}
static void __exit exit_rc_map_tt_1500(void)
{
rc_map_unregister(&tt_1500_map);
}
module_init(init_rc_map_tt_1500)
module_exit(exit_rc_map_tt_1500)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Skin1980/Kexec-kk-kernel-G3 | drivers/net/wireless/rt2x00/rt73usb.c | 3351 | 77424 | /*
Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com>
<http://rt2x00.serialmonkey.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
Module: rt73usb
Abstract: rt73usb device specific routines.
Supported chipsets: rt2571W & rt2671.
*/
#include <linux/crc-itu-t.h>
#include <linux/delay.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include "rt2x00.h"
#include "rt2x00usb.h"
#include "rt73usb.h"
/*
* Allow hardware encryption to be disabled.
*/
static bool modparam_nohwcrypt;
module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
/*
* Register access.
* All access to the CSR registers will go through the methods
* rt2x00usb_register_read and rt2x00usb_register_write.
* BBP and RF register require indirect register access,
* and use the CSR registers BBPCSR and RFCSR to achieve this.
* These indirect registers work with busy bits,
* and we will try maximal REGISTER_BUSY_COUNT times to access
* the register while taking a REGISTER_BUSY_DELAY us delay
* between each attampt. When the busy bit is still set at that time,
* the access attempt is considered to have failed,
* and we will print an error.
* The _lock versions must be used if you already hold the csr_mutex
*/
#define WAIT_FOR_BBP(__dev, __reg) \
rt2x00usb_regbusy_read((__dev), PHY_CSR3, PHY_CSR3_BUSY, (__reg))
#define WAIT_FOR_RF(__dev, __reg) \
rt2x00usb_regbusy_read((__dev), PHY_CSR4, PHY_CSR4_BUSY, (__reg))
static void rt73usb_bbp_write(struct rt2x00_dev *rt2x00dev,
const unsigned int word, const u8 value)
{
u32 reg;
mutex_lock(&rt2x00dev->csr_mutex);
/*
* Wait until the BBP becomes available, afterwards we
* can safely write the new data into the register.
*/
if (WAIT_FOR_BBP(rt2x00dev, ®)) {
reg = 0;
rt2x00_set_field32(®, PHY_CSR3_VALUE, value);
rt2x00_set_field32(®, PHY_CSR3_REGNUM, word);
rt2x00_set_field32(®, PHY_CSR3_BUSY, 1);
rt2x00_set_field32(®, PHY_CSR3_READ_CONTROL, 0);
rt2x00usb_register_write_lock(rt2x00dev, PHY_CSR3, reg);
}
mutex_unlock(&rt2x00dev->csr_mutex);
}
static void rt73usb_bbp_read(struct rt2x00_dev *rt2x00dev,
const unsigned int word, u8 *value)
{
u32 reg;
mutex_lock(&rt2x00dev->csr_mutex);
/*
* Wait until the BBP becomes available, afterwards we
* can safely write the read request into the register.
* After the data has been written, we wait until hardware
* returns the correct value, if at any time the register
* doesn't become available in time, reg will be 0xffffffff
* which means we return 0xff to the caller.
*/
if (WAIT_FOR_BBP(rt2x00dev, ®)) {
reg = 0;
rt2x00_set_field32(®, PHY_CSR3_REGNUM, word);
rt2x00_set_field32(®, PHY_CSR3_BUSY, 1);
rt2x00_set_field32(®, PHY_CSR3_READ_CONTROL, 1);
rt2x00usb_register_write_lock(rt2x00dev, PHY_CSR3, reg);
WAIT_FOR_BBP(rt2x00dev, ®);
}
*value = rt2x00_get_field32(reg, PHY_CSR3_VALUE);
mutex_unlock(&rt2x00dev->csr_mutex);
}
static void rt73usb_rf_write(struct rt2x00_dev *rt2x00dev,
const unsigned int word, const u32 value)
{
u32 reg;
mutex_lock(&rt2x00dev->csr_mutex);
/*
* Wait until the RF becomes available, afterwards we
* can safely write the new data into the register.
*/
if (WAIT_FOR_RF(rt2x00dev, ®)) {
reg = 0;
rt2x00_set_field32(®, PHY_CSR4_VALUE, value);
/*
* RF5225 and RF2527 contain 21 bits per RF register value,
* all others contain 20 bits.
*/
rt2x00_set_field32(®, PHY_CSR4_NUMBER_OF_BITS,
20 + (rt2x00_rf(rt2x00dev, RF5225) ||
rt2x00_rf(rt2x00dev, RF2527)));
rt2x00_set_field32(®, PHY_CSR4_IF_SELECT, 0);
rt2x00_set_field32(®, PHY_CSR4_BUSY, 1);
rt2x00usb_register_write_lock(rt2x00dev, PHY_CSR4, reg);
rt2x00_rf_write(rt2x00dev, word, value);
}
mutex_unlock(&rt2x00dev->csr_mutex);
}
#ifdef CONFIG_RT2X00_LIB_DEBUGFS
static const struct rt2x00debug rt73usb_rt2x00debug = {
.owner = THIS_MODULE,
.csr = {
.read = rt2x00usb_register_read,
.write = rt2x00usb_register_write,
.flags = RT2X00DEBUGFS_OFFSET,
.word_base = CSR_REG_BASE,
.word_size = sizeof(u32),
.word_count = CSR_REG_SIZE / sizeof(u32),
},
.eeprom = {
.read = rt2x00_eeprom_read,
.write = rt2x00_eeprom_write,
.word_base = EEPROM_BASE,
.word_size = sizeof(u16),
.word_count = EEPROM_SIZE / sizeof(u16),
},
.bbp = {
.read = rt73usb_bbp_read,
.write = rt73usb_bbp_write,
.word_base = BBP_BASE,
.word_size = sizeof(u8),
.word_count = BBP_SIZE / sizeof(u8),
},
.rf = {
.read = rt2x00_rf_read,
.write = rt73usb_rf_write,
.word_base = RF_BASE,
.word_size = sizeof(u32),
.word_count = RF_SIZE / sizeof(u32),
},
};
#endif /* CONFIG_RT2X00_LIB_DEBUGFS */
static int rt73usb_rfkill_poll(struct rt2x00_dev *rt2x00dev)
{
u32 reg;
rt2x00usb_register_read(rt2x00dev, MAC_CSR13, ®);
return rt2x00_get_field32(reg, MAC_CSR13_BIT7);
}
#ifdef CONFIG_RT2X00_LIB_LEDS
static void rt73usb_brightness_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
struct rt2x00_led *led =
container_of(led_cdev, struct rt2x00_led, led_dev);
unsigned int enabled = brightness != LED_OFF;
unsigned int a_mode =
(enabled && led->rt2x00dev->curr_band == IEEE80211_BAND_5GHZ);
unsigned int bg_mode =
(enabled && led->rt2x00dev->curr_band == IEEE80211_BAND_2GHZ);
if (led->type == LED_TYPE_RADIO) {
rt2x00_set_field16(&led->rt2x00dev->led_mcu_reg,
MCU_LEDCS_RADIO_STATUS, enabled);
rt2x00usb_vendor_request_sw(led->rt2x00dev, USB_LED_CONTROL,
0, led->rt2x00dev->led_mcu_reg,
REGISTER_TIMEOUT);
} else if (led->type == LED_TYPE_ASSOC) {
rt2x00_set_field16(&led->rt2x00dev->led_mcu_reg,
MCU_LEDCS_LINK_BG_STATUS, bg_mode);
rt2x00_set_field16(&led->rt2x00dev->led_mcu_reg,
MCU_LEDCS_LINK_A_STATUS, a_mode);
rt2x00usb_vendor_request_sw(led->rt2x00dev, USB_LED_CONTROL,
0, led->rt2x00dev->led_mcu_reg,
REGISTER_TIMEOUT);
} else if (led->type == LED_TYPE_QUALITY) {
/*
* The brightness is divided into 6 levels (0 - 5),
* this means we need to convert the brightness
* argument into the matching level within that range.
*/
rt2x00usb_vendor_request_sw(led->rt2x00dev, USB_LED_CONTROL,
brightness / (LED_FULL / 6),
led->rt2x00dev->led_mcu_reg,
REGISTER_TIMEOUT);
}
}
static int rt73usb_blink_set(struct led_classdev *led_cdev,
unsigned long *delay_on,
unsigned long *delay_off)
{
struct rt2x00_led *led =
container_of(led_cdev, struct rt2x00_led, led_dev);
u32 reg;
rt2x00usb_register_read(led->rt2x00dev, MAC_CSR14, ®);
rt2x00_set_field32(®, MAC_CSR14_ON_PERIOD, *delay_on);
rt2x00_set_field32(®, MAC_CSR14_OFF_PERIOD, *delay_off);
rt2x00usb_register_write(led->rt2x00dev, MAC_CSR14, reg);
return 0;
}
static void rt73usb_init_led(struct rt2x00_dev *rt2x00dev,
struct rt2x00_led *led,
enum led_type type)
{
led->rt2x00dev = rt2x00dev;
led->type = type;
led->led_dev.brightness_set = rt73usb_brightness_set;
led->led_dev.blink_set = rt73usb_blink_set;
led->flags = LED_INITIALIZED;
}
#endif /* CONFIG_RT2X00_LIB_LEDS */
/*
* Configuration handlers.
*/
static int rt73usb_config_shared_key(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_crypto *crypto,
struct ieee80211_key_conf *key)
{
struct hw_key_entry key_entry;
struct rt2x00_field32 field;
u32 mask;
u32 reg;
if (crypto->cmd == SET_KEY) {
/*
* rt2x00lib can't determine the correct free
* key_idx for shared keys. We have 1 register
* with key valid bits. The goal is simple, read
* the register, if that is full we have no slots
* left.
* Note that each BSS is allowed to have up to 4
* shared keys, so put a mask over the allowed
* entries.
*/
mask = (0xf << crypto->bssidx);
rt2x00usb_register_read(rt2x00dev, SEC_CSR0, ®);
reg &= mask;
if (reg && reg == mask)
return -ENOSPC;
key->hw_key_idx += reg ? ffz(reg) : 0;
/*
* Upload key to hardware
*/
memcpy(key_entry.key, crypto->key,
sizeof(key_entry.key));
memcpy(key_entry.tx_mic, crypto->tx_mic,
sizeof(key_entry.tx_mic));
memcpy(key_entry.rx_mic, crypto->rx_mic,
sizeof(key_entry.rx_mic));
reg = SHARED_KEY_ENTRY(key->hw_key_idx);
rt2x00usb_register_multiwrite(rt2x00dev, reg,
&key_entry, sizeof(key_entry));
/*
* The cipher types are stored over 2 registers.
* bssidx 0 and 1 keys are stored in SEC_CSR1 and
* bssidx 1 and 2 keys are stored in SEC_CSR5.
* Using the correct defines correctly will cause overhead,
* so just calculate the correct offset.
*/
if (key->hw_key_idx < 8) {
field.bit_offset = (3 * key->hw_key_idx);
field.bit_mask = 0x7 << field.bit_offset;
rt2x00usb_register_read(rt2x00dev, SEC_CSR1, ®);
rt2x00_set_field32(®, field, crypto->cipher);
rt2x00usb_register_write(rt2x00dev, SEC_CSR1, reg);
} else {
field.bit_offset = (3 * (key->hw_key_idx - 8));
field.bit_mask = 0x7 << field.bit_offset;
rt2x00usb_register_read(rt2x00dev, SEC_CSR5, ®);
rt2x00_set_field32(®, field, crypto->cipher);
rt2x00usb_register_write(rt2x00dev, SEC_CSR5, reg);
}
/*
* The driver does not support the IV/EIV generation
* in hardware. However it doesn't support the IV/EIV
* inside the ieee80211 frame either, but requires it
* to be provided separately for the descriptor.
* rt2x00lib will cut the IV/EIV data out of all frames
* given to us by mac80211, but we must tell mac80211
* to generate the IV/EIV data.
*/
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
}
/*
* SEC_CSR0 contains only single-bit fields to indicate
* a particular key is valid. Because using the FIELD32()
* defines directly will cause a lot of overhead we use
* a calculation to determine the correct bit directly.
*/
mask = 1 << key->hw_key_idx;
rt2x00usb_register_read(rt2x00dev, SEC_CSR0, ®);
if (crypto->cmd == SET_KEY)
reg |= mask;
else if (crypto->cmd == DISABLE_KEY)
reg &= ~mask;
rt2x00usb_register_write(rt2x00dev, SEC_CSR0, reg);
return 0;
}
static int rt73usb_config_pairwise_key(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_crypto *crypto,
struct ieee80211_key_conf *key)
{
struct hw_pairwise_ta_entry addr_entry;
struct hw_key_entry key_entry;
u32 mask;
u32 reg;
if (crypto->cmd == SET_KEY) {
/*
* rt2x00lib can't determine the correct free
* key_idx for pairwise keys. We have 2 registers
* with key valid bits. The goal is simple, read
* the first register, if that is full move to
* the next register.
* When both registers are full, we drop the key,
* otherwise we use the first invalid entry.
*/
rt2x00usb_register_read(rt2x00dev, SEC_CSR2, ®);
if (reg && reg == ~0) {
key->hw_key_idx = 32;
rt2x00usb_register_read(rt2x00dev, SEC_CSR3, ®);
if (reg && reg == ~0)
return -ENOSPC;
}
key->hw_key_idx += reg ? ffz(reg) : 0;
/*
* Upload key to hardware
*/
memcpy(key_entry.key, crypto->key,
sizeof(key_entry.key));
memcpy(key_entry.tx_mic, crypto->tx_mic,
sizeof(key_entry.tx_mic));
memcpy(key_entry.rx_mic, crypto->rx_mic,
sizeof(key_entry.rx_mic));
reg = PAIRWISE_KEY_ENTRY(key->hw_key_idx);
rt2x00usb_register_multiwrite(rt2x00dev, reg,
&key_entry, sizeof(key_entry));
/*
* Send the address and cipher type to the hardware register.
*/
memset(&addr_entry, 0, sizeof(addr_entry));
memcpy(&addr_entry, crypto->address, ETH_ALEN);
addr_entry.cipher = crypto->cipher;
reg = PAIRWISE_TA_ENTRY(key->hw_key_idx);
rt2x00usb_register_multiwrite(rt2x00dev, reg,
&addr_entry, sizeof(addr_entry));
/*
* Enable pairwise lookup table for given BSS idx,
* without this received frames will not be decrypted
* by the hardware.
*/
rt2x00usb_register_read(rt2x00dev, SEC_CSR4, ®);
reg |= (1 << crypto->bssidx);
rt2x00usb_register_write(rt2x00dev, SEC_CSR4, reg);
/*
* The driver does not support the IV/EIV generation
* in hardware. However it doesn't support the IV/EIV
* inside the ieee80211 frame either, but requires it
* to be provided separately for the descriptor.
* rt2x00lib will cut the IV/EIV data out of all frames
* given to us by mac80211, but we must tell mac80211
* to generate the IV/EIV data.
*/
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
}
/*
* SEC_CSR2 and SEC_CSR3 contain only single-bit fields to indicate
* a particular key is valid. Because using the FIELD32()
* defines directly will cause a lot of overhead we use
* a calculation to determine the correct bit directly.
*/
if (key->hw_key_idx < 32) {
mask = 1 << key->hw_key_idx;
rt2x00usb_register_read(rt2x00dev, SEC_CSR2, ®);
if (crypto->cmd == SET_KEY)
reg |= mask;
else if (crypto->cmd == DISABLE_KEY)
reg &= ~mask;
rt2x00usb_register_write(rt2x00dev, SEC_CSR2, reg);
} else {
mask = 1 << (key->hw_key_idx - 32);
rt2x00usb_register_read(rt2x00dev, SEC_CSR3, ®);
if (crypto->cmd == SET_KEY)
reg |= mask;
else if (crypto->cmd == DISABLE_KEY)
reg &= ~mask;
rt2x00usb_register_write(rt2x00dev, SEC_CSR3, reg);
}
return 0;
}
static void rt73usb_config_filter(struct rt2x00_dev *rt2x00dev,
const unsigned int filter_flags)
{
u32 reg;
/*
* Start configuration steps.
* Note that the version error will always be dropped
* and broadcast frames will always be accepted since
* there is no filter for it at this time.
*/
rt2x00usb_register_read(rt2x00dev, TXRX_CSR0, ®);
rt2x00_set_field32(®, TXRX_CSR0_DROP_CRC,
!(filter_flags & FIF_FCSFAIL));
rt2x00_set_field32(®, TXRX_CSR0_DROP_PHYSICAL,
!(filter_flags & FIF_PLCPFAIL));
rt2x00_set_field32(®, TXRX_CSR0_DROP_CONTROL,
!(filter_flags & (FIF_CONTROL | FIF_PSPOLL)));
rt2x00_set_field32(®, TXRX_CSR0_DROP_NOT_TO_ME,
!(filter_flags & FIF_PROMISC_IN_BSS));
rt2x00_set_field32(®, TXRX_CSR0_DROP_TO_DS,
!(filter_flags & FIF_PROMISC_IN_BSS) &&
!rt2x00dev->intf_ap_count);
rt2x00_set_field32(®, TXRX_CSR0_DROP_VERSION_ERROR, 1);
rt2x00_set_field32(®, TXRX_CSR0_DROP_MULTICAST,
!(filter_flags & FIF_ALLMULTI));
rt2x00_set_field32(®, TXRX_CSR0_DROP_BROADCAST, 0);
rt2x00_set_field32(®, TXRX_CSR0_DROP_ACK_CTS,
!(filter_flags & FIF_CONTROL));
rt2x00usb_register_write(rt2x00dev, TXRX_CSR0, reg);
}
static void rt73usb_config_intf(struct rt2x00_dev *rt2x00dev,
struct rt2x00_intf *intf,
struct rt2x00intf_conf *conf,
const unsigned int flags)
{
u32 reg;
if (flags & CONFIG_UPDATE_TYPE) {
/*
* Enable synchronisation.
*/
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
rt2x00_set_field32(®, TXRX_CSR9_TSF_SYNC, conf->sync);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
}
if (flags & CONFIG_UPDATE_MAC) {
reg = le32_to_cpu(conf->mac[1]);
rt2x00_set_field32(®, MAC_CSR3_UNICAST_TO_ME_MASK, 0xff);
conf->mac[1] = cpu_to_le32(reg);
rt2x00usb_register_multiwrite(rt2x00dev, MAC_CSR2,
conf->mac, sizeof(conf->mac));
}
if (flags & CONFIG_UPDATE_BSSID) {
reg = le32_to_cpu(conf->bssid[1]);
rt2x00_set_field32(®, MAC_CSR5_BSS_ID_MASK, 3);
conf->bssid[1] = cpu_to_le32(reg);
rt2x00usb_register_multiwrite(rt2x00dev, MAC_CSR4,
conf->bssid, sizeof(conf->bssid));
}
}
static void rt73usb_config_erp(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_erp *erp,
u32 changed)
{
u32 reg;
rt2x00usb_register_read(rt2x00dev, TXRX_CSR0, ®);
rt2x00_set_field32(®, TXRX_CSR0_RX_ACK_TIMEOUT, 0x32);
rt2x00_set_field32(®, TXRX_CSR0_TSF_OFFSET, IEEE80211_HEADER);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR0, reg);
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
rt2x00usb_register_read(rt2x00dev, TXRX_CSR4, ®);
rt2x00_set_field32(®, TXRX_CSR4_AUTORESPOND_ENABLE, 1);
rt2x00_set_field32(®, TXRX_CSR4_AUTORESPOND_PREAMBLE,
!!erp->short_preamble);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR4, reg);
}
if (changed & BSS_CHANGED_BASIC_RATES)
rt2x00usb_register_write(rt2x00dev, TXRX_CSR5,
erp->basic_rates);
if (changed & BSS_CHANGED_BEACON_INT) {
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_INTERVAL,
erp->beacon_int * 16);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
}
if (changed & BSS_CHANGED_ERP_SLOT) {
rt2x00usb_register_read(rt2x00dev, MAC_CSR9, ®);
rt2x00_set_field32(®, MAC_CSR9_SLOT_TIME, erp->slot_time);
rt2x00usb_register_write(rt2x00dev, MAC_CSR9, reg);
rt2x00usb_register_read(rt2x00dev, MAC_CSR8, ®);
rt2x00_set_field32(®, MAC_CSR8_SIFS, erp->sifs);
rt2x00_set_field32(®, MAC_CSR8_SIFS_AFTER_RX_OFDM, 3);
rt2x00_set_field32(®, MAC_CSR8_EIFS, erp->eifs);
rt2x00usb_register_write(rt2x00dev, MAC_CSR8, reg);
}
}
static void rt73usb_config_antenna_5x(struct rt2x00_dev *rt2x00dev,
struct antenna_setup *ant)
{
u8 r3;
u8 r4;
u8 r77;
u8 temp;
rt73usb_bbp_read(rt2x00dev, 3, &r3);
rt73usb_bbp_read(rt2x00dev, 4, &r4);
rt73usb_bbp_read(rt2x00dev, 77, &r77);
rt2x00_set_field8(&r3, BBP_R3_SMART_MODE, 0);
/*
* Configure the RX antenna.
*/
switch (ant->rx) {
case ANTENNA_HW_DIVERSITY:
rt2x00_set_field8(&r4, BBP_R4_RX_ANTENNA_CONTROL, 2);
temp = !test_bit(CAPABILITY_FRAME_TYPE, &rt2x00dev->cap_flags)
&& (rt2x00dev->curr_band != IEEE80211_BAND_5GHZ);
rt2x00_set_field8(&r4, BBP_R4_RX_FRAME_END, temp);
break;
case ANTENNA_A:
rt2x00_set_field8(&r4, BBP_R4_RX_ANTENNA_CONTROL, 1);
rt2x00_set_field8(&r4, BBP_R4_RX_FRAME_END, 0);
if (rt2x00dev->curr_band == IEEE80211_BAND_5GHZ)
rt2x00_set_field8(&r77, BBP_R77_RX_ANTENNA, 0);
else
rt2x00_set_field8(&r77, BBP_R77_RX_ANTENNA, 3);
break;
case ANTENNA_B:
default:
rt2x00_set_field8(&r4, BBP_R4_RX_ANTENNA_CONTROL, 1);
rt2x00_set_field8(&r4, BBP_R4_RX_FRAME_END, 0);
if (rt2x00dev->curr_band == IEEE80211_BAND_5GHZ)
rt2x00_set_field8(&r77, BBP_R77_RX_ANTENNA, 3);
else
rt2x00_set_field8(&r77, BBP_R77_RX_ANTENNA, 0);
break;
}
rt73usb_bbp_write(rt2x00dev, 77, r77);
rt73usb_bbp_write(rt2x00dev, 3, r3);
rt73usb_bbp_write(rt2x00dev, 4, r4);
}
static void rt73usb_config_antenna_2x(struct rt2x00_dev *rt2x00dev,
struct antenna_setup *ant)
{
u8 r3;
u8 r4;
u8 r77;
rt73usb_bbp_read(rt2x00dev, 3, &r3);
rt73usb_bbp_read(rt2x00dev, 4, &r4);
rt73usb_bbp_read(rt2x00dev, 77, &r77);
rt2x00_set_field8(&r3, BBP_R3_SMART_MODE, 0);
rt2x00_set_field8(&r4, BBP_R4_RX_FRAME_END,
!test_bit(CAPABILITY_FRAME_TYPE, &rt2x00dev->cap_flags));
/*
* Configure the RX antenna.
*/
switch (ant->rx) {
case ANTENNA_HW_DIVERSITY:
rt2x00_set_field8(&r4, BBP_R4_RX_ANTENNA_CONTROL, 2);
break;
case ANTENNA_A:
rt2x00_set_field8(&r77, BBP_R77_RX_ANTENNA, 3);
rt2x00_set_field8(&r4, BBP_R4_RX_ANTENNA_CONTROL, 1);
break;
case ANTENNA_B:
default:
rt2x00_set_field8(&r77, BBP_R77_RX_ANTENNA, 0);
rt2x00_set_field8(&r4, BBP_R4_RX_ANTENNA_CONTROL, 1);
break;
}
rt73usb_bbp_write(rt2x00dev, 77, r77);
rt73usb_bbp_write(rt2x00dev, 3, r3);
rt73usb_bbp_write(rt2x00dev, 4, r4);
}
struct antenna_sel {
u8 word;
/*
* value[0] -> non-LNA
* value[1] -> LNA
*/
u8 value[2];
};
static const struct antenna_sel antenna_sel_a[] = {
{ 96, { 0x58, 0x78 } },
{ 104, { 0x38, 0x48 } },
{ 75, { 0xfe, 0x80 } },
{ 86, { 0xfe, 0x80 } },
{ 88, { 0xfe, 0x80 } },
{ 35, { 0x60, 0x60 } },
{ 97, { 0x58, 0x58 } },
{ 98, { 0x58, 0x58 } },
};
static const struct antenna_sel antenna_sel_bg[] = {
{ 96, { 0x48, 0x68 } },
{ 104, { 0x2c, 0x3c } },
{ 75, { 0xfe, 0x80 } },
{ 86, { 0xfe, 0x80 } },
{ 88, { 0xfe, 0x80 } },
{ 35, { 0x50, 0x50 } },
{ 97, { 0x48, 0x48 } },
{ 98, { 0x48, 0x48 } },
};
static void rt73usb_config_ant(struct rt2x00_dev *rt2x00dev,
struct antenna_setup *ant)
{
const struct antenna_sel *sel;
unsigned int lna;
unsigned int i;
u32 reg;
/*
* We should never come here because rt2x00lib is supposed
* to catch this and send us the correct antenna explicitely.
*/
BUG_ON(ant->rx == ANTENNA_SW_DIVERSITY ||
ant->tx == ANTENNA_SW_DIVERSITY);
if (rt2x00dev->curr_band == IEEE80211_BAND_5GHZ) {
sel = antenna_sel_a;
lna = test_bit(CAPABILITY_EXTERNAL_LNA_A, &rt2x00dev->cap_flags);
} else {
sel = antenna_sel_bg;
lna = test_bit(CAPABILITY_EXTERNAL_LNA_BG, &rt2x00dev->cap_flags);
}
for (i = 0; i < ARRAY_SIZE(antenna_sel_a); i++)
rt73usb_bbp_write(rt2x00dev, sel[i].word, sel[i].value[lna]);
rt2x00usb_register_read(rt2x00dev, PHY_CSR0, ®);
rt2x00_set_field32(®, PHY_CSR0_PA_PE_BG,
(rt2x00dev->curr_band == IEEE80211_BAND_2GHZ));
rt2x00_set_field32(®, PHY_CSR0_PA_PE_A,
(rt2x00dev->curr_band == IEEE80211_BAND_5GHZ));
rt2x00usb_register_write(rt2x00dev, PHY_CSR0, reg);
if (rt2x00_rf(rt2x00dev, RF5226) || rt2x00_rf(rt2x00dev, RF5225))
rt73usb_config_antenna_5x(rt2x00dev, ant);
else if (rt2x00_rf(rt2x00dev, RF2528) || rt2x00_rf(rt2x00dev, RF2527))
rt73usb_config_antenna_2x(rt2x00dev, ant);
}
static void rt73usb_config_lna_gain(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_conf *libconf)
{
u16 eeprom;
short lna_gain = 0;
if (libconf->conf->channel->band == IEEE80211_BAND_2GHZ) {
if (test_bit(CAPABILITY_EXTERNAL_LNA_BG, &rt2x00dev->cap_flags))
lna_gain += 14;
rt2x00_eeprom_read(rt2x00dev, EEPROM_RSSI_OFFSET_BG, &eeprom);
lna_gain -= rt2x00_get_field16(eeprom, EEPROM_RSSI_OFFSET_BG_1);
} else {
rt2x00_eeprom_read(rt2x00dev, EEPROM_RSSI_OFFSET_A, &eeprom);
lna_gain -= rt2x00_get_field16(eeprom, EEPROM_RSSI_OFFSET_A_1);
}
rt2x00dev->lna_gain = lna_gain;
}
static void rt73usb_config_channel(struct rt2x00_dev *rt2x00dev,
struct rf_channel *rf, const int txpower)
{
u8 r3;
u8 r94;
u8 smart;
rt2x00_set_field32(&rf->rf3, RF3_TXPOWER, TXPOWER_TO_DEV(txpower));
rt2x00_set_field32(&rf->rf4, RF4_FREQ_OFFSET, rt2x00dev->freq_offset);
smart = !(rt2x00_rf(rt2x00dev, RF5225) || rt2x00_rf(rt2x00dev, RF2527));
rt73usb_bbp_read(rt2x00dev, 3, &r3);
rt2x00_set_field8(&r3, BBP_R3_SMART_MODE, smart);
rt73usb_bbp_write(rt2x00dev, 3, r3);
r94 = 6;
if (txpower > MAX_TXPOWER && txpower <= (MAX_TXPOWER + r94))
r94 += txpower - MAX_TXPOWER;
else if (txpower < MIN_TXPOWER && txpower >= (MIN_TXPOWER - r94))
r94 += txpower;
rt73usb_bbp_write(rt2x00dev, 94, r94);
rt73usb_rf_write(rt2x00dev, 1, rf->rf1);
rt73usb_rf_write(rt2x00dev, 2, rf->rf2);
rt73usb_rf_write(rt2x00dev, 3, rf->rf3 & ~0x00000004);
rt73usb_rf_write(rt2x00dev, 4, rf->rf4);
rt73usb_rf_write(rt2x00dev, 1, rf->rf1);
rt73usb_rf_write(rt2x00dev, 2, rf->rf2);
rt73usb_rf_write(rt2x00dev, 3, rf->rf3 | 0x00000004);
rt73usb_rf_write(rt2x00dev, 4, rf->rf4);
rt73usb_rf_write(rt2x00dev, 1, rf->rf1);
rt73usb_rf_write(rt2x00dev, 2, rf->rf2);
rt73usb_rf_write(rt2x00dev, 3, rf->rf3 & ~0x00000004);
rt73usb_rf_write(rt2x00dev, 4, rf->rf4);
udelay(10);
}
static void rt73usb_config_txpower(struct rt2x00_dev *rt2x00dev,
const int txpower)
{
struct rf_channel rf;
rt2x00_rf_read(rt2x00dev, 1, &rf.rf1);
rt2x00_rf_read(rt2x00dev, 2, &rf.rf2);
rt2x00_rf_read(rt2x00dev, 3, &rf.rf3);
rt2x00_rf_read(rt2x00dev, 4, &rf.rf4);
rt73usb_config_channel(rt2x00dev, &rf, txpower);
}
static void rt73usb_config_retry_limit(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_conf *libconf)
{
u32 reg;
rt2x00usb_register_read(rt2x00dev, TXRX_CSR4, ®);
rt2x00_set_field32(®, TXRX_CSR4_OFDM_TX_RATE_DOWN, 1);
rt2x00_set_field32(®, TXRX_CSR4_OFDM_TX_RATE_STEP, 0);
rt2x00_set_field32(®, TXRX_CSR4_OFDM_TX_FALLBACK_CCK, 0);
rt2x00_set_field32(®, TXRX_CSR4_LONG_RETRY_LIMIT,
libconf->conf->long_frame_max_tx_count);
rt2x00_set_field32(®, TXRX_CSR4_SHORT_RETRY_LIMIT,
libconf->conf->short_frame_max_tx_count);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR4, reg);
}
static void rt73usb_config_ps(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_conf *libconf)
{
enum dev_state state =
(libconf->conf->flags & IEEE80211_CONF_PS) ?
STATE_SLEEP : STATE_AWAKE;
u32 reg;
if (state == STATE_SLEEP) {
rt2x00usb_register_read(rt2x00dev, MAC_CSR11, ®);
rt2x00_set_field32(®, MAC_CSR11_DELAY_AFTER_TBCN,
rt2x00dev->beacon_int - 10);
rt2x00_set_field32(®, MAC_CSR11_TBCN_BEFORE_WAKEUP,
libconf->conf->listen_interval - 1);
rt2x00_set_field32(®, MAC_CSR11_WAKEUP_LATENCY, 5);
/* We must first disable autowake before it can be enabled */
rt2x00_set_field32(®, MAC_CSR11_AUTOWAKE, 0);
rt2x00usb_register_write(rt2x00dev, MAC_CSR11, reg);
rt2x00_set_field32(®, MAC_CSR11_AUTOWAKE, 1);
rt2x00usb_register_write(rt2x00dev, MAC_CSR11, reg);
rt2x00usb_vendor_request_sw(rt2x00dev, USB_DEVICE_MODE, 0,
USB_MODE_SLEEP, REGISTER_TIMEOUT);
} else {
rt2x00usb_register_read(rt2x00dev, MAC_CSR11, ®);
rt2x00_set_field32(®, MAC_CSR11_DELAY_AFTER_TBCN, 0);
rt2x00_set_field32(®, MAC_CSR11_TBCN_BEFORE_WAKEUP, 0);
rt2x00_set_field32(®, MAC_CSR11_AUTOWAKE, 0);
rt2x00_set_field32(®, MAC_CSR11_WAKEUP_LATENCY, 0);
rt2x00usb_register_write(rt2x00dev, MAC_CSR11, reg);
rt2x00usb_vendor_request_sw(rt2x00dev, USB_DEVICE_MODE, 0,
USB_MODE_WAKEUP, REGISTER_TIMEOUT);
}
}
static void rt73usb_config(struct rt2x00_dev *rt2x00dev,
struct rt2x00lib_conf *libconf,
const unsigned int flags)
{
/* Always recalculate LNA gain before changing configuration */
rt73usb_config_lna_gain(rt2x00dev, libconf);
if (flags & IEEE80211_CONF_CHANGE_CHANNEL)
rt73usb_config_channel(rt2x00dev, &libconf->rf,
libconf->conf->power_level);
if ((flags & IEEE80211_CONF_CHANGE_POWER) &&
!(flags & IEEE80211_CONF_CHANGE_CHANNEL))
rt73usb_config_txpower(rt2x00dev, libconf->conf->power_level);
if (flags & IEEE80211_CONF_CHANGE_RETRY_LIMITS)
rt73usb_config_retry_limit(rt2x00dev, libconf);
if (flags & IEEE80211_CONF_CHANGE_PS)
rt73usb_config_ps(rt2x00dev, libconf);
}
/*
* Link tuning
*/
static void rt73usb_link_stats(struct rt2x00_dev *rt2x00dev,
struct link_qual *qual)
{
u32 reg;
/*
* Update FCS error count from register.
*/
rt2x00usb_register_read(rt2x00dev, STA_CSR0, ®);
qual->rx_failed = rt2x00_get_field32(reg, STA_CSR0_FCS_ERROR);
/*
* Update False CCA count from register.
*/
rt2x00usb_register_read(rt2x00dev, STA_CSR1, ®);
qual->false_cca = rt2x00_get_field32(reg, STA_CSR1_FALSE_CCA_ERROR);
}
static inline void rt73usb_set_vgc(struct rt2x00_dev *rt2x00dev,
struct link_qual *qual, u8 vgc_level)
{
if (qual->vgc_level != vgc_level) {
rt73usb_bbp_write(rt2x00dev, 17, vgc_level);
qual->vgc_level = vgc_level;
qual->vgc_level_reg = vgc_level;
}
}
static void rt73usb_reset_tuner(struct rt2x00_dev *rt2x00dev,
struct link_qual *qual)
{
rt73usb_set_vgc(rt2x00dev, qual, 0x20);
}
static void rt73usb_link_tuner(struct rt2x00_dev *rt2x00dev,
struct link_qual *qual, const u32 count)
{
u8 up_bound;
u8 low_bound;
/*
* Determine r17 bounds.
*/
if (rt2x00dev->curr_band == IEEE80211_BAND_5GHZ) {
low_bound = 0x28;
up_bound = 0x48;
if (test_bit(CAPABILITY_EXTERNAL_LNA_A, &rt2x00dev->cap_flags)) {
low_bound += 0x10;
up_bound += 0x10;
}
} else {
if (qual->rssi > -82) {
low_bound = 0x1c;
up_bound = 0x40;
} else if (qual->rssi > -84) {
low_bound = 0x1c;
up_bound = 0x20;
} else {
low_bound = 0x1c;
up_bound = 0x1c;
}
if (test_bit(CAPABILITY_EXTERNAL_LNA_BG, &rt2x00dev->cap_flags)) {
low_bound += 0x14;
up_bound += 0x10;
}
}
/*
* If we are not associated, we should go straight to the
* dynamic CCA tuning.
*/
if (!rt2x00dev->intf_associated)
goto dynamic_cca_tune;
/*
* Special big-R17 for very short distance
*/
if (qual->rssi > -35) {
rt73usb_set_vgc(rt2x00dev, qual, 0x60);
return;
}
/*
* Special big-R17 for short distance
*/
if (qual->rssi >= -58) {
rt73usb_set_vgc(rt2x00dev, qual, up_bound);
return;
}
/*
* Special big-R17 for middle-short distance
*/
if (qual->rssi >= -66) {
rt73usb_set_vgc(rt2x00dev, qual, low_bound + 0x10);
return;
}
/*
* Special mid-R17 for middle distance
*/
if (qual->rssi >= -74) {
rt73usb_set_vgc(rt2x00dev, qual, low_bound + 0x08);
return;
}
/*
* Special case: Change up_bound based on the rssi.
* Lower up_bound when rssi is weaker then -74 dBm.
*/
up_bound -= 2 * (-74 - qual->rssi);
if (low_bound > up_bound)
up_bound = low_bound;
if (qual->vgc_level > up_bound) {
rt73usb_set_vgc(rt2x00dev, qual, up_bound);
return;
}
dynamic_cca_tune:
/*
* r17 does not yet exceed upper limit, continue and base
* the r17 tuning on the false CCA count.
*/
if ((qual->false_cca > 512) && (qual->vgc_level < up_bound))
rt73usb_set_vgc(rt2x00dev, qual,
min_t(u8, qual->vgc_level + 4, up_bound));
else if ((qual->false_cca < 100) && (qual->vgc_level > low_bound))
rt73usb_set_vgc(rt2x00dev, qual,
max_t(u8, qual->vgc_level - 4, low_bound));
}
/*
* Queue handlers.
*/
static void rt73usb_start_queue(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
u32 reg;
switch (queue->qid) {
case QID_RX:
rt2x00usb_register_read(rt2x00dev, TXRX_CSR0, ®);
rt2x00_set_field32(®, TXRX_CSR0_DISABLE_RX, 0);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR0, reg);
break;
case QID_BEACON:
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
rt2x00_set_field32(®, TXRX_CSR9_TSF_TICKING, 1);
rt2x00_set_field32(®, TXRX_CSR9_TBTT_ENABLE, 1);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
break;
default:
break;
}
}
static void rt73usb_stop_queue(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
u32 reg;
switch (queue->qid) {
case QID_RX:
rt2x00usb_register_read(rt2x00dev, TXRX_CSR0, ®);
rt2x00_set_field32(®, TXRX_CSR0_DISABLE_RX, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR0, reg);
break;
case QID_BEACON:
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
rt2x00_set_field32(®, TXRX_CSR9_TSF_TICKING, 0);
rt2x00_set_field32(®, TXRX_CSR9_TBTT_ENABLE, 0);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 0);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
break;
default:
break;
}
}
/*
* Firmware functions
*/
static char *rt73usb_get_firmware_name(struct rt2x00_dev *rt2x00dev)
{
return FIRMWARE_RT2571;
}
static int rt73usb_check_firmware(struct rt2x00_dev *rt2x00dev,
const u8 *data, const size_t len)
{
u16 fw_crc;
u16 crc;
/*
* Only support 2kb firmware files.
*/
if (len != 2048)
return FW_BAD_LENGTH;
/*
* The last 2 bytes in the firmware array are the crc checksum itself,
* this means that we should never pass those 2 bytes to the crc
* algorithm.
*/
fw_crc = (data[len - 2] << 8 | data[len - 1]);
/*
* Use the crc itu-t algorithm.
*/
crc = crc_itu_t(0, data, len - 2);
crc = crc_itu_t_byte(crc, 0);
crc = crc_itu_t_byte(crc, 0);
return (fw_crc == crc) ? FW_OK : FW_BAD_CRC;
}
static int rt73usb_load_firmware(struct rt2x00_dev *rt2x00dev,
const u8 *data, const size_t len)
{
unsigned int i;
int status;
u32 reg;
/*
* Wait for stable hardware.
*/
for (i = 0; i < 100; i++) {
rt2x00usb_register_read(rt2x00dev, MAC_CSR0, ®);
if (reg)
break;
msleep(1);
}
if (!reg) {
ERROR(rt2x00dev, "Unstable hardware.\n");
return -EBUSY;
}
/*
* Write firmware to device.
*/
rt2x00usb_register_multiwrite(rt2x00dev, FIRMWARE_IMAGE_BASE, data, len);
/*
* Send firmware request to device to load firmware,
* we need to specify a long timeout time.
*/
status = rt2x00usb_vendor_request_sw(rt2x00dev, USB_DEVICE_MODE,
0, USB_MODE_FIRMWARE,
REGISTER_TIMEOUT_FIRMWARE);
if (status < 0) {
ERROR(rt2x00dev, "Failed to write Firmware to device.\n");
return status;
}
return 0;
}
/*
* Initialization functions.
*/
static int rt73usb_init_registers(struct rt2x00_dev *rt2x00dev)
{
u32 reg;
rt2x00usb_register_read(rt2x00dev, TXRX_CSR0, ®);
rt2x00_set_field32(®, TXRX_CSR0_AUTO_TX_SEQ, 1);
rt2x00_set_field32(®, TXRX_CSR0_DISABLE_RX, 0);
rt2x00_set_field32(®, TXRX_CSR0_TX_WITHOUT_WAITING, 0);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR0, reg);
rt2x00usb_register_read(rt2x00dev, TXRX_CSR1, ®);
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID0, 47); /* CCK Signal */
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID0_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID1, 30); /* Rssi */
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID1_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID2, 42); /* OFDM Rate */
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID2_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID3, 30); /* Rssi */
rt2x00_set_field32(®, TXRX_CSR1_BBP_ID3_VALID, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR1, reg);
/*
* CCK TXD BBP registers
*/
rt2x00usb_register_read(rt2x00dev, TXRX_CSR2, ®);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID0, 13);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID0_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID1, 12);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID1_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID2, 11);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID2_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID3, 10);
rt2x00_set_field32(®, TXRX_CSR2_BBP_ID3_VALID, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR2, reg);
/*
* OFDM TXD BBP registers
*/
rt2x00usb_register_read(rt2x00dev, TXRX_CSR3, ®);
rt2x00_set_field32(®, TXRX_CSR3_BBP_ID0, 7);
rt2x00_set_field32(®, TXRX_CSR3_BBP_ID0_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR3_BBP_ID1, 6);
rt2x00_set_field32(®, TXRX_CSR3_BBP_ID1_VALID, 1);
rt2x00_set_field32(®, TXRX_CSR3_BBP_ID2, 5);
rt2x00_set_field32(®, TXRX_CSR3_BBP_ID2_VALID, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR3, reg);
rt2x00usb_register_read(rt2x00dev, TXRX_CSR7, ®);
rt2x00_set_field32(®, TXRX_CSR7_ACK_CTS_6MBS, 59);
rt2x00_set_field32(®, TXRX_CSR7_ACK_CTS_9MBS, 53);
rt2x00_set_field32(®, TXRX_CSR7_ACK_CTS_12MBS, 49);
rt2x00_set_field32(®, TXRX_CSR7_ACK_CTS_18MBS, 46);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR7, reg);
rt2x00usb_register_read(rt2x00dev, TXRX_CSR8, ®);
rt2x00_set_field32(®, TXRX_CSR8_ACK_CTS_24MBS, 44);
rt2x00_set_field32(®, TXRX_CSR8_ACK_CTS_36MBS, 42);
rt2x00_set_field32(®, TXRX_CSR8_ACK_CTS_48MBS, 42);
rt2x00_set_field32(®, TXRX_CSR8_ACK_CTS_54MBS, 42);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR8, reg);
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_INTERVAL, 0);
rt2x00_set_field32(®, TXRX_CSR9_TSF_TICKING, 0);
rt2x00_set_field32(®, TXRX_CSR9_TSF_SYNC, 0);
rt2x00_set_field32(®, TXRX_CSR9_TBTT_ENABLE, 0);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 0);
rt2x00_set_field32(®, TXRX_CSR9_TIMESTAMP_COMPENSATE, 0);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR15, 0x0000000f);
rt2x00usb_register_read(rt2x00dev, MAC_CSR6, ®);
rt2x00_set_field32(®, MAC_CSR6_MAX_FRAME_UNIT, 0xfff);
rt2x00usb_register_write(rt2x00dev, MAC_CSR6, reg);
rt2x00usb_register_write(rt2x00dev, MAC_CSR10, 0x00000718);
if (rt2x00dev->ops->lib->set_device_state(rt2x00dev, STATE_AWAKE))
return -EBUSY;
rt2x00usb_register_write(rt2x00dev, MAC_CSR13, 0x00007f00);
/*
* Invalidate all Shared Keys (SEC_CSR0),
* and clear the Shared key Cipher algorithms (SEC_CSR1 & SEC_CSR5)
*/
rt2x00usb_register_write(rt2x00dev, SEC_CSR0, 0x00000000);
rt2x00usb_register_write(rt2x00dev, SEC_CSR1, 0x00000000);
rt2x00usb_register_write(rt2x00dev, SEC_CSR5, 0x00000000);
reg = 0x000023b0;
if (rt2x00_rf(rt2x00dev, RF5225) || rt2x00_rf(rt2x00dev, RF2527))
rt2x00_set_field32(®, PHY_CSR1_RF_RPI, 1);
rt2x00usb_register_write(rt2x00dev, PHY_CSR1, reg);
rt2x00usb_register_write(rt2x00dev, PHY_CSR5, 0x00040a06);
rt2x00usb_register_write(rt2x00dev, PHY_CSR6, 0x00080606);
rt2x00usb_register_write(rt2x00dev, PHY_CSR7, 0x00000408);
rt2x00usb_register_read(rt2x00dev, MAC_CSR9, ®);
rt2x00_set_field32(®, MAC_CSR9_CW_SELECT, 0);
rt2x00usb_register_write(rt2x00dev, MAC_CSR9, reg);
/*
* Clear all beacons
* For the Beacon base registers we only need to clear
* the first byte since that byte contains the VALID and OWNER
* bits which (when set to 0) will invalidate the entire beacon.
*/
rt2x00usb_register_write(rt2x00dev, HW_BEACON_BASE0, 0);
rt2x00usb_register_write(rt2x00dev, HW_BEACON_BASE1, 0);
rt2x00usb_register_write(rt2x00dev, HW_BEACON_BASE2, 0);
rt2x00usb_register_write(rt2x00dev, HW_BEACON_BASE3, 0);
/*
* We must clear the error counters.
* These registers are cleared on read,
* so we may pass a useless variable to store the value.
*/
rt2x00usb_register_read(rt2x00dev, STA_CSR0, ®);
rt2x00usb_register_read(rt2x00dev, STA_CSR1, ®);
rt2x00usb_register_read(rt2x00dev, STA_CSR2, ®);
/*
* Reset MAC and BBP registers.
*/
rt2x00usb_register_read(rt2x00dev, MAC_CSR1, ®);
rt2x00_set_field32(®, MAC_CSR1_SOFT_RESET, 1);
rt2x00_set_field32(®, MAC_CSR1_BBP_RESET, 1);
rt2x00usb_register_write(rt2x00dev, MAC_CSR1, reg);
rt2x00usb_register_read(rt2x00dev, MAC_CSR1, ®);
rt2x00_set_field32(®, MAC_CSR1_SOFT_RESET, 0);
rt2x00_set_field32(®, MAC_CSR1_BBP_RESET, 0);
rt2x00usb_register_write(rt2x00dev, MAC_CSR1, reg);
rt2x00usb_register_read(rt2x00dev, MAC_CSR1, ®);
rt2x00_set_field32(®, MAC_CSR1_HOST_READY, 1);
rt2x00usb_register_write(rt2x00dev, MAC_CSR1, reg);
return 0;
}
static int rt73usb_wait_bbp_ready(struct rt2x00_dev *rt2x00dev)
{
unsigned int i;
u8 value;
for (i = 0; i < REGISTER_BUSY_COUNT; i++) {
rt73usb_bbp_read(rt2x00dev, 0, &value);
if ((value != 0xff) && (value != 0x00))
return 0;
udelay(REGISTER_BUSY_DELAY);
}
ERROR(rt2x00dev, "BBP register access failed, aborting.\n");
return -EACCES;
}
static int rt73usb_init_bbp(struct rt2x00_dev *rt2x00dev)
{
unsigned int i;
u16 eeprom;
u8 reg_id;
u8 value;
if (unlikely(rt73usb_wait_bbp_ready(rt2x00dev)))
return -EACCES;
rt73usb_bbp_write(rt2x00dev, 3, 0x80);
rt73usb_bbp_write(rt2x00dev, 15, 0x30);
rt73usb_bbp_write(rt2x00dev, 21, 0xc8);
rt73usb_bbp_write(rt2x00dev, 22, 0x38);
rt73usb_bbp_write(rt2x00dev, 23, 0x06);
rt73usb_bbp_write(rt2x00dev, 24, 0xfe);
rt73usb_bbp_write(rt2x00dev, 25, 0x0a);
rt73usb_bbp_write(rt2x00dev, 26, 0x0d);
rt73usb_bbp_write(rt2x00dev, 32, 0x0b);
rt73usb_bbp_write(rt2x00dev, 34, 0x12);
rt73usb_bbp_write(rt2x00dev, 37, 0x07);
rt73usb_bbp_write(rt2x00dev, 39, 0xf8);
rt73usb_bbp_write(rt2x00dev, 41, 0x60);
rt73usb_bbp_write(rt2x00dev, 53, 0x10);
rt73usb_bbp_write(rt2x00dev, 54, 0x18);
rt73usb_bbp_write(rt2x00dev, 60, 0x10);
rt73usb_bbp_write(rt2x00dev, 61, 0x04);
rt73usb_bbp_write(rt2x00dev, 62, 0x04);
rt73usb_bbp_write(rt2x00dev, 75, 0xfe);
rt73usb_bbp_write(rt2x00dev, 86, 0xfe);
rt73usb_bbp_write(rt2x00dev, 88, 0xfe);
rt73usb_bbp_write(rt2x00dev, 90, 0x0f);
rt73usb_bbp_write(rt2x00dev, 99, 0x00);
rt73usb_bbp_write(rt2x00dev, 102, 0x16);
rt73usb_bbp_write(rt2x00dev, 107, 0x04);
for (i = 0; i < EEPROM_BBP_SIZE; i++) {
rt2x00_eeprom_read(rt2x00dev, EEPROM_BBP_START + i, &eeprom);
if (eeprom != 0xffff && eeprom != 0x0000) {
reg_id = rt2x00_get_field16(eeprom, EEPROM_BBP_REG_ID);
value = rt2x00_get_field16(eeprom, EEPROM_BBP_VALUE);
rt73usb_bbp_write(rt2x00dev, reg_id, value);
}
}
return 0;
}
/*
* Device state switch handlers.
*/
static int rt73usb_enable_radio(struct rt2x00_dev *rt2x00dev)
{
/*
* Initialize all registers.
*/
if (unlikely(rt73usb_init_registers(rt2x00dev) ||
rt73usb_init_bbp(rt2x00dev)))
return -EIO;
return 0;
}
static void rt73usb_disable_radio(struct rt2x00_dev *rt2x00dev)
{
rt2x00usb_register_write(rt2x00dev, MAC_CSR10, 0x00001818);
/*
* Disable synchronisation.
*/
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, 0);
rt2x00usb_disable_radio(rt2x00dev);
}
static int rt73usb_set_state(struct rt2x00_dev *rt2x00dev, enum dev_state state)
{
u32 reg, reg2;
unsigned int i;
char put_to_sleep;
put_to_sleep = (state != STATE_AWAKE);
rt2x00usb_register_read(rt2x00dev, MAC_CSR12, ®);
rt2x00_set_field32(®, MAC_CSR12_FORCE_WAKEUP, !put_to_sleep);
rt2x00_set_field32(®, MAC_CSR12_PUT_TO_SLEEP, put_to_sleep);
rt2x00usb_register_write(rt2x00dev, MAC_CSR12, reg);
/*
* Device is not guaranteed to be in the requested state yet.
* We must wait until the register indicates that the
* device has entered the correct state.
*/
for (i = 0; i < REGISTER_BUSY_COUNT; i++) {
rt2x00usb_register_read(rt2x00dev, MAC_CSR12, ®2);
state = rt2x00_get_field32(reg2, MAC_CSR12_BBP_CURRENT_STATE);
if (state == !put_to_sleep)
return 0;
rt2x00usb_register_write(rt2x00dev, MAC_CSR12, reg);
msleep(10);
}
return -EBUSY;
}
static int rt73usb_set_device_state(struct rt2x00_dev *rt2x00dev,
enum dev_state state)
{
int retval = 0;
switch (state) {
case STATE_RADIO_ON:
retval = rt73usb_enable_radio(rt2x00dev);
break;
case STATE_RADIO_OFF:
rt73usb_disable_radio(rt2x00dev);
break;
case STATE_RADIO_IRQ_ON:
case STATE_RADIO_IRQ_OFF:
/* No support, but no error either */
break;
case STATE_DEEP_SLEEP:
case STATE_SLEEP:
case STATE_STANDBY:
case STATE_AWAKE:
retval = rt73usb_set_state(rt2x00dev, state);
break;
default:
retval = -ENOTSUPP;
break;
}
if (unlikely(retval))
ERROR(rt2x00dev, "Device failed to enter state %d (%d).\n",
state, retval);
return retval;
}
/*
* TX descriptor initialization
*/
static void rt73usb_write_tx_desc(struct queue_entry *entry,
struct txentry_desc *txdesc)
{
struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb);
__le32 *txd = (__le32 *) entry->skb->data;
u32 word;
/*
* Start writing the descriptor words.
*/
rt2x00_desc_read(txd, 0, &word);
rt2x00_set_field32(&word, TXD_W0_BURST,
test_bit(ENTRY_TXD_BURST, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_VALID, 1);
rt2x00_set_field32(&word, TXD_W0_MORE_FRAG,
test_bit(ENTRY_TXD_MORE_FRAG, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_ACK,
test_bit(ENTRY_TXD_ACK, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_TIMESTAMP,
test_bit(ENTRY_TXD_REQ_TIMESTAMP, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_OFDM,
(txdesc->rate_mode == RATE_MODE_OFDM));
rt2x00_set_field32(&word, TXD_W0_IFS, txdesc->u.plcp.ifs);
rt2x00_set_field32(&word, TXD_W0_RETRY_MODE,
test_bit(ENTRY_TXD_RETRY_MODE, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_TKIP_MIC,
test_bit(ENTRY_TXD_ENCRYPT_MMIC, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_KEY_TABLE,
test_bit(ENTRY_TXD_ENCRYPT_PAIRWISE, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_KEY_INDEX, txdesc->key_idx);
rt2x00_set_field32(&word, TXD_W0_DATABYTE_COUNT, txdesc->length);
rt2x00_set_field32(&word, TXD_W0_BURST2,
test_bit(ENTRY_TXD_BURST, &txdesc->flags));
rt2x00_set_field32(&word, TXD_W0_CIPHER_ALG, txdesc->cipher);
rt2x00_desc_write(txd, 0, word);
rt2x00_desc_read(txd, 1, &word);
rt2x00_set_field32(&word, TXD_W1_HOST_Q_ID, entry->queue->qid);
rt2x00_set_field32(&word, TXD_W1_AIFSN, entry->queue->aifs);
rt2x00_set_field32(&word, TXD_W1_CWMIN, entry->queue->cw_min);
rt2x00_set_field32(&word, TXD_W1_CWMAX, entry->queue->cw_max);
rt2x00_set_field32(&word, TXD_W1_IV_OFFSET, txdesc->iv_offset);
rt2x00_set_field32(&word, TXD_W1_HW_SEQUENCE,
test_bit(ENTRY_TXD_GENERATE_SEQ, &txdesc->flags));
rt2x00_desc_write(txd, 1, word);
rt2x00_desc_read(txd, 2, &word);
rt2x00_set_field32(&word, TXD_W2_PLCP_SIGNAL, txdesc->u.plcp.signal);
rt2x00_set_field32(&word, TXD_W2_PLCP_SERVICE, txdesc->u.plcp.service);
rt2x00_set_field32(&word, TXD_W2_PLCP_LENGTH_LOW,
txdesc->u.plcp.length_low);
rt2x00_set_field32(&word, TXD_W2_PLCP_LENGTH_HIGH,
txdesc->u.plcp.length_high);
rt2x00_desc_write(txd, 2, word);
if (test_bit(ENTRY_TXD_ENCRYPT, &txdesc->flags)) {
_rt2x00_desc_write(txd, 3, skbdesc->iv[0]);
_rt2x00_desc_write(txd, 4, skbdesc->iv[1]);
}
rt2x00_desc_read(txd, 5, &word);
rt2x00_set_field32(&word, TXD_W5_TX_POWER,
TXPOWER_TO_DEV(entry->queue->rt2x00dev->tx_power));
rt2x00_set_field32(&word, TXD_W5_WAITING_DMA_DONE_INT, 1);
rt2x00_desc_write(txd, 5, word);
/*
* Register descriptor details in skb frame descriptor.
*/
skbdesc->flags |= SKBDESC_DESC_IN_SKB;
skbdesc->desc = txd;
skbdesc->desc_len = TXD_DESC_SIZE;
}
/*
* TX data initialization
*/
static void rt73usb_write_beacon(struct queue_entry *entry,
struct txentry_desc *txdesc)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
unsigned int beacon_base;
unsigned int padding_len;
u32 orig_reg, reg;
/*
* Disable beaconing while we are reloading the beacon data,
* otherwise we might be sending out invalid data.
*/
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
orig_reg = reg;
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 0);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
/*
* Add space for the descriptor in front of the skb.
*/
skb_push(entry->skb, TXD_DESC_SIZE);
memset(entry->skb->data, 0, TXD_DESC_SIZE);
/*
* Write the TX descriptor for the beacon.
*/
rt73usb_write_tx_desc(entry, txdesc);
/*
* Dump beacon to userspace through debugfs.
*/
rt2x00debug_dump_frame(rt2x00dev, DUMP_FRAME_BEACON, entry->skb);
/*
* Write entire beacon with descriptor and padding to register.
*/
padding_len = roundup(entry->skb->len, 4) - entry->skb->len;
if (padding_len && skb_pad(entry->skb, padding_len)) {
ERROR(rt2x00dev, "Failure padding beacon, aborting\n");
/* skb freed by skb_pad() on failure */
entry->skb = NULL;
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, orig_reg);
return;
}
beacon_base = HW_BEACON_OFFSET(entry->entry_idx);
rt2x00usb_register_multiwrite(rt2x00dev, beacon_base, entry->skb->data,
entry->skb->len + padding_len);
/*
* Enable beaconing again.
*
* For Wi-Fi faily generated beacons between participating stations.
* Set TBTT phase adaptive adjustment step to 8us (default 16us)
*/
rt2x00usb_register_write(rt2x00dev, TXRX_CSR10, 0x00001008);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
/*
* Clean up the beacon skb.
*/
dev_kfree_skb(entry->skb);
entry->skb = NULL;
}
static void rt73usb_clear_beacon(struct queue_entry *entry)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
unsigned int beacon_base;
u32 reg;
/*
* Disable beaconing while we are reloading the beacon data,
* otherwise we might be sending out invalid data.
*/
rt2x00usb_register_read(rt2x00dev, TXRX_CSR9, ®);
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 0);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
/*
* Clear beacon.
*/
beacon_base = HW_BEACON_OFFSET(entry->entry_idx);
rt2x00usb_register_write(rt2x00dev, beacon_base, 0);
/*
* Enable beaconing again.
*/
rt2x00_set_field32(®, TXRX_CSR9_BEACON_GEN, 1);
rt2x00usb_register_write(rt2x00dev, TXRX_CSR9, reg);
}
static int rt73usb_get_tx_data_len(struct queue_entry *entry)
{
int length;
/*
* The length _must_ be a multiple of 4,
* but it must _not_ be a multiple of the USB packet size.
*/
length = roundup(entry->skb->len, 4);
length += (4 * !(length % entry->queue->usb_maxpacket));
return length;
}
/*
* RX control handlers
*/
static int rt73usb_agc_to_rssi(struct rt2x00_dev *rt2x00dev, int rxd_w1)
{
u8 offset = rt2x00dev->lna_gain;
u8 lna;
lna = rt2x00_get_field32(rxd_w1, RXD_W1_RSSI_LNA);
switch (lna) {
case 3:
offset += 90;
break;
case 2:
offset += 74;
break;
case 1:
offset += 64;
break;
default:
return 0;
}
if (rt2x00dev->curr_band == IEEE80211_BAND_5GHZ) {
if (test_bit(CAPABILITY_EXTERNAL_LNA_A, &rt2x00dev->cap_flags)) {
if (lna == 3 || lna == 2)
offset += 10;
} else {
if (lna == 3)
offset += 6;
else if (lna == 2)
offset += 8;
}
}
return rt2x00_get_field32(rxd_w1, RXD_W1_RSSI_AGC) * 2 - offset;
}
static void rt73usb_fill_rxdone(struct queue_entry *entry,
struct rxdone_entry_desc *rxdesc)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb);
__le32 *rxd = (__le32 *)entry->skb->data;
u32 word0;
u32 word1;
/*
* Copy descriptor to the skbdesc->desc buffer, making it safe from moving of
* frame data in rt2x00usb.
*/
memcpy(skbdesc->desc, rxd, skbdesc->desc_len);
rxd = (__le32 *)skbdesc->desc;
/*
* It is now safe to read the descriptor on all architectures.
*/
rt2x00_desc_read(rxd, 0, &word0);
rt2x00_desc_read(rxd, 1, &word1);
if (rt2x00_get_field32(word0, RXD_W0_CRC_ERROR))
rxdesc->flags |= RX_FLAG_FAILED_FCS_CRC;
rxdesc->cipher = rt2x00_get_field32(word0, RXD_W0_CIPHER_ALG);
rxdesc->cipher_status = rt2x00_get_field32(word0, RXD_W0_CIPHER_ERROR);
if (rxdesc->cipher != CIPHER_NONE) {
_rt2x00_desc_read(rxd, 2, &rxdesc->iv[0]);
_rt2x00_desc_read(rxd, 3, &rxdesc->iv[1]);
rxdesc->dev_flags |= RXDONE_CRYPTO_IV;
_rt2x00_desc_read(rxd, 4, &rxdesc->icv);
rxdesc->dev_flags |= RXDONE_CRYPTO_ICV;
/*
* Hardware has stripped IV/EIV data from 802.11 frame during
* decryption. It has provided the data separately but rt2x00lib
* should decide if it should be reinserted.
*/
rxdesc->flags |= RX_FLAG_IV_STRIPPED;
/*
* The hardware has already checked the Michael Mic and has
* stripped it from the frame. Signal this to mac80211.
*/
rxdesc->flags |= RX_FLAG_MMIC_STRIPPED;
if (rxdesc->cipher_status == RX_CRYPTO_SUCCESS)
rxdesc->flags |= RX_FLAG_DECRYPTED;
else if (rxdesc->cipher_status == RX_CRYPTO_FAIL_MIC)
rxdesc->flags |= RX_FLAG_MMIC_ERROR;
}
/*
* Obtain the status about this packet.
* When frame was received with an OFDM bitrate,
* the signal is the PLCP value. If it was received with
* a CCK bitrate the signal is the rate in 100kbit/s.
*/
rxdesc->signal = rt2x00_get_field32(word1, RXD_W1_SIGNAL);
rxdesc->rssi = rt73usb_agc_to_rssi(rt2x00dev, word1);
rxdesc->size = rt2x00_get_field32(word0, RXD_W0_DATABYTE_COUNT);
if (rt2x00_get_field32(word0, RXD_W0_OFDM))
rxdesc->dev_flags |= RXDONE_SIGNAL_PLCP;
else
rxdesc->dev_flags |= RXDONE_SIGNAL_BITRATE;
if (rt2x00_get_field32(word0, RXD_W0_MY_BSS))
rxdesc->dev_flags |= RXDONE_MY_BSS;
/*
* Set skb pointers, and update frame information.
*/
skb_pull(entry->skb, entry->queue->desc_size);
skb_trim(entry->skb, rxdesc->size);
}
/*
* Device probe functions.
*/
static int rt73usb_validate_eeprom(struct rt2x00_dev *rt2x00dev)
{
u16 word;
u8 *mac;
s8 value;
rt2x00usb_eeprom_read(rt2x00dev, rt2x00dev->eeprom, EEPROM_SIZE);
/*
* Start validation of the data that has been read.
*/
mac = rt2x00_eeprom_addr(rt2x00dev, EEPROM_MAC_ADDR_0);
if (!is_valid_ether_addr(mac)) {
random_ether_addr(mac);
EEPROM(rt2x00dev, "MAC: %pM\n", mac);
}
rt2x00_eeprom_read(rt2x00dev, EEPROM_ANTENNA, &word);
if (word == 0xffff) {
rt2x00_set_field16(&word, EEPROM_ANTENNA_NUM, 2);
rt2x00_set_field16(&word, EEPROM_ANTENNA_TX_DEFAULT,
ANTENNA_B);
rt2x00_set_field16(&word, EEPROM_ANTENNA_RX_DEFAULT,
ANTENNA_B);
rt2x00_set_field16(&word, EEPROM_ANTENNA_FRAME_TYPE, 0);
rt2x00_set_field16(&word, EEPROM_ANTENNA_DYN_TXAGC, 0);
rt2x00_set_field16(&word, EEPROM_ANTENNA_HARDWARE_RADIO, 0);
rt2x00_set_field16(&word, EEPROM_ANTENNA_RF_TYPE, RF5226);
rt2x00_eeprom_write(rt2x00dev, EEPROM_ANTENNA, word);
EEPROM(rt2x00dev, "Antenna: 0x%04x\n", word);
}
rt2x00_eeprom_read(rt2x00dev, EEPROM_NIC, &word);
if (word == 0xffff) {
rt2x00_set_field16(&word, EEPROM_NIC_EXTERNAL_LNA, 0);
rt2x00_eeprom_write(rt2x00dev, EEPROM_NIC, word);
EEPROM(rt2x00dev, "NIC: 0x%04x\n", word);
}
rt2x00_eeprom_read(rt2x00dev, EEPROM_LED, &word);
if (word == 0xffff) {
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_RDY_G, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_RDY_A, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_ACT, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_GPIO_0, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_GPIO_1, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_GPIO_2, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_GPIO_3, 0);
rt2x00_set_field16(&word, EEPROM_LED_POLARITY_GPIO_4, 0);
rt2x00_set_field16(&word, EEPROM_LED_LED_MODE,
LED_MODE_DEFAULT);
rt2x00_eeprom_write(rt2x00dev, EEPROM_LED, word);
EEPROM(rt2x00dev, "Led: 0x%04x\n", word);
}
rt2x00_eeprom_read(rt2x00dev, EEPROM_FREQ, &word);
if (word == 0xffff) {
rt2x00_set_field16(&word, EEPROM_FREQ_OFFSET, 0);
rt2x00_set_field16(&word, EEPROM_FREQ_SEQ, 0);
rt2x00_eeprom_write(rt2x00dev, EEPROM_FREQ, word);
EEPROM(rt2x00dev, "Freq: 0x%04x\n", word);
}
rt2x00_eeprom_read(rt2x00dev, EEPROM_RSSI_OFFSET_BG, &word);
if (word == 0xffff) {
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_BG_1, 0);
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_BG_2, 0);
rt2x00_eeprom_write(rt2x00dev, EEPROM_RSSI_OFFSET_BG, word);
EEPROM(rt2x00dev, "RSSI OFFSET BG: 0x%04x\n", word);
} else {
value = rt2x00_get_field16(word, EEPROM_RSSI_OFFSET_BG_1);
if (value < -10 || value > 10)
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_BG_1, 0);
value = rt2x00_get_field16(word, EEPROM_RSSI_OFFSET_BG_2);
if (value < -10 || value > 10)
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_BG_2, 0);
rt2x00_eeprom_write(rt2x00dev, EEPROM_RSSI_OFFSET_BG, word);
}
rt2x00_eeprom_read(rt2x00dev, EEPROM_RSSI_OFFSET_A, &word);
if (word == 0xffff) {
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_A_1, 0);
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_A_2, 0);
rt2x00_eeprom_write(rt2x00dev, EEPROM_RSSI_OFFSET_A, word);
EEPROM(rt2x00dev, "RSSI OFFSET A: 0x%04x\n", word);
} else {
value = rt2x00_get_field16(word, EEPROM_RSSI_OFFSET_A_1);
if (value < -10 || value > 10)
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_A_1, 0);
value = rt2x00_get_field16(word, EEPROM_RSSI_OFFSET_A_2);
if (value < -10 || value > 10)
rt2x00_set_field16(&word, EEPROM_RSSI_OFFSET_A_2, 0);
rt2x00_eeprom_write(rt2x00dev, EEPROM_RSSI_OFFSET_A, word);
}
return 0;
}
static int rt73usb_init_eeprom(struct rt2x00_dev *rt2x00dev)
{
u32 reg;
u16 value;
u16 eeprom;
/*
* Read EEPROM word for configuration.
*/
rt2x00_eeprom_read(rt2x00dev, EEPROM_ANTENNA, &eeprom);
/*
* Identify RF chipset.
*/
value = rt2x00_get_field16(eeprom, EEPROM_ANTENNA_RF_TYPE);
rt2x00usb_register_read(rt2x00dev, MAC_CSR0, ®);
rt2x00_set_chip(rt2x00dev, rt2x00_get_field32(reg, MAC_CSR0_CHIPSET),
value, rt2x00_get_field32(reg, MAC_CSR0_REVISION));
if (!rt2x00_rt(rt2x00dev, RT2573) || (rt2x00_rev(rt2x00dev) == 0)) {
ERROR(rt2x00dev, "Invalid RT chipset detected.\n");
return -ENODEV;
}
if (!rt2x00_rf(rt2x00dev, RF5226) &&
!rt2x00_rf(rt2x00dev, RF2528) &&
!rt2x00_rf(rt2x00dev, RF5225) &&
!rt2x00_rf(rt2x00dev, RF2527)) {
ERROR(rt2x00dev, "Invalid RF chipset detected.\n");
return -ENODEV;
}
/*
* Identify default antenna configuration.
*/
rt2x00dev->default_ant.tx =
rt2x00_get_field16(eeprom, EEPROM_ANTENNA_TX_DEFAULT);
rt2x00dev->default_ant.rx =
rt2x00_get_field16(eeprom, EEPROM_ANTENNA_RX_DEFAULT);
/*
* Read the Frame type.
*/
if (rt2x00_get_field16(eeprom, EEPROM_ANTENNA_FRAME_TYPE))
__set_bit(CAPABILITY_FRAME_TYPE, &rt2x00dev->cap_flags);
/*
* Detect if this device has an hardware controlled radio.
*/
if (rt2x00_get_field16(eeprom, EEPROM_ANTENNA_HARDWARE_RADIO))
__set_bit(CAPABILITY_HW_BUTTON, &rt2x00dev->cap_flags);
/*
* Read frequency offset.
*/
rt2x00_eeprom_read(rt2x00dev, EEPROM_FREQ, &eeprom);
rt2x00dev->freq_offset = rt2x00_get_field16(eeprom, EEPROM_FREQ_OFFSET);
/*
* Read external LNA informations.
*/
rt2x00_eeprom_read(rt2x00dev, EEPROM_NIC, &eeprom);
if (rt2x00_get_field16(eeprom, EEPROM_NIC_EXTERNAL_LNA)) {
__set_bit(CAPABILITY_EXTERNAL_LNA_A, &rt2x00dev->cap_flags);
__set_bit(CAPABILITY_EXTERNAL_LNA_BG, &rt2x00dev->cap_flags);
}
/*
* Store led settings, for correct led behaviour.
*/
#ifdef CONFIG_RT2X00_LIB_LEDS
rt2x00_eeprom_read(rt2x00dev, EEPROM_LED, &eeprom);
rt73usb_init_led(rt2x00dev, &rt2x00dev->led_radio, LED_TYPE_RADIO);
rt73usb_init_led(rt2x00dev, &rt2x00dev->led_assoc, LED_TYPE_ASSOC);
if (value == LED_MODE_SIGNAL_STRENGTH)
rt73usb_init_led(rt2x00dev, &rt2x00dev->led_qual,
LED_TYPE_QUALITY);
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_LED_MODE, value);
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_GPIO_0,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_GPIO_0));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_GPIO_1,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_GPIO_1));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_GPIO_2,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_GPIO_2));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_GPIO_3,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_GPIO_3));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_GPIO_4,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_GPIO_4));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_ACT,
rt2x00_get_field16(eeprom, EEPROM_LED_POLARITY_ACT));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_READY_BG,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_RDY_G));
rt2x00_set_field16(&rt2x00dev->led_mcu_reg, MCU_LEDCS_POLARITY_READY_A,
rt2x00_get_field16(eeprom,
EEPROM_LED_POLARITY_RDY_A));
#endif /* CONFIG_RT2X00_LIB_LEDS */
return 0;
}
/*
* RF value list for RF2528
* Supports: 2.4 GHz
*/
static const struct rf_channel rf_vals_bg_2528[] = {
{ 1, 0x00002c0c, 0x00000786, 0x00068255, 0x000fea0b },
{ 2, 0x00002c0c, 0x00000786, 0x00068255, 0x000fea1f },
{ 3, 0x00002c0c, 0x0000078a, 0x00068255, 0x000fea0b },
{ 4, 0x00002c0c, 0x0000078a, 0x00068255, 0x000fea1f },
{ 5, 0x00002c0c, 0x0000078e, 0x00068255, 0x000fea0b },
{ 6, 0x00002c0c, 0x0000078e, 0x00068255, 0x000fea1f },
{ 7, 0x00002c0c, 0x00000792, 0x00068255, 0x000fea0b },
{ 8, 0x00002c0c, 0x00000792, 0x00068255, 0x000fea1f },
{ 9, 0x00002c0c, 0x00000796, 0x00068255, 0x000fea0b },
{ 10, 0x00002c0c, 0x00000796, 0x00068255, 0x000fea1f },
{ 11, 0x00002c0c, 0x0000079a, 0x00068255, 0x000fea0b },
{ 12, 0x00002c0c, 0x0000079a, 0x00068255, 0x000fea1f },
{ 13, 0x00002c0c, 0x0000079e, 0x00068255, 0x000fea0b },
{ 14, 0x00002c0c, 0x000007a2, 0x00068255, 0x000fea13 },
};
/*
* RF value list for RF5226
* Supports: 2.4 GHz & 5.2 GHz
*/
static const struct rf_channel rf_vals_5226[] = {
{ 1, 0x00002c0c, 0x00000786, 0x00068255, 0x000fea0b },
{ 2, 0x00002c0c, 0x00000786, 0x00068255, 0x000fea1f },
{ 3, 0x00002c0c, 0x0000078a, 0x00068255, 0x000fea0b },
{ 4, 0x00002c0c, 0x0000078a, 0x00068255, 0x000fea1f },
{ 5, 0x00002c0c, 0x0000078e, 0x00068255, 0x000fea0b },
{ 6, 0x00002c0c, 0x0000078e, 0x00068255, 0x000fea1f },
{ 7, 0x00002c0c, 0x00000792, 0x00068255, 0x000fea0b },
{ 8, 0x00002c0c, 0x00000792, 0x00068255, 0x000fea1f },
{ 9, 0x00002c0c, 0x00000796, 0x00068255, 0x000fea0b },
{ 10, 0x00002c0c, 0x00000796, 0x00068255, 0x000fea1f },
{ 11, 0x00002c0c, 0x0000079a, 0x00068255, 0x000fea0b },
{ 12, 0x00002c0c, 0x0000079a, 0x00068255, 0x000fea1f },
{ 13, 0x00002c0c, 0x0000079e, 0x00068255, 0x000fea0b },
{ 14, 0x00002c0c, 0x000007a2, 0x00068255, 0x000fea13 },
/* 802.11 UNI / HyperLan 2 */
{ 36, 0x00002c0c, 0x0000099a, 0x00098255, 0x000fea23 },
{ 40, 0x00002c0c, 0x000009a2, 0x00098255, 0x000fea03 },
{ 44, 0x00002c0c, 0x000009a6, 0x00098255, 0x000fea0b },
{ 48, 0x00002c0c, 0x000009aa, 0x00098255, 0x000fea13 },
{ 52, 0x00002c0c, 0x000009ae, 0x00098255, 0x000fea1b },
{ 56, 0x00002c0c, 0x000009b2, 0x00098255, 0x000fea23 },
{ 60, 0x00002c0c, 0x000009ba, 0x00098255, 0x000fea03 },
{ 64, 0x00002c0c, 0x000009be, 0x00098255, 0x000fea0b },
/* 802.11 HyperLan 2 */
{ 100, 0x00002c0c, 0x00000a2a, 0x000b8255, 0x000fea03 },
{ 104, 0x00002c0c, 0x00000a2e, 0x000b8255, 0x000fea0b },
{ 108, 0x00002c0c, 0x00000a32, 0x000b8255, 0x000fea13 },
{ 112, 0x00002c0c, 0x00000a36, 0x000b8255, 0x000fea1b },
{ 116, 0x00002c0c, 0x00000a3a, 0x000b8255, 0x000fea23 },
{ 120, 0x00002c0c, 0x00000a82, 0x000b8255, 0x000fea03 },
{ 124, 0x00002c0c, 0x00000a86, 0x000b8255, 0x000fea0b },
{ 128, 0x00002c0c, 0x00000a8a, 0x000b8255, 0x000fea13 },
{ 132, 0x00002c0c, 0x00000a8e, 0x000b8255, 0x000fea1b },
{ 136, 0x00002c0c, 0x00000a92, 0x000b8255, 0x000fea23 },
/* 802.11 UNII */
{ 140, 0x00002c0c, 0x00000a9a, 0x000b8255, 0x000fea03 },
{ 149, 0x00002c0c, 0x00000aa2, 0x000b8255, 0x000fea1f },
{ 153, 0x00002c0c, 0x00000aa6, 0x000b8255, 0x000fea27 },
{ 157, 0x00002c0c, 0x00000aae, 0x000b8255, 0x000fea07 },
{ 161, 0x00002c0c, 0x00000ab2, 0x000b8255, 0x000fea0f },
{ 165, 0x00002c0c, 0x00000ab6, 0x000b8255, 0x000fea17 },
/* MMAC(Japan)J52 ch 34,38,42,46 */
{ 34, 0x00002c0c, 0x0008099a, 0x000da255, 0x000d3a0b },
{ 38, 0x00002c0c, 0x0008099e, 0x000da255, 0x000d3a13 },
{ 42, 0x00002c0c, 0x000809a2, 0x000da255, 0x000d3a1b },
{ 46, 0x00002c0c, 0x000809a6, 0x000da255, 0x000d3a23 },
};
/*
* RF value list for RF5225 & RF2527
* Supports: 2.4 GHz & 5.2 GHz
*/
static const struct rf_channel rf_vals_5225_2527[] = {
{ 1, 0x00002ccc, 0x00004786, 0x00068455, 0x000ffa0b },
{ 2, 0x00002ccc, 0x00004786, 0x00068455, 0x000ffa1f },
{ 3, 0x00002ccc, 0x0000478a, 0x00068455, 0x000ffa0b },
{ 4, 0x00002ccc, 0x0000478a, 0x00068455, 0x000ffa1f },
{ 5, 0x00002ccc, 0x0000478e, 0x00068455, 0x000ffa0b },
{ 6, 0x00002ccc, 0x0000478e, 0x00068455, 0x000ffa1f },
{ 7, 0x00002ccc, 0x00004792, 0x00068455, 0x000ffa0b },
{ 8, 0x00002ccc, 0x00004792, 0x00068455, 0x000ffa1f },
{ 9, 0x00002ccc, 0x00004796, 0x00068455, 0x000ffa0b },
{ 10, 0x00002ccc, 0x00004796, 0x00068455, 0x000ffa1f },
{ 11, 0x00002ccc, 0x0000479a, 0x00068455, 0x000ffa0b },
{ 12, 0x00002ccc, 0x0000479a, 0x00068455, 0x000ffa1f },
{ 13, 0x00002ccc, 0x0000479e, 0x00068455, 0x000ffa0b },
{ 14, 0x00002ccc, 0x000047a2, 0x00068455, 0x000ffa13 },
/* 802.11 UNI / HyperLan 2 */
{ 36, 0x00002ccc, 0x0000499a, 0x0009be55, 0x000ffa23 },
{ 40, 0x00002ccc, 0x000049a2, 0x0009be55, 0x000ffa03 },
{ 44, 0x00002ccc, 0x000049a6, 0x0009be55, 0x000ffa0b },
{ 48, 0x00002ccc, 0x000049aa, 0x0009be55, 0x000ffa13 },
{ 52, 0x00002ccc, 0x000049ae, 0x0009ae55, 0x000ffa1b },
{ 56, 0x00002ccc, 0x000049b2, 0x0009ae55, 0x000ffa23 },
{ 60, 0x00002ccc, 0x000049ba, 0x0009ae55, 0x000ffa03 },
{ 64, 0x00002ccc, 0x000049be, 0x0009ae55, 0x000ffa0b },
/* 802.11 HyperLan 2 */
{ 100, 0x00002ccc, 0x00004a2a, 0x000bae55, 0x000ffa03 },
{ 104, 0x00002ccc, 0x00004a2e, 0x000bae55, 0x000ffa0b },
{ 108, 0x00002ccc, 0x00004a32, 0x000bae55, 0x000ffa13 },
{ 112, 0x00002ccc, 0x00004a36, 0x000bae55, 0x000ffa1b },
{ 116, 0x00002ccc, 0x00004a3a, 0x000bbe55, 0x000ffa23 },
{ 120, 0x00002ccc, 0x00004a82, 0x000bbe55, 0x000ffa03 },
{ 124, 0x00002ccc, 0x00004a86, 0x000bbe55, 0x000ffa0b },
{ 128, 0x00002ccc, 0x00004a8a, 0x000bbe55, 0x000ffa13 },
{ 132, 0x00002ccc, 0x00004a8e, 0x000bbe55, 0x000ffa1b },
{ 136, 0x00002ccc, 0x00004a92, 0x000bbe55, 0x000ffa23 },
/* 802.11 UNII */
{ 140, 0x00002ccc, 0x00004a9a, 0x000bbe55, 0x000ffa03 },
{ 149, 0x00002ccc, 0x00004aa2, 0x000bbe55, 0x000ffa1f },
{ 153, 0x00002ccc, 0x00004aa6, 0x000bbe55, 0x000ffa27 },
{ 157, 0x00002ccc, 0x00004aae, 0x000bbe55, 0x000ffa07 },
{ 161, 0x00002ccc, 0x00004ab2, 0x000bbe55, 0x000ffa0f },
{ 165, 0x00002ccc, 0x00004ab6, 0x000bbe55, 0x000ffa17 },
/* MMAC(Japan)J52 ch 34,38,42,46 */
{ 34, 0x00002ccc, 0x0000499a, 0x0009be55, 0x000ffa0b },
{ 38, 0x00002ccc, 0x0000499e, 0x0009be55, 0x000ffa13 },
{ 42, 0x00002ccc, 0x000049a2, 0x0009be55, 0x000ffa1b },
{ 46, 0x00002ccc, 0x000049a6, 0x0009be55, 0x000ffa23 },
};
static int rt73usb_probe_hw_mode(struct rt2x00_dev *rt2x00dev)
{
struct hw_mode_spec *spec = &rt2x00dev->spec;
struct channel_info *info;
char *tx_power;
unsigned int i;
/*
* Initialize all hw fields.
*
* Don't set IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING unless we are
* capable of sending the buffered frames out after the DTIM
* transmission using rt2x00lib_beacondone. This will send out
* multicast and broadcast traffic immediately instead of buffering it
* infinitly and thus dropping it after some time.
*/
rt2x00dev->hw->flags =
IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_PS_NULLFUNC_STACK;
SET_IEEE80211_DEV(rt2x00dev->hw, rt2x00dev->dev);
SET_IEEE80211_PERM_ADDR(rt2x00dev->hw,
rt2x00_eeprom_addr(rt2x00dev,
EEPROM_MAC_ADDR_0));
/*
* Initialize hw_mode information.
*/
spec->supported_bands = SUPPORT_BAND_2GHZ;
spec->supported_rates = SUPPORT_RATE_CCK | SUPPORT_RATE_OFDM;
if (rt2x00_rf(rt2x00dev, RF2528)) {
spec->num_channels = ARRAY_SIZE(rf_vals_bg_2528);
spec->channels = rf_vals_bg_2528;
} else if (rt2x00_rf(rt2x00dev, RF5226)) {
spec->supported_bands |= SUPPORT_BAND_5GHZ;
spec->num_channels = ARRAY_SIZE(rf_vals_5226);
spec->channels = rf_vals_5226;
} else if (rt2x00_rf(rt2x00dev, RF2527)) {
spec->num_channels = 14;
spec->channels = rf_vals_5225_2527;
} else if (rt2x00_rf(rt2x00dev, RF5225)) {
spec->supported_bands |= SUPPORT_BAND_5GHZ;
spec->num_channels = ARRAY_SIZE(rf_vals_5225_2527);
spec->channels = rf_vals_5225_2527;
}
/*
* Create channel information array
*/
info = kcalloc(spec->num_channels, sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
spec->channels_info = info;
tx_power = rt2x00_eeprom_addr(rt2x00dev, EEPROM_TXPOWER_G_START);
for (i = 0; i < 14; i++) {
info[i].max_power = MAX_TXPOWER;
info[i].default_power1 = TXPOWER_FROM_DEV(tx_power[i]);
}
if (spec->num_channels > 14) {
tx_power = rt2x00_eeprom_addr(rt2x00dev, EEPROM_TXPOWER_A_START);
for (i = 14; i < spec->num_channels; i++) {
info[i].max_power = MAX_TXPOWER;
info[i].default_power1 = TXPOWER_FROM_DEV(tx_power[i]);
}
}
return 0;
}
static int rt73usb_probe_hw(struct rt2x00_dev *rt2x00dev)
{
int retval;
/*
* Allocate eeprom data.
*/
retval = rt73usb_validate_eeprom(rt2x00dev);
if (retval)
return retval;
retval = rt73usb_init_eeprom(rt2x00dev);
if (retval)
return retval;
/*
* Initialize hw specifications.
*/
retval = rt73usb_probe_hw_mode(rt2x00dev);
if (retval)
return retval;
/*
* This device has multiple filters for control frames,
* but has no a separate filter for PS Poll frames.
*/
__set_bit(CAPABILITY_CONTROL_FILTERS, &rt2x00dev->cap_flags);
/*
* This device requires firmware.
*/
__set_bit(REQUIRE_FIRMWARE, &rt2x00dev->cap_flags);
if (!modparam_nohwcrypt)
__set_bit(CAPABILITY_HW_CRYPTO, &rt2x00dev->cap_flags);
__set_bit(CAPABILITY_LINK_TUNING, &rt2x00dev->cap_flags);
__set_bit(REQUIRE_PS_AUTOWAKE, &rt2x00dev->cap_flags);
/*
* Set the rssi offset.
*/
rt2x00dev->rssi_offset = DEFAULT_RSSI_OFFSET;
return 0;
}
/*
* IEEE80211 stack callback functions.
*/
static int rt73usb_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue_idx,
const struct ieee80211_tx_queue_params *params)
{
struct rt2x00_dev *rt2x00dev = hw->priv;
struct data_queue *queue;
struct rt2x00_field32 field;
int retval;
u32 reg;
u32 offset;
/*
* First pass the configuration through rt2x00lib, that will
* update the queue settings and validate the input. After that
* we are free to update the registers based on the value
* in the queue parameter.
*/
retval = rt2x00mac_conf_tx(hw, vif, queue_idx, params);
if (retval)
return retval;
/*
* We only need to perform additional register initialization
* for WMM queues/
*/
if (queue_idx >= 4)
return 0;
queue = rt2x00queue_get_tx_queue(rt2x00dev, queue_idx);
/* Update WMM TXOP register */
offset = AC_TXOP_CSR0 + (sizeof(u32) * (!!(queue_idx & 2)));
field.bit_offset = (queue_idx & 1) * 16;
field.bit_mask = 0xffff << field.bit_offset;
rt2x00usb_register_read(rt2x00dev, offset, ®);
rt2x00_set_field32(®, field, queue->txop);
rt2x00usb_register_write(rt2x00dev, offset, reg);
/* Update WMM registers */
field.bit_offset = queue_idx * 4;
field.bit_mask = 0xf << field.bit_offset;
rt2x00usb_register_read(rt2x00dev, AIFSN_CSR, ®);
rt2x00_set_field32(®, field, queue->aifs);
rt2x00usb_register_write(rt2x00dev, AIFSN_CSR, reg);
rt2x00usb_register_read(rt2x00dev, CWMIN_CSR, ®);
rt2x00_set_field32(®, field, queue->cw_min);
rt2x00usb_register_write(rt2x00dev, CWMIN_CSR, reg);
rt2x00usb_register_read(rt2x00dev, CWMAX_CSR, ®);
rt2x00_set_field32(®, field, queue->cw_max);
rt2x00usb_register_write(rt2x00dev, CWMAX_CSR, reg);
return 0;
}
static u64 rt73usb_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct rt2x00_dev *rt2x00dev = hw->priv;
u64 tsf;
u32 reg;
rt2x00usb_register_read(rt2x00dev, TXRX_CSR13, ®);
tsf = (u64) rt2x00_get_field32(reg, TXRX_CSR13_HIGH_TSFTIMER) << 32;
rt2x00usb_register_read(rt2x00dev, TXRX_CSR12, ®);
tsf |= rt2x00_get_field32(reg, TXRX_CSR12_LOW_TSFTIMER);
return tsf;
}
static const struct ieee80211_ops rt73usb_mac80211_ops = {
.tx = rt2x00mac_tx,
.start = rt2x00mac_start,
.stop = rt2x00mac_stop,
.add_interface = rt2x00mac_add_interface,
.remove_interface = rt2x00mac_remove_interface,
.config = rt2x00mac_config,
.configure_filter = rt2x00mac_configure_filter,
.set_tim = rt2x00mac_set_tim,
.set_key = rt2x00mac_set_key,
.sw_scan_start = rt2x00mac_sw_scan_start,
.sw_scan_complete = rt2x00mac_sw_scan_complete,
.get_stats = rt2x00mac_get_stats,
.bss_info_changed = rt2x00mac_bss_info_changed,
.conf_tx = rt73usb_conf_tx,
.get_tsf = rt73usb_get_tsf,
.rfkill_poll = rt2x00mac_rfkill_poll,
.flush = rt2x00mac_flush,
.set_antenna = rt2x00mac_set_antenna,
.get_antenna = rt2x00mac_get_antenna,
.get_ringparam = rt2x00mac_get_ringparam,
.tx_frames_pending = rt2x00mac_tx_frames_pending,
};
static const struct rt2x00lib_ops rt73usb_rt2x00_ops = {
.probe_hw = rt73usb_probe_hw,
.get_firmware_name = rt73usb_get_firmware_name,
.check_firmware = rt73usb_check_firmware,
.load_firmware = rt73usb_load_firmware,
.initialize = rt2x00usb_initialize,
.uninitialize = rt2x00usb_uninitialize,
.clear_entry = rt2x00usb_clear_entry,
.set_device_state = rt73usb_set_device_state,
.rfkill_poll = rt73usb_rfkill_poll,
.link_stats = rt73usb_link_stats,
.reset_tuner = rt73usb_reset_tuner,
.link_tuner = rt73usb_link_tuner,
.watchdog = rt2x00usb_watchdog,
.start_queue = rt73usb_start_queue,
.kick_queue = rt2x00usb_kick_queue,
.stop_queue = rt73usb_stop_queue,
.flush_queue = rt2x00usb_flush_queue,
.write_tx_desc = rt73usb_write_tx_desc,
.write_beacon = rt73usb_write_beacon,
.clear_beacon = rt73usb_clear_beacon,
.get_tx_data_len = rt73usb_get_tx_data_len,
.fill_rxdone = rt73usb_fill_rxdone,
.config_shared_key = rt73usb_config_shared_key,
.config_pairwise_key = rt73usb_config_pairwise_key,
.config_filter = rt73usb_config_filter,
.config_intf = rt73usb_config_intf,
.config_erp = rt73usb_config_erp,
.config_ant = rt73usb_config_ant,
.config = rt73usb_config,
};
static const struct data_queue_desc rt73usb_queue_rx = {
.entry_num = 32,
.data_size = DATA_FRAME_SIZE,
.desc_size = RXD_DESC_SIZE,
.priv_size = sizeof(struct queue_entry_priv_usb),
};
static const struct data_queue_desc rt73usb_queue_tx = {
.entry_num = 32,
.data_size = DATA_FRAME_SIZE,
.desc_size = TXD_DESC_SIZE,
.priv_size = sizeof(struct queue_entry_priv_usb),
};
static const struct data_queue_desc rt73usb_queue_bcn = {
.entry_num = 4,
.data_size = MGMT_FRAME_SIZE,
.desc_size = TXINFO_SIZE,
.priv_size = sizeof(struct queue_entry_priv_usb),
};
static const struct rt2x00_ops rt73usb_ops = {
.name = KBUILD_MODNAME,
.max_sta_intf = 1,
.max_ap_intf = 4,
.eeprom_size = EEPROM_SIZE,
.rf_size = RF_SIZE,
.tx_queues = NUM_TX_QUEUES,
.extra_tx_headroom = TXD_DESC_SIZE,
.rx = &rt73usb_queue_rx,
.tx = &rt73usb_queue_tx,
.bcn = &rt73usb_queue_bcn,
.lib = &rt73usb_rt2x00_ops,
.hw = &rt73usb_mac80211_ops,
#ifdef CONFIG_RT2X00_LIB_DEBUGFS
.debugfs = &rt73usb_rt2x00debug,
#endif /* CONFIG_RT2X00_LIB_DEBUGFS */
};
/*
* rt73usb module information.
*/
static struct usb_device_id rt73usb_device_table[] = {
/* AboCom */
{ USB_DEVICE(0x07b8, 0xb21b) },
{ USB_DEVICE(0x07b8, 0xb21c) },
{ USB_DEVICE(0x07b8, 0xb21d) },
{ USB_DEVICE(0x07b8, 0xb21e) },
{ USB_DEVICE(0x07b8, 0xb21f) },
/* AL */
{ USB_DEVICE(0x14b2, 0x3c10) },
/* Amigo */
{ USB_DEVICE(0x148f, 0x9021) },
{ USB_DEVICE(0x0eb0, 0x9021) },
/* AMIT */
{ USB_DEVICE(0x18c5, 0x0002) },
/* Askey */
{ USB_DEVICE(0x1690, 0x0722) },
/* ASUS */
{ USB_DEVICE(0x0b05, 0x1723) },
{ USB_DEVICE(0x0b05, 0x1724) },
/* Belkin */
{ USB_DEVICE(0x050d, 0x705a) },
{ USB_DEVICE(0x050d, 0x905b) },
{ USB_DEVICE(0x050d, 0x905c) },
/* Billionton */
{ USB_DEVICE(0x1631, 0xc019) },
{ USB_DEVICE(0x08dd, 0x0120) },
/* Buffalo */
{ USB_DEVICE(0x0411, 0x00d8) },
{ USB_DEVICE(0x0411, 0x00d9) },
{ USB_DEVICE(0x0411, 0x00e6) },
{ USB_DEVICE(0x0411, 0x00f4) },
{ USB_DEVICE(0x0411, 0x0116) },
{ USB_DEVICE(0x0411, 0x0119) },
{ USB_DEVICE(0x0411, 0x0137) },
/* CEIVA */
{ USB_DEVICE(0x178d, 0x02be) },
/* CNet */
{ USB_DEVICE(0x1371, 0x9022) },
{ USB_DEVICE(0x1371, 0x9032) },
/* Conceptronic */
{ USB_DEVICE(0x14b2, 0x3c22) },
/* Corega */
{ USB_DEVICE(0x07aa, 0x002e) },
/* D-Link */
{ USB_DEVICE(0x07d1, 0x3c03) },
{ USB_DEVICE(0x07d1, 0x3c04) },
{ USB_DEVICE(0x07d1, 0x3c06) },
{ USB_DEVICE(0x07d1, 0x3c07) },
/* Edimax */
{ USB_DEVICE(0x7392, 0x7318) },
{ USB_DEVICE(0x7392, 0x7618) },
/* EnGenius */
{ USB_DEVICE(0x1740, 0x3701) },
/* Gemtek */
{ USB_DEVICE(0x15a9, 0x0004) },
/* Gigabyte */
{ USB_DEVICE(0x1044, 0x8008) },
{ USB_DEVICE(0x1044, 0x800a) },
/* Huawei-3Com */
{ USB_DEVICE(0x1472, 0x0009) },
/* Hercules */
{ USB_DEVICE(0x06f8, 0xe002) },
{ USB_DEVICE(0x06f8, 0xe010) },
{ USB_DEVICE(0x06f8, 0xe020) },
/* Linksys */
{ USB_DEVICE(0x13b1, 0x0020) },
{ USB_DEVICE(0x13b1, 0x0023) },
{ USB_DEVICE(0x13b1, 0x0028) },
/* MSI */
{ USB_DEVICE(0x0db0, 0x4600) },
{ USB_DEVICE(0x0db0, 0x6877) },
{ USB_DEVICE(0x0db0, 0x6874) },
{ USB_DEVICE(0x0db0, 0xa861) },
{ USB_DEVICE(0x0db0, 0xa874) },
/* Ovislink */
{ USB_DEVICE(0x1b75, 0x7318) },
/* Ralink */
{ USB_DEVICE(0x04bb, 0x093d) },
{ USB_DEVICE(0x148f, 0x2573) },
{ USB_DEVICE(0x148f, 0x2671) },
{ USB_DEVICE(0x0812, 0x3101) },
/* Qcom */
{ USB_DEVICE(0x18e8, 0x6196) },
{ USB_DEVICE(0x18e8, 0x6229) },
{ USB_DEVICE(0x18e8, 0x6238) },
/* Samsung */
{ USB_DEVICE(0x04e8, 0x4471) },
/* Senao */
{ USB_DEVICE(0x1740, 0x7100) },
/* Sitecom */
{ USB_DEVICE(0x0df6, 0x0024) },
{ USB_DEVICE(0x0df6, 0x0027) },
{ USB_DEVICE(0x0df6, 0x002f) },
{ USB_DEVICE(0x0df6, 0x90ac) },
{ USB_DEVICE(0x0df6, 0x9712) },
/* Surecom */
{ USB_DEVICE(0x0769, 0x31f3) },
/* Tilgin */
{ USB_DEVICE(0x6933, 0x5001) },
/* Philips */
{ USB_DEVICE(0x0471, 0x200a) },
/* Planex */
{ USB_DEVICE(0x2019, 0xab01) },
{ USB_DEVICE(0x2019, 0xab50) },
/* WideTell */
{ USB_DEVICE(0x7167, 0x3840) },
/* Zcom */
{ USB_DEVICE(0x0cde, 0x001c) },
/* ZyXEL */
{ USB_DEVICE(0x0586, 0x3415) },
{ 0, }
};
MODULE_AUTHOR(DRV_PROJECT);
MODULE_VERSION(DRV_VERSION);
MODULE_DESCRIPTION("Ralink RT73 USB Wireless LAN driver.");
MODULE_SUPPORTED_DEVICE("Ralink RT2571W & RT2671 USB chipset based cards");
MODULE_DEVICE_TABLE(usb, rt73usb_device_table);
MODULE_FIRMWARE(FIRMWARE_RT2571);
MODULE_LICENSE("GPL");
static int rt73usb_probe(struct usb_interface *usb_intf,
const struct usb_device_id *id)
{
return rt2x00usb_probe(usb_intf, &rt73usb_ops);
}
static struct usb_driver rt73usb_driver = {
.name = KBUILD_MODNAME,
.id_table = rt73usb_device_table,
.probe = rt73usb_probe,
.disconnect = rt2x00usb_disconnect,
.suspend = rt2x00usb_suspend,
.resume = rt2x00usb_resume,
};
module_usb_driver(rt73usb_driver);
| gpl-2.0 |
morogoku/MoRoKernel-I9300-4.4.4 | fs/notify/fanotify/fanotify.c | 4119 | 6422 | #include <linux/fanotify.h>
#include <linux/fdtable.h>
#include <linux/fsnotify_backend.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/kernel.h> /* UINT_MAX */
#include <linux/mount.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/wait.h>
static bool should_merge(struct fsnotify_event *old, struct fsnotify_event *new)
{
pr_debug("%s: old=%p new=%p\n", __func__, old, new);
if (old->to_tell == new->to_tell &&
old->data_type == new->data_type &&
old->tgid == new->tgid) {
switch (old->data_type) {
case (FSNOTIFY_EVENT_PATH):
#ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
/* dont merge two permission events */
if ((old->mask & FAN_ALL_PERM_EVENTS) &&
(new->mask & FAN_ALL_PERM_EVENTS))
return false;
#endif
if ((old->path.mnt == new->path.mnt) &&
(old->path.dentry == new->path.dentry))
return true;
break;
case (FSNOTIFY_EVENT_NONE):
return true;
default:
BUG();
};
}
return false;
}
/* and the list better be locked by something too! */
static struct fsnotify_event *fanotify_merge(struct list_head *list,
struct fsnotify_event *event)
{
struct fsnotify_event_holder *test_holder;
struct fsnotify_event *test_event = NULL;
struct fsnotify_event *new_event;
pr_debug("%s: list=%p event=%p\n", __func__, list, event);
list_for_each_entry_reverse(test_holder, list, event_list) {
if (should_merge(test_holder->event, event)) {
test_event = test_holder->event;
break;
}
}
if (!test_event)
return NULL;
fsnotify_get_event(test_event);
/* if they are exactly the same we are done */
if (test_event->mask == event->mask)
return test_event;
/*
* if the refcnt == 2 this is the only queue
* for this event and so we can update the mask
* in place.
*/
if (atomic_read(&test_event->refcnt) == 2) {
test_event->mask |= event->mask;
return test_event;
}
new_event = fsnotify_clone_event(test_event);
/* done with test_event */
fsnotify_put_event(test_event);
/* couldn't allocate memory, merge was not possible */
if (unlikely(!new_event))
return ERR_PTR(-ENOMEM);
/* build new event and replace it on the list */
new_event->mask = (test_event->mask | event->mask);
fsnotify_replace_event(test_holder, new_event);
/* we hold a reference on new_event from clone_event */
return new_event;
}
#ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
static int fanotify_get_response_from_access(struct fsnotify_group *group,
struct fsnotify_event *event)
{
int ret;
pr_debug("%s: group=%p event=%p\n", __func__, group, event);
wait_event(group->fanotify_data.access_waitq, event->response ||
atomic_read(&group->fanotify_data.bypass_perm));
if (!event->response) /* bypass_perm set */
return 0;
/* userspace responded, convert to something usable */
spin_lock(&event->lock);
switch (event->response) {
case FAN_ALLOW:
ret = 0;
break;
case FAN_DENY:
default:
ret = -EPERM;
}
event->response = 0;
spin_unlock(&event->lock);
pr_debug("%s: group=%p event=%p about to return ret=%d\n", __func__,
group, event, ret);
return ret;
}
#endif
static int fanotify_handle_event(struct fsnotify_group *group,
struct fsnotify_mark *inode_mark,
struct fsnotify_mark *fanotify_mark,
struct fsnotify_event *event)
{
int ret = 0;
struct fsnotify_event *notify_event = NULL;
BUILD_BUG_ON(FAN_ACCESS != FS_ACCESS);
BUILD_BUG_ON(FAN_MODIFY != FS_MODIFY);
BUILD_BUG_ON(FAN_CLOSE_NOWRITE != FS_CLOSE_NOWRITE);
BUILD_BUG_ON(FAN_CLOSE_WRITE != FS_CLOSE_WRITE);
BUILD_BUG_ON(FAN_OPEN != FS_OPEN);
BUILD_BUG_ON(FAN_EVENT_ON_CHILD != FS_EVENT_ON_CHILD);
BUILD_BUG_ON(FAN_Q_OVERFLOW != FS_Q_OVERFLOW);
BUILD_BUG_ON(FAN_OPEN_PERM != FS_OPEN_PERM);
BUILD_BUG_ON(FAN_ACCESS_PERM != FS_ACCESS_PERM);
BUILD_BUG_ON(FAN_ONDIR != FS_ISDIR);
pr_debug("%s: group=%p event=%p\n", __func__, group, event);
notify_event = fsnotify_add_notify_event(group, event, NULL, fanotify_merge);
if (IS_ERR(notify_event))
return PTR_ERR(notify_event);
#ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
if (event->mask & FAN_ALL_PERM_EVENTS) {
/* if we merged we need to wait on the new event */
if (notify_event)
event = notify_event;
ret = fanotify_get_response_from_access(group, event);
}
#endif
if (notify_event)
fsnotify_put_event(notify_event);
return ret;
}
static bool fanotify_should_send_event(struct fsnotify_group *group,
struct inode *to_tell,
struct fsnotify_mark *inode_mark,
struct fsnotify_mark *vfsmnt_mark,
__u32 event_mask, void *data, int data_type)
{
__u32 marks_mask, marks_ignored_mask;
struct path *path = data;
pr_debug("%s: group=%p to_tell=%p inode_mark=%p vfsmnt_mark=%p "
"mask=%x data=%p data_type=%d\n", __func__, group, to_tell,
inode_mark, vfsmnt_mark, event_mask, data, data_type);
/* if we don't have enough info to send an event to userspace say no */
if (data_type != FSNOTIFY_EVENT_PATH)
return false;
/* sorry, fanotify only gives a damn about files and dirs */
if (!S_ISREG(path->dentry->d_inode->i_mode) &&
!S_ISDIR(path->dentry->d_inode->i_mode))
return false;
if (inode_mark && vfsmnt_mark) {
marks_mask = (vfsmnt_mark->mask | inode_mark->mask);
marks_ignored_mask = (vfsmnt_mark->ignored_mask | inode_mark->ignored_mask);
} else if (inode_mark) {
/*
* if the event is for a child and this inode doesn't care about
* events on the child, don't send it!
*/
if ((event_mask & FS_EVENT_ON_CHILD) &&
!(inode_mark->mask & FS_EVENT_ON_CHILD))
return false;
marks_mask = inode_mark->mask;
marks_ignored_mask = inode_mark->ignored_mask;
} else if (vfsmnt_mark) {
marks_mask = vfsmnt_mark->mask;
marks_ignored_mask = vfsmnt_mark->ignored_mask;
} else {
BUG();
}
if (S_ISDIR(path->dentry->d_inode->i_mode) &&
(marks_ignored_mask & FS_ISDIR))
return false;
if (event_mask & marks_mask & ~marks_ignored_mask)
return true;
return false;
}
static void fanotify_free_group_priv(struct fsnotify_group *group)
{
struct user_struct *user;
user = group->fanotify_data.user;
atomic_dec(&user->fanotify_listeners);
free_uid(user);
}
const struct fsnotify_ops fanotify_fsnotify_ops = {
.handle_event = fanotify_handle_event,
.should_send_event = fanotify_should_send_event,
.free_group_priv = fanotify_free_group_priv,
.free_event_priv = NULL,
.freeing_mark = NULL,
};
| gpl-2.0 |
emansih/d855_CM_kernel | drivers/net/ethernet/i825xx/znet.c | 4887 | 29827 | /* znet.c: An Zenith Z-Note ethernet driver for linux. */
/*
Written by Donald Becker.
The author may be reached as becker@scyld.com.
This driver is based on the Linux skeleton driver. The copyright of the
skeleton driver is held by the United States Government, as represented
by DIRNSA, and it is released under the GPL.
Thanks to Mike Hollick for alpha testing and suggestions.
References:
The Crynwr packet driver.
"82593 CSMA/CD Core LAN Controller" Intel datasheet, 1992
Intel Microcommunications Databook, Vol. 1, 1990.
As usual with Intel, the documentation is incomplete and inaccurate.
I had to read the Crynwr packet driver to figure out how to actually
use the i82593, and guess at what register bits matched the loosely
related i82586.
Theory of Operation
The i82593 used in the Zenith Z-Note series operates using two(!) slave
DMA channels, one interrupt, and one 8-bit I/O port.
While there several ways to configure '593 DMA system, I chose the one
that seemed commensurate with the highest system performance in the face
of moderate interrupt latency: Both DMA channels are configured as
recirculating ring buffers, with one channel (#0) dedicated to Rx and
the other channel (#1) to Tx and configuration. (Note that this is
different than the Crynwr driver, where the Tx DMA channel is initialized
before each operation. That approach simplifies operation and Tx error
recovery, but requires additional I/O in normal operation and precludes
transmit buffer chaining.)
Both rings are set to 8192 bytes using {TX,RX}_RING_SIZE. This provides
a reasonable ring size for Rx, while simplifying DMA buffer allocation --
DMA buffers must not cross a 128K boundary. (In truth the size selection
was influenced by my lack of '593 documentation. I thus was constrained
to use the Crynwr '593 initialization table, which sets the Rx ring size
to 8K.)
Despite my usual low opinion about Intel-designed parts, I must admit
that the bulk data handling of the i82593 is a good design for
an integrated system, like a laptop, where using two slave DMA channels
doesn't pose a problem. I still take issue with using only a single I/O
port. In the same controlled environment there are essentially no
limitations on I/O space, and using multiple locations would eliminate
the need for multiple operations when looking at status registers,
setting the Rx ring boundary, or switching to promiscuous mode.
I also question Zenith's selection of the '593: one of the advertised
advantages of earlier Intel parts was that if you figured out the magic
initialization incantation you could use the same part on many different
network types. Zenith's use of the "FriendlyNet" (sic) connector rather
than an on-board transceiver leads me to believe that they were planning
to take advantage of this. But, uhmmm, the '593 omits all but ethernet
functionality from the serial subsystem.
*/
/* 10/2002
o Resurected for Linux 2.5+ by Marc Zyngier <maz@wild-wind.fr.eu.org> :
- Removed strange DMA snooping in znet_sent_packet, which lead to
TX buffer corruption on my laptop.
- Use init_etherdev stuff.
- Use kmalloc-ed DMA buffers.
- Use as few global variables as possible.
- Use proper resources management.
- Use wireless/i82593.h as much as possible (structure, constants)
- Compiles as module or build-in.
- Now survives unplugging/replugging cable.
Some code was taken from wavelan_cs.
Tested on a vintage Zenith Z-Note 433Lnp+. Probably broken on
anything else. Testers (and detailed bug reports) are welcome :-).
o TODO :
- Properly handle multicast
- Understand why some traffic patterns add a 1s latency...
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/bitops.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <linux/i82593.h>
static char version[] __initdata = "znet.c:v1.02 9/23/94 becker@scyld.com\n";
#ifndef ZNET_DEBUG
#define ZNET_DEBUG 1
#endif
static unsigned int znet_debug = ZNET_DEBUG;
module_param (znet_debug, int, 0);
MODULE_PARM_DESC (znet_debug, "ZNet debug level");
MODULE_LICENSE("GPL");
/* The DMA modes we need aren't in <dma.h>. */
#define DMA_RX_MODE 0x14 /* Auto init, I/O to mem, ++, demand. */
#define DMA_TX_MODE 0x18 /* Auto init, Mem to I/O, ++, demand. */
#define dma_page_eq(ptr1, ptr2) ((long)(ptr1)>>17 == (long)(ptr2)>>17)
#define RX_BUF_SIZE 8192
#define TX_BUF_SIZE 8192
#define DMA_BUF_SIZE (RX_BUF_SIZE + 16) /* 8k + 16 bytes for trailers */
#define TX_TIMEOUT (HZ/10)
struct znet_private {
int rx_dma, tx_dma;
spinlock_t lock;
short sia_base, sia_size, io_size;
struct i82593_conf_block i593_init;
/* The starting, current, and end pointers for the packet buffers. */
ushort *rx_start, *rx_cur, *rx_end;
ushort *tx_start, *tx_cur, *tx_end;
ushort tx_buf_len; /* Tx buffer length, in words. */
};
/* Only one can be built-in;-> */
static struct net_device *znet_dev;
struct netidblk {
char magic[8]; /* The magic number (string) "NETIDBLK" */
unsigned char netid[8]; /* The physical station address */
char nettype, globalopt;
char vendor[8]; /* The machine vendor and product name. */
char product[8];
char irq1, irq2; /* Interrupts, only one is currently used. */
char dma1, dma2;
short dma_mem_misc[8]; /* DMA buffer locations (unused in Linux). */
short iobase1, iosize1;
short iobase2, iosize2; /* Second iobase unused. */
char driver_options; /* Misc. bits */
char pad;
};
static int znet_open(struct net_device *dev);
static netdev_tx_t znet_send_packet(struct sk_buff *skb,
struct net_device *dev);
static irqreturn_t znet_interrupt(int irq, void *dev_id);
static void znet_rx(struct net_device *dev);
static int znet_close(struct net_device *dev);
static void hardware_init(struct net_device *dev);
static void update_stop_hit(short ioaddr, unsigned short rx_stop_offset);
static void znet_tx_timeout (struct net_device *dev);
/* Request needed resources */
static int znet_request_resources (struct net_device *dev)
{
struct znet_private *znet = netdev_priv(dev);
if (request_irq (dev->irq, znet_interrupt, 0, "ZNet", dev))
goto failed;
if (request_dma (znet->rx_dma, "ZNet rx"))
goto free_irq;
if (request_dma (znet->tx_dma, "ZNet tx"))
goto free_rx_dma;
if (!request_region (znet->sia_base, znet->sia_size, "ZNet SIA"))
goto free_tx_dma;
if (!request_region (dev->base_addr, znet->io_size, "ZNet I/O"))
goto free_sia;
return 0; /* Happy ! */
free_sia:
release_region (znet->sia_base, znet->sia_size);
free_tx_dma:
free_dma (znet->tx_dma);
free_rx_dma:
free_dma (znet->rx_dma);
free_irq:
free_irq (dev->irq, dev);
failed:
return -1;
}
static void znet_release_resources (struct net_device *dev)
{
struct znet_private *znet = netdev_priv(dev);
release_region (znet->sia_base, znet->sia_size);
release_region (dev->base_addr, znet->io_size);
free_dma (znet->tx_dma);
free_dma (znet->rx_dma);
free_irq (dev->irq, dev);
}
/* Keep the magical SIA stuff in a single function... */
static void znet_transceiver_power (struct net_device *dev, int on)
{
struct znet_private *znet = netdev_priv(dev);
unsigned char v;
/* Turn on/off the 82501 SIA, using zenith-specific magic. */
/* Select LAN control register */
outb(0x10, znet->sia_base);
if (on)
v = inb(znet->sia_base + 1) | 0x84;
else
v = inb(znet->sia_base + 1) & ~0x84;
outb(v, znet->sia_base+1); /* Turn on/off LAN power (bit 2). */
}
/* Init the i82593, with current promisc/mcast configuration.
Also used from hardware_init. */
static void znet_set_multicast_list (struct net_device *dev)
{
struct znet_private *znet = netdev_priv(dev);
short ioaddr = dev->base_addr;
struct i82593_conf_block *cfblk = &znet->i593_init;
memset(cfblk, 0x00, sizeof(struct i82593_conf_block));
/* The configuration block. What an undocumented nightmare.
The first set of values are those suggested (without explanation)
for ethernet in the Intel 82586 databook. The rest appear to be
completely undocumented, except for cryptic notes in the Crynwr
packet driver. This driver uses the Crynwr values verbatim. */
/* maz : Rewritten to take advantage of the wanvelan includes.
At least we have names, not just blind values */
/* Byte 0 */
cfblk->fifo_limit = 10; /* = 16 B rx and 80 B tx fifo thresholds */
cfblk->forgnesi = 0; /* 0=82C501, 1=AMD7992B compatibility */
cfblk->fifo_32 = 1;
cfblk->d6mod = 0; /* Run in i82593 advanced mode */
cfblk->throttle_enb = 1;
/* Byte 1 */
cfblk->throttle = 8; /* Continuous w/interrupts, 128-clock DMA. */
cfblk->cntrxint = 0; /* enable continuous mode receive interrupts */
cfblk->contin = 1; /* enable continuous mode */
/* Byte 2 */
cfblk->addr_len = ETH_ALEN;
cfblk->acloc = 1; /* Disable source addr insertion by i82593 */
cfblk->preamb_len = 2; /* 8 bytes preamble */
cfblk->loopback = 0; /* Loopback off */
/* Byte 3 */
cfblk->lin_prio = 0; /* Default priorities & backoff methods. */
cfblk->tbofstop = 0;
cfblk->exp_prio = 0;
cfblk->bof_met = 0;
/* Byte 4 */
cfblk->ifrm_spc = 6; /* 96 bit times interframe spacing */
/* Byte 5 */
cfblk->slottim_low = 0; /* 512 bit times slot time (low) */
/* Byte 6 */
cfblk->slottim_hi = 2; /* 512 bit times slot time (high) */
cfblk->max_retr = 15; /* 15 collisions retries */
/* Byte 7 */
cfblk->prmisc = ((dev->flags & IFF_PROMISC) ? 1 : 0); /* Promiscuous mode */
cfblk->bc_dis = 0; /* Enable broadcast reception */
cfblk->crs_1 = 0; /* Don't transmit without carrier sense */
cfblk->nocrc_ins = 0; /* i82593 generates CRC */
cfblk->crc_1632 = 0; /* 32-bit Autodin-II CRC */
cfblk->crs_cdt = 0; /* CD not to be interpreted as CS */
/* Byte 8 */
cfblk->cs_filter = 0; /* CS is recognized immediately */
cfblk->crs_src = 0; /* External carrier sense */
cfblk->cd_filter = 0; /* CD is recognized immediately */
/* Byte 9 */
cfblk->min_fr_len = ETH_ZLEN >> 2; /* Minimum frame length */
/* Byte A */
cfblk->lng_typ = 1; /* Type/length checks OFF */
cfblk->lng_fld = 1; /* Disable 802.3 length field check */
cfblk->rxcrc_xf = 1; /* Don't transfer CRC to memory */
cfblk->artx = 1; /* Disable automatic retransmission */
cfblk->sarec = 1; /* Disable source addr trig of CD */
cfblk->tx_jabber = 0; /* Disable jabber jam sequence */
cfblk->hash_1 = 1; /* Use bits 0-5 in mc address hash */
cfblk->lbpkpol = 0; /* Loopback pin active high */
/* Byte B */
cfblk->fdx = 0; /* Disable full duplex operation */
/* Byte C */
cfblk->dummy_6 = 0x3f; /* all ones, Default multicast addresses & backoff. */
cfblk->mult_ia = 0; /* No multiple individual addresses */
cfblk->dis_bof = 0; /* Disable the backoff algorithm ?! */
/* Byte D */
cfblk->dummy_1 = 1; /* set to 1 */
cfblk->tx_ifs_retrig = 3; /* Hmm... Disabled */
cfblk->mc_all = (!netdev_mc_empty(dev) ||
(dev->flags & IFF_ALLMULTI)); /* multicast all mode */
cfblk->rcv_mon = 0; /* Monitor mode disabled */
cfblk->frag_acpt = 0; /* Do not accept fragments */
cfblk->tstrttrs = 0; /* No start transmission threshold */
/* Byte E */
cfblk->fretx = 1; /* FIFO automatic retransmission */
cfblk->runt_eop = 0; /* drop "runt" packets */
cfblk->hw_sw_pin = 0; /* ?? */
cfblk->big_endn = 0; /* Big Endian ? no... */
cfblk->syncrqs = 1; /* Synchronous DRQ deassertion... */
cfblk->sttlen = 1; /* 6 byte status registers */
cfblk->rx_eop = 0; /* Signal EOP on packet reception */
cfblk->tx_eop = 0; /* Signal EOP on packet transmission */
/* Byte F */
cfblk->rbuf_size = RX_BUF_SIZE >> 12; /* Set receive buffer size */
cfblk->rcvstop = 1; /* Enable Receive Stop Register */
if (znet_debug > 2) {
int i;
unsigned char *c;
for (i = 0, c = (char *) cfblk; i < sizeof (*cfblk); i++)
printk ("%02X ", c[i]);
printk ("\n");
}
*znet->tx_cur++ = sizeof(struct i82593_conf_block);
memcpy(znet->tx_cur, cfblk, sizeof(struct i82593_conf_block));
znet->tx_cur += sizeof(struct i82593_conf_block)/2;
outb(OP0_CONFIGURE | CR0_CHNL, ioaddr);
/* XXX FIXME maz : Add multicast addresses here, so having a
* multicast address configured isn't equal to IFF_ALLMULTI */
}
static const struct net_device_ops znet_netdev_ops = {
.ndo_open = znet_open,
.ndo_stop = znet_close,
.ndo_start_xmit = znet_send_packet,
.ndo_set_rx_mode = znet_set_multicast_list,
.ndo_tx_timeout = znet_tx_timeout,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/* The Z-Note probe is pretty easy. The NETIDBLK exists in the safe-to-probe
BIOS area. We just scan for the signature, and pull the vital parameters
out of the structure. */
static int __init znet_probe (void)
{
int i;
struct netidblk *netinfo;
struct znet_private *znet;
struct net_device *dev;
char *p;
int err = -ENOMEM;
/* This code scans the region 0xf0000 to 0xfffff for a "NETIDBLK". */
for(p = (char *)phys_to_virt(0xf0000); p < (char *)phys_to_virt(0x100000); p++)
if (*p == 'N' && strncmp(p, "NETIDBLK", 8) == 0)
break;
if (p >= (char *)phys_to_virt(0x100000)) {
if (znet_debug > 1)
printk(KERN_INFO "No Z-Note ethernet adaptor found.\n");
return -ENODEV;
}
dev = alloc_etherdev(sizeof(struct znet_private));
if (!dev)
return -ENOMEM;
znet = netdev_priv(dev);
netinfo = (struct netidblk *)p;
dev->base_addr = netinfo->iobase1;
dev->irq = netinfo->irq1;
/* The station address is in the "netidblk" at 0x0f0000. */
for (i = 0; i < 6; i++)
dev->dev_addr[i] = netinfo->netid[i];
printk(KERN_INFO "%s: ZNET at %#3lx, %pM"
", using IRQ %d DMA %d and %d.\n",
dev->name, dev->base_addr, dev->dev_addr,
dev->irq, netinfo->dma1, netinfo->dma2);
if (znet_debug > 1) {
printk(KERN_INFO "%s: vendor '%16.16s' IRQ1 %d IRQ2 %d DMA1 %d DMA2 %d.\n",
dev->name, netinfo->vendor,
netinfo->irq1, netinfo->irq2,
netinfo->dma1, netinfo->dma2);
printk(KERN_INFO "%s: iobase1 %#x size %d iobase2 %#x size %d net type %2.2x.\n",
dev->name, netinfo->iobase1, netinfo->iosize1,
netinfo->iobase2, netinfo->iosize2, netinfo->nettype);
}
if (znet_debug > 0)
printk(KERN_INFO "%s", version);
znet->rx_dma = netinfo->dma1;
znet->tx_dma = netinfo->dma2;
spin_lock_init(&znet->lock);
znet->sia_base = 0xe6; /* Magic address for the 82501 SIA */
znet->sia_size = 2;
/* maz: Despite the '593 being advertised above as using a
* single 8bits I/O port, this driver does many 16bits
* access. So set io_size accordingly */
znet->io_size = 2;
if (!(znet->rx_start = kmalloc (DMA_BUF_SIZE, GFP_KERNEL | GFP_DMA)))
goto free_dev;
if (!(znet->tx_start = kmalloc (DMA_BUF_SIZE, GFP_KERNEL | GFP_DMA)))
goto free_rx;
if (!dma_page_eq (znet->rx_start, znet->rx_start + (RX_BUF_SIZE/2-1)) ||
!dma_page_eq (znet->tx_start, znet->tx_start + (TX_BUF_SIZE/2-1))) {
printk (KERN_WARNING "tx/rx crossing DMA frontiers, giving up\n");
goto free_tx;
}
znet->rx_end = znet->rx_start + RX_BUF_SIZE/2;
znet->tx_buf_len = TX_BUF_SIZE/2;
znet->tx_end = znet->tx_start + znet->tx_buf_len;
/* The ZNET-specific entries in the device structure. */
dev->netdev_ops = &znet_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
err = register_netdev(dev);
if (err)
goto free_tx;
znet_dev = dev;
return 0;
free_tx:
kfree(znet->tx_start);
free_rx:
kfree(znet->rx_start);
free_dev:
free_netdev(dev);
return err;
}
static int znet_open(struct net_device *dev)
{
int ioaddr = dev->base_addr;
if (znet_debug > 2)
printk(KERN_DEBUG "%s: znet_open() called.\n", dev->name);
/* These should never fail. You can't add devices to a sealed box! */
if (znet_request_resources (dev)) {
printk(KERN_WARNING "%s: Not opened -- resource busy?!?\n", dev->name);
return -EBUSY;
}
znet_transceiver_power (dev, 1);
/* According to the Crynwr driver we should wait 50 msec. for the
LAN clock to stabilize. My experiments indicates that the '593 can
be initialized immediately. The delay is probably needed for the
DC-to-DC converter to come up to full voltage, and for the oscillator
to be spot-on at 20Mhz before transmitting.
Until this proves to be a problem we rely on the higher layers for the
delay and save allocating a timer entry. */
/* maz : Well, I'm getting every time the following message
* without the delay on a 486@33. This machine is much too
* fast... :-) So maybe the Crynwr driver wasn't wrong after
* all, even if the message is completly harmless on my
* setup. */
mdelay (50);
/* This follows the packet driver's lead, and checks for success. */
if (inb(ioaddr) != 0x10 && inb(ioaddr) != 0x00)
printk(KERN_WARNING "%s: Problem turning on the transceiver power.\n",
dev->name);
hardware_init(dev);
netif_start_queue (dev);
return 0;
}
static void znet_tx_timeout (struct net_device *dev)
{
int ioaddr = dev->base_addr;
ushort event, tx_status, rx_offset, state;
outb (CR0_STATUS_0, ioaddr);
event = inb (ioaddr);
outb (CR0_STATUS_1, ioaddr);
tx_status = inw (ioaddr);
outb (CR0_STATUS_2, ioaddr);
rx_offset = inw (ioaddr);
outb (CR0_STATUS_3, ioaddr);
state = inb (ioaddr);
printk (KERN_WARNING "%s: transmit timed out, status %02x %04x %04x %02x,"
" resetting.\n", dev->name, event, tx_status, rx_offset, state);
if (tx_status == TX_LOST_CRS)
printk (KERN_WARNING "%s: Tx carrier error, check transceiver cable.\n",
dev->name);
outb (OP0_RESET, ioaddr);
hardware_init (dev);
netif_wake_queue (dev);
}
static netdev_tx_t znet_send_packet(struct sk_buff *skb, struct net_device *dev)
{
int ioaddr = dev->base_addr;
struct znet_private *znet = netdev_priv(dev);
unsigned long flags;
short length = skb->len;
if (znet_debug > 4)
printk(KERN_DEBUG "%s: ZNet_send_packet.\n", dev->name);
if (length < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
length = ETH_ZLEN;
}
netif_stop_queue (dev);
/* Check that the part hasn't reset itself, probably from suspend. */
outb(CR0_STATUS_0, ioaddr);
if (inw(ioaddr) == 0x0010 &&
inw(ioaddr) == 0x0000 &&
inw(ioaddr) == 0x0010) {
if (znet_debug > 1)
printk (KERN_WARNING "%s : waking up\n", dev->name);
hardware_init(dev);
znet_transceiver_power (dev, 1);
}
if (1) {
unsigned char *buf = (void *)skb->data;
ushort *tx_link = znet->tx_cur - 1;
ushort rnd_len = (length + 1)>>1;
dev->stats.tx_bytes+=length;
if (znet->tx_cur >= znet->tx_end)
znet->tx_cur = znet->tx_start;
*znet->tx_cur++ = length;
if (znet->tx_cur + rnd_len + 1 > znet->tx_end) {
int semi_cnt = (znet->tx_end - znet->tx_cur)<<1; /* Cvrt to byte cnt. */
memcpy(znet->tx_cur, buf, semi_cnt);
rnd_len -= semi_cnt>>1;
memcpy(znet->tx_start, buf + semi_cnt, length - semi_cnt);
znet->tx_cur = znet->tx_start + rnd_len;
} else {
memcpy(znet->tx_cur, buf, skb->len);
znet->tx_cur += rnd_len;
}
*znet->tx_cur++ = 0;
spin_lock_irqsave(&znet->lock, flags);
{
*tx_link = OP0_TRANSMIT | CR0_CHNL;
/* Is this always safe to do? */
outb(OP0_TRANSMIT | CR0_CHNL, ioaddr);
}
spin_unlock_irqrestore (&znet->lock, flags);
netif_start_queue (dev);
if (znet_debug > 4)
printk(KERN_DEBUG "%s: Transmitter queued, length %d.\n", dev->name, length);
}
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* The ZNET interrupt handler. */
static irqreturn_t znet_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct znet_private *znet = netdev_priv(dev);
int ioaddr;
int boguscnt = 20;
int handled = 0;
spin_lock (&znet->lock);
ioaddr = dev->base_addr;
outb(CR0_STATUS_0, ioaddr);
do {
ushort status = inb(ioaddr);
if (znet_debug > 5) {
ushort result, rx_ptr, running;
outb(CR0_STATUS_1, ioaddr);
result = inw(ioaddr);
outb(CR0_STATUS_2, ioaddr);
rx_ptr = inw(ioaddr);
outb(CR0_STATUS_3, ioaddr);
running = inb(ioaddr);
printk(KERN_DEBUG "%s: interrupt, status %02x, %04x %04x %02x serial %d.\n",
dev->name, status, result, rx_ptr, running, boguscnt);
}
if ((status & SR0_INTERRUPT) == 0)
break;
handled = 1;
if ((status & SR0_EVENT_MASK) == SR0_TRANSMIT_DONE ||
(status & SR0_EVENT_MASK) == SR0_RETRANSMIT_DONE ||
(status & SR0_EVENT_MASK) == SR0_TRANSMIT_NO_CRC_DONE) {
int tx_status;
outb(CR0_STATUS_1, ioaddr);
tx_status = inw(ioaddr);
/* It's undocumented, but tx_status seems to match the i82586. */
if (tx_status & TX_OK) {
dev->stats.tx_packets++;
dev->stats.collisions += tx_status & TX_NCOL_MASK;
} else {
if (tx_status & (TX_LOST_CTS | TX_LOST_CRS))
dev->stats.tx_carrier_errors++;
if (tx_status & TX_UND_RUN)
dev->stats.tx_fifo_errors++;
if (!(tx_status & TX_HRT_BEAT))
dev->stats.tx_heartbeat_errors++;
if (tx_status & TX_MAX_COL)
dev->stats.tx_aborted_errors++;
/* ...and the catch-all. */
if ((tx_status | (TX_LOST_CRS | TX_LOST_CTS | TX_UND_RUN | TX_HRT_BEAT | TX_MAX_COL)) != (TX_LOST_CRS | TX_LOST_CTS | TX_UND_RUN | TX_HRT_BEAT | TX_MAX_COL))
dev->stats.tx_errors++;
/* Transceiver may be stuck if cable
* was removed while emitting a
* packet. Flip it off, then on to
* reset it. This is very empirical,
* but it seems to work. */
znet_transceiver_power (dev, 0);
znet_transceiver_power (dev, 1);
}
netif_wake_queue (dev);
}
if ((status & SR0_RECEPTION) ||
(status & SR0_EVENT_MASK) == SR0_STOP_REG_HIT) {
znet_rx(dev);
}
/* Clear the interrupts we've handled. */
outb(CR0_INT_ACK, ioaddr);
} while (boguscnt--);
spin_unlock (&znet->lock);
return IRQ_RETVAL(handled);
}
static void znet_rx(struct net_device *dev)
{
struct znet_private *znet = netdev_priv(dev);
int ioaddr = dev->base_addr;
int boguscount = 1;
short next_frame_end_offset = 0; /* Offset of next frame start. */
short *cur_frame_end;
short cur_frame_end_offset;
outb(CR0_STATUS_2, ioaddr);
cur_frame_end_offset = inw(ioaddr);
if (cur_frame_end_offset == znet->rx_cur - znet->rx_start) {
printk(KERN_WARNING "%s: Interrupted, but nothing to receive, offset %03x.\n",
dev->name, cur_frame_end_offset);
return;
}
/* Use same method as the Crynwr driver: construct a forward list in
the same area of the backwards links we now have. This allows us to
pass packets to the upper layers in the order they were received --
important for fast-path sequential operations. */
while (znet->rx_start + cur_frame_end_offset != znet->rx_cur &&
++boguscount < 5) {
unsigned short hi_cnt, lo_cnt, hi_status, lo_status;
int count, status;
if (cur_frame_end_offset < 4) {
/* Oh no, we have a special case: the frame trailer wraps around
the end of the ring buffer. We've saved space at the end of
the ring buffer for just this problem. */
memcpy(znet->rx_end, znet->rx_start, 8);
cur_frame_end_offset += (RX_BUF_SIZE/2);
}
cur_frame_end = znet->rx_start + cur_frame_end_offset - 4;
lo_status = *cur_frame_end++;
hi_status = *cur_frame_end++;
status = ((hi_status & 0xff) << 8) + (lo_status & 0xff);
lo_cnt = *cur_frame_end++;
hi_cnt = *cur_frame_end++;
count = ((hi_cnt & 0xff) << 8) + (lo_cnt & 0xff);
if (znet_debug > 5)
printk(KERN_DEBUG "Constructing trailer at location %03x, %04x %04x %04x %04x"
" count %#x status %04x.\n",
cur_frame_end_offset<<1, lo_status, hi_status, lo_cnt, hi_cnt,
count, status);
cur_frame_end[-4] = status;
cur_frame_end[-3] = next_frame_end_offset;
cur_frame_end[-2] = count;
next_frame_end_offset = cur_frame_end_offset;
cur_frame_end_offset -= ((count + 1)>>1) + 3;
if (cur_frame_end_offset < 0)
cur_frame_end_offset += RX_BUF_SIZE/2;
}
/* Now step forward through the list. */
do {
ushort *this_rfp_ptr = znet->rx_start + next_frame_end_offset;
int status = this_rfp_ptr[-4];
int pkt_len = this_rfp_ptr[-2];
if (znet_debug > 5)
printk(KERN_DEBUG "Looking at trailer ending at %04x status %04x length %03x"
" next %04x.\n", next_frame_end_offset<<1, status, pkt_len,
this_rfp_ptr[-3]<<1);
/* Once again we must assume that the i82586 docs apply. */
if ( ! (status & RX_RCV_OK)) { /* There was an error. */
dev->stats.rx_errors++;
if (status & RX_CRC_ERR) dev->stats.rx_crc_errors++;
if (status & RX_ALG_ERR) dev->stats.rx_frame_errors++;
#if 0
if (status & 0x0200) dev->stats.rx_over_errors++; /* Wrong. */
if (status & 0x0100) dev->stats.rx_fifo_errors++;
#else
/* maz : Wild guess... */
if (status & RX_OVRRUN) dev->stats.rx_over_errors++;
#endif
if (status & RX_SRT_FRM) dev->stats.rx_length_errors++;
} else if (pkt_len > 1536) {
dev->stats.rx_length_errors++;
} else {
/* Malloc up new buffer. */
struct sk_buff *skb;
skb = netdev_alloc_skb(dev, pkt_len);
if (skb == NULL) {
if (znet_debug)
printk(KERN_WARNING "%s: Memory squeeze, dropping packet.\n", dev->name);
dev->stats.rx_dropped++;
break;
}
if (&znet->rx_cur[(pkt_len+1)>>1] > znet->rx_end) {
int semi_cnt = (znet->rx_end - znet->rx_cur)<<1;
memcpy(skb_put(skb,semi_cnt), znet->rx_cur, semi_cnt);
memcpy(skb_put(skb,pkt_len-semi_cnt), znet->rx_start,
pkt_len - semi_cnt);
} else {
memcpy(skb_put(skb,pkt_len), znet->rx_cur, pkt_len);
if (znet_debug > 6) {
unsigned int *packet = (unsigned int *) skb->data;
printk(KERN_DEBUG "Packet data is %08x %08x %08x %08x.\n", packet[0],
packet[1], packet[2], packet[3]);
}
}
skb->protocol=eth_type_trans(skb,dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
znet->rx_cur = this_rfp_ptr;
if (znet->rx_cur >= znet->rx_end)
znet->rx_cur -= RX_BUF_SIZE/2;
update_stop_hit(ioaddr, (znet->rx_cur - znet->rx_start)<<1);
next_frame_end_offset = this_rfp_ptr[-3];
if (next_frame_end_offset == 0) /* Read all the frames? */
break; /* Done for now */
this_rfp_ptr = znet->rx_start + next_frame_end_offset;
} while (--boguscount);
/* If any worth-while packets have been received, dev_rint()
has done a mark_bh(INET_BH) for us and will work on them
when we get to the bottom-half routine. */
}
/* The inverse routine to znet_open(). */
static int znet_close(struct net_device *dev)
{
int ioaddr = dev->base_addr;
netif_stop_queue (dev);
outb(OP0_RESET, ioaddr); /* CMD0_RESET */
if (znet_debug > 1)
printk(KERN_DEBUG "%s: Shutting down ethercard.\n", dev->name);
/* Turn off transceiver power. */
znet_transceiver_power (dev, 0);
znet_release_resources (dev);
return 0;
}
static void show_dma(struct net_device *dev)
{
short ioaddr = dev->base_addr;
unsigned char stat = inb (ioaddr);
struct znet_private *znet = netdev_priv(dev);
unsigned long flags;
short dma_port = ((znet->tx_dma&3)<<2) + IO_DMA2_BASE;
unsigned addr = inb(dma_port);
short residue;
addr |= inb(dma_port) << 8;
residue = get_dma_residue(znet->tx_dma);
if (znet_debug > 1) {
flags=claim_dma_lock();
printk(KERN_DEBUG "Stat:%02x Addr: %04x cnt:%3x\n",
stat, addr<<1, residue);
release_dma_lock(flags);
}
}
/* Initialize the hardware. We have to do this when the board is open()ed
or when we come out of suspend mode. */
static void hardware_init(struct net_device *dev)
{
unsigned long flags;
short ioaddr = dev->base_addr;
struct znet_private *znet = netdev_priv(dev);
znet->rx_cur = znet->rx_start;
znet->tx_cur = znet->tx_start;
/* Reset the chip, and start it up. */
outb(OP0_RESET, ioaddr);
flags=claim_dma_lock();
disable_dma(znet->rx_dma); /* reset by an interrupting task. */
clear_dma_ff(znet->rx_dma);
set_dma_mode(znet->rx_dma, DMA_RX_MODE);
set_dma_addr(znet->rx_dma, (unsigned int) znet->rx_start);
set_dma_count(znet->rx_dma, RX_BUF_SIZE);
enable_dma(znet->rx_dma);
/* Now set up the Tx channel. */
disable_dma(znet->tx_dma);
clear_dma_ff(znet->tx_dma);
set_dma_mode(znet->tx_dma, DMA_TX_MODE);
set_dma_addr(znet->tx_dma, (unsigned int) znet->tx_start);
set_dma_count(znet->tx_dma, znet->tx_buf_len<<1);
enable_dma(znet->tx_dma);
release_dma_lock(flags);
if (znet_debug > 1)
printk(KERN_DEBUG "%s: Initializing the i82593, rx buf %p tx buf %p\n",
dev->name, znet->rx_start,znet->tx_start);
/* Do an empty configure command, just like the Crynwr driver. This
resets to chip to its default values. */
*znet->tx_cur++ = 0;
*znet->tx_cur++ = 0;
show_dma(dev);
outb(OP0_CONFIGURE | CR0_CHNL, ioaddr);
znet_set_multicast_list (dev);
*znet->tx_cur++ = 6;
memcpy(znet->tx_cur, dev->dev_addr, 6);
znet->tx_cur += 3;
show_dma(dev);
outb(OP0_IA_SETUP | CR0_CHNL, ioaddr);
show_dma(dev);
update_stop_hit(ioaddr, 8192);
if (znet_debug > 1) printk(KERN_DEBUG "enabling Rx.\n");
outb(OP0_RCV_ENABLE, ioaddr);
netif_start_queue (dev);
}
static void update_stop_hit(short ioaddr, unsigned short rx_stop_offset)
{
outb(OP0_SWIT_TO_PORT_1 | CR0_CHNL, ioaddr);
if (znet_debug > 5)
printk(KERN_DEBUG "Updating stop hit with value %02x.\n",
(rx_stop_offset >> 6) | CR1_STOP_REG_UPDATE);
outb((rx_stop_offset >> 6) | CR1_STOP_REG_UPDATE, ioaddr);
outb(OP1_SWIT_TO_PORT_0, ioaddr);
}
static __exit void znet_cleanup (void)
{
if (znet_dev) {
struct znet_private *znet = netdev_priv(znet_dev);
unregister_netdev (znet_dev);
kfree (znet->rx_start);
kfree (znet->tx_start);
free_netdev (znet_dev);
}
}
module_init (znet_probe);
module_exit (znet_cleanup);
| gpl-2.0 |
aicjofs/android_kernel_lge_v500_20d | drivers/i2c/busses/i2c-ocores.c | 4887 | 9870 | /*
* i2c-ocores.c: I2C bus driver for OpenCores I2C controller
* (http://www.opencores.org/projects.cgi/web/i2c/overview).
*
* Peter Korsgaard <jacmet@sunsite.dk>
*
* 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.
*/
/*
* Device tree configuration:
*
* Required properties:
* - compatible : "opencores,i2c-ocores"
* - reg : bus address start and address range size of device
* - interrupts : interrupt number
* - regstep : size of device registers in bytes
* - clock-frequency : frequency of bus clock in Hz
*
* Example:
*
* i2c0: ocores@a0000000 {
* compatible = "opencores,i2c-ocores";
* reg = <0xa0000000 0x8>;
* interrupts = <10>;
*
* regstep = <1>;
* clock-frequency = <20000000>;
*
* -- Devices connected on this I2C bus get
* -- defined here; address- and size-cells
* -- apply to these child devices
*
* #address-cells = <1>;
* #size-cells = <0>;
*
* dummy@60 {
* compatible = "dummy";
* reg = <60>;
* };
* };
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/wait.h>
#include <linux/i2c-ocores.h>
#include <linux/slab.h>
#include <linux/io.h>
struct ocores_i2c {
void __iomem *base;
int regstep;
wait_queue_head_t wait;
struct i2c_adapter adap;
struct i2c_msg *msg;
int pos;
int nmsgs;
int state; /* see STATE_ */
int clock_khz;
};
/* registers */
#define OCI2C_PRELOW 0
#define OCI2C_PREHIGH 1
#define OCI2C_CONTROL 2
#define OCI2C_DATA 3
#define OCI2C_CMD 4 /* write only */
#define OCI2C_STATUS 4 /* read only, same address as OCI2C_CMD */
#define OCI2C_CTRL_IEN 0x40
#define OCI2C_CTRL_EN 0x80
#define OCI2C_CMD_START 0x91
#define OCI2C_CMD_STOP 0x41
#define OCI2C_CMD_READ 0x21
#define OCI2C_CMD_WRITE 0x11
#define OCI2C_CMD_READ_ACK 0x21
#define OCI2C_CMD_READ_NACK 0x29
#define OCI2C_CMD_IACK 0x01
#define OCI2C_STAT_IF 0x01
#define OCI2C_STAT_TIP 0x02
#define OCI2C_STAT_ARBLOST 0x20
#define OCI2C_STAT_BUSY 0x40
#define OCI2C_STAT_NACK 0x80
#define STATE_DONE 0
#define STATE_START 1
#define STATE_WRITE 2
#define STATE_READ 3
#define STATE_ERROR 4
static inline void oc_setreg(struct ocores_i2c *i2c, int reg, u8 value)
{
iowrite8(value, i2c->base + reg * i2c->regstep);
}
static inline u8 oc_getreg(struct ocores_i2c *i2c, int reg)
{
return ioread8(i2c->base + reg * i2c->regstep);
}
static void ocores_process(struct ocores_i2c *i2c)
{
struct i2c_msg *msg = i2c->msg;
u8 stat = oc_getreg(i2c, OCI2C_STATUS);
if ((i2c->state == STATE_DONE) || (i2c->state == STATE_ERROR)) {
/* stop has been sent */
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_IACK);
wake_up(&i2c->wait);
return;
}
/* error? */
if (stat & OCI2C_STAT_ARBLOST) {
i2c->state = STATE_ERROR;
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_STOP);
return;
}
if ((i2c->state == STATE_START) || (i2c->state == STATE_WRITE)) {
i2c->state =
(msg->flags & I2C_M_RD) ? STATE_READ : STATE_WRITE;
if (stat & OCI2C_STAT_NACK) {
i2c->state = STATE_ERROR;
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_STOP);
return;
}
} else
msg->buf[i2c->pos++] = oc_getreg(i2c, OCI2C_DATA);
/* end of msg? */
if (i2c->pos == msg->len) {
i2c->nmsgs--;
i2c->msg++;
i2c->pos = 0;
msg = i2c->msg;
if (i2c->nmsgs) { /* end? */
/* send start? */
if (!(msg->flags & I2C_M_NOSTART)) {
u8 addr = (msg->addr << 1);
if (msg->flags & I2C_M_RD)
addr |= 1;
i2c->state = STATE_START;
oc_setreg(i2c, OCI2C_DATA, addr);
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_START);
return;
} else
i2c->state = (msg->flags & I2C_M_RD)
? STATE_READ : STATE_WRITE;
} else {
i2c->state = STATE_DONE;
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_STOP);
return;
}
}
if (i2c->state == STATE_READ) {
oc_setreg(i2c, OCI2C_CMD, i2c->pos == (msg->len-1) ?
OCI2C_CMD_READ_NACK : OCI2C_CMD_READ_ACK);
} else {
oc_setreg(i2c, OCI2C_DATA, msg->buf[i2c->pos++]);
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_WRITE);
}
}
static irqreturn_t ocores_isr(int irq, void *dev_id)
{
struct ocores_i2c *i2c = dev_id;
ocores_process(i2c);
return IRQ_HANDLED;
}
static int ocores_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
{
struct ocores_i2c *i2c = i2c_get_adapdata(adap);
i2c->msg = msgs;
i2c->pos = 0;
i2c->nmsgs = num;
i2c->state = STATE_START;
oc_setreg(i2c, OCI2C_DATA,
(i2c->msg->addr << 1) |
((i2c->msg->flags & I2C_M_RD) ? 1:0));
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_START);
if (wait_event_timeout(i2c->wait, (i2c->state == STATE_ERROR) ||
(i2c->state == STATE_DONE), HZ))
return (i2c->state == STATE_DONE) ? num : -EIO;
else
return -ETIMEDOUT;
}
static void ocores_init(struct ocores_i2c *i2c)
{
int prescale;
u8 ctrl = oc_getreg(i2c, OCI2C_CONTROL);
/* make sure the device is disabled */
oc_setreg(i2c, OCI2C_CONTROL, ctrl & ~(OCI2C_CTRL_EN|OCI2C_CTRL_IEN));
prescale = (i2c->clock_khz / (5*100)) - 1;
oc_setreg(i2c, OCI2C_PRELOW, prescale & 0xff);
oc_setreg(i2c, OCI2C_PREHIGH, prescale >> 8);
/* Init the device */
oc_setreg(i2c, OCI2C_CMD, OCI2C_CMD_IACK);
oc_setreg(i2c, OCI2C_CONTROL, ctrl | OCI2C_CTRL_IEN | OCI2C_CTRL_EN);
}
static u32 ocores_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm ocores_algorithm = {
.master_xfer = ocores_xfer,
.functionality = ocores_func,
};
static struct i2c_adapter ocores_adapter = {
.owner = THIS_MODULE,
.name = "i2c-ocores",
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &ocores_algorithm,
};
#ifdef CONFIG_OF
static int ocores_i2c_of_probe(struct platform_device* pdev,
struct ocores_i2c* i2c)
{
const __be32* val;
val = of_get_property(pdev->dev.of_node, "regstep", NULL);
if (!val) {
dev_err(&pdev->dev, "Missing required parameter 'regstep'");
return -ENODEV;
}
i2c->regstep = be32_to_cpup(val);
val = of_get_property(pdev->dev.of_node, "clock-frequency", NULL);
if (!val) {
dev_err(&pdev->dev,
"Missing required parameter 'clock-frequency'");
return -ENODEV;
}
i2c->clock_khz = be32_to_cpup(val) / 1000;
return 0;
}
#else
#define ocores_i2c_of_probe(pdev,i2c) -ENODEV
#endif
static int __devinit ocores_i2c_probe(struct platform_device *pdev)
{
struct ocores_i2c *i2c;
struct ocores_i2c_platform_data *pdata;
struct resource *res, *res2;
int ret;
int i;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
res2 = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res2)
return -ENODEV;
i2c = devm_kzalloc(&pdev->dev, sizeof(*i2c), GFP_KERNEL);
if (!i2c)
return -ENOMEM;
if (!devm_request_mem_region(&pdev->dev, res->start,
resource_size(res), pdev->name)) {
dev_err(&pdev->dev, "Memory region busy\n");
return -EBUSY;
}
i2c->base = devm_ioremap_nocache(&pdev->dev, res->start,
resource_size(res));
if (!i2c->base) {
dev_err(&pdev->dev, "Unable to map registers\n");
return -EIO;
}
pdata = pdev->dev.platform_data;
if (pdata) {
i2c->regstep = pdata->regstep;
i2c->clock_khz = pdata->clock_khz;
} else {
ret = ocores_i2c_of_probe(pdev, i2c);
if (ret)
return ret;
}
ocores_init(i2c);
init_waitqueue_head(&i2c->wait);
ret = devm_request_irq(&pdev->dev, res2->start, ocores_isr, 0,
pdev->name, i2c);
if (ret) {
dev_err(&pdev->dev, "Cannot claim IRQ\n");
return ret;
}
/* hook up driver to tree */
platform_set_drvdata(pdev, i2c);
i2c->adap = ocores_adapter;
i2c_set_adapdata(&i2c->adap, i2c);
i2c->adap.dev.parent = &pdev->dev;
i2c->adap.dev.of_node = pdev->dev.of_node;
/* add i2c adapter to i2c tree */
ret = i2c_add_adapter(&i2c->adap);
if (ret) {
dev_err(&pdev->dev, "Failed to add adapter\n");
return ret;
}
/* add in known devices to the bus */
if (pdata) {
for (i = 0; i < pdata->num_devices; i++)
i2c_new_device(&i2c->adap, pdata->devices + i);
}
return 0;
}
static int __devexit ocores_i2c_remove(struct platform_device* pdev)
{
struct ocores_i2c *i2c = platform_get_drvdata(pdev);
/* disable i2c logic */
oc_setreg(i2c, OCI2C_CONTROL, oc_getreg(i2c, OCI2C_CONTROL)
& ~(OCI2C_CTRL_EN|OCI2C_CTRL_IEN));
/* remove adapter & data */
i2c_del_adapter(&i2c->adap);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int ocores_i2c_suspend(struct platform_device *pdev, pm_message_t state)
{
struct ocores_i2c *i2c = platform_get_drvdata(pdev);
u8 ctrl = oc_getreg(i2c, OCI2C_CONTROL);
/* make sure the device is disabled */
oc_setreg(i2c, OCI2C_CONTROL, ctrl & ~(OCI2C_CTRL_EN|OCI2C_CTRL_IEN));
return 0;
}
static int ocores_i2c_resume(struct platform_device *pdev)
{
struct ocores_i2c *i2c = platform_get_drvdata(pdev);
ocores_init(i2c);
return 0;
}
#else
#define ocores_i2c_suspend NULL
#define ocores_i2c_resume NULL
#endif
static struct of_device_id ocores_i2c_match[] = {
{ .compatible = "opencores,i2c-ocores", },
{},
};
MODULE_DEVICE_TABLE(of, ocores_i2c_match);
static struct platform_driver ocores_i2c_driver = {
.probe = ocores_i2c_probe,
.remove = __devexit_p(ocores_i2c_remove),
.suspend = ocores_i2c_suspend,
.resume = ocores_i2c_resume,
.driver = {
.owner = THIS_MODULE,
.name = "ocores-i2c",
.of_match_table = ocores_i2c_match,
},
};
module_platform_driver(ocores_i2c_driver);
MODULE_AUTHOR("Peter Korsgaard <jacmet@sunsite.dk>");
MODULE_DESCRIPTION("OpenCores I2C bus driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:ocores-i2c");
| gpl-2.0 |
manishj-patel/netbook_kernel_3.4.5_plus | drivers/acpi/blacklist.c | 5399 | 9103 | /*
* blacklist.c
*
* Check to see if the given machine has a known bad ACPI BIOS
* or if the BIOS is too old.
* Check given machine against acpi_osi_dmi_table[].
*
* Copyright (C) 2004 Len Brown <len.brown@intel.com>
* Copyright (C) 2002 Andy Grover <andrew.grover@intel.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/kernel.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <acpi/acpi_bus.h>
#include <linux/dmi.h>
#include "internal.h"
enum acpi_blacklist_predicates {
all_versions,
less_than_or_equal,
equal,
greater_than_or_equal,
};
struct acpi_blacklist_item {
char oem_id[7];
char oem_table_id[9];
u32 oem_revision;
char *table;
enum acpi_blacklist_predicates oem_revision_predicate;
char *reason;
u32 is_critical_error;
};
static struct dmi_system_id acpi_osi_dmi_table[] __initdata;
/*
* POLICY: If *anything* doesn't work, put it on the blacklist.
* If they are critical errors, mark it critical, and abort driver load.
*/
static struct acpi_blacklist_item acpi_blacklist[] __initdata = {
/* Compaq Presario 1700 */
{"PTLTD ", " DSDT ", 0x06040000, ACPI_SIG_DSDT, less_than_or_equal,
"Multiple problems", 1},
/* Sony FX120, FX140, FX150? */
{"SONY ", "U0 ", 0x20010313, ACPI_SIG_DSDT, less_than_or_equal,
"ACPI driver problem", 1},
/* Compaq Presario 800, Insyde BIOS */
{"INT440", "SYSFexxx", 0x00001001, ACPI_SIG_DSDT, less_than_or_equal,
"Does not use _REG to protect EC OpRegions", 1},
/* IBM 600E - _ADR should return 7, but it returns 1 */
{"IBM ", "TP600E ", 0x00000105, ACPI_SIG_DSDT, less_than_or_equal,
"Incorrect _ADR", 1},
{""}
};
#if CONFIG_ACPI_BLACKLIST_YEAR
static int __init blacklist_by_year(void)
{
int year;
/* Doesn't exist? Likely an old system */
if (!dmi_get_date(DMI_BIOS_DATE, &year, NULL, NULL)) {
printk(KERN_ERR PREFIX "no DMI BIOS year, "
"acpi=force is required to enable ACPI\n" );
return 1;
}
/* 0? Likely a buggy new BIOS */
if (year == 0) {
printk(KERN_ERR PREFIX "DMI BIOS year==0, "
"assuming ACPI-capable machine\n" );
return 0;
}
if (year < CONFIG_ACPI_BLACKLIST_YEAR) {
printk(KERN_ERR PREFIX "BIOS age (%d) fails cutoff (%d), "
"acpi=force is required to enable ACPI\n",
year, CONFIG_ACPI_BLACKLIST_YEAR);
return 1;
}
return 0;
}
#else
static inline int blacklist_by_year(void)
{
return 0;
}
#endif
int __init acpi_blacklisted(void)
{
int i = 0;
int blacklisted = 0;
struct acpi_table_header table_header;
while (acpi_blacklist[i].oem_id[0] != '\0') {
if (acpi_get_table_header(acpi_blacklist[i].table, 0, &table_header)) {
i++;
continue;
}
if (strncmp(acpi_blacklist[i].oem_id, table_header.oem_id, 6)) {
i++;
continue;
}
if (strncmp
(acpi_blacklist[i].oem_table_id, table_header.oem_table_id,
8)) {
i++;
continue;
}
if ((acpi_blacklist[i].oem_revision_predicate == all_versions)
|| (acpi_blacklist[i].oem_revision_predicate ==
less_than_or_equal
&& table_header.oem_revision <=
acpi_blacklist[i].oem_revision)
|| (acpi_blacklist[i].oem_revision_predicate ==
greater_than_or_equal
&& table_header.oem_revision >=
acpi_blacklist[i].oem_revision)
|| (acpi_blacklist[i].oem_revision_predicate == equal
&& table_header.oem_revision ==
acpi_blacklist[i].oem_revision)) {
printk(KERN_ERR PREFIX
"Vendor \"%6.6s\" System \"%8.8s\" "
"Revision 0x%x has a known ACPI BIOS problem.\n",
acpi_blacklist[i].oem_id,
acpi_blacklist[i].oem_table_id,
acpi_blacklist[i].oem_revision);
printk(KERN_ERR PREFIX
"Reason: %s. This is a %s error\n",
acpi_blacklist[i].reason,
(acpi_blacklist[i].
is_critical_error ? "non-recoverable" :
"recoverable"));
blacklisted = acpi_blacklist[i].is_critical_error;
break;
} else {
i++;
}
}
blacklisted += blacklist_by_year();
dmi_check_system(acpi_osi_dmi_table);
return blacklisted;
}
#ifdef CONFIG_DMI
static int __init dmi_enable_osi_linux(const struct dmi_system_id *d)
{
acpi_dmi_osi_linux(1, d); /* enable */
return 0;
}
static int __init dmi_disable_osi_vista(const struct dmi_system_id *d)
{
printk(KERN_NOTICE PREFIX "DMI detected: %s\n", d->ident);
acpi_osi_setup("!Windows 2006");
acpi_osi_setup("!Windows 2006 SP1");
acpi_osi_setup("!Windows 2006 SP2");
return 0;
}
static int __init dmi_disable_osi_win7(const struct dmi_system_id *d)
{
printk(KERN_NOTICE PREFIX "DMI detected: %s\n", d->ident);
acpi_osi_setup("!Windows 2009");
return 0;
}
static struct dmi_system_id acpi_osi_dmi_table[] __initdata = {
{
.callback = dmi_disable_osi_vista,
.ident = "Fujitsu Siemens",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "ESPRIMO Mobile V5505"),
},
},
{
/*
* There have a NVIF method in MSI GX723 DSDT need call by Nvidia
* driver (e.g. nouveau) when user press brightness hotkey.
* Currently, nouveau driver didn't do the job and it causes there
* have a infinite while loop in DSDT when user press hotkey.
* We add MSI GX723's dmi information to this table for workaround
* this issue.
* Will remove MSI GX723 from the table after nouveau grows support.
*/
.callback = dmi_disable_osi_vista,
.ident = "MSI GX723",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "GX723"),
},
},
{
.callback = dmi_disable_osi_vista,
.ident = "Sony VGN-NS10J_S",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-NS10J_S"),
},
},
{
.callback = dmi_disable_osi_vista,
.ident = "Sony VGN-SR290J",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR290J"),
},
},
{
.callback = dmi_disable_osi_vista,
.ident = "VGN-NS50B_L",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-NS50B_L"),
},
},
{
.callback = dmi_disable_osi_vista,
.ident = "Toshiba Satellite L355",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"),
DMI_MATCH(DMI_PRODUCT_VERSION, "Satellite L355"),
},
},
{
.callback = dmi_disable_osi_win7,
.ident = "ASUS K50IJ",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K50IJ"),
},
},
{
.callback = dmi_disable_osi_vista,
.ident = "Toshiba P305D",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"),
DMI_MATCH(DMI_PRODUCT_NAME, "Satellite P305D"),
},
},
/*
* BIOS invocation of _OSI(Linux) is almost always a BIOS bug.
* Linux ignores it, except for the machines enumerated below.
*/
/*
* Lenovo has a mix of systems OSI(Linux) situations
* and thus we can not wildcard the vendor.
*
* _OSI(Linux) helps sound
* DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad R61"),
* DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad T61"),
* T400, T500
* _OSI(Linux) has Linux specific hooks
* DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad X61"),
* _OSI(Linux) is a NOP:
* DMI_MATCH(DMI_PRODUCT_VERSION, "3000 N100"),
* DMI_MATCH(DMI_PRODUCT_VERSION, "LENOVO3000 V100"),
*/
{
.callback = dmi_enable_osi_linux,
.ident = "Lenovo ThinkPad R61",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad R61"),
},
},
{
.callback = dmi_enable_osi_linux,
.ident = "Lenovo ThinkPad T61",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad T61"),
},
},
{
.callback = dmi_enable_osi_linux,
.ident = "Lenovo ThinkPad X61",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad X61"),
},
},
{
.callback = dmi_enable_osi_linux,
.ident = "Lenovo ThinkPad T400",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad T400"),
},
},
{
.callback = dmi_enable_osi_linux,
.ident = "Lenovo ThinkPad T500",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad T500"),
},
},
{}
};
#endif /* CONFIG_DMI */
| gpl-2.0 |
Alex131089/raspberrypi-linux-3.6 | drivers/ide/buddha.c | 7703 | 5699 | /*
* Amiga Buddha, Catweasel and X-Surf IDE Driver
*
* Copyright (C) 1997, 2001 by Geert Uytterhoeven and others
*
* This driver was written based on the specifications in README.buddha and
* the X-Surf info from Inside_XSurf.txt available at
* http://www.jschoenfeld.com
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*
* TODO:
* - test it :-)
* - tune the timings using the speed-register
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/blkdev.h>
#include <linux/zorro.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <asm/amigahw.h>
#include <asm/amigaints.h>
/*
* The Buddha has 2 IDE interfaces, the Catweasel has 3, X-Surf has 2
*/
#define BUDDHA_NUM_HWIFS 2
#define CATWEASEL_NUM_HWIFS 3
#define XSURF_NUM_HWIFS 2
#define MAX_NUM_HWIFS 3
/*
* Bases of the IDE interfaces (relative to the board address)
*/
#define BUDDHA_BASE1 0x800
#define BUDDHA_BASE2 0xa00
#define BUDDHA_BASE3 0xc00
#define XSURF_BASE1 0xb000 /* 2.5" Interface */
#define XSURF_BASE2 0xd000 /* 3.5" Interface */
static u_int buddha_bases[CATWEASEL_NUM_HWIFS] __initdata = {
BUDDHA_BASE1, BUDDHA_BASE2, BUDDHA_BASE3
};
static u_int xsurf_bases[XSURF_NUM_HWIFS] __initdata = {
XSURF_BASE1, XSURF_BASE2
};
/*
* Offsets from one of the above bases
*/
#define BUDDHA_CONTROL 0x11a
/*
* Other registers
*/
#define BUDDHA_IRQ1 0xf00 /* MSB = 1, Harddisk is source of */
#define BUDDHA_IRQ2 0xf40 /* interrupt */
#define BUDDHA_IRQ3 0xf80
#define XSURF_IRQ1 0x7e
#define XSURF_IRQ2 0x7e
static int buddha_irqports[CATWEASEL_NUM_HWIFS] __initdata = {
BUDDHA_IRQ1, BUDDHA_IRQ2, BUDDHA_IRQ3
};
static int xsurf_irqports[XSURF_NUM_HWIFS] __initdata = {
XSURF_IRQ1, XSURF_IRQ2
};
#define BUDDHA_IRQ_MR 0xfc0 /* master interrupt enable */
/*
* Board information
*/
typedef enum BuddhaType_Enum {
BOARD_BUDDHA, BOARD_CATWEASEL, BOARD_XSURF
} BuddhaType;
static const char *buddha_board_name[] = { "Buddha", "Catweasel", "X-Surf" };
/*
* Check and acknowledge the interrupt status
*/
static int buddha_test_irq(ide_hwif_t *hwif)
{
unsigned char ch;
ch = z_readb(hwif->io_ports.irq_addr);
if (!(ch & 0x80))
return 0;
return 1;
}
static void xsurf_clear_irq(ide_drive_t *drive)
{
/*
* X-Surf needs 0 written to IRQ register to ensure ISA bit A11 stays at 0
*/
z_writeb(0, drive->hwif->io_ports.irq_addr);
}
static void __init buddha_setup_ports(struct ide_hw *hw, unsigned long base,
unsigned long ctl, unsigned long irq_port)
{
int i;
memset(hw, 0, sizeof(*hw));
hw->io_ports.data_addr = base;
for (i = 1; i < 8; i++)
hw->io_ports_array[i] = base + 2 + i * 4;
hw->io_ports.ctl_addr = ctl;
hw->io_ports.irq_addr = irq_port;
hw->irq = IRQ_AMIGA_PORTS;
}
static const struct ide_port_ops buddha_port_ops = {
.test_irq = buddha_test_irq,
};
static const struct ide_port_ops xsurf_port_ops = {
.clear_irq = xsurf_clear_irq,
.test_irq = buddha_test_irq,
};
static const struct ide_port_info buddha_port_info = {
.port_ops = &buddha_port_ops,
.host_flags = IDE_HFLAG_MMIO | IDE_HFLAG_NO_DMA,
.irq_flags = IRQF_SHARED,
.chipset = ide_generic,
};
/*
* Probe for a Buddha or Catweasel IDE interface
*/
static int __init buddha_init(void)
{
struct zorro_dev *z = NULL;
u_long buddha_board = 0;
BuddhaType type;
int buddha_num_hwifs, i;
while ((z = zorro_find_device(ZORRO_WILDCARD, z))) {
unsigned long board;
struct ide_hw hw[MAX_NUM_HWIFS], *hws[MAX_NUM_HWIFS];
struct ide_port_info d = buddha_port_info;
if (z->id == ZORRO_PROD_INDIVIDUAL_COMPUTERS_BUDDHA) {
buddha_num_hwifs = BUDDHA_NUM_HWIFS;
type=BOARD_BUDDHA;
} else if (z->id == ZORRO_PROD_INDIVIDUAL_COMPUTERS_CATWEASEL) {
buddha_num_hwifs = CATWEASEL_NUM_HWIFS;
type=BOARD_CATWEASEL;
} else if (z->id == ZORRO_PROD_INDIVIDUAL_COMPUTERS_X_SURF) {
buddha_num_hwifs = XSURF_NUM_HWIFS;
type=BOARD_XSURF;
d.port_ops = &xsurf_port_ops;
} else
continue;
board = z->resource.start;
if(type != BOARD_XSURF) {
if (!request_mem_region(board+BUDDHA_BASE1, 0x800, "IDE"))
continue;
} else {
if (!request_mem_region(board+XSURF_BASE1, 0x1000, "IDE"))
continue;
if (!request_mem_region(board+XSURF_BASE2, 0x1000, "IDE"))
goto fail_base2;
if (!request_mem_region(board+XSURF_IRQ1, 0x8, "IDE")) {
release_mem_region(board+XSURF_BASE2, 0x1000);
fail_base2:
release_mem_region(board+XSURF_BASE1, 0x1000);
continue;
}
}
buddha_board = ZTWO_VADDR(board);
/* write to BUDDHA_IRQ_MR to enable the board IRQ */
/* X-Surf doesn't have this. IRQs are always on */
if (type != BOARD_XSURF)
z_writeb(0, buddha_board+BUDDHA_IRQ_MR);
printk(KERN_INFO "ide: %s IDE controller\n",
buddha_board_name[type]);
for (i = 0; i < buddha_num_hwifs; i++) {
unsigned long base, ctl, irq_port;
if (type != BOARD_XSURF) {
base = buddha_board + buddha_bases[i];
ctl = base + BUDDHA_CONTROL;
irq_port = buddha_board + buddha_irqports[i];
} else {
base = buddha_board + xsurf_bases[i];
/* X-Surf has no CS1* (Control/AltStat) */
ctl = 0;
irq_port = buddha_board + xsurf_irqports[i];
}
buddha_setup_ports(&hw[i], base, ctl, irq_port);
hws[i] = &hw[i];
}
ide_host_add(&d, hws, i, NULL);
}
return 0;
}
module_init(buddha_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
NoelMacwan/android_kernel_sony_msm8928 | arch/ia64/kvm/asm-offsets.c | 11799 | 9551 | /*
* asm-offsets.c Generate definitions needed by assembly language modules.
* This code generates raw asm output which is post-processed
* to extract and format the required data.
*
* Anthony Xu <anthony.xu@intel.com>
* Xiantao Zhang <xiantao.zhang@intel.com>
* Copyright (c) 2007 Intel Corporation KVM support.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
*/
#include <linux/kvm_host.h>
#include <linux/kbuild.h>
#include "vcpu.h"
void foo(void)
{
DEFINE(VMM_TASK_SIZE, sizeof(struct kvm_vcpu));
DEFINE(VMM_PT_REGS_SIZE, sizeof(struct kvm_pt_regs));
BLANK();
DEFINE(VMM_VCPU_META_RR0_OFFSET,
offsetof(struct kvm_vcpu, arch.metaphysical_rr0));
DEFINE(VMM_VCPU_META_SAVED_RR0_OFFSET,
offsetof(struct kvm_vcpu,
arch.metaphysical_saved_rr0));
DEFINE(VMM_VCPU_VRR0_OFFSET,
offsetof(struct kvm_vcpu, arch.vrr[0]));
DEFINE(VMM_VPD_IRR0_OFFSET,
offsetof(struct vpd, irr[0]));
DEFINE(VMM_VCPU_ITC_CHECK_OFFSET,
offsetof(struct kvm_vcpu, arch.itc_check));
DEFINE(VMM_VCPU_IRQ_CHECK_OFFSET,
offsetof(struct kvm_vcpu, arch.irq_check));
DEFINE(VMM_VPD_VHPI_OFFSET,
offsetof(struct vpd, vhpi));
DEFINE(VMM_VCPU_VSA_BASE_OFFSET,
offsetof(struct kvm_vcpu, arch.vsa_base));
DEFINE(VMM_VCPU_VPD_OFFSET,
offsetof(struct kvm_vcpu, arch.vpd));
DEFINE(VMM_VCPU_IRQ_CHECK,
offsetof(struct kvm_vcpu, arch.irq_check));
DEFINE(VMM_VCPU_TIMER_PENDING,
offsetof(struct kvm_vcpu, arch.timer_pending));
DEFINE(VMM_VCPU_META_SAVED_RR0_OFFSET,
offsetof(struct kvm_vcpu, arch.metaphysical_saved_rr0));
DEFINE(VMM_VCPU_MODE_FLAGS_OFFSET,
offsetof(struct kvm_vcpu, arch.mode_flags));
DEFINE(VMM_VCPU_ITC_OFS_OFFSET,
offsetof(struct kvm_vcpu, arch.itc_offset));
DEFINE(VMM_VCPU_LAST_ITC_OFFSET,
offsetof(struct kvm_vcpu, arch.last_itc));
DEFINE(VMM_VCPU_SAVED_GP_OFFSET,
offsetof(struct kvm_vcpu, arch.saved_gp));
BLANK();
DEFINE(VMM_PT_REGS_B6_OFFSET,
offsetof(struct kvm_pt_regs, b6));
DEFINE(VMM_PT_REGS_B7_OFFSET,
offsetof(struct kvm_pt_regs, b7));
DEFINE(VMM_PT_REGS_AR_CSD_OFFSET,
offsetof(struct kvm_pt_regs, ar_csd));
DEFINE(VMM_PT_REGS_AR_SSD_OFFSET,
offsetof(struct kvm_pt_regs, ar_ssd));
DEFINE(VMM_PT_REGS_R8_OFFSET,
offsetof(struct kvm_pt_regs, r8));
DEFINE(VMM_PT_REGS_R9_OFFSET,
offsetof(struct kvm_pt_regs, r9));
DEFINE(VMM_PT_REGS_R10_OFFSET,
offsetof(struct kvm_pt_regs, r10));
DEFINE(VMM_PT_REGS_R11_OFFSET,
offsetof(struct kvm_pt_regs, r11));
DEFINE(VMM_PT_REGS_CR_IPSR_OFFSET,
offsetof(struct kvm_pt_regs, cr_ipsr));
DEFINE(VMM_PT_REGS_CR_IIP_OFFSET,
offsetof(struct kvm_pt_regs, cr_iip));
DEFINE(VMM_PT_REGS_CR_IFS_OFFSET,
offsetof(struct kvm_pt_regs, cr_ifs));
DEFINE(VMM_PT_REGS_AR_UNAT_OFFSET,
offsetof(struct kvm_pt_regs, ar_unat));
DEFINE(VMM_PT_REGS_AR_PFS_OFFSET,
offsetof(struct kvm_pt_regs, ar_pfs));
DEFINE(VMM_PT_REGS_AR_RSC_OFFSET,
offsetof(struct kvm_pt_regs, ar_rsc));
DEFINE(VMM_PT_REGS_AR_RNAT_OFFSET,
offsetof(struct kvm_pt_regs, ar_rnat));
DEFINE(VMM_PT_REGS_AR_BSPSTORE_OFFSET,
offsetof(struct kvm_pt_regs, ar_bspstore));
DEFINE(VMM_PT_REGS_PR_OFFSET,
offsetof(struct kvm_pt_regs, pr));
DEFINE(VMM_PT_REGS_B0_OFFSET,
offsetof(struct kvm_pt_regs, b0));
DEFINE(VMM_PT_REGS_LOADRS_OFFSET,
offsetof(struct kvm_pt_regs, loadrs));
DEFINE(VMM_PT_REGS_R1_OFFSET,
offsetof(struct kvm_pt_regs, r1));
DEFINE(VMM_PT_REGS_R12_OFFSET,
offsetof(struct kvm_pt_regs, r12));
DEFINE(VMM_PT_REGS_R13_OFFSET,
offsetof(struct kvm_pt_regs, r13));
DEFINE(VMM_PT_REGS_AR_FPSR_OFFSET,
offsetof(struct kvm_pt_regs, ar_fpsr));
DEFINE(VMM_PT_REGS_R15_OFFSET,
offsetof(struct kvm_pt_regs, r15));
DEFINE(VMM_PT_REGS_R14_OFFSET,
offsetof(struct kvm_pt_regs, r14));
DEFINE(VMM_PT_REGS_R2_OFFSET,
offsetof(struct kvm_pt_regs, r2));
DEFINE(VMM_PT_REGS_R3_OFFSET,
offsetof(struct kvm_pt_regs, r3));
DEFINE(VMM_PT_REGS_R16_OFFSET,
offsetof(struct kvm_pt_regs, r16));
DEFINE(VMM_PT_REGS_R17_OFFSET,
offsetof(struct kvm_pt_regs, r17));
DEFINE(VMM_PT_REGS_R18_OFFSET,
offsetof(struct kvm_pt_regs, r18));
DEFINE(VMM_PT_REGS_R19_OFFSET,
offsetof(struct kvm_pt_regs, r19));
DEFINE(VMM_PT_REGS_R20_OFFSET,
offsetof(struct kvm_pt_regs, r20));
DEFINE(VMM_PT_REGS_R21_OFFSET,
offsetof(struct kvm_pt_regs, r21));
DEFINE(VMM_PT_REGS_R22_OFFSET,
offsetof(struct kvm_pt_regs, r22));
DEFINE(VMM_PT_REGS_R23_OFFSET,
offsetof(struct kvm_pt_regs, r23));
DEFINE(VMM_PT_REGS_R24_OFFSET,
offsetof(struct kvm_pt_regs, r24));
DEFINE(VMM_PT_REGS_R25_OFFSET,
offsetof(struct kvm_pt_regs, r25));
DEFINE(VMM_PT_REGS_R26_OFFSET,
offsetof(struct kvm_pt_regs, r26));
DEFINE(VMM_PT_REGS_R27_OFFSET,
offsetof(struct kvm_pt_regs, r27));
DEFINE(VMM_PT_REGS_R28_OFFSET,
offsetof(struct kvm_pt_regs, r28));
DEFINE(VMM_PT_REGS_R29_OFFSET,
offsetof(struct kvm_pt_regs, r29));
DEFINE(VMM_PT_REGS_R30_OFFSET,
offsetof(struct kvm_pt_regs, r30));
DEFINE(VMM_PT_REGS_R31_OFFSET,
offsetof(struct kvm_pt_regs, r31));
DEFINE(VMM_PT_REGS_AR_CCV_OFFSET,
offsetof(struct kvm_pt_regs, ar_ccv));
DEFINE(VMM_PT_REGS_F6_OFFSET,
offsetof(struct kvm_pt_regs, f6));
DEFINE(VMM_PT_REGS_F7_OFFSET,
offsetof(struct kvm_pt_regs, f7));
DEFINE(VMM_PT_REGS_F8_OFFSET,
offsetof(struct kvm_pt_regs, f8));
DEFINE(VMM_PT_REGS_F9_OFFSET,
offsetof(struct kvm_pt_regs, f9));
DEFINE(VMM_PT_REGS_F10_OFFSET,
offsetof(struct kvm_pt_regs, f10));
DEFINE(VMM_PT_REGS_F11_OFFSET,
offsetof(struct kvm_pt_regs, f11));
DEFINE(VMM_PT_REGS_R4_OFFSET,
offsetof(struct kvm_pt_regs, r4));
DEFINE(VMM_PT_REGS_R5_OFFSET,
offsetof(struct kvm_pt_regs, r5));
DEFINE(VMM_PT_REGS_R6_OFFSET,
offsetof(struct kvm_pt_regs, r6));
DEFINE(VMM_PT_REGS_R7_OFFSET,
offsetof(struct kvm_pt_regs, r7));
DEFINE(VMM_PT_REGS_EML_UNAT_OFFSET,
offsetof(struct kvm_pt_regs, eml_unat));
DEFINE(VMM_VCPU_IIPA_OFFSET,
offsetof(struct kvm_vcpu, arch.cr_iipa));
DEFINE(VMM_VCPU_OPCODE_OFFSET,
offsetof(struct kvm_vcpu, arch.opcode));
DEFINE(VMM_VCPU_CAUSE_OFFSET, offsetof(struct kvm_vcpu, arch.cause));
DEFINE(VMM_VCPU_ISR_OFFSET,
offsetof(struct kvm_vcpu, arch.cr_isr));
DEFINE(VMM_PT_REGS_R16_SLOT,
(((offsetof(struct kvm_pt_regs, r16)
- sizeof(struct kvm_pt_regs)) >> 3) & 0x3f));
DEFINE(VMM_VCPU_MODE_FLAGS_OFFSET,
offsetof(struct kvm_vcpu, arch.mode_flags));
DEFINE(VMM_VCPU_GP_OFFSET, offsetof(struct kvm_vcpu, arch.__gp));
BLANK();
DEFINE(VMM_VPD_BASE_OFFSET, offsetof(struct kvm_vcpu, arch.vpd));
DEFINE(VMM_VPD_VIFS_OFFSET, offsetof(struct vpd, ifs));
DEFINE(VMM_VLSAPIC_INSVC_BASE_OFFSET,
offsetof(struct kvm_vcpu, arch.insvc[0]));
DEFINE(VMM_VPD_VPTA_OFFSET, offsetof(struct vpd, pta));
DEFINE(VMM_VPD_VPSR_OFFSET, offsetof(struct vpd, vpsr));
DEFINE(VMM_CTX_R4_OFFSET, offsetof(union context, gr[4]));
DEFINE(VMM_CTX_R5_OFFSET, offsetof(union context, gr[5]));
DEFINE(VMM_CTX_R12_OFFSET, offsetof(union context, gr[12]));
DEFINE(VMM_CTX_R13_OFFSET, offsetof(union context, gr[13]));
DEFINE(VMM_CTX_KR0_OFFSET, offsetof(union context, ar[0]));
DEFINE(VMM_CTX_KR1_OFFSET, offsetof(union context, ar[1]));
DEFINE(VMM_CTX_B0_OFFSET, offsetof(union context, br[0]));
DEFINE(VMM_CTX_B1_OFFSET, offsetof(union context, br[1]));
DEFINE(VMM_CTX_B2_OFFSET, offsetof(union context, br[2]));
DEFINE(VMM_CTX_RR0_OFFSET, offsetof(union context, rr[0]));
DEFINE(VMM_CTX_RSC_OFFSET, offsetof(union context, ar[16]));
DEFINE(VMM_CTX_BSPSTORE_OFFSET, offsetof(union context, ar[18]));
DEFINE(VMM_CTX_RNAT_OFFSET, offsetof(union context, ar[19]));
DEFINE(VMM_CTX_FCR_OFFSET, offsetof(union context, ar[21]));
DEFINE(VMM_CTX_EFLAG_OFFSET, offsetof(union context, ar[24]));
DEFINE(VMM_CTX_CFLG_OFFSET, offsetof(union context, ar[27]));
DEFINE(VMM_CTX_FSR_OFFSET, offsetof(union context, ar[28]));
DEFINE(VMM_CTX_FIR_OFFSET, offsetof(union context, ar[29]));
DEFINE(VMM_CTX_FDR_OFFSET, offsetof(union context, ar[30]));
DEFINE(VMM_CTX_UNAT_OFFSET, offsetof(union context, ar[36]));
DEFINE(VMM_CTX_FPSR_OFFSET, offsetof(union context, ar[40]));
DEFINE(VMM_CTX_PFS_OFFSET, offsetof(union context, ar[64]));
DEFINE(VMM_CTX_LC_OFFSET, offsetof(union context, ar[65]));
DEFINE(VMM_CTX_DCR_OFFSET, offsetof(union context, cr[0]));
DEFINE(VMM_CTX_IVA_OFFSET, offsetof(union context, cr[2]));
DEFINE(VMM_CTX_PTA_OFFSET, offsetof(union context, cr[8]));
DEFINE(VMM_CTX_IBR0_OFFSET, offsetof(union context, ibr[0]));
DEFINE(VMM_CTX_DBR0_OFFSET, offsetof(union context, dbr[0]));
DEFINE(VMM_CTX_F2_OFFSET, offsetof(union context, fr[2]));
DEFINE(VMM_CTX_F3_OFFSET, offsetof(union context, fr[3]));
DEFINE(VMM_CTX_F32_OFFSET, offsetof(union context, fr[32]));
DEFINE(VMM_CTX_F33_OFFSET, offsetof(union context, fr[33]));
DEFINE(VMM_CTX_PKR0_OFFSET, offsetof(union context, pkr[0]));
DEFINE(VMM_CTX_PSR_OFFSET, offsetof(union context, psr));
BLANK();
}
| gpl-2.0 |
MyAOSP/kernel_asus_tf300t | arch/ia64/sn/kernel/bte_error.c | 13847 | 7665 | /*
* 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) 2000-2007 Silicon Graphics, Inc. All Rights Reserved.
*/
#include <linux/types.h>
#include <asm/sn/sn_sal.h>
#include "ioerror.h"
#include <asm/sn/addrs.h>
#include <asm/sn/shubio.h>
#include <asm/sn/geo.h>
#include "xtalk/xwidgetdev.h"
#include "xtalk/hubdev.h"
#include <asm/sn/bte.h>
#include <asm/param.h>
/*
* Bte error handling is done in two parts. The first captures
* any crb related errors. Since there can be multiple crbs per
* interface and multiple interfaces active, we need to wait until
* all active crbs are completed. This is the first job of the
* second part error handler. When all bte related CRBs are cleanly
* completed, it resets the interfaces and gets them ready for new
* transfers to be queued.
*/
void bte_error_handler(unsigned long);
/*
* Wait until all BTE related CRBs are completed
* and then reset the interfaces.
*/
int shub1_bte_error_handler(unsigned long _nodepda)
{
struct nodepda_s *err_nodepda = (struct nodepda_s *)_nodepda;
struct timer_list *recovery_timer = &err_nodepda->bte_recovery_timer;
nasid_t nasid;
int i;
int valid_crbs;
ii_imem_u_t imem; /* II IMEM Register */
ii_icrb0_d_u_t icrbd; /* II CRB Register D */
ii_ibcr_u_t ibcr;
ii_icmr_u_t icmr;
ii_ieclr_u_t ieclr;
BTE_PRINTK(("shub1_bte_error_handler(%p) - %d\n", err_nodepda,
smp_processor_id()));
if ((err_nodepda->bte_if[0].bh_error == BTE_SUCCESS) &&
(err_nodepda->bte_if[1].bh_error == BTE_SUCCESS)) {
BTE_PRINTK(("eh:%p:%d Nothing to do.\n", err_nodepda,
smp_processor_id()));
return 1;
}
/* Determine information about our hub */
nasid = cnodeid_to_nasid(err_nodepda->bte_if[0].bte_cnode);
/*
* A BTE transfer can use multiple CRBs. We need to make sure
* that all the BTE CRBs are complete (or timed out) before
* attempting to clean up the error. Resetting the BTE while
* there are still BTE CRBs active will hang the BTE.
* We should look at all the CRBs to see if they are allocated
* to the BTE and see if they are still active. When none
* are active, we can continue with the cleanup.
*
* We also want to make sure that the local NI port is up.
* When a router resets the NI port can go down, while it
* goes through the LLP handshake, but then comes back up.
*/
icmr.ii_icmr_regval = REMOTE_HUB_L(nasid, IIO_ICMR);
if (icmr.ii_icmr_fld_s.i_crb_mark != 0) {
/*
* There are errors which still need to be cleaned up by
* hubiio_crb_error_handler
*/
mod_timer(recovery_timer, jiffies + (HZ * 5));
BTE_PRINTK(("eh:%p:%d Marked Giving up\n", err_nodepda,
smp_processor_id()));
return 1;
}
if (icmr.ii_icmr_fld_s.i_crb_vld != 0) {
valid_crbs = icmr.ii_icmr_fld_s.i_crb_vld;
for (i = 0; i < IIO_NUM_CRBS; i++) {
if (!((1 << i) & valid_crbs)) {
/* This crb was not marked as valid, ignore */
continue;
}
icrbd.ii_icrb0_d_regval =
REMOTE_HUB_L(nasid, IIO_ICRB_D(i));
if (icrbd.d_bteop) {
mod_timer(recovery_timer, jiffies + (HZ * 5));
BTE_PRINTK(("eh:%p:%d Valid %d, Giving up\n",
err_nodepda, smp_processor_id(),
i));
return 1;
}
}
}
BTE_PRINTK(("eh:%p:%d Cleaning up\n", err_nodepda, smp_processor_id()));
/* Re-enable both bte interfaces */
imem.ii_imem_regval = REMOTE_HUB_L(nasid, IIO_IMEM);
imem.ii_imem_fld_s.i_b0_esd = imem.ii_imem_fld_s.i_b1_esd = 1;
REMOTE_HUB_S(nasid, IIO_IMEM, imem.ii_imem_regval);
/* Clear BTE0/1 error bits */
ieclr.ii_ieclr_regval = 0;
if (err_nodepda->bte_if[0].bh_error != BTE_SUCCESS)
ieclr.ii_ieclr_fld_s.i_e_bte_0 = 1;
if (err_nodepda->bte_if[1].bh_error != BTE_SUCCESS)
ieclr.ii_ieclr_fld_s.i_e_bte_1 = 1;
REMOTE_HUB_S(nasid, IIO_IECLR, ieclr.ii_ieclr_regval);
/* Reinitialize both BTE state machines. */
ibcr.ii_ibcr_regval = REMOTE_HUB_L(nasid, IIO_IBCR);
ibcr.ii_ibcr_fld_s.i_soft_reset = 1;
REMOTE_HUB_S(nasid, IIO_IBCR, ibcr.ii_ibcr_regval);
del_timer(recovery_timer);
return 0;
}
/*
* Wait until all BTE related CRBs are completed
* and then reset the interfaces.
*/
int shub2_bte_error_handler(unsigned long _nodepda)
{
struct nodepda_s *err_nodepda = (struct nodepda_s *)_nodepda;
struct timer_list *recovery_timer = &err_nodepda->bte_recovery_timer;
struct bteinfo_s *bte;
nasid_t nasid;
u64 status;
int i;
nasid = cnodeid_to_nasid(err_nodepda->bte_if[0].bte_cnode);
/*
* Verify that all the BTEs are complete
*/
for (i = 0; i < BTES_PER_NODE; i++) {
bte = &err_nodepda->bte_if[i];
status = BTE_LNSTAT_LOAD(bte);
if (status & IBLS_ERROR) {
bte->bh_error = BTE_SHUB2_ERROR(status);
continue;
}
if (!(status & IBLS_BUSY))
continue;
mod_timer(recovery_timer, jiffies + (HZ * 5));
BTE_PRINTK(("eh:%p:%d Marked Giving up\n", err_nodepda,
smp_processor_id()));
return 1;
}
if (ia64_sn_bte_recovery(nasid))
panic("bte_error_handler(): Fatal BTE Error");
del_timer(recovery_timer);
return 0;
}
/*
* Wait until all BTE related CRBs are completed
* and then reset the interfaces.
*/
void bte_error_handler(unsigned long _nodepda)
{
struct nodepda_s *err_nodepda = (struct nodepda_s *)_nodepda;
spinlock_t *recovery_lock = &err_nodepda->bte_recovery_lock;
int i;
unsigned long irq_flags;
volatile u64 *notify;
bte_result_t bh_error;
BTE_PRINTK(("bte_error_handler(%p) - %d\n", err_nodepda,
smp_processor_id()));
spin_lock_irqsave(recovery_lock, irq_flags);
/*
* Lock all interfaces on this node to prevent new transfers
* from being queued.
*/
for (i = 0; i < BTES_PER_NODE; i++) {
if (err_nodepda->bte_if[i].cleanup_active) {
continue;
}
spin_lock(&err_nodepda->bte_if[i].spinlock);
BTE_PRINTK(("eh:%p:%d locked %d\n", err_nodepda,
smp_processor_id(), i));
err_nodepda->bte_if[i].cleanup_active = 1;
}
if (is_shub1()) {
if (shub1_bte_error_handler(_nodepda)) {
spin_unlock_irqrestore(recovery_lock, irq_flags);
return;
}
} else {
if (shub2_bte_error_handler(_nodepda)) {
spin_unlock_irqrestore(recovery_lock, irq_flags);
return;
}
}
for (i = 0; i < BTES_PER_NODE; i++) {
bh_error = err_nodepda->bte_if[i].bh_error;
if (bh_error != BTE_SUCCESS) {
/* There is an error which needs to be notified */
notify = err_nodepda->bte_if[i].most_rcnt_na;
BTE_PRINTK(("cnode %d bte %d error=0x%lx\n",
err_nodepda->bte_if[i].bte_cnode,
err_nodepda->bte_if[i].bte_num,
IBLS_ERROR | (u64) bh_error));
*notify = IBLS_ERROR | bh_error;
err_nodepda->bte_if[i].bh_error = BTE_SUCCESS;
}
err_nodepda->bte_if[i].cleanup_active = 0;
BTE_PRINTK(("eh:%p:%d Unlocked %d\n", err_nodepda,
smp_processor_id(), i));
spin_unlock(&err_nodepda->bte_if[i].spinlock);
}
spin_unlock_irqrestore(recovery_lock, irq_flags);
}
/*
* First part error handler. This is called whenever any error CRB interrupt
* is generated by the II.
*/
void
bte_crb_error_handler(cnodeid_t cnode, int btenum,
int crbnum, ioerror_t * ioe, int bteop)
{
struct bteinfo_s *bte;
bte = &(NODEPDA(cnode)->bte_if[btenum]);
/*
* The caller has already figured out the error type, we save that
* in the bte handle structure for the thread exercising the
* interface to consume.
*/
bte->bh_error = ioe->ie_errortype + BTEFAIL_OFFSET;
bte->bte_error_count++;
BTE_PRINTK(("Got an error on cnode %d bte %d: HW error type 0x%x\n",
bte->bte_cnode, bte->bte_num, ioe->ie_errortype));
bte_error_handler((unsigned long) NODEPDA(cnode));
}
| gpl-2.0 |
alex9755/Core | src/server/worldserver/RemoteAccess/RARunnable.cpp | 24 | 2344 | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** \file
\ingroup Trinityd
*/
#include "Common.h"
#include "Config.h"
#include "Log.h"
#include "RARunnable.h"
#include "World.h"
#include <ace/Reactor_Impl.h>
#include <ace/TP_Reactor.h>
#include <ace/Dev_Poll_Reactor.h>
#include <ace/Acceptor.h>
#include <ace/SOCK_Acceptor.h>
#include "RASocket.h"
RARunnable::RARunnable()
{
ACE_Reactor_Impl* imp;
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
imp = new ACE_Dev_Poll_Reactor();
imp->max_notify_iterations (128);
imp->restart (1);
#else
imp = new ACE_TP_Reactor();
imp->max_notify_iterations (128);
#endif
m_Reactor = new ACE_Reactor (imp, 1);
}
RARunnable::~RARunnable()
{
delete m_Reactor;
}
void RARunnable::run()
{
if (!sConfigMgr->GetBoolDefault("Ra.Enable", false))
return;
ACE_Acceptor<RASocket, ACE_SOCK_ACCEPTOR> acceptor;
uint16 raPort = uint16(sConfigMgr->GetIntDefault("Ra.Port", 3443));
std::string stringIp = sConfigMgr->GetStringDefault("Ra.IP", "0.0.0.0");
ACE_INET_Addr listenAddress(raPort, stringIp.c_str());
if (acceptor.open(listenAddress, m_Reactor) == -1)
{
TC_LOG_ERROR("server.worldserver", "Trinity RA can not bind to port %d on %s", raPort, stringIp.c_str());
return;
}
TC_LOG_INFO("server.worldserver", "Starting Trinity RA on port %d on %s", raPort, stringIp.c_str());
while (!World::IsStopped())
{
ACE_Time_Value interval(0, 100000);
if (m_Reactor->run_reactor_event_loop(interval) == -1)
break;
}
TC_LOG_DEBUG("server.worldserver", "Trinity RA thread exiting");
}
| gpl-2.0 |
smarkwell/asuswrt-merlin | release/src/router/openpam/lib/libpam/openpam_check_owner_perms.c | 24 | 4034 | /*-
* Copyright (c) 2011 Dag-Erling Smørgrav
* 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. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: openpam_check_owner_perms.c 648 2013-03-05 17:54:27Z des $
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <security/pam_appl.h>
#include "openpam_impl.h"
/*
* OpenPAM internal
*
* Verify that the file or directory referenced by the given descriptor is
* owned by either root or the arbitrator and that it is not writable by
* group or other.
*/
int
openpam_check_desc_owner_perms(const char *name, int fd)
{
uid_t root, arbitrator;
struct stat sb;
int serrno;
root = 0;
arbitrator = geteuid();
if (fstat(fd, &sb) != 0) {
serrno = errno;
openpam_log(PAM_LOG_ERROR, "%s: %m", name);
errno = serrno;
return (-1);
}
if (!S_ISREG(sb.st_mode)) {
openpam_log(PAM_LOG_ERROR,
"%s: not a regular file", name);
errno = EINVAL;
return (-1);
}
if ((sb.st_uid != root && sb.st_uid != arbitrator) ||
(sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
openpam_log(PAM_LOG_ERROR,
"%s: insecure ownership or permissions", name);
errno = EPERM;
return (-1);
}
return (0);
}
/*
* OpenPAM internal
*
* Verify that a file or directory and all components of the path leading
* up to it are owned by either root or the arbitrator and that they are
* not writable by group or other.
*
* Note that openpam_check_desc_owner_perms() should be used instead if
* possible to avoid a race between the ownership / permission check and
* the actual open().
*/
int
openpam_check_path_owner_perms(const char *path)
{
uid_t root, arbitrator;
char pathbuf[PATH_MAX];
struct stat sb;
int len, serrno, tip;
tip = 1;
root = 0;
arbitrator = geteuid();
if (realpath(path, pathbuf) == NULL)
return (-1);
len = strlen(pathbuf);
while (len > 0) {
if (stat(pathbuf, &sb) != 0) {
if (errno != ENOENT) {
serrno = errno;
openpam_log(PAM_LOG_ERROR, "%s: %m", pathbuf);
errno = serrno;
}
return (-1);
}
if (tip && !S_ISREG(sb.st_mode)) {
openpam_log(PAM_LOG_ERROR,
"%s: not a regular file", pathbuf);
errno = EINVAL;
return (-1);
}
if ((sb.st_uid != root && sb.st_uid != arbitrator) ||
(sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
openpam_log(PAM_LOG_ERROR,
"%s: insecure ownership or permissions", pathbuf);
errno = EPERM;
return (-1);
}
while (--len > 0 && pathbuf[len] != '/')
pathbuf[len] = '\0';
tip = 0;
}
return (0);
}
/*
* NOPARSE
*/
| gpl-2.0 |
gupascal/distcc | src/dotd.c | 24 | 8965 | /* -*- c-file-style: "java"; indent-tabs-mode: nil; tab-width: 4; fill-column: 78 -*-
*
* Copyright 2007 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "distcc.h"
#include "exitcode.h"
#include "dotd.h"
#include "snprintf.h"
/* The dotd file is compiler generated,
* so it should not have lines with more than
* twice the length of the maximum path length.
*/
#define MAX_DOTD_LINE_LEN (MAXPATHLEN * 2)
/* Replaces the first occurrence of needle in haystack with
new_needle. haystack must be of at least hay_size,
and hay_size must be large enough to hold the string
after the replacement.
new_needle should not overlap with the haystack.
Returns 0 if all goes well, 1 otherwise.
*/
static int dcc_strgraft(char *haystack, size_t hay_size,
const char *needle, const char *new_needle)
{
char *found;
size_t needle_len = 0;
size_t new_needle_len = 0;
found = strstr(haystack, needle);
if (found == NULL)
return 0;
needle_len = strlen(needle);
new_needle_len = strlen(new_needle);
if (strlen(haystack) - needle_len + new_needle_len + 1 > hay_size)
return 1;
/* make some room in the haystack for the new needle */
memmove(found + new_needle_len,
found + needle_len,
strlen(found + needle_len) + 1);
memcpy(found, new_needle, new_needle_len);
return 0;
}
/* Given the name of a dotd file, and the name of the directory
* masquerading as root, write a @p new_dotd file that
* contains everything in dotd, but with the "root" directory removed.
* It will also substitute client_out_name for server_out_name,
* rewriting the dependency target.
*/
int dcc_cleanup_dotd(const char *dotd_fname,
char **new_dotd_fname,
const char *root_dir,
const char *client_out_name,
const char *server_out_name)
{
/* When we do the substitution of server-side output name to
* client-side output name, we may end up with a line that
* longer than the longest line we expect from the compiler.
*/
char buf[2 * MAX_DOTD_LINE_LEN];
FILE *dotd, *tmp_dotd;
char *found;
int ret;
dotd = fopen(dotd_fname, "r");
if (dotd == NULL) {
return 1;
}
ret = dcc_make_tmpnam(dcc_find_basename(dotd_fname),
".d", new_dotd_fname);
if (ret) {
fclose(dotd);
return ret;
}
tmp_dotd = fopen(*new_dotd_fname, "w");
if (tmp_dotd == NULL) {
fclose(dotd);
return 1;
}
while (fgets(buf, MAX_DOTD_LINE_LEN, dotd)) {
if ((strchr(buf, '\n') == NULL) && !feof(dotd)) {
/* Line length must have exceeded MAX_DOTD_LINE_LEN: bail out. */
fclose(dotd);
fclose(tmp_dotd);
return 1;
}
/* First, the dependency target substitution */
if (dcc_strgraft(buf, sizeof(buf),
server_out_name, client_out_name)) {
fclose(dotd);
fclose(tmp_dotd);
return 1;
}
/* Second, the trimming of the "root" directory" */
found = strstr(buf, root_dir);
while (found) {
char *rest_of_buf = found + strlen(root_dir);
memmove(found, rest_of_buf, strlen(rest_of_buf) + 1);
found = strstr(found, root_dir);
}
if (fprintf(tmp_dotd, "%s", buf) < 0) {
fclose(dotd);
fclose(tmp_dotd);
return 1;
}
}
if (ferror(dotd) || ferror(tmp_dotd)) {
return 1;
}
fclose(dotd);
if (fclose(tmp_dotd) < 0) {
return 1;
}
return 0;
}
/* Go through arguments (in @p argv), and relevant environment variables, and
* find out where the dependencies output should go. Return that location in a
* newly allocated string in @p dotd_fname. @p needs_dotd is set to true if the
* compilation command line and environent imply that a .d file must be
* produced. @p sets_dotd_target is set to true if there is a -MQ or -MT
* option. This is to be used on the client, so that the client knows where to
* put the .d file it gets from the server. @p dotd_target is set only if
* @needs_dotd is true and @sets_dotd_target is false and the target is given in
* the DEPENDENCIES_OUTPUT environment variable.
*
* Note: -M is not handled here, because this option implies -E.
*
* TODO(manos): it does not support SUNPRO_DEPENDENCIES.
*/
int dcc_get_dotd_info(char **argv, char **dotd_fname,
int *needs_dotd, int *sets_dotd_target,
char **dotd_target)
{
char *deps_output = 0;
char *input_file;
char *output_file;
char **new_args; /* will throw this away */
int has_dash_o = 0;
char *env_var = 0;
int i;
char *a;
*needs_dotd = 0;
*sets_dotd_target = 0;
*dotd_target = NULL;
env_var = getenv("DEPENDENCIES_OUTPUT");
if (env_var != NULL) {
*needs_dotd = 1;
}
for (i = 0; (a = argv[i]); i++) {
if (strcmp(a, "-MT") == 0) {
*sets_dotd_target = 1;
++i;
continue;
}
if (strcmp(a, "-MQ") == 0) {
*sets_dotd_target = 1;
++i;
continue;
}
/* Catch-all for all -MD, -MMD, etc, options.
* -MQ and -MT do not imply a deps file is expected.
*/
if (strncmp(a, "-M", 2) == 0) {
*needs_dotd = 1;
}
if (strcmp(a, "-MF") == 0) {
++i;
deps_output = argv[i];
} else if (strncmp(a, "-MF", 3) == 0) {
deps_output = argv[i] + 3;
} else if (strcmp(a, "-o") == 0) {
has_dash_o = 1;
}
}
/* TODO(csilvers): we also need to parse -Wp,-x,-y,-z, in the same
* way we do gcc flags in the for loop above. Note that the -Wp
* flags are passed to cpp, with slightly different semantics than
* gcc flags (eg -Wp,-MD takes a filename argument, while -MD does
* not).
*/
if (deps_output) {
*dotd_fname = strdup(deps_output);
if (*dotd_fname == NULL) {
return EXIT_OUT_OF_MEMORY;
} else {
return 0;
}
}
/* ok, so there is no explicit setting of the deps filename. */
deps_output = env_var;
if (deps_output) {
char *space;
*dotd_fname = strdup(deps_output);
if (*dotd_fname == NULL) {
return EXIT_OUT_OF_MEMORY;
}
space = strchr(*dotd_fname, ' ');
if (space != NULL) {
*space = '\0';
*dotd_target = space + 1;
}
return 0;
}
/* and it's not set explicitly in the variable */
{ /* Call dcc_scan_args to find the input/output files in order to calculate
a name for the .d file.*/
char *extension;
char *tmp_dotd_fname;
dcc_scan_args(argv, &input_file, &output_file, &new_args);
/* if .o is set, just append .d.
* otherwise, take the basename of the input, and set the suffix to .d */
if (has_dash_o)
tmp_dotd_fname = strdup(output_file);
else
tmp_dotd_fname = strdup(input_file);
if (tmp_dotd_fname == NULL) return EXIT_OUT_OF_MEMORY;
extension = dcc_find_extension(tmp_dotd_fname);
/* Whether derived from input or output filename, we peel the extension
off (if it exists). */
if (extension) {
/* dcc_find_extension guarantees that there is space for 'd'. */
extension[1] = 'd';
extension[2] = '\0';
*dotd_fname = tmp_dotd_fname;
}
else { /* There is no extension (or name ends with a "."). */
if (tmp_dotd_fname[strlen(tmp_dotd_fname) - 1] == '.')
checked_asprintf(dotd_fname, "%s%s", tmp_dotd_fname, "d");
else
checked_asprintf(dotd_fname, "%s%s", tmp_dotd_fname, ".d");
if (*dotd_fname == NULL) {
return EXIT_OUT_OF_MEMORY;
}
free(tmp_dotd_fname);
}
return 0;
}
}
| gpl-2.0 |
codie72/TrinityCore | src/server/game/Entities/Object/Updates/UpdateFieldFlags.cpp | 24 | 139107 | /*
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UpdateFieldFlags.h"
uint32 ItemUpdateFieldFlags[CONTAINER_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID+1
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC, // OBJECT_FIELD_ENTRY
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE_X
UF_FLAG_NONE, // OBJECT_FIELD_PADDING
UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER
UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER+1
UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED
UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED+1
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR+1
UF_FLAG_PUBLIC, // ITEM_FIELD_GIFTCREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_GIFTCREATOR+1
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_STACK_COUNT
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_DURATION
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_SPELL_CHARGES+1
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_SPELL_CHARGES+2
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_SPELL_CHARGES+3
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_SPELL_CHARGES+4
UF_FLAG_PUBLIC, // ITEM_FIELD_FLAGS
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_1_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_1_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_1_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_2_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_2_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_2_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_3_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_3_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_3_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_4_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_4_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_4_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_5_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_5_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_5_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_6_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_6_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_6_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_7_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_7_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_7_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_8_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_8_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_8_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_9_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_9_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_9_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_10_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_10_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_10_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_11_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_11_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_11_3
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_12_1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_12_1+1
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT_12_3
UF_FLAG_PUBLIC, // ITEM_FIELD_PROPERTY_SEED
UF_FLAG_PUBLIC, // ITEM_FIELD_RANDOM_PROPERTIES_ID
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_DURABILITY
UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER, // ITEM_FIELD_MAXDURABILITY
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATE_PLAYED_TIME
UF_FLAG_NONE, // ITEM_FIELD_PAD
UF_FLAG_PUBLIC, // CONTAINER_FIELD_NUM_SLOTS
UF_FLAG_NONE, // CONTAINER_ALIGN_PAD
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+1
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+2
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+3
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+4
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+5
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+6
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+7
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+8
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+9
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+10
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+11
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+12
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+13
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+14
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+15
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+16
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+17
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+18
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+19
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+20
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+21
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+22
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+23
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+24
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+25
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+26
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+27
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+28
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+29
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+30
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+31
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+32
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+33
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+34
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+35
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+36
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+37
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+38
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+39
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+40
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+41
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+42
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+43
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+44
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+45
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+46
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+47
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+48
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+49
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+50
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+51
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+52
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+53
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+54
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+55
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+56
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+57
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+58
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+59
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+60
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+61
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+62
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+63
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+64
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+65
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+66
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+67
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+68
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+69
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+70
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOT_1+71
};
uint32 UnitUpdateFieldFlags[PLAYER_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID+1
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC, // OBJECT_FIELD_ENTRY
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE_X
UF_FLAG_NONE, // OBJECT_FIELD_PADDING
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM+1
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON+1
UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER
UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER+1
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMEDBY
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMEDBY+1
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONEDBY
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONEDBY+1
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATEDBY
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATEDBY+1
UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET
UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET+1
UF_FLAG_PUBLIC, // UNIT_FIELD_CHANNEL_OBJECT
UF_FLAG_PUBLIC, // UNIT_FIELD_CHANNEL_OBJECT+1
UF_FLAG_PUBLIC, // UNIT_CHANNEL_SPELL
UF_FLAG_PUBLIC, // UNIT_FIELD_BYTES_0
UF_FLAG_PUBLIC, // UNIT_FIELD_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER1
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER2
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER3
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER4
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER5
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER6
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER7
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXHEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER1
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER2
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER3
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER4
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER5
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER6
UF_FLAG_PUBLIC, // UNIT_FIELD_MAXPOWER7
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER+6
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER+6
UF_FLAG_PUBLIC, // UNIT_FIELD_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_FACTIONTEMPLATE
UF_FLAG_PUBLIC, // UNIT_VIRTUAL_ITEM_SLOT_ID
UF_FLAG_PUBLIC, // UNIT_VIRTUAL_ITEM_SLOT_ID+1
UF_FLAG_PUBLIC, // UNIT_VIRTUAL_ITEM_SLOT_ID+2
UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS_2
UF_FLAG_PUBLIC, // UNIT_FIELD_AURASTATE
UF_FLAG_PUBLIC, // UNIT_FIELD_BASEATTACKTIME
UF_FLAG_PUBLIC, // UNIT_FIELD_BASEATTACKTIME+1
UF_FLAG_PRIVATE, // UNIT_FIELD_RANGEDATTACKTIME
UF_FLAG_PUBLIC, // UNIT_FIELD_BOUNDINGRADIUS
UF_FLAG_PUBLIC, // UNIT_FIELD_COMBATREACH
UF_FLAG_PUBLIC, // UNIT_FIELD_DISPLAYID
UF_FLAG_PUBLIC, // UNIT_FIELD_NATIVEDISPLAYID
UF_FLAG_PUBLIC, // UNIT_FIELD_MOUNTDISPLAYID
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_MINDAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_MAXDAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_MINOFFHANDDAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_MAXOFFHANDDAMAGE
UF_FLAG_PUBLIC, // UNIT_FIELD_BYTES_1
UF_FLAG_PUBLIC, // UNIT_FIELD_PETNUMBER
UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NAME_TIMESTAMP
UF_FLAG_OWNER, // UNIT_FIELD_PETEXPERIENCE
UF_FLAG_OWNER, // UNIT_FIELD_PETNEXTLEVELEXP
UF_FLAG_DYNAMIC, // UNIT_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // UNIT_MOD_CAST_SPEED
UF_FLAG_PUBLIC, // UNIT_CREATED_BY_SPELL
UF_FLAG_DYNAMIC, // UNIT_NPC_FLAGS
UF_FLAG_PUBLIC, // UNIT_NPC_EMOTESTATE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT0
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POSSTAT0
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POSSTAT1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POSSTAT2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POSSTAT3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POSSTAT4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_NEGSTAT0
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_NEGSTAT1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_NEGSTAT2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_NEGSTAT3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_NEGSTAT4
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_SPECIAL_INFO, // UNIT_FIELD_RESISTANCES+6
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+6
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+6
UF_FLAG_PUBLIC, // UNIT_FIELD_BASE_MANA
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_BASE_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_BYTES_2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MODS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MODS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MINRANGEDDAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAXRANGEDDAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER+6
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER+1
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER+2
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER+3
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER+4
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER+5
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER+6
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAXHEALTHMODIFIER
UF_FLAG_PUBLIC, // UNIT_FIELD_HOVERHEIGHT
UF_FLAG_NONE, // UNIT_FIELD_PADDING
UF_FLAG_PUBLIC, // PLAYER_DUEL_ARBITER
UF_FLAG_PUBLIC, // PLAYER_DUEL_ARBITER+1
UF_FLAG_PUBLIC, // PLAYER_FLAGS
UF_FLAG_PUBLIC, // PLAYER_GUILDID
UF_FLAG_PUBLIC, // PLAYER_GUILDRANK
UF_FLAG_PUBLIC, // PLAYER_BYTES
UF_FLAG_PUBLIC, // PLAYER_BYTES_2
UF_FLAG_PUBLIC, // PLAYER_BYTES_3
UF_FLAG_PUBLIC, // PLAYER_DUEL_TEAM
UF_FLAG_PUBLIC, // PLAYER_GUILD_TIMESTAMP
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_1_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_1_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_1_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_1_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_1_4
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_2_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_2_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_2_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_2_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_2_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_3_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_3_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_3_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_3_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_3_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_4_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_4_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_4_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_4_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_4_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_5_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_5_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_5_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_5_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_5_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_6_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_6_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_6_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_6_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_6_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_7_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_7_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_7_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_7_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_7_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_8_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_8_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_8_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_8_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_8_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_9_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_9_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_9_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_9_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_9_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_10_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_10_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_10_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_10_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_10_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_11_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_11_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_11_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_11_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_11_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_12_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_12_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_12_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_12_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_12_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_13_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_13_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_13_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_13_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_13_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_14_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_14_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_14_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_14_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_14_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_15_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_15_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_15_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_15_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_15_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_16_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_16_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_16_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_16_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_16_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_17_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_17_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_17_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_17_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_17_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_18_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_18_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_18_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_18_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_18_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_19_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_19_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_19_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_19_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_19_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_20_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_20_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_20_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_20_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_20_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_21_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_21_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_21_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_21_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_21_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_22_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_22_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_22_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_22_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_22_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_23_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_23_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_23_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_23_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_23_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_24_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_24_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_24_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_24_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_24_5
UF_FLAG_PARTY_MEMBER, // PLAYER_QUEST_LOG_25_1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_25_2
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_25_3
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_25_3+1
UF_FLAG_PRIVATE, // PLAYER_QUEST_LOG_25_5
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_1_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_2_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_2_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_3_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_3_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_4_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_4_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_5_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_5_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_6_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_6_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_7_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_7_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_8_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_8_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_9_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_9_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_10_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_10_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_11_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_11_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_12_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_12_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_13_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_13_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_14_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_14_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_15_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_15_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_16_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_16_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_17_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_17_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_18_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_18_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_19_ENTRYID
UF_FLAG_PUBLIC, // PLAYER_VISIBLE_ITEM_19_ENCHANTMENT
UF_FLAG_PUBLIC, // PLAYER_CHOSEN_TITLE
UF_FLAG_PUBLIC, // PLAYER_FAKE_INEBRIATION
UF_FLAG_NONE, // PLAYER_FIELD_PAD_0
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+24
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+25
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+26
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+27
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+28
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+29
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+30
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+31
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+32
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+33
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+34
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+35
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+36
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+37
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+38
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+39
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+40
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+41
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+42
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+43
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+44
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOT_HEAD+45
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+24
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+25
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+26
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+27
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+28
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+29
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+30
UF_FLAG_PRIVATE, // PLAYER_FIELD_PACK_SLOT_1+31
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+24
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+25
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+26
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+27
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+28
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+29
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+30
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+31
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+32
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+33
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+34
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+35
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+36
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+37
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+38
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+39
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+40
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+41
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+42
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+43
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+44
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+45
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+46
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+47
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+48
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+49
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+50
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+51
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+52
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+53
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+54
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANK_SLOT_1+55
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_BANKBAG_SLOT_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_VENDORBUYBACK_SLOT_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+24
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+25
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+26
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+27
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+28
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+29
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+30
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+31
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+32
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+33
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+34
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+35
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+36
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+37
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+38
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+39
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+40
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+41
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+42
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+43
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+44
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+45
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+46
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+47
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+48
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+49
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+50
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+51
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+52
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+53
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+54
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+55
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+56
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+57
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+58
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+59
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+60
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+61
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+62
UF_FLAG_PRIVATE, // PLAYER_FIELD_KEYRING_SLOT_1+63
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+24
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+25
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+26
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+27
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+28
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+29
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+30
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+31
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+32
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+33
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+34
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+35
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+36
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+37
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+38
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+39
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+40
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+41
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+42
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+43
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+44
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+45
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+46
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+47
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+48
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+49
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+50
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+51
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+52
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+53
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+54
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+55
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+56
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+57
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+58
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+59
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+60
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+61
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+62
UF_FLAG_PRIVATE, // PLAYER_FIELD_CURRENCYTOKEN_SLOT_1+63
UF_FLAG_PRIVATE, // PLAYER_FARSIGHT
UF_FLAG_PRIVATE, // PLAYER_FARSIGHT+1
UF_FLAG_PRIVATE, // PLAYER__FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER__FIELD_KNOWN_TITLES+1
UF_FLAG_PRIVATE, // PLAYER__FIELD_KNOWN_TITLES1
UF_FLAG_PRIVATE, // PLAYER__FIELD_KNOWN_TITLES1+1
UF_FLAG_PRIVATE, // PLAYER__FIELD_KNOWN_TITLES2
UF_FLAG_PRIVATE, // PLAYER__FIELD_KNOWN_TITLES2+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_CURRENCIES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_CURRENCIES+1
UF_FLAG_PRIVATE, // PLAYER_XP
UF_FLAG_PRIVATE, // PLAYER_NEXT_LEVEL_XP
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+1
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+2
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+3
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+4
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+5
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+6
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+7
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+8
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+9
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+10
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+11
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+12
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+13
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+14
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+15
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+16
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+17
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+18
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+19
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+20
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+21
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+22
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+23
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+24
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+25
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+26
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+27
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+28
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+29
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+30
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+31
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+32
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+33
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+34
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+35
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+36
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+37
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+38
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+39
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+40
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+41
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+42
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+43
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+44
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+45
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+46
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+47
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+48
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+49
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+50
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+51
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+52
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+53
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+54
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+55
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+56
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+57
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+58
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+59
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+60
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+61
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+62
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+63
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+64
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+65
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+66
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+67
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+68
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+69
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+70
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+71
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+72
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+73
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+74
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+75
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+76
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+77
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+78
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+79
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+80
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+81
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+82
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+83
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+84
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+85
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+86
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+87
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+88
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+89
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+90
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+91
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+92
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+93
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+94
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+95
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+96
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+97
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+98
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+99
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+100
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+101
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+102
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+103
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+104
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+105
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+106
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+107
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+108
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+109
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+110
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+111
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+112
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+113
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+114
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+115
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+116
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+117
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+118
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+119
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+120
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+121
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+122
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+123
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+124
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+125
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+126
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+127
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+128
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+129
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+130
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+131
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+132
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+133
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+134
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+135
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+136
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+137
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+138
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+139
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+140
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+141
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+142
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+143
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+144
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+145
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+146
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+147
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+148
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+149
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+150
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+151
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+152
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+153
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+154
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+155
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+156
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+157
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+158
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+159
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+160
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+161
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+162
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+163
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+164
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+165
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+166
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+167
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+168
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+169
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+170
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+171
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+172
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+173
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+174
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+175
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+176
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+177
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+178
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+179
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+180
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+181
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+182
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+183
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+184
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+185
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+186
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+187
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+188
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+189
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+190
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+191
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+192
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+193
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+194
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+195
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+196
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+197
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+198
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+199
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+200
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+201
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+202
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+203
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+204
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+205
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+206
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+207
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+208
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+209
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+210
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+211
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+212
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+213
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+214
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+215
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+216
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+217
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+218
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+219
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+220
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+221
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+222
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+223
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+224
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+225
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+226
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+227
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+228
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+229
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+230
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+231
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+232
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+233
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+234
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+235
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+236
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+237
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+238
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+239
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+240
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+241
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+242
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+243
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+244
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+245
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+246
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+247
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+248
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+249
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+250
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+251
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+252
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+253
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+254
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+255
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+256
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+257
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+258
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+259
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+260
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+261
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+262
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+263
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+264
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+265
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+266
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+267
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+268
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+269
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+270
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+271
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+272
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+273
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+274
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+275
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+276
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+277
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+278
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+279
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+280
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+281
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+282
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+283
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+284
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+285
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+286
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+287
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+288
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+289
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+290
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+291
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+292
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+293
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+294
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+295
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+296
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+297
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+298
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+299
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+300
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+301
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+302
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+303
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+304
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+305
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+306
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+307
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+308
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+309
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+310
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+311
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+312
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+313
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+314
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+315
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+316
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+317
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+318
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+319
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+320
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+321
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+322
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+323
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+324
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+325
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+326
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+327
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+328
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+329
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+330
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+331
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+332
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+333
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+334
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+335
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+336
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+337
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+338
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+339
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+340
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+341
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+342
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+343
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+344
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+345
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+346
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+347
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+348
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+349
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+350
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+351
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+352
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+353
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+354
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+355
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+356
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+357
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+358
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+359
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+360
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+361
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+362
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+363
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+364
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+365
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+366
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+367
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+368
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+369
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+370
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+371
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+372
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+373
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+374
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+375
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+376
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+377
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+378
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+379
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+380
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+381
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+382
UF_FLAG_PRIVATE, // PLAYER_SKILL_INFO_1_1+383
UF_FLAG_PRIVATE, // PLAYER_CHARACTER_POINTS1
UF_FLAG_PRIVATE, // PLAYER_CHARACTER_POINTS2
UF_FLAG_PRIVATE, // PLAYER_TRACK_CREATURES
UF_FLAG_PRIVATE, // PLAYER_TRACK_RESOURCES
UF_FLAG_PRIVATE, // PLAYER_BLOCK_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_DODGE_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_PARRY_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_EXPERTISE
UF_FLAG_PRIVATE, // PLAYER_OFFHAND_EXPERTISE
UF_FLAG_PRIVATE, // PLAYER_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_RANGED_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_OFFHAND_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1+1
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1+2
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1+3
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1+4
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1+5
UF_FLAG_PRIVATE, // PLAYER_SPELL_CRIT_PERCENTAGE1+6
UF_FLAG_PRIVATE, // PLAYER_SHIELD_BLOCK
UF_FLAG_PRIVATE, // PLAYER_SHIELD_BLOCK_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+1
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+2
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+3
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+4
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+5
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+6
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+7
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+8
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+9
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+10
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+11
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+12
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+13
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+14
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+15
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+16
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+17
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+18
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+19
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+20
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+21
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+22
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+23
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+24
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+25
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+26
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+27
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+28
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+29
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+30
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+31
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+32
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+33
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+34
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+35
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+36
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+37
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+38
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+39
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+40
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+41
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+42
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+43
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+44
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+45
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+46
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+47
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+48
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+49
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+50
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+51
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+52
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+53
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+54
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+55
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+56
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+57
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+58
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+59
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+60
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+61
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+62
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+63
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+64
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+65
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+66
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+67
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+68
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+69
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+70
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+71
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+72
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+73
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+74
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+75
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+76
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+77
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+78
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+79
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+80
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+81
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+82
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+83
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+84
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+85
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+86
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+87
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+88
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+89
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+90
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+91
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+92
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+93
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+94
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+95
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+96
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+97
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+98
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+99
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+100
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+101
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+102
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+103
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+104
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+105
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+106
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+107
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+108
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+109
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+110
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+111
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+112
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+113
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+114
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+115
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+116
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+117
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+118
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+119
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+120
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+121
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+122
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+123
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+124
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+125
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+126
UF_FLAG_PRIVATE, // PLAYER_EXPLORED_ZONES_1+127
UF_FLAG_PRIVATE, // PLAYER_REST_STATE_EXPERIENCE
UF_FLAG_PRIVATE, // PLAYER_FIELD_COINAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_PCT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_DONE_PCT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_TARGET_RESISTANCE
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BYTES
UF_FLAG_PRIVATE, // PLAYER_AMMO_ID
UF_FLAG_PRIVATE, // PLAYER_SELF_RES_SPELL
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_MEDALS
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_KILLS
UF_FLAG_PRIVATE, // PLAYER_FIELD_TODAY_CONTRIBUTION
UF_FLAG_PRIVATE, // PLAYER_FIELD_YESTERDAY_CONTRIBUTION
UF_FLAG_PRIVATE, // PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
UF_FLAG_PRIVATE, // PLAYER_FIELD_BYTES2
UF_FLAG_PRIVATE, // PLAYER_FIELD_WATCHED_FACTION_INDEX
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_1+24
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_TEAM_INFO_1_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_HONOR_CURRENCY
UF_FLAG_PRIVATE, // PLAYER_FIELD_ARENA_CURRENCY
UF_FLAG_PRIVATE, // PLAYER_FIELD_MAX_LEVEL
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+6
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+7
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+8
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+9
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+10
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+11
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+12
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+13
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+14
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+15
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+16
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+17
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+18
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+19
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+20
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+21
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+22
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+23
UF_FLAG_PRIVATE, // PLAYER_FIELD_DAILY_QUESTS_1+24
UF_FLAG_PRIVATE, // PLAYER_RUNE_REGEN_1
UF_FLAG_PRIVATE, // PLAYER_RUNE_REGEN_1+1
UF_FLAG_PRIVATE, // PLAYER_RUNE_REGEN_1+2
UF_FLAG_PRIVATE, // PLAYER_RUNE_REGEN_1+3
UF_FLAG_PRIVATE, // PLAYER_NO_REAGENT_COST_1
UF_FLAG_PRIVATE, // PLAYER_NO_REAGENT_COST_1+1
UF_FLAG_PRIVATE, // PLAYER_NO_REAGENT_COST_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_1+5
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS_1
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS_1+1
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS_1+2
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS_1+3
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS_1+4
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS_1+5
UF_FLAG_PRIVATE, // PLAYER_GLYPHS_ENABLED
UF_FLAG_PRIVATE, // PLAYER_PET_SPELL_POWER
};
uint32 GameObjectUpdateFieldFlags[GAMEOBJECT_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID+1
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC, // OBJECT_FIELD_ENTRY
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE_X
UF_FLAG_NONE, // OBJECT_FIELD_PADDING
UF_FLAG_PUBLIC, // OBJECT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // OBJECT_FIELD_CREATED_BY+1
UF_FLAG_PUBLIC, // GAMEOBJECT_DISPLAYID
UF_FLAG_PUBLIC, // GAMEOBJECT_FLAGS
UF_FLAG_PUBLIC, // GAMEOBJECT_PARENTROTATION
UF_FLAG_PUBLIC, // GAMEOBJECT_PARENTROTATION+1
UF_FLAG_PUBLIC, // GAMEOBJECT_PARENTROTATION+2
UF_FLAG_PUBLIC, // GAMEOBJECT_PARENTROTATION+3
UF_FLAG_DYNAMIC, // GAMEOBJECT_DYNAMIC
UF_FLAG_PUBLIC, // GAMEOBJECT_FACTION
UF_FLAG_PUBLIC, // GAMEOBJECT_LEVEL
UF_FLAG_PUBLIC, // GAMEOBJECT_BYTES_1
};
uint32 DynamicObjectUpdateFieldFlags[DYNAMICOBJECT_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID+1
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC, // OBJECT_FIELD_ENTRY
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE_X
UF_FLAG_NONE, // OBJECT_FIELD_PADDING
UF_FLAG_PUBLIC, // DYNAMICOBJECT_CASTER
UF_FLAG_PUBLIC, // DYNAMICOBJECT_CASTER+1
UF_FLAG_PUBLIC, // DYNAMICOBJECT_BYTES
UF_FLAG_PUBLIC, // DYNAMICOBJECT_SPELLID
UF_FLAG_PUBLIC, // DYNAMICOBJECT_RADIUS
UF_FLAG_PUBLIC, // DYNAMICOBJECT_CASTTIME
};
uint32 CorpseUpdateFieldFlags[CORPSE_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID+1
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC, // OBJECT_FIELD_ENTRY
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE_X
UF_FLAG_NONE, // OBJECT_FIELD_PADDING
UF_FLAG_PUBLIC, // CORPSE_FIELD_OWNER
UF_FLAG_PUBLIC, // CORPSE_FIELD_OWNER+1
UF_FLAG_PUBLIC, // CORPSE_FIELD_PARTY
UF_FLAG_PUBLIC, // CORPSE_FIELD_PARTY+1
UF_FLAG_PUBLIC, // CORPSE_FIELD_DISPLAY_ID
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+1
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+2
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+3
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+4
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+5
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+6
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+7
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+8
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+9
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+10
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+11
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+12
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+13
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+14
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+15
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+16
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+17
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEM+18
UF_FLAG_PUBLIC, // CORPSE_FIELD_BYTES_1
UF_FLAG_PUBLIC, // CORPSE_FIELD_BYTES_2
UF_FLAG_PUBLIC, // CORPSE_FIELD_GUILD
UF_FLAG_PUBLIC, // CORPSE_FIELD_FLAGS
UF_FLAG_DYNAMIC, // CORPSE_FIELD_DYNAMIC_FLAGS
UF_FLAG_NONE, // CORPSE_FIELD_PAD
};
| gpl-2.0 |
allanm84/linux-fslc | fs/open.c | 24 | 27333 | /*
* linux/fs/open.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/fsnotify.h>
#include <linux/module.h>
#include <linux/tty.h>
#include <linux/namei.h>
#include <linux/backing-dev.h>
#include <linux/capability.h>
#include <linux/securebits.h>
#include <linux/security.h>
#include <linux/mount.h>
#include <linux/fcntl.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/fs.h>
#include <linux/personality.h>
#include <linux/pagemap.h>
#include <linux/syscalls.h>
#include <linux/rcupdate.h>
#include <linux/audit.h>
#include <linux/falloc.h>
#include <linux/fs_struct.h>
#include <linux/ima.h>
#include <linux/dnotify.h>
#include <linux/compat.h>
#include "internal.h"
int do_truncate(struct dentry *dentry, loff_t length, unsigned int time_attrs,
struct file *filp)
{
int ret;
struct iattr newattrs;
/* Not pretty: "inode->i_size" shouldn't really be signed. But it is. */
if (length < 0)
return -EINVAL;
newattrs.ia_size = length;
newattrs.ia_valid = ATTR_SIZE | time_attrs;
if (filp) {
newattrs.ia_file = filp;
newattrs.ia_valid |= ATTR_FILE;
}
/* Remove suid/sgid on truncate too */
ret = should_remove_suid(dentry);
if (ret)
newattrs.ia_valid |= ret | ATTR_FORCE;
mutex_lock(&dentry->d_inode->i_mutex);
/* Note any delegations or leases have already been broken: */
ret = notify_change(dentry, &newattrs, NULL);
mutex_unlock(&dentry->d_inode->i_mutex);
return ret;
}
long vfs_truncate(struct path *path, loff_t length)
{
struct inode *inode;
long error;
inode = path->dentry->d_inode;
/* For directories it's -EISDIR, for other non-regulars - -EINVAL */
if (S_ISDIR(inode->i_mode))
return -EISDIR;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
error = mnt_want_write(path->mnt);
if (error)
goto out;
error = inode_permission(inode, MAY_WRITE);
if (error)
goto mnt_drop_write_and_out;
error = -EPERM;
if (IS_APPEND(inode))
goto mnt_drop_write_and_out;
error = get_write_access(inode);
if (error)
goto mnt_drop_write_and_out;
/*
* Make sure that there are no leases. get_write_access() protects
* against the truncate racing with a lease-granting setlease().
*/
error = break_lease(inode, O_WRONLY);
if (error)
goto put_write_and_out;
error = locks_verify_truncate(inode, NULL, length);
if (!error)
error = security_path_truncate(path);
if (!error)
error = do_truncate(path->dentry, length, 0, NULL);
put_write_and_out:
put_write_access(inode);
mnt_drop_write_and_out:
mnt_drop_write(path->mnt);
out:
return error;
}
EXPORT_SYMBOL_GPL(vfs_truncate);
static long do_sys_truncate(const char __user *pathname, loff_t length)
{
unsigned int lookup_flags = LOOKUP_FOLLOW;
struct path path;
int error;
if (length < 0) /* sorry, but loff_t says... */
return -EINVAL;
retry:
error = user_path_at(AT_FDCWD, pathname, lookup_flags, &path);
if (!error) {
error = vfs_truncate(&path, length);
path_put(&path);
}
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
return error;
}
SYSCALL_DEFINE2(truncate, const char __user *, path, long, length)
{
return do_sys_truncate(path, length);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(truncate, const char __user *, path, compat_off_t, length)
{
return do_sys_truncate(path, length);
}
#endif
static long do_sys_ftruncate(unsigned int fd, loff_t length, int small)
{
struct inode *inode;
struct dentry *dentry;
struct fd f;
int error;
error = -EINVAL;
if (length < 0)
goto out;
error = -EBADF;
f = fdget(fd);
if (!f.file)
goto out;
/* explicitly opened as large or we are on 64-bit box */
if (f.file->f_flags & O_LARGEFILE)
small = 0;
dentry = f.file->f_path.dentry;
inode = dentry->d_inode;
error = -EINVAL;
if (!S_ISREG(inode->i_mode) || !(f.file->f_mode & FMODE_WRITE))
goto out_putf;
error = -EINVAL;
/* Cannot ftruncate over 2^31 bytes without large file support */
if (small && length > MAX_NON_LFS)
goto out_putf;
error = -EPERM;
if (IS_APPEND(inode))
goto out_putf;
sb_start_write(inode->i_sb);
error = locks_verify_truncate(inode, f.file, length);
if (!error)
error = security_path_truncate(&f.file->f_path);
if (!error)
error = do_truncate(dentry, length, ATTR_MTIME|ATTR_CTIME, f.file);
sb_end_write(inode->i_sb);
out_putf:
fdput(f);
out:
return error;
}
SYSCALL_DEFINE2(ftruncate, unsigned int, fd, unsigned long, length)
{
return do_sys_ftruncate(fd, length, 1);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(ftruncate, unsigned int, fd, compat_ulong_t, length)
{
return do_sys_ftruncate(fd, length, 1);
}
#endif
/* LFS versions of truncate are only needed on 32 bit machines */
#if BITS_PER_LONG == 32
SYSCALL_DEFINE2(truncate64, const char __user *, path, loff_t, length)
{
return do_sys_truncate(path, length);
}
SYSCALL_DEFINE2(ftruncate64, unsigned int, fd, loff_t, length)
{
return do_sys_ftruncate(fd, length, 0);
}
#endif /* BITS_PER_LONG == 32 */
int vfs_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
long ret;
if (offset < 0 || len <= 0)
return -EINVAL;
/* Return error if mode is not supported */
if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE))
return -EOPNOTSUPP;
/* Punch hole and zero range are mutually exclusive */
if ((mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE)) ==
(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE))
return -EOPNOTSUPP;
/* Punch hole must have keep size set */
if ((mode & FALLOC_FL_PUNCH_HOLE) &&
!(mode & FALLOC_FL_KEEP_SIZE))
return -EOPNOTSUPP;
/* Collapse range should only be used exclusively. */
if ((mode & FALLOC_FL_COLLAPSE_RANGE) &&
(mode & ~FALLOC_FL_COLLAPSE_RANGE))
return -EINVAL;
if (!(file->f_mode & FMODE_WRITE))
return -EBADF;
/*
* We can only allow pure fallocate on append only files
*/
if ((mode & ~FALLOC_FL_KEEP_SIZE) && IS_APPEND(inode))
return -EPERM;
if (IS_IMMUTABLE(inode))
return -EPERM;
/*
* We cannot allow any fallocate operation on an active swapfile
*/
if (IS_SWAPFILE(inode))
return -ETXTBSY;
/*
* Revalidate the write permissions, in case security policy has
* changed since the files were opened.
*/
ret = security_file_permission(file, MAY_WRITE);
if (ret)
return ret;
if (S_ISFIFO(inode->i_mode))
return -ESPIPE;
/*
* Let individual file system decide if it supports preallocation
* for directories or not.
*/
if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
return -ENODEV;
/* Check for wrap through zero too */
if (((offset + len) > inode->i_sb->s_maxbytes) || ((offset + len) < 0))
return -EFBIG;
if (!file->f_op->fallocate)
return -EOPNOTSUPP;
sb_start_write(inode->i_sb);
ret = file->f_op->fallocate(file, mode, offset, len);
/*
* Create inotify and fanotify events.
*
* To keep the logic simple always create events if fallocate succeeds.
* This implies that events are even created if the file size remains
* unchanged, e.g. when using flag FALLOC_FL_KEEP_SIZE.
*/
if (ret == 0)
fsnotify_modify(file);
sb_end_write(inode->i_sb);
return ret;
}
EXPORT_SYMBOL_GPL(vfs_fallocate);
SYSCALL_DEFINE4(fallocate, int, fd, int, mode, loff_t, offset, loff_t, len)
{
struct fd f = fdget(fd);
int error = -EBADF;
if (f.file) {
error = vfs_fallocate(f.file, mode, offset, len);
fdput(f);
}
return error;
}
/*
* access() needs to use the real uid/gid, not the effective uid/gid.
* We do this by temporarily clearing all FS-related capabilities and
* switching the fsuid/fsgid around to the real ones.
*/
SYSCALL_DEFINE3(faccessat, int, dfd, const char __user *, filename, int, mode)
{
const struct cred *old_cred;
struct cred *override_cred;
struct path path;
struct inode *inode;
int res;
unsigned int lookup_flags = LOOKUP_FOLLOW;
if (mode & ~S_IRWXO) /* where's F_OK, X_OK, W_OK, R_OK? */
return -EINVAL;
override_cred = prepare_creds();
if (!override_cred)
return -ENOMEM;
override_cred->fsuid = override_cred->uid;
override_cred->fsgid = override_cred->gid;
if (!issecure(SECURE_NO_SETUID_FIXUP)) {
/* Clear the capabilities if we switch to a non-root user */
kuid_t root_uid = make_kuid(override_cred->user_ns, 0);
if (!uid_eq(override_cred->uid, root_uid))
cap_clear(override_cred->cap_effective);
else
override_cred->cap_effective =
override_cred->cap_permitted;
}
old_cred = override_creds(override_cred);
retry:
res = user_path_at(dfd, filename, lookup_flags, &path);
if (res)
goto out;
inode = path.dentry->d_inode;
if ((mode & MAY_EXEC) && S_ISREG(inode->i_mode)) {
/*
* MAY_EXEC on regular files is denied if the fs is mounted
* with the "noexec" flag.
*/
res = -EACCES;
if (path.mnt->mnt_flags & MNT_NOEXEC)
goto out_path_release;
}
res = inode_permission(inode, mode | MAY_ACCESS);
/* SuS v2 requires we report a read only fs too */
if (res || !(mode & S_IWOTH) || special_file(inode->i_mode))
goto out_path_release;
/*
* This is a rare case where using __mnt_is_readonly()
* is OK without a mnt_want/drop_write() pair. Since
* no actual write to the fs is performed here, we do
* not need to telegraph to that to anyone.
*
* By doing this, we accept that this access is
* inherently racy and know that the fs may change
* state before we even see this result.
*/
if (__mnt_is_readonly(path.mnt))
res = -EROFS;
out_path_release:
path_put(&path);
if (retry_estale(res, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out:
revert_creds(old_cred);
put_cred(override_cred);
return res;
}
SYSCALL_DEFINE2(access, const char __user *, filename, int, mode)
{
return sys_faccessat(AT_FDCWD, filename, mode);
}
SYSCALL_DEFINE1(chdir, const char __user *, filename)
{
struct path path;
int error;
unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
retry:
error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
if (error)
goto out;
error = inode_permission(path.dentry->d_inode, MAY_EXEC | MAY_CHDIR);
if (error)
goto dput_and_out;
set_fs_pwd(current->fs, &path);
dput_and_out:
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out:
return error;
}
SYSCALL_DEFINE1(fchdir, unsigned int, fd)
{
struct fd f = fdget_raw(fd);
struct inode *inode;
int error = -EBADF;
error = -EBADF;
if (!f.file)
goto out;
inode = file_inode(f.file);
error = -ENOTDIR;
if (!S_ISDIR(inode->i_mode))
goto out_putf;
error = inode_permission(inode, MAY_EXEC | MAY_CHDIR);
if (!error)
set_fs_pwd(current->fs, &f.file->f_path);
out_putf:
fdput(f);
out:
return error;
}
SYSCALL_DEFINE1(chroot, const char __user *, filename)
{
struct path path;
int error;
unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
retry:
error = user_path_at(AT_FDCWD, filename, lookup_flags, &path);
if (error)
goto out;
error = inode_permission(path.dentry->d_inode, MAY_EXEC | MAY_CHDIR);
if (error)
goto dput_and_out;
error = -EPERM;
if (!ns_capable(current_user_ns(), CAP_SYS_CHROOT))
goto dput_and_out;
error = security_path_chroot(&path);
if (error)
goto dput_and_out;
set_fs_root(current->fs, &path);
error = 0;
dput_and_out:
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out:
return error;
}
static int chmod_common(struct path *path, umode_t mode)
{
struct inode *inode = path->dentry->d_inode;
struct inode *delegated_inode = NULL;
struct iattr newattrs;
int error;
error = mnt_want_write(path->mnt);
if (error)
return error;
retry_deleg:
mutex_lock(&inode->i_mutex);
error = security_path_chmod(path, mode);
if (error)
goto out_unlock;
newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
newattrs.ia_valid = ATTR_MODE | ATTR_CTIME;
error = notify_change(path->dentry, &newattrs, &delegated_inode);
out_unlock:
mutex_unlock(&inode->i_mutex);
if (delegated_inode) {
error = break_deleg_wait(&delegated_inode);
if (!error)
goto retry_deleg;
}
mnt_drop_write(path->mnt);
return error;
}
SYSCALL_DEFINE2(fchmod, unsigned int, fd, umode_t, mode)
{
struct fd f = fdget(fd);
int err = -EBADF;
if (f.file) {
audit_file(f.file);
err = chmod_common(&f.file->f_path, mode);
fdput(f);
}
return err;
}
SYSCALL_DEFINE3(fchmodat, int, dfd, const char __user *, filename, umode_t, mode)
{
struct path path;
int error;
unsigned int lookup_flags = LOOKUP_FOLLOW;
retry:
error = user_path_at(dfd, filename, lookup_flags, &path);
if (!error) {
error = chmod_common(&path, mode);
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
}
return error;
}
SYSCALL_DEFINE2(chmod, const char __user *, filename, umode_t, mode)
{
return sys_fchmodat(AT_FDCWD, filename, mode);
}
static int chown_common(struct path *path, uid_t user, gid_t group)
{
struct inode *inode = path->dentry->d_inode;
struct inode *delegated_inode = NULL;
int error;
struct iattr newattrs;
kuid_t uid;
kgid_t gid;
uid = make_kuid(current_user_ns(), user);
gid = make_kgid(current_user_ns(), group);
retry_deleg:
newattrs.ia_valid = ATTR_CTIME;
if (user != (uid_t) -1) {
if (!uid_valid(uid))
return -EINVAL;
newattrs.ia_valid |= ATTR_UID;
newattrs.ia_uid = uid;
}
if (group != (gid_t) -1) {
if (!gid_valid(gid))
return -EINVAL;
newattrs.ia_valid |= ATTR_GID;
newattrs.ia_gid = gid;
}
if (!S_ISDIR(inode->i_mode))
newattrs.ia_valid |=
ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_KILL_PRIV;
mutex_lock(&inode->i_mutex);
error = security_path_chown(path, uid, gid);
if (!error)
error = notify_change(path->dentry, &newattrs, &delegated_inode);
mutex_unlock(&inode->i_mutex);
if (delegated_inode) {
error = break_deleg_wait(&delegated_inode);
if (!error)
goto retry_deleg;
}
return error;
}
SYSCALL_DEFINE5(fchownat, int, dfd, const char __user *, filename, uid_t, user,
gid_t, group, int, flag)
{
struct path path;
int error = -EINVAL;
int lookup_flags;
if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0)
goto out;
lookup_flags = (flag & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW;
if (flag & AT_EMPTY_PATH)
lookup_flags |= LOOKUP_EMPTY;
retry:
error = user_path_at(dfd, filename, lookup_flags, &path);
if (error)
goto out;
error = mnt_want_write(path.mnt);
if (error)
goto out_release;
error = chown_common(&path, user, group);
mnt_drop_write(path.mnt);
out_release:
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out:
return error;
}
SYSCALL_DEFINE3(chown, const char __user *, filename, uid_t, user, gid_t, group)
{
return sys_fchownat(AT_FDCWD, filename, user, group, 0);
}
SYSCALL_DEFINE3(lchown, const char __user *, filename, uid_t, user, gid_t, group)
{
return sys_fchownat(AT_FDCWD, filename, user, group,
AT_SYMLINK_NOFOLLOW);
}
SYSCALL_DEFINE3(fchown, unsigned int, fd, uid_t, user, gid_t, group)
{
struct fd f = fdget(fd);
int error = -EBADF;
if (!f.file)
goto out;
error = mnt_want_write_file(f.file);
if (error)
goto out_fput;
audit_file(f.file);
error = chown_common(&f.file->f_path, user, group);
mnt_drop_write_file(f.file);
out_fput:
fdput(f);
out:
return error;
}
int open_check_o_direct(struct file *f)
{
/* NB: we're sure to have correct a_ops only after f_op->open */
if (f->f_flags & O_DIRECT) {
if (!f->f_mapping->a_ops || !f->f_mapping->a_ops->direct_IO)
return -EINVAL;
}
return 0;
}
static int do_dentry_open(struct file *f,
int (*open)(struct inode *, struct file *),
const struct cred *cred)
{
static const struct file_operations empty_fops = {};
struct inode *inode;
int error;
f->f_mode = OPEN_FMODE(f->f_flags) | FMODE_LSEEK |
FMODE_PREAD | FMODE_PWRITE;
path_get(&f->f_path);
inode = f->f_inode = f->f_path.dentry->d_inode;
f->f_mapping = inode->i_mapping;
if (unlikely(f->f_flags & O_PATH)) {
f->f_mode = FMODE_PATH;
f->f_op = &empty_fops;
return 0;
}
if (f->f_mode & FMODE_WRITE && !special_file(inode->i_mode)) {
error = get_write_access(inode);
if (unlikely(error))
goto cleanup_file;
error = __mnt_want_write(f->f_path.mnt);
if (unlikely(error)) {
put_write_access(inode);
goto cleanup_file;
}
f->f_mode |= FMODE_WRITER;
}
/* POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
if (S_ISREG(inode->i_mode))
f->f_mode |= FMODE_ATOMIC_POS;
f->f_op = fops_get(inode->i_fop);
if (unlikely(WARN_ON(!f->f_op))) {
error = -ENODEV;
goto cleanup_all;
}
error = security_file_open(f, cred);
if (error)
goto cleanup_all;
error = break_lease(inode, f->f_flags);
if (error)
goto cleanup_all;
if (!open)
open = f->f_op->open;
if (open) {
error = open(inode, f);
if (error)
goto cleanup_all;
}
if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
i_readcount_inc(inode);
if ((f->f_mode & FMODE_READ) &&
likely(f->f_op->read || f->f_op->aio_read || f->f_op->read_iter))
f->f_mode |= FMODE_CAN_READ;
if ((f->f_mode & FMODE_WRITE) &&
likely(f->f_op->write || f->f_op->aio_write || f->f_op->write_iter))
f->f_mode |= FMODE_CAN_WRITE;
f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
return 0;
cleanup_all:
fops_put(f->f_op);
if (f->f_mode & FMODE_WRITER) {
put_write_access(inode);
__mnt_drop_write(f->f_path.mnt);
}
cleanup_file:
path_put(&f->f_path);
f->f_path.mnt = NULL;
f->f_path.dentry = NULL;
f->f_inode = NULL;
return error;
}
/**
* finish_open - finish opening a file
* @file: file pointer
* @dentry: pointer to dentry
* @open: open callback
* @opened: state of open
*
* This can be used to finish opening a file passed to i_op->atomic_open().
*
* If the open callback is set to NULL, then the standard f_op->open()
* filesystem callback is substituted.
*
* NB: the dentry reference is _not_ consumed. If, for example, the dentry is
* the return value of d_splice_alias(), then the caller needs to perform dput()
* on it after finish_open().
*
* On successful return @file is a fully instantiated open file. After this, if
* an error occurs in ->atomic_open(), it needs to clean up with fput().
*
* Returns zero on success or -errno if the open failed.
*/
int finish_open(struct file *file, struct dentry *dentry,
int (*open)(struct inode *, struct file *),
int *opened)
{
int error;
BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */
file->f_path.dentry = dentry;
error = do_dentry_open(file, open, current_cred());
if (!error)
*opened |= FILE_OPENED;
return error;
}
EXPORT_SYMBOL(finish_open);
/**
* finish_no_open - finish ->atomic_open() without opening the file
*
* @file: file pointer
* @dentry: dentry or NULL (as returned from ->lookup())
*
* This can be used to set the result of a successful lookup in ->atomic_open().
*
* NB: unlike finish_open() this function does consume the dentry reference and
* the caller need not dput() it.
*
* Returns "1" which must be the return value of ->atomic_open() after having
* called this function.
*/
int finish_no_open(struct file *file, struct dentry *dentry)
{
file->f_path.dentry = dentry;
return 1;
}
EXPORT_SYMBOL(finish_no_open);
struct file *dentry_open(const struct path *path, int flags,
const struct cred *cred)
{
int error;
struct file *f;
validate_creds(cred);
/* We must always pass in a valid mount pointer. */
BUG_ON(!path->mnt);
f = get_empty_filp();
if (!IS_ERR(f)) {
f->f_flags = flags;
error = vfs_open(path, f, cred);
if (!error) {
/* from now on we need fput() to dispose of f */
error = open_check_o_direct(f);
if (error) {
fput(f);
f = ERR_PTR(error);
}
} else {
put_filp(f);
f = ERR_PTR(error);
}
}
return f;
}
EXPORT_SYMBOL(dentry_open);
/**
* vfs_open - open the file at the given path
* @path: path to open
* @filp: newly allocated file with f_flag initialized
* @cred: credentials to use
*/
int vfs_open(const struct path *path, struct file *filp,
const struct cred *cred)
{
struct inode *inode = path->dentry->d_inode;
if (inode->i_op->dentry_open)
return inode->i_op->dentry_open(path->dentry, filp, cred);
else {
filp->f_path = *path;
return do_dentry_open(filp, NULL, cred);
}
}
EXPORT_SYMBOL(vfs_open);
static inline int build_open_flags(int flags, umode_t mode, struct open_flags *op)
{
int lookup_flags = 0;
int acc_mode;
if (flags & (O_CREAT | __O_TMPFILE))
op->mode = (mode & S_IALLUGO) | S_IFREG;
else
op->mode = 0;
/* Must never be set by userspace */
flags &= ~FMODE_NONOTIFY & ~O_CLOEXEC;
/*
* O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only
* check for O_DSYNC if the need any syncing at all we enforce it's
* always set instead of having to deal with possibly weird behaviour
* for malicious applications setting only __O_SYNC.
*/
if (flags & __O_SYNC)
flags |= O_DSYNC;
if (flags & __O_TMPFILE) {
if ((flags & O_TMPFILE_MASK) != O_TMPFILE)
return -EINVAL;
acc_mode = MAY_OPEN | ACC_MODE(flags);
if (!(acc_mode & MAY_WRITE))
return -EINVAL;
} else if (flags & O_PATH) {
/*
* If we have O_PATH in the open flag. Then we
* cannot have anything other than the below set of flags
*/
flags &= O_DIRECTORY | O_NOFOLLOW | O_PATH;
acc_mode = 0;
} else {
acc_mode = MAY_OPEN | ACC_MODE(flags);
}
op->open_flag = flags;
/* O_TRUNC implies we need access checks for write permissions */
if (flags & O_TRUNC)
acc_mode |= MAY_WRITE;
/* Allow the LSM permission hook to distinguish append
access from general write access. */
if (flags & O_APPEND)
acc_mode |= MAY_APPEND;
op->acc_mode = acc_mode;
op->intent = flags & O_PATH ? 0 : LOOKUP_OPEN;
if (flags & O_CREAT) {
op->intent |= LOOKUP_CREATE;
if (flags & O_EXCL)
op->intent |= LOOKUP_EXCL;
}
if (flags & O_DIRECTORY)
lookup_flags |= LOOKUP_DIRECTORY;
if (!(flags & O_NOFOLLOW))
lookup_flags |= LOOKUP_FOLLOW;
op->lookup_flags = lookup_flags;
return 0;
}
/**
* file_open_name - open file and return file pointer
*
* @name: struct filename containing path to open
* @flags: open flags as per the open(2) second argument
* @mode: mode for the new file if O_CREAT is set, else ignored
*
* This is the helper to open a file from kernelspace if you really
* have to. But in generally you should not do this, so please move
* along, nothing to see here..
*/
struct file *file_open_name(struct filename *name, int flags, umode_t mode)
{
struct open_flags op;
int err = build_open_flags(flags, mode, &op);
return err ? ERR_PTR(err) : do_filp_open(AT_FDCWD, name, &op);
}
/**
* filp_open - open file and return file pointer
*
* @filename: path to open
* @flags: open flags as per the open(2) second argument
* @mode: mode for the new file if O_CREAT is set, else ignored
*
* This is the helper to open a file from kernelspace if you really
* have to. But in generally you should not do this, so please move
* along, nothing to see here..
*/
struct file *filp_open(const char *filename, int flags, umode_t mode)
{
struct filename *name = getname_kernel(filename);
struct file *file = ERR_CAST(name);
if (!IS_ERR(name)) {
file = file_open_name(name, flags, mode);
putname(name);
}
return file;
}
EXPORT_SYMBOL(filp_open);
struct file *file_open_root(struct dentry *dentry, struct vfsmount *mnt,
const char *filename, int flags)
{
struct open_flags op;
int err = build_open_flags(flags, 0, &op);
if (err)
return ERR_PTR(err);
if (flags & O_CREAT)
return ERR_PTR(-EINVAL);
if (!filename && (flags & O_DIRECTORY))
if (!dentry->d_inode->i_op->lookup)
return ERR_PTR(-ENOTDIR);
return do_file_open_root(dentry, mnt, filename, &op);
}
EXPORT_SYMBOL(file_open_root);
long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode)
{
struct open_flags op;
int fd = build_open_flags(flags, mode, &op);
struct filename *tmp;
if (fd)
return fd;
tmp = getname(filename);
if (IS_ERR(tmp))
return PTR_ERR(tmp);
fd = get_unused_fd_flags(flags);
if (fd >= 0) {
struct file *f = do_filp_open(dfd, tmp, &op);
if (IS_ERR(f)) {
put_unused_fd(fd);
fd = PTR_ERR(f);
} else {
fsnotify_open(f);
fd_install(fd, f);
}
}
putname(tmp);
return fd;
}
SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
{
if (force_o_largefile())
flags |= O_LARGEFILE;
return do_sys_open(AT_FDCWD, filename, flags, mode);
}
SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags,
umode_t, mode)
{
if (force_o_largefile())
flags |= O_LARGEFILE;
return do_sys_open(dfd, filename, flags, mode);
}
#ifndef __alpha__
/*
* For backward compatibility? Maybe this should be moved
* into arch/i386 instead?
*/
SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode)
{
return sys_open(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode);
}
#endif
/*
* "id" is the POSIX thread ID. We use the
* files pointer for this..
*/
int filp_close(struct file *filp, fl_owner_t id)
{
int retval = 0;
if (!file_count(filp)) {
printk(KERN_ERR "VFS: Close: file count is 0\n");
return 0;
}
if (filp->f_op->flush)
retval = filp->f_op->flush(filp, id);
if (likely(!(filp->f_mode & FMODE_PATH))) {
dnotify_flush(filp, id);
locks_remove_posix(filp, id);
}
fput(filp);
return retval;
}
EXPORT_SYMBOL(filp_close);
/*
* Careful here! We test whether the file pointer is NULL before
* releasing the fd. This ensures that one clone task can't release
* an fd while another clone is opening it.
*/
SYSCALL_DEFINE1(close, unsigned int, fd)
{
int retval = __close_fd(current->files, fd);
/* can't restart close syscall because file table entry was cleared */
if (unlikely(retval == -ERESTARTSYS ||
retval == -ERESTARTNOINTR ||
retval == -ERESTARTNOHAND ||
retval == -ERESTART_RESTARTBLOCK))
retval = -EINTR;
return retval;
}
EXPORT_SYMBOL(sys_close);
/*
* This routine simulates a hangup on the tty, to arrange that users
* are given clean terminals at login time.
*/
SYSCALL_DEFINE0(vhangup)
{
if (capable(CAP_SYS_TTY_CONFIG)) {
tty_vhangup_self();
return 0;
}
return -EPERM;
}
/*
* Called when an inode is about to be open.
* We use this to disallow opening large files on 32bit systems if
* the caller didn't specify O_LARGEFILE. On 64bit systems we force
* on this flag in sys_open.
*/
int generic_file_open(struct inode * inode, struct file * filp)
{
if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
return -EOVERFLOW;
return 0;
}
EXPORT_SYMBOL(generic_file_open);
/*
* This is used by subsystems that don't want seekable
* file descriptors. The function is not supposed to ever fail, the only
* reason it returns an 'int' and not 'void' is so that it can be plugged
* directly into file_operations structure.
*/
int nonseekable_open(struct inode *inode, struct file *filp)
{
filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
return 0;
}
EXPORT_SYMBOL(nonseekable_open);
| gpl-2.0 |
hgl888/linux | drivers/usb/gadget/function/u_ether.c | 24 | 29390 | /*
* u_ether.c -- Ethernet-over-USB link layer utilities for Gadget stack
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
* Copyright (C) 2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
/* #define VERBOSE_DEBUG */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/device.h>
#include <linux/ctype.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include "u_ether.h"
/*
* This component encapsulates the Ethernet link glue needed to provide
* one (!) network link through the USB gadget stack, normally "usb0".
*
* The control and data models are handled by the function driver which
* connects to this code; such as CDC Ethernet (ECM or EEM),
* "CDC Subset", or RNDIS. That includes all descriptor and endpoint
* management.
*
* Link level addressing is handled by this component using module
* parameters; if no such parameters are provided, random link level
* addresses are used. Each end of the link uses one address. The
* host end address is exported in various ways, and is often recorded
* in configuration databases.
*
* The driver which assembles each configuration using such a link is
* responsible for ensuring that each configuration includes at most one
* instance of is network link. (The network layer provides ways for
* this single "physical" link to be used by multiple virtual links.)
*/
#define UETH__VERSION "29-May-2008"
/* Experiments show that both Linux and Windows hosts allow up to 16k
* frame sizes. Set the max size to 15k+52 to prevent allocating 32k
* blocks and still have efficient handling. */
#define GETHER_MAX_ETH_FRAME_LEN 15412
struct eth_dev {
/* lock is held while accessing port_usb
*/
spinlock_t lock;
struct gether *port_usb;
struct net_device *net;
struct usb_gadget *gadget;
spinlock_t req_lock; /* guard {rx,tx}_reqs */
struct list_head tx_reqs, rx_reqs;
atomic_t tx_qlen;
struct sk_buff_head rx_frames;
unsigned qmult;
unsigned header_len;
struct sk_buff *(*wrap)(struct gether *, struct sk_buff *skb);
int (*unwrap)(struct gether *,
struct sk_buff *skb,
struct sk_buff_head *list);
struct work_struct work;
unsigned long todo;
#define WORK_RX_MEMORY 0
bool zlp;
bool no_skb_reserve;
u8 host_mac[ETH_ALEN];
u8 dev_mac[ETH_ALEN];
};
/*-------------------------------------------------------------------------*/
#define RX_EXTRA 20 /* bytes guarding against rx overflows */
#define DEFAULT_QLEN 2 /* double buffering by default */
/* for dual-speed hardware, use deeper queues at high/super speed */
static inline int qlen(struct usb_gadget *gadget, unsigned qmult)
{
if (gadget_is_dualspeed(gadget) && (gadget->speed == USB_SPEED_HIGH ||
gadget->speed == USB_SPEED_SUPER))
return qmult * DEFAULT_QLEN;
else
return DEFAULT_QLEN;
}
/*-------------------------------------------------------------------------*/
/* REVISIT there must be a better way than having two sets
* of debug calls ...
*/
#undef DBG
#undef VDBG
#undef ERROR
#undef INFO
#define xprintk(d, level, fmt, args...) \
printk(level "%s: " fmt , (d)->net->name , ## args)
#ifdef DEBUG
#undef DEBUG
#define DBG(dev, fmt, args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev, fmt, args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE_DEBUG
#define VDBG DBG
#else
#define VDBG(dev, fmt, args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev, fmt, args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define INFO(dev, fmt, args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*-------------------------------------------------------------------------*/
/* NETWORK DRIVER HOOKUP (to the layer above this driver) */
static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p)
{
struct eth_dev *dev = netdev_priv(net);
strlcpy(p->driver, "g_ether", sizeof(p->driver));
strlcpy(p->version, UETH__VERSION, sizeof(p->version));
strlcpy(p->fw_version, dev->gadget->name, sizeof(p->fw_version));
strlcpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof(p->bus_info));
}
/* REVISIT can also support:
* - WOL (by tracking suspends and issuing remote wakeup)
* - msglevel (implies updated messaging)
* - ... probably more ethtool ops
*/
static const struct ethtool_ops ops = {
.get_drvinfo = eth_get_drvinfo,
.get_link = ethtool_op_get_link,
};
static void defer_kevent(struct eth_dev *dev, int flag)
{
if (test_and_set_bit(flag, &dev->todo))
return;
if (!schedule_work(&dev->work))
ERROR(dev, "kevent %d may have been dropped\n", flag);
else
DBG(dev, "kevent %d scheduled\n", flag);
}
static void rx_complete(struct usb_ep *ep, struct usb_request *req);
static int
rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags)
{
struct sk_buff *skb;
int retval = -ENOMEM;
size_t size = 0;
struct usb_ep *out;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
out = dev->port_usb->out_ep;
else
out = NULL;
spin_unlock_irqrestore(&dev->lock, flags);
if (!out)
return -ENOTCONN;
/* Padding up to RX_EXTRA handles minor disagreements with host.
* Normally we use the USB "terminate on short read" convention;
* so allow up to (N*maxpacket), since that memory is normally
* already allocated. Some hardware doesn't deal well with short
* reads (e.g. DMA must be N*maxpacket), so for now don't trim a
* byte off the end (to force hardware errors on overflow).
*
* RNDIS uses internal framing, and explicitly allows senders to
* pad to end-of-packet. That's potentially nice for speed, but
* means receivers can't recover lost synch on their own (because
* new packets don't only start after a short RX).
*/
size += sizeof(struct ethhdr) + dev->net->mtu + RX_EXTRA;
size += dev->port_usb->header_len;
size += out->maxpacket - 1;
size -= size % out->maxpacket;
if (dev->port_usb->is_fixed)
size = max_t(size_t, size, dev->port_usb->fixed_out_len);
skb = __netdev_alloc_skb(dev->net, size + NET_IP_ALIGN, gfp_flags);
if (skb == NULL) {
DBG(dev, "no rx skb\n");
goto enomem;
}
/* Some platforms perform better when IP packets are aligned,
* but on at least one, checksumming fails otherwise. Note:
* RNDIS headers involve variable numbers of LE32 values.
*/
if (likely(!dev->no_skb_reserve))
skb_reserve(skb, NET_IP_ALIGN);
req->buf = skb->data;
req->length = size;
req->complete = rx_complete;
req->context = skb;
retval = usb_ep_queue(out, req, gfp_flags);
if (retval == -ENOMEM)
enomem:
defer_kevent(dev, WORK_RX_MEMORY);
if (retval) {
DBG(dev, "rx submit --> %d\n", retval);
if (skb)
dev_kfree_skb_any(skb);
spin_lock_irqsave(&dev->req_lock, flags);
list_add(&req->list, &dev->rx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
}
return retval;
}
static void rx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct sk_buff *skb = req->context, *skb2;
struct eth_dev *dev = ep->driver_data;
int status = req->status;
switch (status) {
/* normal completion */
case 0:
skb_put(skb, req->actual);
if (dev->unwrap) {
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
status = dev->unwrap(dev->port_usb,
skb,
&dev->rx_frames);
} else {
dev_kfree_skb_any(skb);
status = -ENOTCONN;
}
spin_unlock_irqrestore(&dev->lock, flags);
} else {
skb_queue_tail(&dev->rx_frames, skb);
}
skb = NULL;
skb2 = skb_dequeue(&dev->rx_frames);
while (skb2) {
if (status < 0
|| ETH_HLEN > skb2->len
|| skb2->len > GETHER_MAX_ETH_FRAME_LEN) {
dev->net->stats.rx_errors++;
dev->net->stats.rx_length_errors++;
DBG(dev, "rx length %d\n", skb2->len);
dev_kfree_skb_any(skb2);
goto next_frame;
}
skb2->protocol = eth_type_trans(skb2, dev->net);
dev->net->stats.rx_packets++;
dev->net->stats.rx_bytes += skb2->len;
/* no buffer copies needed, unless hardware can't
* use skb buffers.
*/
status = netif_rx(skb2);
next_frame:
skb2 = skb_dequeue(&dev->rx_frames);
}
break;
/* software-driven interface shutdown */
case -ECONNRESET: /* unlink */
case -ESHUTDOWN: /* disconnect etc */
VDBG(dev, "rx shutdown, code %d\n", status);
goto quiesce;
/* for hardware automagic (such as pxa) */
case -ECONNABORTED: /* endpoint reset */
DBG(dev, "rx %s reset\n", ep->name);
defer_kevent(dev, WORK_RX_MEMORY);
quiesce:
dev_kfree_skb_any(skb);
goto clean;
/* data overrun */
case -EOVERFLOW:
dev->net->stats.rx_over_errors++;
/* FALLTHROUGH */
default:
dev->net->stats.rx_errors++;
DBG(dev, "rx status %d\n", status);
break;
}
if (skb)
dev_kfree_skb_any(skb);
if (!netif_running(dev->net)) {
clean:
spin_lock(&dev->req_lock);
list_add(&req->list, &dev->rx_reqs);
spin_unlock(&dev->req_lock);
req = NULL;
}
if (req)
rx_submit(dev, req, GFP_ATOMIC);
}
static int prealloc(struct list_head *list, struct usb_ep *ep, unsigned n)
{
unsigned i;
struct usb_request *req;
if (!n)
return -ENOMEM;
/* queue/recycle up to N requests */
i = n;
list_for_each_entry(req, list, list) {
if (i-- == 0)
goto extra;
}
while (i--) {
req = usb_ep_alloc_request(ep, GFP_ATOMIC);
if (!req)
return list_empty(list) ? -ENOMEM : 0;
list_add(&req->list, list);
}
return 0;
extra:
/* free extras */
for (;;) {
struct list_head *next;
next = req->list.next;
list_del(&req->list);
usb_ep_free_request(ep, req);
if (next == list)
break;
req = container_of(next, struct usb_request, list);
}
return 0;
}
static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n)
{
int status;
spin_lock(&dev->req_lock);
status = prealloc(&dev->tx_reqs, link->in_ep, n);
if (status < 0)
goto fail;
status = prealloc(&dev->rx_reqs, link->out_ep, n);
if (status < 0)
goto fail;
goto done;
fail:
DBG(dev, "can't alloc requests\n");
done:
spin_unlock(&dev->req_lock);
return status;
}
static void rx_fill(struct eth_dev *dev, gfp_t gfp_flags)
{
struct usb_request *req;
unsigned long flags;
/* fill unused rxq slots with some skb */
spin_lock_irqsave(&dev->req_lock, flags);
while (!list_empty(&dev->rx_reqs)) {
req = container_of(dev->rx_reqs.next,
struct usb_request, list);
list_del_init(&req->list);
spin_unlock_irqrestore(&dev->req_lock, flags);
if (rx_submit(dev, req, gfp_flags) < 0) {
defer_kevent(dev, WORK_RX_MEMORY);
return;
}
spin_lock_irqsave(&dev->req_lock, flags);
}
spin_unlock_irqrestore(&dev->req_lock, flags);
}
static void eth_work(struct work_struct *work)
{
struct eth_dev *dev = container_of(work, struct eth_dev, work);
if (test_and_clear_bit(WORK_RX_MEMORY, &dev->todo)) {
if (netif_running(dev->net))
rx_fill(dev, GFP_KERNEL);
}
if (dev->todo)
DBG(dev, "work done, flags = 0x%lx\n", dev->todo);
}
static void tx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct sk_buff *skb = req->context;
struct eth_dev *dev = ep->driver_data;
switch (req->status) {
default:
dev->net->stats.tx_errors++;
VDBG(dev, "tx err %d\n", req->status);
/* FALLTHROUGH */
case -ECONNRESET: /* unlink */
case -ESHUTDOWN: /* disconnect etc */
dev_kfree_skb_any(skb);
break;
case 0:
dev->net->stats.tx_bytes += skb->len;
dev_consume_skb_any(skb);
}
dev->net->stats.tx_packets++;
spin_lock(&dev->req_lock);
list_add(&req->list, &dev->tx_reqs);
spin_unlock(&dev->req_lock);
atomic_dec(&dev->tx_qlen);
if (netif_carrier_ok(dev->net))
netif_wake_queue(dev->net);
}
static inline int is_promisc(u16 cdc_filter)
{
return cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
}
static netdev_tx_t eth_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
int length = 0;
int retval;
struct usb_request *req = NULL;
unsigned long flags;
struct usb_ep *in;
u16 cdc_filter;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
in = dev->port_usb->in_ep;
cdc_filter = dev->port_usb->cdc_filter;
} else {
in = NULL;
cdc_filter = 0;
}
spin_unlock_irqrestore(&dev->lock, flags);
if (skb && !in) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* apply outgoing CDC or RNDIS filters */
if (skb && !is_promisc(cdc_filter)) {
u8 *dest = skb->data;
if (is_multicast_ether_addr(dest)) {
u16 type;
/* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
* SET_ETHERNET_MULTICAST_FILTERS requests
*/
if (is_broadcast_ether_addr(dest))
type = USB_CDC_PACKET_TYPE_BROADCAST;
else
type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
if (!(cdc_filter & type)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
}
/* ignores USB_CDC_PACKET_TYPE_DIRECTED */
}
spin_lock_irqsave(&dev->req_lock, flags);
/*
* this freelist can be empty if an interrupt triggered disconnect()
* and reconfigured the gadget (shutting down this queue) after the
* network stack decided to xmit but before we got the spinlock.
*/
if (list_empty(&dev->tx_reqs)) {
spin_unlock_irqrestore(&dev->req_lock, flags);
return NETDEV_TX_BUSY;
}
req = container_of(dev->tx_reqs.next, struct usb_request, list);
list_del(&req->list);
/* temporarily stop TX queue when the freelist empties */
if (list_empty(&dev->tx_reqs))
netif_stop_queue(net);
spin_unlock_irqrestore(&dev->req_lock, flags);
/* no buffer copies needed, unless the network stack did it
* or the hardware can't use skb buffers.
* or there's not enough space for extra headers we need
*/
if (dev->wrap) {
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
skb = dev->wrap(dev->port_usb, skb);
spin_unlock_irqrestore(&dev->lock, flags);
if (!skb) {
/* Multi frame CDC protocols may store the frame for
* later which is not a dropped frame.
*/
if (dev->port_usb &&
dev->port_usb->supports_multi_frame)
goto multiframe;
goto drop;
}
}
length = skb->len;
req->buf = skb->data;
req->context = skb;
req->complete = tx_complete;
/* NCM requires no zlp if transfer is dwNtbInMaxSize */
if (dev->port_usb &&
dev->port_usb->is_fixed &&
length == dev->port_usb->fixed_in_len &&
(length % in->maxpacket) == 0)
req->zero = 0;
else
req->zero = 1;
/* use zlp framing on tx for strict CDC-Ether conformance,
* though any robust network rx path ignores extra padding.
* and some hardware doesn't like to write zlps.
*/
if (req->zero && !dev->zlp && (length % in->maxpacket) == 0)
length++;
req->length = length;
retval = usb_ep_queue(in, req, GFP_ATOMIC);
switch (retval) {
default:
DBG(dev, "tx queue err %d\n", retval);
break;
case 0:
netif_trans_update(net);
atomic_inc(&dev->tx_qlen);
}
if (retval) {
dev_kfree_skb_any(skb);
drop:
dev->net->stats.tx_dropped++;
multiframe:
spin_lock_irqsave(&dev->req_lock, flags);
if (list_empty(&dev->tx_reqs))
netif_start_queue(net);
list_add(&req->list, &dev->tx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
}
return NETDEV_TX_OK;
}
/*-------------------------------------------------------------------------*/
static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
{
DBG(dev, "%s\n", __func__);
/* fill the rx queue */
rx_fill(dev, gfp_flags);
/* and open the tx floodgates */
atomic_set(&dev->tx_qlen, 0);
netif_wake_queue(dev->net);
}
static int eth_open(struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
struct gether *link;
DBG(dev, "%s\n", __func__);
if (netif_carrier_ok(dev->net))
eth_start(dev, GFP_KERNEL);
spin_lock_irq(&dev->lock);
link = dev->port_usb;
if (link && link->open)
link->open(link);
spin_unlock_irq(&dev->lock);
return 0;
}
static int eth_stop(struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
unsigned long flags;
VDBG(dev, "%s\n", __func__);
netif_stop_queue(net);
DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n",
dev->net->stats.rx_packets, dev->net->stats.tx_packets,
dev->net->stats.rx_errors, dev->net->stats.tx_errors
);
/* ensure there are no more active requests */
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
struct gether *link = dev->port_usb;
const struct usb_endpoint_descriptor *in;
const struct usb_endpoint_descriptor *out;
if (link->close)
link->close(link);
/* NOTE: we have no abort-queue primitive we could use
* to cancel all pending I/O. Instead, we disable then
* reenable the endpoints ... this idiom may leave toggle
* wrong, but that's a self-correcting error.
*
* REVISIT: we *COULD* just let the transfers complete at
* their own pace; the network stack can handle old packets.
* For the moment we leave this here, since it works.
*/
in = link->in_ep->desc;
out = link->out_ep->desc;
usb_ep_disable(link->in_ep);
usb_ep_disable(link->out_ep);
if (netif_carrier_ok(net)) {
DBG(dev, "host still using in/out endpoints\n");
link->in_ep->desc = in;
link->out_ep->desc = out;
usb_ep_enable(link->in_ep);
usb_ep_enable(link->out_ep);
}
}
spin_unlock_irqrestore(&dev->lock, flags);
return 0;
}
/*-------------------------------------------------------------------------*/
static int get_ether_addr(const char *str, u8 *dev_addr)
{
if (str) {
unsigned i;
for (i = 0; i < 6; i++) {
unsigned char num;
if ((*str == '.') || (*str == ':'))
str++;
num = hex_to_bin(*str++) << 4;
num |= hex_to_bin(*str++);
dev_addr [i] = num;
}
if (is_valid_ether_addr(dev_addr))
return 0;
}
eth_random_addr(dev_addr);
return 1;
}
static int get_ether_addr_str(u8 dev_addr[ETH_ALEN], char *str, int len)
{
if (len < 18)
return -EINVAL;
snprintf(str, len, "%pM", dev_addr);
return 18;
}
static const struct net_device_ops eth_netdev_ops = {
.ndo_open = eth_open,
.ndo_stop = eth_stop,
.ndo_start_xmit = eth_start_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static struct device_type gadget_type = {
.name = "gadget",
};
/**
* gether_setup_name - initialize one ethernet-over-usb link
* @g: gadget to associated with these links
* @ethaddr: NULL, or a buffer in which the ethernet address of the
* host side of the link is recorded
* @netname: name for network device (for example, "usb")
* Context: may sleep
*
* This sets up the single network link that may be exported by a
* gadget driver using this framework. The link layer addresses are
* set up using module parameters.
*
* Returns an eth_dev pointer on success, or an ERR_PTR on failure.
*/
struct eth_dev *gether_setup_name(struct usb_gadget *g,
const char *dev_addr, const char *host_addr,
u8 ethaddr[ETH_ALEN], unsigned qmult, const char *netname)
{
struct eth_dev *dev;
struct net_device *net;
int status;
net = alloc_etherdev(sizeof *dev);
if (!net)
return ERR_PTR(-ENOMEM);
dev = netdev_priv(net);
spin_lock_init(&dev->lock);
spin_lock_init(&dev->req_lock);
INIT_WORK(&dev->work, eth_work);
INIT_LIST_HEAD(&dev->tx_reqs);
INIT_LIST_HEAD(&dev->rx_reqs);
skb_queue_head_init(&dev->rx_frames);
/* network device setup */
dev->net = net;
dev->qmult = qmult;
snprintf(net->name, sizeof(net->name), "%s%%d", netname);
if (get_ether_addr(dev_addr, net->dev_addr))
dev_warn(&g->dev,
"using random %s ethernet address\n", "self");
if (get_ether_addr(host_addr, dev->host_mac))
dev_warn(&g->dev,
"using random %s ethernet address\n", "host");
if (ethaddr)
memcpy(ethaddr, dev->host_mac, ETH_ALEN);
net->netdev_ops = ð_netdev_ops;
net->ethtool_ops = &ops;
/* MTU range: 14 - 15412 */
net->min_mtu = ETH_HLEN;
net->max_mtu = GETHER_MAX_ETH_FRAME_LEN;
dev->gadget = g;
SET_NETDEV_DEV(net, &g->dev);
SET_NETDEV_DEVTYPE(net, &gadget_type);
status = register_netdev(net);
if (status < 0) {
dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
free_netdev(net);
dev = ERR_PTR(status);
} else {
INFO(dev, "MAC %pM\n", net->dev_addr);
INFO(dev, "HOST MAC %pM\n", dev->host_mac);
/*
* two kinds of host-initiated state changes:
* - iff DATA transfer is active, carrier is "on"
* - tx queueing enabled if open *and* carrier is "on"
*/
netif_carrier_off(net);
}
return dev;
}
EXPORT_SYMBOL_GPL(gether_setup_name);
struct net_device *gether_setup_name_default(const char *netname)
{
struct net_device *net;
struct eth_dev *dev;
net = alloc_etherdev(sizeof(*dev));
if (!net)
return ERR_PTR(-ENOMEM);
dev = netdev_priv(net);
spin_lock_init(&dev->lock);
spin_lock_init(&dev->req_lock);
INIT_WORK(&dev->work, eth_work);
INIT_LIST_HEAD(&dev->tx_reqs);
INIT_LIST_HEAD(&dev->rx_reqs);
skb_queue_head_init(&dev->rx_frames);
/* network device setup */
dev->net = net;
dev->qmult = QMULT_DEFAULT;
snprintf(net->name, sizeof(net->name), "%s%%d", netname);
eth_random_addr(dev->dev_mac);
pr_warn("using random %s ethernet address\n", "self");
eth_random_addr(dev->host_mac);
pr_warn("using random %s ethernet address\n", "host");
net->netdev_ops = ð_netdev_ops;
net->ethtool_ops = &ops;
SET_NETDEV_DEVTYPE(net, &gadget_type);
return net;
}
EXPORT_SYMBOL_GPL(gether_setup_name_default);
int gether_register_netdev(struct net_device *net)
{
struct eth_dev *dev;
struct usb_gadget *g;
struct sockaddr sa;
int status;
if (!net->dev.parent)
return -EINVAL;
dev = netdev_priv(net);
g = dev->gadget;
status = register_netdev(net);
if (status < 0) {
dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
return status;
} else {
INFO(dev, "HOST MAC %pM\n", dev->host_mac);
/* two kinds of host-initiated state changes:
* - iff DATA transfer is active, carrier is "on"
* - tx queueing enabled if open *and* carrier is "on"
*/
netif_carrier_off(net);
}
sa.sa_family = net->type;
memcpy(sa.sa_data, dev->dev_mac, ETH_ALEN);
rtnl_lock();
status = dev_set_mac_address(net, &sa);
rtnl_unlock();
if (status)
pr_warn("cannot set self ethernet address: %d\n", status);
else
INFO(dev, "MAC %pM\n", dev->dev_mac);
return status;
}
EXPORT_SYMBOL_GPL(gether_register_netdev);
void gether_set_gadget(struct net_device *net, struct usb_gadget *g)
{
struct eth_dev *dev;
dev = netdev_priv(net);
dev->gadget = g;
SET_NETDEV_DEV(net, &g->dev);
}
EXPORT_SYMBOL_GPL(gether_set_gadget);
int gether_set_dev_addr(struct net_device *net, const char *dev_addr)
{
struct eth_dev *dev;
u8 new_addr[ETH_ALEN];
dev = netdev_priv(net);
if (get_ether_addr(dev_addr, new_addr))
return -EINVAL;
memcpy(dev->dev_mac, new_addr, ETH_ALEN);
return 0;
}
EXPORT_SYMBOL_GPL(gether_set_dev_addr);
int gether_get_dev_addr(struct net_device *net, char *dev_addr, int len)
{
struct eth_dev *dev;
int ret;
dev = netdev_priv(net);
ret = get_ether_addr_str(dev->dev_mac, dev_addr, len);
if (ret + 1 < len) {
dev_addr[ret++] = '\n';
dev_addr[ret] = '\0';
}
return ret;
}
EXPORT_SYMBOL_GPL(gether_get_dev_addr);
int gether_set_host_addr(struct net_device *net, const char *host_addr)
{
struct eth_dev *dev;
u8 new_addr[ETH_ALEN];
dev = netdev_priv(net);
if (get_ether_addr(host_addr, new_addr))
return -EINVAL;
memcpy(dev->host_mac, new_addr, ETH_ALEN);
return 0;
}
EXPORT_SYMBOL_GPL(gether_set_host_addr);
int gether_get_host_addr(struct net_device *net, char *host_addr, int len)
{
struct eth_dev *dev;
int ret;
dev = netdev_priv(net);
ret = get_ether_addr_str(dev->host_mac, host_addr, len);
if (ret + 1 < len) {
host_addr[ret++] = '\n';
host_addr[ret] = '\0';
}
return ret;
}
EXPORT_SYMBOL_GPL(gether_get_host_addr);
int gether_get_host_addr_cdc(struct net_device *net, char *host_addr, int len)
{
struct eth_dev *dev;
if (len < 13)
return -EINVAL;
dev = netdev_priv(net);
snprintf(host_addr, len, "%pm", dev->host_mac);
return strlen(host_addr);
}
EXPORT_SYMBOL_GPL(gether_get_host_addr_cdc);
void gether_get_host_addr_u8(struct net_device *net, u8 host_mac[ETH_ALEN])
{
struct eth_dev *dev;
dev = netdev_priv(net);
memcpy(host_mac, dev->host_mac, ETH_ALEN);
}
EXPORT_SYMBOL_GPL(gether_get_host_addr_u8);
void gether_set_qmult(struct net_device *net, unsigned qmult)
{
struct eth_dev *dev;
dev = netdev_priv(net);
dev->qmult = qmult;
}
EXPORT_SYMBOL_GPL(gether_set_qmult);
unsigned gether_get_qmult(struct net_device *net)
{
struct eth_dev *dev;
dev = netdev_priv(net);
return dev->qmult;
}
EXPORT_SYMBOL_GPL(gether_get_qmult);
int gether_get_ifname(struct net_device *net, char *name, int len)
{
int ret;
rtnl_lock();
ret = snprintf(name, len, "%s\n", netdev_name(net));
rtnl_unlock();
return ret < len ? ret : len;
}
EXPORT_SYMBOL_GPL(gether_get_ifname);
/**
* gether_cleanup - remove Ethernet-over-USB device
* Context: may sleep
*
* This is called to free all resources allocated by @gether_setup().
*/
void gether_cleanup(struct eth_dev *dev)
{
if (!dev)
return;
unregister_netdev(dev->net);
flush_work(&dev->work);
free_netdev(dev->net);
}
EXPORT_SYMBOL_GPL(gether_cleanup);
/**
* gether_connect - notify network layer that USB link is active
* @link: the USB link, set up with endpoints, descriptors matching
* current device speed, and any framing wrapper(s) set up.
* Context: irqs blocked
*
* This is called to activate endpoints and let the network layer know
* the connection is active ("carrier detect"). It may cause the I/O
* queues to open and start letting network packets flow, but will in
* any case activate the endpoints so that they respond properly to the
* USB host.
*
* Verify net_device pointer returned using IS_ERR(). If it doesn't
* indicate some error code (negative errno), ep->driver_data values
* have been overwritten.
*/
struct net_device *gether_connect(struct gether *link)
{
struct eth_dev *dev = link->ioport;
int result = 0;
if (!dev)
return ERR_PTR(-EINVAL);
link->in_ep->driver_data = dev;
result = usb_ep_enable(link->in_ep);
if (result != 0) {
DBG(dev, "enable %s --> %d\n",
link->in_ep->name, result);
goto fail0;
}
link->out_ep->driver_data = dev;
result = usb_ep_enable(link->out_ep);
if (result != 0) {
DBG(dev, "enable %s --> %d\n",
link->out_ep->name, result);
goto fail1;
}
if (result == 0)
result = alloc_requests(dev, link, qlen(dev->gadget,
dev->qmult));
if (result == 0) {
dev->zlp = link->is_zlp_ok;
dev->no_skb_reserve = link->no_skb_reserve;
DBG(dev, "qlen %d\n", qlen(dev->gadget, dev->qmult));
dev->header_len = link->header_len;
dev->unwrap = link->unwrap;
dev->wrap = link->wrap;
spin_lock(&dev->lock);
dev->port_usb = link;
if (netif_running(dev->net)) {
if (link->open)
link->open(link);
} else {
if (link->close)
link->close(link);
}
spin_unlock(&dev->lock);
netif_carrier_on(dev->net);
if (netif_running(dev->net))
eth_start(dev, GFP_ATOMIC);
/* on error, disable any endpoints */
} else {
(void) usb_ep_disable(link->out_ep);
fail1:
(void) usb_ep_disable(link->in_ep);
}
fail0:
/* caller is responsible for cleanup on error */
if (result < 0)
return ERR_PTR(result);
return dev->net;
}
EXPORT_SYMBOL_GPL(gether_connect);
/**
* gether_disconnect - notify network layer that USB link is inactive
* @link: the USB link, on which gether_connect() was called
* Context: irqs blocked
*
* This is called to deactivate endpoints and let the network layer know
* the connection went inactive ("no carrier").
*
* On return, the state is as if gether_connect() had never been called.
* The endpoints are inactive, and accordingly without active USB I/O.
* Pointers to endpoint descriptors and endpoint private data are nulled.
*/
void gether_disconnect(struct gether *link)
{
struct eth_dev *dev = link->ioport;
struct usb_request *req;
WARN_ON(!dev);
if (!dev)
return;
DBG(dev, "%s\n", __func__);
netif_stop_queue(dev->net);
netif_carrier_off(dev->net);
/* disable endpoints, forcing (synchronous) completion
* of all pending i/o. then free the request objects
* and forget about the endpoints.
*/
usb_ep_disable(link->in_ep);
spin_lock(&dev->req_lock);
while (!list_empty(&dev->tx_reqs)) {
req = container_of(dev->tx_reqs.next,
struct usb_request, list);
list_del(&req->list);
spin_unlock(&dev->req_lock);
usb_ep_free_request(link->in_ep, req);
spin_lock(&dev->req_lock);
}
spin_unlock(&dev->req_lock);
link->in_ep->desc = NULL;
usb_ep_disable(link->out_ep);
spin_lock(&dev->req_lock);
while (!list_empty(&dev->rx_reqs)) {
req = container_of(dev->rx_reqs.next,
struct usb_request, list);
list_del(&req->list);
spin_unlock(&dev->req_lock);
usb_ep_free_request(link->out_ep, req);
spin_lock(&dev->req_lock);
}
spin_unlock(&dev->req_lock);
link->out_ep->desc = NULL;
/* finish forgetting about this USB link episode */
dev->header_len = 0;
dev->unwrap = NULL;
dev->wrap = NULL;
spin_lock(&dev->lock);
dev->port_usb = NULL;
spin_unlock(&dev->lock);
}
EXPORT_SYMBOL_GPL(gether_disconnect);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Brownell");
| gpl-2.0 |
vcaputo/systemd | src/core/dbus-socket.c | 24 | 10595 | /***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include "alloc-util.h"
#include "bus-util.h"
#include "dbus-cgroup.h"
#include "dbus-execute.h"
#include "dbus-socket.h"
#include "socket.h"
#include "string-util.h"
#include "unit.h"
static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_result, socket_result, SocketResult);
static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_bind_ipv6_only, socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
static int property_get_listen(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
Socket *s = SOCKET(userdata);
SocketPort *p;
int r;
assert(bus);
assert(reply);
assert(s);
r = sd_bus_message_open_container(reply, 'a', "(ss)");
if (r < 0)
return r;
LIST_FOREACH(port, p, s->ports) {
_cleanup_free_ char *address = NULL;
const char *a;
switch (p->type) {
case SOCKET_SOCKET: {
r = socket_address_print(&p->address, &address);
if (r)
return r;
a = address;
break;
}
case SOCKET_SPECIAL:
case SOCKET_MQUEUE:
case SOCKET_FIFO:
case SOCKET_USB_FUNCTION:
a = p->path;
break;
default:
assert_not_reached("Unknown socket type");
}
r = sd_bus_message_append(reply, "(ss)", socket_port_type_to_string(p), a);
if (r < 0)
return r;
}
return sd_bus_message_close_container(reply);
}
static int property_get_fdname(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
Socket *s = SOCKET(userdata);
assert(bus);
assert(reply);
assert(s);
return sd_bus_message_append(reply, "s", socket_fdname(s));
}
const sd_bus_vtable bus_socket_vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_PROPERTY("BindIPv6Only", "s", property_get_bind_ipv6_only, offsetof(Socket, bind_ipv6_only), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Backlog", "u", bus_property_get_unsigned, offsetof(Socket, backlog), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("TimeoutUSec", "t", bus_property_get_usec, offsetof(Socket, timeout_usec), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("BindToDevice", "s", NULL, offsetof(Socket, bind_to_device), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SocketUser", "s", NULL, offsetof(Socket, user), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SocketGroup", "s", NULL, offsetof(Socket, group), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SocketMode", "u", bus_property_get_mode, offsetof(Socket, socket_mode), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("DirectoryMode", "u", bus_property_get_mode, offsetof(Socket, directory_mode), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Accept", "b", bus_property_get_bool, offsetof(Socket, accept), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Writable", "b", bus_property_get_bool, offsetof(Socket, writable), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("KeepAlive", "b", bus_property_get_bool, offsetof(Socket, keep_alive), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("KeepAliveTimeUSec", "t", bus_property_get_usec, offsetof(Socket, keep_alive_time), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("KeepAliveIntervalUSec", "t", bus_property_get_usec, offsetof(Socket, keep_alive_interval), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("KeepAliveProbes", "u", bus_property_get_unsigned, offsetof(Socket, keep_alive_cnt), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("DeferAcceptUSec" , "t", bus_property_get_usec, offsetof(Socket, defer_accept), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("NoDelay", "b", bus_property_get_bool, offsetof(Socket, no_delay), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Priority", "i", bus_property_get_int, offsetof(Socket, priority), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("ReceiveBuffer", "t", bus_property_get_size, offsetof(Socket, receive_buffer), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SendBuffer", "t", bus_property_get_size, offsetof(Socket, send_buffer), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("IPTOS", "i", bus_property_get_int, offsetof(Socket, ip_tos), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("IPTTL", "i", bus_property_get_int, offsetof(Socket, ip_ttl), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("PipeSize", "t", bus_property_get_size, offsetof(Socket, pipe_size), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("FreeBind", "b", bus_property_get_bool, offsetof(Socket, free_bind), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Transparent", "b", bus_property_get_bool, offsetof(Socket, transparent), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Broadcast", "b", bus_property_get_bool, offsetof(Socket, broadcast), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("PassCredentials", "b", bus_property_get_bool, offsetof(Socket, pass_cred), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("PassSecurity", "b", bus_property_get_bool, offsetof(Socket, pass_sec), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("RemoveOnStop", "b", bus_property_get_bool, offsetof(Socket, remove_on_stop), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Listen", "a(ss)", property_get_listen, 0, SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Symlinks", "as", NULL, offsetof(Socket, symlinks), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("Mark", "i", bus_property_get_int, offsetof(Socket, mark), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("MaxConnections", "u", bus_property_get_unsigned, offsetof(Socket, max_connections), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("MaxConnectionsPerSource", "u", bus_property_get_unsigned, offsetof(Socket, max_connections_per_source), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("MessageQueueMaxMessages", "x", bus_property_get_long, offsetof(Socket, mq_maxmsg), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("MessageQueueMessageSize", "x", bus_property_get_long, offsetof(Socket, mq_msgsize), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("ReusePort", "b", bus_property_get_bool, offsetof(Socket, reuse_port), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SmackLabel", "s", NULL, offsetof(Socket, smack), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SmackLabelIPIn", "s", NULL, offsetof(Socket, smack_ip_in), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SmackLabelIPOut", "s", NULL, offsetof(Socket, smack_ip_out), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("ControlPID", "u", bus_property_get_pid, offsetof(Socket, control_pid), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
SD_BUS_PROPERTY("Result", "s", property_get_result, offsetof(Socket, result), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
SD_BUS_PROPERTY("NConnections", "u", bus_property_get_unsigned, offsetof(Socket, n_connections), 0),
SD_BUS_PROPERTY("NAccepted", "u", bus_property_get_unsigned, offsetof(Socket, n_accepted), 0),
SD_BUS_PROPERTY("FileDescriptorName", "s", property_get_fdname, 0, 0),
SD_BUS_PROPERTY("SocketProtocol", "i", bus_property_get_int, offsetof(Socket, socket_protocol), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("TriggerLimitIntervalUSec", "t", bus_property_get_usec, offsetof(Socket, trigger_limit.interval), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("TriggerLimitBurst", "u", bus_property_get_unsigned, offsetof(Socket, trigger_limit.burst), SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("UID", "u", NULL, offsetof(Unit, ref_uid), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
SD_BUS_PROPERTY("GID", "u", NULL, offsetof(Unit, ref_gid), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
BUS_EXEC_COMMAND_LIST_VTABLE("ExecStartPre", offsetof(Socket, exec_command[SOCKET_EXEC_START_PRE]), SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION),
BUS_EXEC_COMMAND_LIST_VTABLE("ExecStartPost", offsetof(Socket, exec_command[SOCKET_EXEC_START_POST]), SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION),
BUS_EXEC_COMMAND_LIST_VTABLE("ExecStopPre", offsetof(Socket, exec_command[SOCKET_EXEC_STOP_PRE]), SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION),
BUS_EXEC_COMMAND_LIST_VTABLE("ExecStopPost", offsetof(Socket, exec_command[SOCKET_EXEC_STOP_POST]), SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION),
SD_BUS_VTABLE_END
};
int bus_socket_set_property(
Unit *u,
const char *name,
sd_bus_message *message,
UnitSetPropertiesMode mode,
sd_bus_error *error) {
Socket *s = SOCKET(u);
assert(s);
assert(name);
assert(message);
return bus_cgroup_set_property(u, &s->cgroup_context, name, message, mode, error);
}
int bus_socket_commit_properties(Unit *u) {
assert(u);
unit_update_cgroup_members_masks(u);
unit_realize_cgroup(u);
return 0;
}
| gpl-2.0 |
voodik/android_kernel_hardkernel_odroidxu3 | fs/locks.c | 536 | 60014 | /*
* linux/fs/locks.c
*
* Provide support for fcntl()'s F_GETLK, F_SETLK, and F_SETLKW calls.
* Doug Evans (dje@spiff.uucp), August 07, 1992
*
* Deadlock detection added.
* FIXME: one thing isn't handled yet:
* - mandatory locks (requires lots of changes elsewhere)
* Kelly Carmichael (kelly@[142.24.8.65]), September 17, 1994.
*
* Miscellaneous edits, and a total rewrite of posix_lock_file() code.
* Kai Petzke (wpp@marie.physik.tu-berlin.de), 1994
*
* Converted file_lock_table to a linked list from an array, which eliminates
* the limits on how many active file locks are open.
* Chad Page (pageone@netcom.com), November 27, 1994
*
* Removed dependency on file descriptors. dup()'ed file descriptors now
* get the same locks as the original file descriptors, and a close() on
* any file descriptor removes ALL the locks on the file for the current
* process. Since locks still depend on the process id, locks are inherited
* after an exec() but not after a fork(). This agrees with POSIX, and both
* BSD and SVR4 practice.
* Andy Walker (andy@lysaker.kvaerner.no), February 14, 1995
*
* Scrapped free list which is redundant now that we allocate locks
* dynamically with kmalloc()/kfree().
* Andy Walker (andy@lysaker.kvaerner.no), February 21, 1995
*
* Implemented two lock personalities - FL_FLOCK and FL_POSIX.
*
* FL_POSIX locks are created with calls to fcntl() and lockf() through the
* fcntl() system call. They have the semantics described above.
*
* FL_FLOCK locks are created with calls to flock(), through the flock()
* system call, which is new. Old C libraries implement flock() via fcntl()
* and will continue to use the old, broken implementation.
*
* FL_FLOCK locks follow the 4.4 BSD flock() semantics. They are associated
* with a file pointer (filp). As a result they can be shared by a parent
* process and its children after a fork(). They are removed when the last
* file descriptor referring to the file pointer is closed (unless explicitly
* unlocked).
*
* FL_FLOCK locks never deadlock, an existing lock is always removed before
* upgrading from shared to exclusive (or vice versa). When this happens
* any processes blocked by the current lock are woken up and allowed to
* run before the new lock is applied.
* Andy Walker (andy@lysaker.kvaerner.no), June 09, 1995
*
* Removed some race conditions in flock_lock_file(), marked other possible
* races. Just grep for FIXME to see them.
* Dmitry Gorodchanin (pgmdsg@ibi.com), February 09, 1996.
*
* Addressed Dmitry's concerns. Deadlock checking no longer recursive.
* Lock allocation changed to GFP_ATOMIC as we can't afford to sleep
* once we've checked for blocking and deadlocking.
* Andy Walker (andy@lysaker.kvaerner.no), April 03, 1996.
*
* Initial implementation of mandatory locks. SunOS turned out to be
* a rotten model, so I implemented the "obvious" semantics.
* See 'Documentation/filesystems/mandatory-locking.txt' for details.
* Andy Walker (andy@lysaker.kvaerner.no), April 06, 1996.
*
* Don't allow mandatory locks on mmap()'ed files. Added simple functions to
* check if a file has mandatory locks, used by mmap(), open() and creat() to
* see if system call should be rejected. Ref. HP-UX/SunOS/Solaris Reference
* Manual, Section 2.
* Andy Walker (andy@lysaker.kvaerner.no), April 09, 1996.
*
* Tidied up block list handling. Added '/proc/locks' interface.
* Andy Walker (andy@lysaker.kvaerner.no), April 24, 1996.
*
* Fixed deadlock condition for pathological code that mixes calls to
* flock() and fcntl().
* Andy Walker (andy@lysaker.kvaerner.no), April 29, 1996.
*
* Allow only one type of locking scheme (FL_POSIX or FL_FLOCK) to be in use
* for a given file at a time. Changed the CONFIG_LOCK_MANDATORY scheme to
* guarantee sensible behaviour in the case where file system modules might
* be compiled with different options than the kernel itself.
* Andy Walker (andy@lysaker.kvaerner.no), May 15, 1996.
*
* Added a couple of missing wake_up() calls. Thanks to Thomas Meckel
* (Thomas.Meckel@mni.fh-giessen.de) for spotting this.
* Andy Walker (andy@lysaker.kvaerner.no), May 15, 1996.
*
* Changed FL_POSIX locks to use the block list in the same way as FL_FLOCK
* locks. Changed process synchronisation to avoid dereferencing locks that
* have already been freed.
* Andy Walker (andy@lysaker.kvaerner.no), Sep 21, 1996.
*
* Made the block list a circular list to minimise searching in the list.
* Andy Walker (andy@lysaker.kvaerner.no), Sep 25, 1996.
*
* Made mandatory locking a mount option. Default is not to allow mandatory
* locking.
* Andy Walker (andy@lysaker.kvaerner.no), Oct 04, 1996.
*
* Some adaptations for NFS support.
* Olaf Kirch (okir@monad.swb.de), Dec 1996,
*
* Fixed /proc/locks interface so that we can't overrun the buffer we are handed.
* Andy Walker (andy@lysaker.kvaerner.no), May 12, 1997.
*
* Use slab allocator instead of kmalloc/kfree.
* Use generic list implementation from <linux/list.h>.
* Sped up posix_locks_deadlock by only considering blocked locks.
* Matthew Wilcox <willy@debian.org>, March, 2000.
*
* Leases and LOCK_MAND
* Matthew Wilcox <willy@debian.org>, June, 2000.
* Stephen Rothwell <sfr@canb.auug.org.au>, June, 2000.
*/
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/security.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <linux/time.h>
#include <linux/rcupdate.h>
#include <linux/pid_namespace.h>
#include <asm/uaccess.h>
#define IS_POSIX(fl) (fl->fl_flags & FL_POSIX)
#define IS_FLOCK(fl) (fl->fl_flags & FL_FLOCK)
#define IS_LEASE(fl) (fl->fl_flags & FL_LEASE)
static bool lease_breaking(struct file_lock *fl)
{
return fl->fl_flags & (FL_UNLOCK_PENDING | FL_DOWNGRADE_PENDING);
}
static int target_leasetype(struct file_lock *fl)
{
if (fl->fl_flags & FL_UNLOCK_PENDING)
return F_UNLCK;
if (fl->fl_flags & FL_DOWNGRADE_PENDING)
return F_RDLCK;
return fl->fl_type;
}
int leases_enable = 1;
int lease_break_time = 45;
#define for_each_lock(inode, lockp) \
for (lockp = &inode->i_flock; *lockp != NULL; lockp = &(*lockp)->fl_next)
static LIST_HEAD(file_lock_list);
static LIST_HEAD(blocked_list);
static DEFINE_SPINLOCK(file_lock_lock);
/*
* Protects the two list heads above, plus the inode->i_flock list
*/
void lock_flocks(void)
{
spin_lock(&file_lock_lock);
}
EXPORT_SYMBOL_GPL(lock_flocks);
void unlock_flocks(void)
{
spin_unlock(&file_lock_lock);
}
EXPORT_SYMBOL_GPL(unlock_flocks);
static struct kmem_cache *filelock_cache __read_mostly;
static void locks_init_lock_heads(struct file_lock *fl)
{
INIT_LIST_HEAD(&fl->fl_link);
INIT_LIST_HEAD(&fl->fl_block);
init_waitqueue_head(&fl->fl_wait);
}
/* Allocate an empty lock structure. */
struct file_lock *locks_alloc_lock(void)
{
struct file_lock *fl = kmem_cache_zalloc(filelock_cache, GFP_KERNEL);
if (fl)
locks_init_lock_heads(fl);
return fl;
}
EXPORT_SYMBOL_GPL(locks_alloc_lock);
void locks_release_private(struct file_lock *fl)
{
if (fl->fl_ops) {
if (fl->fl_ops->fl_release_private)
fl->fl_ops->fl_release_private(fl);
fl->fl_ops = NULL;
}
fl->fl_lmops = NULL;
}
EXPORT_SYMBOL_GPL(locks_release_private);
/* Free a lock which is not in use. */
void locks_free_lock(struct file_lock *fl)
{
BUG_ON(waitqueue_active(&fl->fl_wait));
BUG_ON(!list_empty(&fl->fl_block));
BUG_ON(!list_empty(&fl->fl_link));
locks_release_private(fl);
kmem_cache_free(filelock_cache, fl);
}
EXPORT_SYMBOL(locks_free_lock);
void locks_init_lock(struct file_lock *fl)
{
memset(fl, 0, sizeof(struct file_lock));
locks_init_lock_heads(fl);
}
EXPORT_SYMBOL(locks_init_lock);
static void locks_copy_private(struct file_lock *new, struct file_lock *fl)
{
if (fl->fl_ops) {
if (fl->fl_ops->fl_copy_lock)
fl->fl_ops->fl_copy_lock(new, fl);
new->fl_ops = fl->fl_ops;
}
if (fl->fl_lmops)
new->fl_lmops = fl->fl_lmops;
}
/*
* Initialize a new lock from an existing file_lock structure.
*/
void __locks_copy_lock(struct file_lock *new, const struct file_lock *fl)
{
new->fl_owner = fl->fl_owner;
new->fl_pid = fl->fl_pid;
new->fl_file = NULL;
new->fl_flags = fl->fl_flags;
new->fl_type = fl->fl_type;
new->fl_start = fl->fl_start;
new->fl_end = fl->fl_end;
new->fl_ops = NULL;
new->fl_lmops = NULL;
}
EXPORT_SYMBOL(__locks_copy_lock);
void locks_copy_lock(struct file_lock *new, struct file_lock *fl)
{
locks_release_private(new);
__locks_copy_lock(new, fl);
new->fl_file = fl->fl_file;
new->fl_ops = fl->fl_ops;
new->fl_lmops = fl->fl_lmops;
locks_copy_private(new, fl);
}
EXPORT_SYMBOL(locks_copy_lock);
static inline int flock_translate_cmd(int cmd) {
if (cmd & LOCK_MAND)
return cmd & (LOCK_MAND | LOCK_RW);
switch (cmd) {
case LOCK_SH:
return F_RDLCK;
case LOCK_EX:
return F_WRLCK;
case LOCK_UN:
return F_UNLCK;
}
return -EINVAL;
}
/* Fill in a file_lock structure with an appropriate FLOCK lock. */
static int flock_make_lock(struct file *filp, struct file_lock **lock,
unsigned int cmd)
{
struct file_lock *fl;
int type = flock_translate_cmd(cmd);
if (type < 0)
return type;
fl = locks_alloc_lock();
if (fl == NULL)
return -ENOMEM;
fl->fl_file = filp;
fl->fl_pid = current->tgid;
fl->fl_flags = FL_FLOCK;
fl->fl_type = type;
fl->fl_end = OFFSET_MAX;
*lock = fl;
return 0;
}
static int assign_type(struct file_lock *fl, long type)
{
switch (type) {
case F_RDLCK:
case F_WRLCK:
case F_UNLCK:
fl->fl_type = type;
break;
default:
return -EINVAL;
}
return 0;
}
/* Verify a "struct flock" and copy it to a "struct file_lock" as a POSIX
* style lock.
*/
static int flock_to_posix_lock(struct file *filp, struct file_lock *fl,
struct flock *l)
{
off_t start, end;
switch (l->l_whence) {
case SEEK_SET:
start = 0;
break;
case SEEK_CUR:
start = filp->f_pos;
break;
case SEEK_END:
start = i_size_read(file_inode(filp));
break;
default:
return -EINVAL;
}
/* POSIX-1996 leaves the case l->l_len < 0 undefined;
POSIX-2001 defines it. */
start += l->l_start;
if (start < 0)
return -EINVAL;
fl->fl_end = OFFSET_MAX;
if (l->l_len > 0) {
end = start + l->l_len - 1;
fl->fl_end = end;
} else if (l->l_len < 0) {
end = start - 1;
fl->fl_end = end;
start += l->l_len;
if (start < 0)
return -EINVAL;
}
fl->fl_start = start; /* we record the absolute position */
if (fl->fl_end < fl->fl_start)
return -EOVERFLOW;
fl->fl_owner = current->files;
fl->fl_pid = current->tgid;
fl->fl_file = filp;
fl->fl_flags = FL_POSIX;
fl->fl_ops = NULL;
fl->fl_lmops = NULL;
return assign_type(fl, l->l_type);
}
#if BITS_PER_LONG == 32
static int flock64_to_posix_lock(struct file *filp, struct file_lock *fl,
struct flock64 *l)
{
loff_t start;
switch (l->l_whence) {
case SEEK_SET:
start = 0;
break;
case SEEK_CUR:
start = filp->f_pos;
break;
case SEEK_END:
start = i_size_read(file_inode(filp));
break;
default:
return -EINVAL;
}
start += l->l_start;
if (start < 0)
return -EINVAL;
fl->fl_end = OFFSET_MAX;
if (l->l_len > 0) {
fl->fl_end = start + l->l_len - 1;
} else if (l->l_len < 0) {
fl->fl_end = start - 1;
start += l->l_len;
if (start < 0)
return -EINVAL;
}
fl->fl_start = start; /* we record the absolute position */
if (fl->fl_end < fl->fl_start)
return -EOVERFLOW;
fl->fl_owner = current->files;
fl->fl_pid = current->tgid;
fl->fl_file = filp;
fl->fl_flags = FL_POSIX;
fl->fl_ops = NULL;
fl->fl_lmops = NULL;
return assign_type(fl, l->l_type);
}
#endif
/* default lease lock manager operations */
static void lease_break_callback(struct file_lock *fl)
{
kill_fasync(&fl->fl_fasync, SIGIO, POLL_MSG);
}
static const struct lock_manager_operations lease_manager_ops = {
.lm_break = lease_break_callback,
.lm_change = lease_modify,
};
/*
* Initialize a lease, use the default lock manager operations
*/
static int lease_init(struct file *filp, long type, struct file_lock *fl)
{
if (assign_type(fl, type) != 0)
return -EINVAL;
fl->fl_owner = current->files;
fl->fl_pid = current->tgid;
fl->fl_file = filp;
fl->fl_flags = FL_LEASE;
fl->fl_start = 0;
fl->fl_end = OFFSET_MAX;
fl->fl_ops = NULL;
fl->fl_lmops = &lease_manager_ops;
return 0;
}
/* Allocate a file_lock initialised to this type of lease */
static struct file_lock *lease_alloc(struct file *filp, long type)
{
struct file_lock *fl = locks_alloc_lock();
int error = -ENOMEM;
if (fl == NULL)
return ERR_PTR(error);
error = lease_init(filp, type, fl);
if (error) {
locks_free_lock(fl);
return ERR_PTR(error);
}
return fl;
}
/* Check if two locks overlap each other.
*/
static inline int locks_overlap(struct file_lock *fl1, struct file_lock *fl2)
{
return ((fl1->fl_end >= fl2->fl_start) &&
(fl2->fl_end >= fl1->fl_start));
}
/*
* Check whether two locks have the same owner.
*/
static int posix_same_owner(struct file_lock *fl1, struct file_lock *fl2)
{
if (fl1->fl_lmops && fl1->fl_lmops->lm_compare_owner)
return fl2->fl_lmops == fl1->fl_lmops &&
fl1->fl_lmops->lm_compare_owner(fl1, fl2);
return fl1->fl_owner == fl2->fl_owner;
}
/* Remove waiter from blocker's block list.
* When blocker ends up pointing to itself then the list is empty.
*/
static void __locks_delete_block(struct file_lock *waiter)
{
list_del_init(&waiter->fl_block);
list_del_init(&waiter->fl_link);
waiter->fl_next = NULL;
}
/*
*/
void locks_delete_block(struct file_lock *waiter)
{
lock_flocks();
__locks_delete_block(waiter);
unlock_flocks();
}
EXPORT_SYMBOL(locks_delete_block);
/* Insert waiter into blocker's block list.
* We use a circular list so that processes can be easily woken up in
* the order they blocked. The documentation doesn't require this but
* it seems like the reasonable thing to do.
*/
static void locks_insert_block(struct file_lock *blocker,
struct file_lock *waiter)
{
BUG_ON(!list_empty(&waiter->fl_block));
list_add_tail(&waiter->fl_block, &blocker->fl_block);
waiter->fl_next = blocker;
if (IS_POSIX(blocker))
list_add(&waiter->fl_link, &blocked_list);
}
/* Wake up processes blocked waiting for blocker.
* If told to wait then schedule the processes until the block list
* is empty, otherwise empty the block list ourselves.
*/
static void locks_wake_up_blocks(struct file_lock *blocker)
{
while (!list_empty(&blocker->fl_block)) {
struct file_lock *waiter;
waiter = list_first_entry(&blocker->fl_block,
struct file_lock, fl_block);
__locks_delete_block(waiter);
if (waiter->fl_lmops && waiter->fl_lmops->lm_notify)
waiter->fl_lmops->lm_notify(waiter);
else
wake_up(&waiter->fl_wait);
}
}
/* Insert file lock fl into an inode's lock list at the position indicated
* by pos. At the same time add the lock to the global file lock list.
*/
static void locks_insert_lock(struct file_lock **pos, struct file_lock *fl)
{
list_add(&fl->fl_link, &file_lock_list);
fl->fl_nspid = get_pid(task_tgid(current));
/* insert into file's list */
fl->fl_next = *pos;
*pos = fl;
}
/*
* Delete a lock and then free it.
* Wake up processes that are blocked waiting for this lock,
* notify the FS that the lock has been cleared and
* finally free the lock.
*/
static void locks_delete_lock(struct file_lock **thisfl_p)
{
struct file_lock *fl = *thisfl_p;
*thisfl_p = fl->fl_next;
fl->fl_next = NULL;
list_del_init(&fl->fl_link);
if (fl->fl_nspid) {
put_pid(fl->fl_nspid);
fl->fl_nspid = NULL;
}
locks_wake_up_blocks(fl);
locks_free_lock(fl);
}
/* Determine if lock sys_fl blocks lock caller_fl. Common functionality
* checks for shared/exclusive status of overlapping locks.
*/
static int locks_conflict(struct file_lock *caller_fl, struct file_lock *sys_fl)
{
if (sys_fl->fl_type == F_WRLCK)
return 1;
if (caller_fl->fl_type == F_WRLCK)
return 1;
return 0;
}
/* Determine if lock sys_fl blocks lock caller_fl. POSIX specific
* checking before calling the locks_conflict().
*/
static int posix_locks_conflict(struct file_lock *caller_fl, struct file_lock *sys_fl)
{
/* POSIX locks owned by the same process do not conflict with
* each other.
*/
if (!IS_POSIX(sys_fl) || posix_same_owner(caller_fl, sys_fl))
return (0);
/* Check whether they overlap */
if (!locks_overlap(caller_fl, sys_fl))
return 0;
return (locks_conflict(caller_fl, sys_fl));
}
/* Determine if lock sys_fl blocks lock caller_fl. FLOCK specific
* checking before calling the locks_conflict().
*/
static int flock_locks_conflict(struct file_lock *caller_fl, struct file_lock *sys_fl)
{
/* FLOCK locks referring to the same filp do not conflict with
* each other.
*/
if (!IS_FLOCK(sys_fl) || (caller_fl->fl_file == sys_fl->fl_file))
return (0);
if ((caller_fl->fl_type & LOCK_MAND) || (sys_fl->fl_type & LOCK_MAND))
return 0;
return (locks_conflict(caller_fl, sys_fl));
}
void
posix_test_lock(struct file *filp, struct file_lock *fl)
{
struct file_lock *cfl;
lock_flocks();
for (cfl = file_inode(filp)->i_flock; cfl; cfl = cfl->fl_next) {
if (!IS_POSIX(cfl))
continue;
if (posix_locks_conflict(fl, cfl))
break;
}
if (cfl) {
__locks_copy_lock(fl, cfl);
if (cfl->fl_nspid)
fl->fl_pid = pid_vnr(cfl->fl_nspid);
} else
fl->fl_type = F_UNLCK;
unlock_flocks();
return;
}
EXPORT_SYMBOL(posix_test_lock);
/*
* Deadlock detection:
*
* We attempt to detect deadlocks that are due purely to posix file
* locks.
*
* We assume that a task can be waiting for at most one lock at a time.
* So for any acquired lock, the process holding that lock may be
* waiting on at most one other lock. That lock in turns may be held by
* someone waiting for at most one other lock. Given a requested lock
* caller_fl which is about to wait for a conflicting lock block_fl, we
* follow this chain of waiters to ensure we are not about to create a
* cycle.
*
* Since we do this before we ever put a process to sleep on a lock, we
* are ensured that there is never a cycle; that is what guarantees that
* the while() loop in posix_locks_deadlock() eventually completes.
*
* Note: the above assumption may not be true when handling lock
* requests from a broken NFS client. It may also fail in the presence
* of tasks (such as posix threads) sharing the same open file table.
*
* To handle those cases, we just bail out after a few iterations.
*/
#define MAX_DEADLK_ITERATIONS 10
/* Find a lock that the owner of the given block_fl is blocking on. */
static struct file_lock *what_owner_is_waiting_for(struct file_lock *block_fl)
{
struct file_lock *fl;
list_for_each_entry(fl, &blocked_list, fl_link) {
if (posix_same_owner(fl, block_fl))
return fl->fl_next;
}
return NULL;
}
static int posix_locks_deadlock(struct file_lock *caller_fl,
struct file_lock *block_fl)
{
int i = 0;
while ((block_fl = what_owner_is_waiting_for(block_fl))) {
if (i++ > MAX_DEADLK_ITERATIONS)
return 0;
if (posix_same_owner(caller_fl, block_fl))
return 1;
}
return 0;
}
/* Try to create a FLOCK lock on filp. We always insert new FLOCK locks
* after any leases, but before any posix locks.
*
* Note that if called with an FL_EXISTS argument, the caller may determine
* whether or not a lock was successfully freed by testing the return
* value for -ENOENT.
*/
static int flock_lock_file(struct file *filp, struct file_lock *request)
{
struct file_lock *new_fl = NULL;
struct file_lock **before;
struct inode * inode = file_inode(filp);
int error = 0;
int found = 0;
if (!(request->fl_flags & FL_ACCESS) && (request->fl_type != F_UNLCK)) {
new_fl = locks_alloc_lock();
if (!new_fl)
return -ENOMEM;
}
lock_flocks();
if (request->fl_flags & FL_ACCESS)
goto find_conflict;
for_each_lock(inode, before) {
struct file_lock *fl = *before;
if (IS_POSIX(fl))
break;
if (IS_LEASE(fl))
continue;
if (filp != fl->fl_file)
continue;
if (request->fl_type == fl->fl_type)
goto out;
found = 1;
locks_delete_lock(before);
break;
}
if (request->fl_type == F_UNLCK) {
if ((request->fl_flags & FL_EXISTS) && !found)
error = -ENOENT;
goto out;
}
/*
* If a higher-priority process was blocked on the old file lock,
* give it the opportunity to lock the file.
*/
if (found) {
unlock_flocks();
cond_resched();
lock_flocks();
}
find_conflict:
for_each_lock(inode, before) {
struct file_lock *fl = *before;
if (IS_POSIX(fl))
break;
if (IS_LEASE(fl))
continue;
if (!flock_locks_conflict(request, fl))
continue;
error = -EAGAIN;
if (!(request->fl_flags & FL_SLEEP))
goto out;
error = FILE_LOCK_DEFERRED;
locks_insert_block(fl, request);
goto out;
}
if (request->fl_flags & FL_ACCESS)
goto out;
locks_copy_lock(new_fl, request);
locks_insert_lock(before, new_fl);
new_fl = NULL;
error = 0;
out:
unlock_flocks();
if (new_fl)
locks_free_lock(new_fl);
return error;
}
static int __posix_lock_file(struct inode *inode, struct file_lock *request, struct file_lock *conflock)
{
struct file_lock *fl;
struct file_lock *new_fl = NULL;
struct file_lock *new_fl2 = NULL;
struct file_lock *left = NULL;
struct file_lock *right = NULL;
struct file_lock **before;
int error, added = 0;
/*
* We may need two file_lock structures for this operation,
* so we get them in advance to avoid races.
*
* In some cases we can be sure, that no new locks will be needed
*/
if (!(request->fl_flags & FL_ACCESS) &&
(request->fl_type != F_UNLCK ||
request->fl_start != 0 || request->fl_end != OFFSET_MAX)) {
new_fl = locks_alloc_lock();
new_fl2 = locks_alloc_lock();
}
lock_flocks();
if (request->fl_type != F_UNLCK) {
for_each_lock(inode, before) {
fl = *before;
if (!IS_POSIX(fl))
continue;
if (!posix_locks_conflict(request, fl))
continue;
if (conflock)
__locks_copy_lock(conflock, fl);
error = -EAGAIN;
if (!(request->fl_flags & FL_SLEEP))
goto out;
error = -EDEADLK;
if (posix_locks_deadlock(request, fl))
goto out;
error = FILE_LOCK_DEFERRED;
locks_insert_block(fl, request);
goto out;
}
}
/* If we're just looking for a conflict, we're done. */
error = 0;
if (request->fl_flags & FL_ACCESS)
goto out;
/*
* Find the first old lock with the same owner as the new lock.
*/
before = &inode->i_flock;
/* First skip locks owned by other processes. */
while ((fl = *before) && (!IS_POSIX(fl) ||
!posix_same_owner(request, fl))) {
before = &fl->fl_next;
}
/* Process locks with this owner. */
while ((fl = *before) && posix_same_owner(request, fl)) {
/* Detect adjacent or overlapping regions (if same lock type)
*/
if (request->fl_type == fl->fl_type) {
/* In all comparisons of start vs end, use
* "start - 1" rather than "end + 1". If end
* is OFFSET_MAX, end + 1 will become negative.
*/
if (fl->fl_end < request->fl_start - 1)
goto next_lock;
/* If the next lock in the list has entirely bigger
* addresses than the new one, insert the lock here.
*/
if (fl->fl_start - 1 > request->fl_end)
break;
/* If we come here, the new and old lock are of the
* same type and adjacent or overlapping. Make one
* lock yielding from the lower start address of both
* locks to the higher end address.
*/
if (fl->fl_start > request->fl_start)
fl->fl_start = request->fl_start;
else
request->fl_start = fl->fl_start;
if (fl->fl_end < request->fl_end)
fl->fl_end = request->fl_end;
else
request->fl_end = fl->fl_end;
if (added) {
locks_delete_lock(before);
continue;
}
request = fl;
added = 1;
}
else {
/* Processing for different lock types is a bit
* more complex.
*/
if (fl->fl_end < request->fl_start)
goto next_lock;
if (fl->fl_start > request->fl_end)
break;
if (request->fl_type == F_UNLCK)
added = 1;
if (fl->fl_start < request->fl_start)
left = fl;
/* If the next lock in the list has a higher end
* address than the new one, insert the new one here.
*/
if (fl->fl_end > request->fl_end) {
right = fl;
break;
}
if (fl->fl_start >= request->fl_start) {
/* The new lock completely replaces an old
* one (This may happen several times).
*/
if (added) {
locks_delete_lock(before);
continue;
}
/* Replace the old lock with the new one.
* Wake up anybody waiting for the old one,
* as the change in lock type might satisfy
* their needs.
*/
locks_wake_up_blocks(fl);
fl->fl_start = request->fl_start;
fl->fl_end = request->fl_end;
fl->fl_type = request->fl_type;
locks_release_private(fl);
locks_copy_private(fl, request);
request = fl;
added = 1;
}
}
/* Go on to next lock.
*/
next_lock:
before = &fl->fl_next;
}
/*
* The above code only modifies existing locks in case of
* merging or replacing. If new lock(s) need to be inserted
* all modifications are done bellow this, so it's safe yet to
* bail out.
*/
error = -ENOLCK; /* "no luck" */
if (right && left == right && !new_fl2)
goto out;
error = 0;
if (!added) {
if (request->fl_type == F_UNLCK) {
if (request->fl_flags & FL_EXISTS)
error = -ENOENT;
goto out;
}
if (!new_fl) {
error = -ENOLCK;
goto out;
}
locks_copy_lock(new_fl, request);
locks_insert_lock(before, new_fl);
new_fl = NULL;
}
if (right) {
if (left == right) {
/* The new lock breaks the old one in two pieces,
* so we have to use the second new lock.
*/
left = new_fl2;
new_fl2 = NULL;
locks_copy_lock(left, right);
locks_insert_lock(before, left);
}
right->fl_start = request->fl_end + 1;
locks_wake_up_blocks(right);
}
if (left) {
left->fl_end = request->fl_start - 1;
locks_wake_up_blocks(left);
}
out:
unlock_flocks();
/*
* Free any unused locks.
*/
if (new_fl)
locks_free_lock(new_fl);
if (new_fl2)
locks_free_lock(new_fl2);
return error;
}
/**
* posix_lock_file - Apply a POSIX-style lock to a file
* @filp: The file to apply the lock to
* @fl: The lock to be applied
* @conflock: Place to return a copy of the conflicting lock, if found.
*
* Add a POSIX style lock to a file.
* We merge adjacent & overlapping locks whenever possible.
* POSIX locks are sorted by owner task, then by starting address
*
* Note that if called with an FL_EXISTS argument, the caller may determine
* whether or not a lock was successfully freed by testing the return
* value for -ENOENT.
*/
int posix_lock_file(struct file *filp, struct file_lock *fl,
struct file_lock *conflock)
{
return __posix_lock_file(file_inode(filp), fl, conflock);
}
EXPORT_SYMBOL(posix_lock_file);
/**
* posix_lock_file_wait - Apply a POSIX-style lock to a file
* @filp: The file to apply the lock to
* @fl: The lock to be applied
*
* Add a POSIX style lock to a file.
* We merge adjacent & overlapping locks whenever possible.
* POSIX locks are sorted by owner task, then by starting address
*/
int posix_lock_file_wait(struct file *filp, struct file_lock *fl)
{
int error;
might_sleep ();
for (;;) {
error = posix_lock_file(filp, fl, NULL);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl->fl_wait, !fl->fl_next);
if (!error)
continue;
locks_delete_block(fl);
break;
}
return error;
}
EXPORT_SYMBOL(posix_lock_file_wait);
/**
* locks_mandatory_locked - Check for an active lock
* @inode: the file to check
*
* Searches the inode's list of locks to find any POSIX locks which conflict.
* This function is called from locks_verify_locked() only.
*/
int locks_mandatory_locked(struct inode *inode)
{
fl_owner_t owner = current->files;
struct file_lock *fl;
/*
* Search the lock list for this inode for any POSIX locks.
*/
lock_flocks();
for (fl = inode->i_flock; fl != NULL; fl = fl->fl_next) {
if (!IS_POSIX(fl))
continue;
if (fl->fl_owner != owner)
break;
}
unlock_flocks();
return fl ? -EAGAIN : 0;
}
/**
* locks_mandatory_area - Check for a conflicting lock
* @read_write: %FLOCK_VERIFY_WRITE for exclusive access, %FLOCK_VERIFY_READ
* for shared
* @inode: the file to check
* @filp: how the file was opened (if it was)
* @offset: start of area to check
* @count: length of area to check
*
* Searches the inode's list of locks to find any POSIX locks which conflict.
* This function is called from rw_verify_area() and
* locks_verify_truncate().
*/
int locks_mandatory_area(int read_write, struct inode *inode,
struct file *filp, loff_t offset,
size_t count)
{
struct file_lock fl;
int error;
locks_init_lock(&fl);
fl.fl_owner = current->files;
fl.fl_pid = current->tgid;
fl.fl_file = filp;
fl.fl_flags = FL_POSIX | FL_ACCESS;
if (filp && !(filp->f_flags & O_NONBLOCK))
fl.fl_flags |= FL_SLEEP;
fl.fl_type = (read_write == FLOCK_VERIFY_WRITE) ? F_WRLCK : F_RDLCK;
fl.fl_start = offset;
fl.fl_end = offset + count - 1;
for (;;) {
error = __posix_lock_file(inode, &fl, NULL);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl.fl_wait, !fl.fl_next);
if (!error) {
/*
* If we've been sleeping someone might have
* changed the permissions behind our back.
*/
if (__mandatory_lock(inode))
continue;
}
locks_delete_block(&fl);
break;
}
return error;
}
EXPORT_SYMBOL(locks_mandatory_area);
static void lease_clear_pending(struct file_lock *fl, int arg)
{
switch (arg) {
case F_UNLCK:
fl->fl_flags &= ~FL_UNLOCK_PENDING;
/* fall through: */
case F_RDLCK:
fl->fl_flags &= ~FL_DOWNGRADE_PENDING;
}
}
/* We already had a lease on this file; just change its type */
int lease_modify(struct file_lock **before, int arg)
{
struct file_lock *fl = *before;
int error = assign_type(fl, arg);
if (error)
return error;
lease_clear_pending(fl, arg);
locks_wake_up_blocks(fl);
if (arg == F_UNLCK) {
struct file *filp = fl->fl_file;
f_delown(filp);
filp->f_owner.signum = 0;
fasync_helper(0, fl->fl_file, 0, &fl->fl_fasync);
if (fl->fl_fasync != NULL) {
printk(KERN_ERR "locks_delete_lock: fasync == %p\n", fl->fl_fasync);
fl->fl_fasync = NULL;
}
locks_delete_lock(before);
}
return 0;
}
EXPORT_SYMBOL(lease_modify);
static bool past_time(unsigned long then)
{
if (!then)
/* 0 is a special value meaning "this never expires": */
return false;
return time_after(jiffies, then);
}
static void time_out_leases(struct inode *inode)
{
struct file_lock **before;
struct file_lock *fl;
before = &inode->i_flock;
while ((fl = *before) && IS_LEASE(fl) && lease_breaking(fl)) {
if (past_time(fl->fl_downgrade_time))
lease_modify(before, F_RDLCK);
if (past_time(fl->fl_break_time))
lease_modify(before, F_UNLCK);
if (fl == *before) /* lease_modify may have freed fl */
before = &fl->fl_next;
}
}
/**
* __break_lease - revoke all outstanding leases on file
* @inode: the inode of the file to return
* @mode: the open mode (read or write)
*
* break_lease (inlined for speed) has checked there already is at least
* some kind of lock (maybe a lease) on this file. Leases are broken on
* a call to open() or truncate(). This function can sleep unless you
* specified %O_NONBLOCK to your open().
*/
int __break_lease(struct inode *inode, unsigned int mode)
{
int error = 0;
struct file_lock *new_fl, *flock;
struct file_lock *fl;
unsigned long break_time;
int i_have_this_lease = 0;
int want_write = (mode & O_ACCMODE) != O_RDONLY;
new_fl = lease_alloc(NULL, want_write ? F_WRLCK : F_RDLCK);
if (IS_ERR(new_fl))
return PTR_ERR(new_fl);
lock_flocks();
time_out_leases(inode);
flock = inode->i_flock;
if ((flock == NULL) || !IS_LEASE(flock))
goto out;
if (!locks_conflict(flock, new_fl))
goto out;
for (fl = flock; fl && IS_LEASE(fl); fl = fl->fl_next)
if (fl->fl_owner == current->files)
i_have_this_lease = 1;
break_time = 0;
if (lease_break_time > 0) {
break_time = jiffies + lease_break_time * HZ;
if (break_time == 0)
break_time++; /* so that 0 means no break time */
}
for (fl = flock; fl && IS_LEASE(fl); fl = fl->fl_next) {
if (want_write) {
if (fl->fl_flags & FL_UNLOCK_PENDING)
continue;
fl->fl_flags |= FL_UNLOCK_PENDING;
fl->fl_break_time = break_time;
} else {
if (lease_breaking(flock))
continue;
fl->fl_flags |= FL_DOWNGRADE_PENDING;
fl->fl_downgrade_time = break_time;
}
fl->fl_lmops->lm_break(fl);
}
if (i_have_this_lease || (mode & O_NONBLOCK)) {
error = -EWOULDBLOCK;
goto out;
}
restart:
break_time = flock->fl_break_time;
if (break_time != 0) {
break_time -= jiffies;
if (break_time == 0)
break_time++;
}
locks_insert_block(flock, new_fl);
unlock_flocks();
error = wait_event_interruptible_timeout(new_fl->fl_wait,
!new_fl->fl_next, break_time);
lock_flocks();
__locks_delete_block(new_fl);
if (error >= 0) {
if (error == 0)
time_out_leases(inode);
/*
* Wait for the next conflicting lease that has not been
* broken yet
*/
for (flock = inode->i_flock; flock && IS_LEASE(flock);
flock = flock->fl_next) {
if (locks_conflict(new_fl, flock))
goto restart;
}
error = 0;
}
out:
unlock_flocks();
locks_free_lock(new_fl);
return error;
}
EXPORT_SYMBOL(__break_lease);
/**
* lease_get_mtime - get the last modified time of an inode
* @inode: the inode
* @time: pointer to a timespec which will contain the last modified time
*
* This is to force NFS clients to flush their caches for files with
* exclusive leases. The justification is that if someone has an
* exclusive lease, then they could be modifying it.
*/
void lease_get_mtime(struct inode *inode, struct timespec *time)
{
struct file_lock *flock = inode->i_flock;
if (flock && IS_LEASE(flock) && (flock->fl_type == F_WRLCK))
*time = current_fs_time(inode->i_sb);
else
*time = inode->i_mtime;
}
EXPORT_SYMBOL(lease_get_mtime);
/**
* fcntl_getlease - Enquire what lease is currently active
* @filp: the file
*
* The value returned by this function will be one of
* (if no lease break is pending):
*
* %F_RDLCK to indicate a shared lease is held.
*
* %F_WRLCK to indicate an exclusive lease is held.
*
* %F_UNLCK to indicate no lease is held.
*
* (if a lease break is pending):
*
* %F_RDLCK to indicate an exclusive lease needs to be
* changed to a shared lease (or removed).
*
* %F_UNLCK to indicate the lease needs to be removed.
*
* XXX: sfr & willy disagree over whether F_INPROGRESS
* should be returned to userspace.
*/
int fcntl_getlease(struct file *filp)
{
struct file_lock *fl;
int type = F_UNLCK;
lock_flocks();
time_out_leases(file_inode(filp));
for (fl = file_inode(filp)->i_flock; fl && IS_LEASE(fl);
fl = fl->fl_next) {
if (fl->fl_file == filp) {
type = target_leasetype(fl);
break;
}
}
unlock_flocks();
return type;
}
int generic_add_lease(struct file *filp, long arg, struct file_lock **flp)
{
struct file_lock *fl, **before, **my_before = NULL, *lease;
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
int error;
lease = *flp;
error = -EAGAIN;
if ((arg == F_RDLCK) && (atomic_read(&inode->i_writecount) > 0))
goto out;
if ((arg == F_WRLCK)
&& ((dentry->d_count > 1)
|| (atomic_read(&inode->i_count) > 1)))
goto out;
/*
* At this point, we know that if there is an exclusive
* lease on this file, then we hold it on this filp
* (otherwise our open of this file would have blocked).
* And if we are trying to acquire an exclusive lease,
* then the file is not open by anyone (including us)
* except for this filp.
*/
error = -EAGAIN;
for (before = &inode->i_flock;
((fl = *before) != NULL) && IS_LEASE(fl);
before = &fl->fl_next) {
if (fl->fl_file == filp) {
my_before = before;
continue;
}
/*
* No exclusive leases if someone else has a lease on
* this file:
*/
if (arg == F_WRLCK)
goto out;
/*
* Modifying our existing lease is OK, but no getting a
* new lease if someone else is opening for write:
*/
if (fl->fl_flags & FL_UNLOCK_PENDING)
goto out;
}
if (my_before != NULL) {
error = lease->fl_lmops->lm_change(my_before, arg);
if (!error)
*flp = *my_before;
goto out;
}
error = -EINVAL;
if (!leases_enable)
goto out;
locks_insert_lock(before, lease);
return 0;
out:
return error;
}
int generic_delete_lease(struct file *filp, struct file_lock **flp)
{
struct file_lock *fl, **before;
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
for (before = &inode->i_flock;
((fl = *before) != NULL) && IS_LEASE(fl);
before = &fl->fl_next) {
if (fl->fl_file != filp)
continue;
return (*flp)->fl_lmops->lm_change(before, F_UNLCK);
}
return -EAGAIN;
}
/**
* generic_setlease - sets a lease on an open file
* @filp: file pointer
* @arg: type of lease to obtain
* @flp: input - file_lock to use, output - file_lock inserted
*
* The (input) flp->fl_lmops->lm_break function is required
* by break_lease().
*
* Called with file_lock_lock held.
*/
int generic_setlease(struct file *filp, long arg, struct file_lock **flp)
{
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
int error;
if ((!uid_eq(current_fsuid(), inode->i_uid)) && !capable(CAP_LEASE))
return -EACCES;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
error = security_file_lock(filp, arg);
if (error)
return error;
time_out_leases(inode);
BUG_ON(!(*flp)->fl_lmops->lm_break);
switch (arg) {
case F_UNLCK:
return generic_delete_lease(filp, flp);
case F_RDLCK:
case F_WRLCK:
return generic_add_lease(filp, arg, flp);
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(generic_setlease);
static int __vfs_setlease(struct file *filp, long arg, struct file_lock **lease)
{
if (filp->f_op && filp->f_op->setlease)
return filp->f_op->setlease(filp, arg, lease);
else
return generic_setlease(filp, arg, lease);
}
/**
* vfs_setlease - sets a lease on an open file
* @filp: file pointer
* @arg: type of lease to obtain
* @lease: file_lock to use
*
* Call this to establish a lease on the file.
* The (*lease)->fl_lmops->lm_break operation must be set; if not,
* break_lease will oops!
*
* This will call the filesystem's setlease file method, if
* defined. Note that there is no getlease method; instead, the
* filesystem setlease method should call back to setlease() to
* add a lease to the inode's lease list, where fcntl_getlease() can
* find it. Since fcntl_getlease() only reports whether the current
* task holds a lease, a cluster filesystem need only do this for
* leases held by processes on this node.
*
* There is also no break_lease method; filesystems that
* handle their own leases should break leases themselves from the
* filesystem's open, create, and (on truncate) setattr methods.
*
* Warning: the only current setlease methods exist only to disable
* leases in certain cases. More vfs changes may be required to
* allow a full filesystem lease implementation.
*/
int vfs_setlease(struct file *filp, long arg, struct file_lock **lease)
{
int error;
lock_flocks();
error = __vfs_setlease(filp, arg, lease);
unlock_flocks();
return error;
}
EXPORT_SYMBOL_GPL(vfs_setlease);
static int do_fcntl_delete_lease(struct file *filp)
{
struct file_lock fl, *flp = &fl;
lease_init(filp, F_UNLCK, flp);
return vfs_setlease(filp, F_UNLCK, &flp);
}
static int do_fcntl_add_lease(unsigned int fd, struct file *filp, long arg)
{
struct file_lock *fl, *ret;
struct fasync_struct *new;
int error;
fl = lease_alloc(filp, arg);
if (IS_ERR(fl))
return PTR_ERR(fl);
new = fasync_alloc();
if (!new) {
locks_free_lock(fl);
return -ENOMEM;
}
ret = fl;
lock_flocks();
error = __vfs_setlease(filp, arg, &ret);
if (error) {
unlock_flocks();
locks_free_lock(fl);
goto out_free_fasync;
}
if (ret != fl)
locks_free_lock(fl);
/*
* fasync_insert_entry() returns the old entry if any.
* If there was no old entry, then it used 'new' and
* inserted it into the fasync list. Clear new so that
* we don't release it here.
*/
if (!fasync_insert_entry(fd, filp, &ret->fl_fasync, new))
new = NULL;
error = __f_setown(filp, task_pid(current), PIDTYPE_PID, 0);
unlock_flocks();
out_free_fasync:
if (new)
fasync_free(new);
return error;
}
/**
* fcntl_setlease - sets a lease on an open file
* @fd: open file descriptor
* @filp: file pointer
* @arg: type of lease to obtain
*
* Call this fcntl to establish a lease on the file.
* Note that you also need to call %F_SETSIG to
* receive a signal when the lease is broken.
*/
int fcntl_setlease(unsigned int fd, struct file *filp, long arg)
{
if (arg == F_UNLCK)
return do_fcntl_delete_lease(filp);
return do_fcntl_add_lease(fd, filp, arg);
}
/**
* flock_lock_file_wait - Apply a FLOCK-style lock to a file
* @filp: The file to apply the lock to
* @fl: The lock to be applied
*
* Add a FLOCK style lock to a file.
*/
int flock_lock_file_wait(struct file *filp, struct file_lock *fl)
{
int error;
might_sleep();
for (;;) {
error = flock_lock_file(filp, fl);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl->fl_wait, !fl->fl_next);
if (!error)
continue;
locks_delete_block(fl);
break;
}
return error;
}
EXPORT_SYMBOL(flock_lock_file_wait);
/**
* sys_flock: - flock() system call.
* @fd: the file descriptor to lock.
* @cmd: the type of lock to apply.
*
* Apply a %FL_FLOCK style lock to an open file descriptor.
* The @cmd can be one of
*
* %LOCK_SH -- a shared lock.
*
* %LOCK_EX -- an exclusive lock.
*
* %LOCK_UN -- remove an existing lock.
*
* %LOCK_MAND -- a `mandatory' flock. This exists to emulate Windows Share Modes.
*
* %LOCK_MAND can be combined with %LOCK_READ or %LOCK_WRITE to allow other
* processes read and write access respectively.
*/
SYSCALL_DEFINE2(flock, unsigned int, fd, unsigned int, cmd)
{
struct fd f = fdget(fd);
struct file_lock *lock;
int can_sleep, unlock;
int error;
error = -EBADF;
if (!f.file)
goto out;
can_sleep = !(cmd & LOCK_NB);
cmd &= ~LOCK_NB;
unlock = (cmd == LOCK_UN);
if (!unlock && !(cmd & LOCK_MAND) &&
!(f.file->f_mode & (FMODE_READ|FMODE_WRITE)))
goto out_putf;
error = flock_make_lock(f.file, &lock, cmd);
if (error)
goto out_putf;
if (can_sleep)
lock->fl_flags |= FL_SLEEP;
error = security_file_lock(f.file, lock->fl_type);
if (error)
goto out_free;
if (f.file->f_op && f.file->f_op->flock)
error = f.file->f_op->flock(f.file,
(can_sleep) ? F_SETLKW : F_SETLK,
lock);
else
error = flock_lock_file_wait(f.file, lock);
out_free:
locks_free_lock(lock);
out_putf:
fdput(f);
out:
return error;
}
/**
* vfs_test_lock - test file byte range lock
* @filp: The file to test lock for
* @fl: The lock to test; also used to hold result
*
* Returns -ERRNO on failure. Indicates presence of conflicting lock by
* setting conf->fl_type to something other than F_UNLCK.
*/
int vfs_test_lock(struct file *filp, struct file_lock *fl)
{
if (filp->f_op && filp->f_op->lock)
return filp->f_op->lock(filp, F_GETLK, fl);
posix_test_lock(filp, fl);
return 0;
}
EXPORT_SYMBOL_GPL(vfs_test_lock);
static int posix_lock_to_flock(struct flock *flock, struct file_lock *fl)
{
flock->l_pid = fl->fl_pid;
#if BITS_PER_LONG == 32
/*
* Make sure we can represent the posix lock via
* legacy 32bit flock.
*/
if (fl->fl_start > OFFT_OFFSET_MAX)
return -EOVERFLOW;
if (fl->fl_end != OFFSET_MAX && fl->fl_end > OFFT_OFFSET_MAX)
return -EOVERFLOW;
#endif
flock->l_start = fl->fl_start;
flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
fl->fl_end - fl->fl_start + 1;
flock->l_whence = 0;
flock->l_type = fl->fl_type;
return 0;
}
#if BITS_PER_LONG == 32
static void posix_lock_to_flock64(struct flock64 *flock, struct file_lock *fl)
{
flock->l_pid = fl->fl_pid;
flock->l_start = fl->fl_start;
flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
fl->fl_end - fl->fl_start + 1;
flock->l_whence = 0;
flock->l_type = fl->fl_type;
}
#endif
/* Report the first existing lock that would conflict with l.
* This implements the F_GETLK command of fcntl().
*/
int fcntl_getlk(struct file *filp, struct flock __user *l)
{
struct file_lock file_lock;
struct flock flock;
int error;
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
error = -EINVAL;
if ((flock.l_type != F_RDLCK) && (flock.l_type != F_WRLCK))
goto out;
error = flock_to_posix_lock(filp, &file_lock, &flock);
if (error)
goto out;
error = vfs_test_lock(filp, &file_lock);
if (error)
goto out;
flock.l_type = file_lock.fl_type;
if (file_lock.fl_type != F_UNLCK) {
error = posix_lock_to_flock(&flock, &file_lock);
if (error)
goto out;
}
error = -EFAULT;
if (!copy_to_user(l, &flock, sizeof(flock)))
error = 0;
out:
return error;
}
/**
* vfs_lock_file - file byte range lock
* @filp: The file to apply the lock to
* @cmd: type of locking operation (F_SETLK, F_GETLK, etc.)
* @fl: The lock to be applied
* @conf: Place to return a copy of the conflicting lock, if found.
*
* A caller that doesn't care about the conflicting lock may pass NULL
* as the final argument.
*
* If the filesystem defines a private ->lock() method, then @conf will
* be left unchanged; so a caller that cares should initialize it to
* some acceptable default.
*
* To avoid blocking kernel daemons, such as lockd, that need to acquire POSIX
* locks, the ->lock() interface may return asynchronously, before the lock has
* been granted or denied by the underlying filesystem, if (and only if)
* lm_grant is set. Callers expecting ->lock() to return asynchronously
* will only use F_SETLK, not F_SETLKW; they will set FL_SLEEP if (and only if)
* the request is for a blocking lock. When ->lock() does return asynchronously,
* it must return FILE_LOCK_DEFERRED, and call ->lm_grant() when the lock
* request completes.
* If the request is for non-blocking lock the file system should return
* FILE_LOCK_DEFERRED then try to get the lock and call the callback routine
* with the result. If the request timed out the callback routine will return a
* nonzero return code and the file system should release the lock. The file
* system is also responsible to keep a corresponding posix lock when it
* grants a lock so the VFS can find out which locks are locally held and do
* the correct lock cleanup when required.
* The underlying filesystem must not drop the kernel lock or call
* ->lm_grant() before returning to the caller with a FILE_LOCK_DEFERRED
* return code.
*/
int vfs_lock_file(struct file *filp, unsigned int cmd, struct file_lock *fl, struct file_lock *conf)
{
if (filp->f_op && filp->f_op->lock)
return filp->f_op->lock(filp, cmd, fl);
else
return posix_lock_file(filp, fl, conf);
}
EXPORT_SYMBOL_GPL(vfs_lock_file);
static int do_lock_file_wait(struct file *filp, unsigned int cmd,
struct file_lock *fl)
{
int error;
error = security_file_lock(filp, fl->fl_type);
if (error)
return error;
for (;;) {
error = vfs_lock_file(filp, cmd, fl, NULL);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl->fl_wait, !fl->fl_next);
if (!error)
continue;
locks_delete_block(fl);
break;
}
return error;
}
/* Apply the lock described by l to an open file descriptor.
* This implements both the F_SETLK and F_SETLKW commands of fcntl().
*/
int fcntl_setlk(unsigned int fd, struct file *filp, unsigned int cmd,
struct flock __user *l)
{
struct file_lock *file_lock = locks_alloc_lock();
struct flock flock;
struct inode *inode;
struct file *f;
int error;
if (file_lock == NULL)
return -ENOLCK;
/*
* This might block, so we do it before checking the inode.
*/
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
inode = file_inode(filp);
/* Don't allow mandatory locks on files that may be memory mapped
* and shared.
*/
if (mandatory_lock(inode) && mapping_writably_mapped(filp->f_mapping)) {
error = -EAGAIN;
goto out;
}
again:
error = flock_to_posix_lock(filp, file_lock, &flock);
if (error)
goto out;
if (cmd == F_SETLKW) {
file_lock->fl_flags |= FL_SLEEP;
}
error = -EBADF;
switch (flock.l_type) {
case F_RDLCK:
if (!(filp->f_mode & FMODE_READ))
goto out;
break;
case F_WRLCK:
if (!(filp->f_mode & FMODE_WRITE))
goto out;
break;
case F_UNLCK:
break;
default:
error = -EINVAL;
goto out;
}
error = do_lock_file_wait(filp, cmd, file_lock);
/*
* Attempt to detect a close/fcntl race and recover by
* releasing the lock that was just acquired.
*/
/*
* we need that spin_lock here - it prevents reordering between
* update of inode->i_flock and check for it done in close().
* rcu_read_lock() wouldn't do.
*/
spin_lock(¤t->files->file_lock);
f = fcheck(fd);
spin_unlock(¤t->files->file_lock);
if (!error && f != filp && flock.l_type != F_UNLCK) {
flock.l_type = F_UNLCK;
goto again;
}
out:
locks_free_lock(file_lock);
return error;
}
#if BITS_PER_LONG == 32
/* Report the first existing lock that would conflict with l.
* This implements the F_GETLK command of fcntl().
*/
int fcntl_getlk64(struct file *filp, struct flock64 __user *l)
{
struct file_lock file_lock;
struct flock64 flock;
int error;
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
error = -EINVAL;
if ((flock.l_type != F_RDLCK) && (flock.l_type != F_WRLCK))
goto out;
error = flock64_to_posix_lock(filp, &file_lock, &flock);
if (error)
goto out;
error = vfs_test_lock(filp, &file_lock);
if (error)
goto out;
flock.l_type = file_lock.fl_type;
if (file_lock.fl_type != F_UNLCK)
posix_lock_to_flock64(&flock, &file_lock);
error = -EFAULT;
if (!copy_to_user(l, &flock, sizeof(flock)))
error = 0;
out:
return error;
}
/* Apply the lock described by l to an open file descriptor.
* This implements both the F_SETLK and F_SETLKW commands of fcntl().
*/
int fcntl_setlk64(unsigned int fd, struct file *filp, unsigned int cmd,
struct flock64 __user *l)
{
struct file_lock *file_lock = locks_alloc_lock();
struct flock64 flock;
struct inode *inode;
struct file *f;
int error;
if (file_lock == NULL)
return -ENOLCK;
/*
* This might block, so we do it before checking the inode.
*/
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
inode = file_inode(filp);
/* Don't allow mandatory locks on files that may be memory mapped
* and shared.
*/
if (mandatory_lock(inode) && mapping_writably_mapped(filp->f_mapping)) {
error = -EAGAIN;
goto out;
}
again:
error = flock64_to_posix_lock(filp, file_lock, &flock);
if (error)
goto out;
if (cmd == F_SETLKW64) {
file_lock->fl_flags |= FL_SLEEP;
}
error = -EBADF;
switch (flock.l_type) {
case F_RDLCK:
if (!(filp->f_mode & FMODE_READ))
goto out;
break;
case F_WRLCK:
if (!(filp->f_mode & FMODE_WRITE))
goto out;
break;
case F_UNLCK:
break;
default:
error = -EINVAL;
goto out;
}
error = do_lock_file_wait(filp, cmd, file_lock);
/*
* Attempt to detect a close/fcntl race and recover by
* releasing the lock that was just acquired.
*/
spin_lock(¤t->files->file_lock);
f = fcheck(fd);
spin_unlock(¤t->files->file_lock);
if (!error && f != filp && flock.l_type != F_UNLCK) {
flock.l_type = F_UNLCK;
goto again;
}
out:
locks_free_lock(file_lock);
return error;
}
#endif /* BITS_PER_LONG == 32 */
/*
* This function is called when the file is being removed
* from the task's fd array. POSIX locks belonging to this task
* are deleted at this time.
*/
void locks_remove_posix(struct file *filp, fl_owner_t owner)
{
struct file_lock lock;
/*
* If there are no locks held on this file, we don't need to call
* posix_lock_file(). Another process could be setting a lock on this
* file at the same time, but we wouldn't remove that lock anyway.
*/
if (!file_inode(filp)->i_flock)
return;
lock.fl_type = F_UNLCK;
lock.fl_flags = FL_POSIX | FL_CLOSE;
lock.fl_start = 0;
lock.fl_end = OFFSET_MAX;
lock.fl_owner = owner;
lock.fl_pid = current->tgid;
lock.fl_file = filp;
lock.fl_ops = NULL;
lock.fl_lmops = NULL;
vfs_lock_file(filp, F_SETLK, &lock, NULL);
if (lock.fl_ops && lock.fl_ops->fl_release_private)
lock.fl_ops->fl_release_private(&lock);
}
EXPORT_SYMBOL(locks_remove_posix);
/*
* This function is called on the last close of an open file.
*/
void locks_remove_flock(struct file *filp)
{
struct inode * inode = file_inode(filp);
struct file_lock *fl;
struct file_lock **before;
if (!inode->i_flock)
return;
if (filp->f_op && filp->f_op->flock) {
struct file_lock fl = {
.fl_pid = current->tgid,
.fl_file = filp,
.fl_flags = FL_FLOCK,
.fl_type = F_UNLCK,
.fl_end = OFFSET_MAX,
};
filp->f_op->flock(filp, F_SETLKW, &fl);
if (fl.fl_ops && fl.fl_ops->fl_release_private)
fl.fl_ops->fl_release_private(&fl);
}
lock_flocks();
before = &inode->i_flock;
while ((fl = *before) != NULL) {
if (fl->fl_file == filp) {
if (IS_FLOCK(fl)) {
locks_delete_lock(before);
continue;
}
if (IS_LEASE(fl)) {
lease_modify(before, F_UNLCK);
continue;
}
/* What? */
BUG();
}
before = &fl->fl_next;
}
unlock_flocks();
}
/**
* posix_unblock_lock - stop waiting for a file lock
* @filp: how the file was opened
* @waiter: the lock which was waiting
*
* lockd needs to block waiting for locks.
*/
int
posix_unblock_lock(struct file *filp, struct file_lock *waiter)
{
int status = 0;
lock_flocks();
if (waiter->fl_next)
__locks_delete_block(waiter);
else
status = -ENOENT;
unlock_flocks();
return status;
}
EXPORT_SYMBOL(posix_unblock_lock);
/**
* vfs_cancel_lock - file byte range unblock lock
* @filp: The file to apply the unblock to
* @fl: The lock to be unblocked
*
* Used by lock managers to cancel blocked requests
*/
int vfs_cancel_lock(struct file *filp, struct file_lock *fl)
{
if (filp->f_op && filp->f_op->lock)
return filp->f_op->lock(filp, F_CANCELLK, fl);
return 0;
}
EXPORT_SYMBOL_GPL(vfs_cancel_lock);
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
static void lock_get_status(struct seq_file *f, struct file_lock *fl,
loff_t id, char *pfx)
{
struct inode *inode = NULL;
unsigned int fl_pid;
if (fl->fl_nspid)
fl_pid = pid_vnr(fl->fl_nspid);
else
fl_pid = fl->fl_pid;
if (fl->fl_file != NULL)
inode = file_inode(fl->fl_file);
seq_printf(f, "%lld:%s ", id, pfx);
if (IS_POSIX(fl)) {
seq_printf(f, "%6s %s ",
(fl->fl_flags & FL_ACCESS) ? "ACCESS" : "POSIX ",
(inode == NULL) ? "*NOINODE*" :
mandatory_lock(inode) ? "MANDATORY" : "ADVISORY ");
} else if (IS_FLOCK(fl)) {
if (fl->fl_type & LOCK_MAND) {
seq_printf(f, "FLOCK MSNFS ");
} else {
seq_printf(f, "FLOCK ADVISORY ");
}
} else if (IS_LEASE(fl)) {
seq_printf(f, "LEASE ");
if (lease_breaking(fl))
seq_printf(f, "BREAKING ");
else if (fl->fl_file)
seq_printf(f, "ACTIVE ");
else
seq_printf(f, "BREAKER ");
} else {
seq_printf(f, "UNKNOWN UNKNOWN ");
}
if (fl->fl_type & LOCK_MAND) {
seq_printf(f, "%s ",
(fl->fl_type & LOCK_READ)
? (fl->fl_type & LOCK_WRITE) ? "RW " : "READ "
: (fl->fl_type & LOCK_WRITE) ? "WRITE" : "NONE ");
} else {
seq_printf(f, "%s ",
(lease_breaking(fl))
? (fl->fl_type == F_UNLCK) ? "UNLCK" : "READ "
: (fl->fl_type == F_WRLCK) ? "WRITE" : "READ ");
}
if (inode) {
#ifdef WE_CAN_BREAK_LSLK_NOW
seq_printf(f, "%d %s:%ld ", fl_pid,
inode->i_sb->s_id, inode->i_ino);
#else
/* userspace relies on this representation of dev_t ;-( */
seq_printf(f, "%d %02x:%02x:%ld ", fl_pid,
MAJOR(inode->i_sb->s_dev),
MINOR(inode->i_sb->s_dev), inode->i_ino);
#endif
} else {
seq_printf(f, "%d <none>:0 ", fl_pid);
}
if (IS_POSIX(fl)) {
if (fl->fl_end == OFFSET_MAX)
seq_printf(f, "%Ld EOF\n", fl->fl_start);
else
seq_printf(f, "%Ld %Ld\n", fl->fl_start, fl->fl_end);
} else {
seq_printf(f, "0 EOF\n");
}
}
static int locks_show(struct seq_file *f, void *v)
{
struct file_lock *fl, *bfl;
fl = list_entry(v, struct file_lock, fl_link);
lock_get_status(f, fl, *((loff_t *)f->private), "");
list_for_each_entry(bfl, &fl->fl_block, fl_block)
lock_get_status(f, bfl, *((loff_t *)f->private), " ->");
return 0;
}
static void *locks_start(struct seq_file *f, loff_t *pos)
{
loff_t *p = f->private;
lock_flocks();
*p = (*pos + 1);
return seq_list_start(&file_lock_list, *pos);
}
static void *locks_next(struct seq_file *f, void *v, loff_t *pos)
{
loff_t *p = f->private;
++*p;
return seq_list_next(v, &file_lock_list, pos);
}
static void locks_stop(struct seq_file *f, void *v)
{
unlock_flocks();
}
static const struct seq_operations locks_seq_operations = {
.start = locks_start,
.next = locks_next,
.stop = locks_stop,
.show = locks_show,
};
static int locks_open(struct inode *inode, struct file *filp)
{
return seq_open_private(filp, &locks_seq_operations, sizeof(loff_t));
}
static const struct file_operations proc_locks_operations = {
.open = locks_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
static int __init proc_locks_init(void)
{
proc_create("locks", 0, NULL, &proc_locks_operations);
return 0;
}
module_init(proc_locks_init);
#endif
/**
* lock_may_read - checks that the region is free of locks
* @inode: the inode that is being read
* @start: the first byte to read
* @len: the number of bytes to read
*
* Emulates Windows locking requirements. Whole-file
* mandatory locks (share modes) can prohibit a read and
* byte-range POSIX locks can prohibit a read if they overlap.
*
* N.B. this function is only ever called
* from knfsd and ownership of locks is never checked.
*/
int lock_may_read(struct inode *inode, loff_t start, unsigned long len)
{
struct file_lock *fl;
int result = 1;
lock_flocks();
for (fl = inode->i_flock; fl != NULL; fl = fl->fl_next) {
if (IS_POSIX(fl)) {
if (fl->fl_type == F_RDLCK)
continue;
if ((fl->fl_end < start) || (fl->fl_start > (start + len)))
continue;
} else if (IS_FLOCK(fl)) {
if (!(fl->fl_type & LOCK_MAND))
continue;
if (fl->fl_type & LOCK_READ)
continue;
} else
continue;
result = 0;
break;
}
unlock_flocks();
return result;
}
EXPORT_SYMBOL(lock_may_read);
/**
* lock_may_write - checks that the region is free of locks
* @inode: the inode that is being written
* @start: the first byte to write
* @len: the number of bytes to write
*
* Emulates Windows locking requirements. Whole-file
* mandatory locks (share modes) can prohibit a write and
* byte-range POSIX locks can prohibit a write if they overlap.
*
* N.B. this function is only ever called
* from knfsd and ownership of locks is never checked.
*/
int lock_may_write(struct inode *inode, loff_t start, unsigned long len)
{
struct file_lock *fl;
int result = 1;
lock_flocks();
for (fl = inode->i_flock; fl != NULL; fl = fl->fl_next) {
if (IS_POSIX(fl)) {
if ((fl->fl_end < start) || (fl->fl_start > (start + len)))
continue;
} else if (IS_FLOCK(fl)) {
if (!(fl->fl_type & LOCK_MAND))
continue;
if (fl->fl_type & LOCK_WRITE)
continue;
} else
continue;
result = 0;
break;
}
unlock_flocks();
return result;
}
EXPORT_SYMBOL(lock_may_write);
static int __init filelock_init(void)
{
filelock_cache = kmem_cache_create("file_lock_cache",
sizeof(struct file_lock), 0, SLAB_PANIC, NULL);
return 0;
}
core_initcall(filelock_init);
| gpl-2.0 |
mtmichaelson/LG_Spectrum_Kernel | drivers/misc/ep93xx_pwm.c | 792 | 9721 | /*
* Simple PWM driver for EP93XX
*
* (c) Copyright 2009 Matthieu Crapet <mcrapet@gmail.com>
* (c) Copyright 2009 H Hartley Sweeten <hsweeten@visionengravers.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.
*
* EP9307 has only one channel:
* - PWMOUT
*
* EP9301/02/12/15 have two channels:
* - PWMOUT
* - PWMOUT1 (alternate function for EGPIO14)
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <mach/platform.h>
#define EP93XX_PWMx_TERM_COUNT 0x00
#define EP93XX_PWMx_DUTY_CYCLE 0x04
#define EP93XX_PWMx_ENABLE 0x08
#define EP93XX_PWMx_INVERT 0x0C
#define EP93XX_PWM_MAX_COUNT 0xFFFF
struct ep93xx_pwm {
void __iomem *mmio_base;
struct clk *clk;
u32 duty_percent;
};
static inline void ep93xx_pwm_writel(struct ep93xx_pwm *pwm,
unsigned int val, unsigned int off)
{
__raw_writel(val, pwm->mmio_base + off);
}
static inline unsigned int ep93xx_pwm_readl(struct ep93xx_pwm *pwm,
unsigned int off)
{
return __raw_readl(pwm->mmio_base + off);
}
static inline void ep93xx_pwm_write_tc(struct ep93xx_pwm *pwm, u16 value)
{
ep93xx_pwm_writel(pwm, value, EP93XX_PWMx_TERM_COUNT);
}
static inline u16 ep93xx_pwm_read_tc(struct ep93xx_pwm *pwm)
{
return ep93xx_pwm_readl(pwm, EP93XX_PWMx_TERM_COUNT);
}
static inline void ep93xx_pwm_write_dc(struct ep93xx_pwm *pwm, u16 value)
{
ep93xx_pwm_writel(pwm, value, EP93XX_PWMx_DUTY_CYCLE);
}
static inline void ep93xx_pwm_enable(struct ep93xx_pwm *pwm)
{
ep93xx_pwm_writel(pwm, 0x1, EP93XX_PWMx_ENABLE);
}
static inline void ep93xx_pwm_disable(struct ep93xx_pwm *pwm)
{
ep93xx_pwm_writel(pwm, 0x0, EP93XX_PWMx_ENABLE);
}
static inline int ep93xx_pwm_is_enabled(struct ep93xx_pwm *pwm)
{
return ep93xx_pwm_readl(pwm, EP93XX_PWMx_ENABLE) & 0x1;
}
static inline void ep93xx_pwm_invert(struct ep93xx_pwm *pwm)
{
ep93xx_pwm_writel(pwm, 0x1, EP93XX_PWMx_INVERT);
}
static inline void ep93xx_pwm_normal(struct ep93xx_pwm *pwm)
{
ep93xx_pwm_writel(pwm, 0x0, EP93XX_PWMx_INVERT);
}
static inline int ep93xx_pwm_is_inverted(struct ep93xx_pwm *pwm)
{
return ep93xx_pwm_readl(pwm, EP93XX_PWMx_INVERT) & 0x1;
}
/*
* /sys/devices/platform/ep93xx-pwm.N
* /min_freq read-only minimum pwm output frequency
* /max_req read-only maximum pwm output frequency
* /freq read-write pwm output frequency (0 = disable output)
* /duty_percent read-write pwm duty cycle percent (1..99)
* /invert read-write invert pwm output
*/
static ssize_t ep93xx_pwm_get_min_freq(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
unsigned long rate = clk_get_rate(pwm->clk);
return sprintf(buf, "%ld\n", rate / (EP93XX_PWM_MAX_COUNT + 1));
}
static ssize_t ep93xx_pwm_get_max_freq(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
unsigned long rate = clk_get_rate(pwm->clk);
return sprintf(buf, "%ld\n", rate / 2);
}
static ssize_t ep93xx_pwm_get_freq(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
if (ep93xx_pwm_is_enabled(pwm)) {
unsigned long rate = clk_get_rate(pwm->clk);
u16 term = ep93xx_pwm_read_tc(pwm);
return sprintf(buf, "%ld\n", rate / (term + 1));
} else {
return sprintf(buf, "disabled\n");
}
}
static ssize_t ep93xx_pwm_set_freq(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
long val;
int err;
err = strict_strtol(buf, 10, &val);
if (err)
return -EINVAL;
if (val == 0) {
ep93xx_pwm_disable(pwm);
} else if (val <= (clk_get_rate(pwm->clk) / 2)) {
u32 term, duty;
val = (clk_get_rate(pwm->clk) / val) - 1;
if (val > EP93XX_PWM_MAX_COUNT)
val = EP93XX_PWM_MAX_COUNT;
if (val < 1)
val = 1;
term = ep93xx_pwm_read_tc(pwm);
duty = ((val + 1) * pwm->duty_percent / 100) - 1;
/* If pwm is running, order is important */
if (val > term) {
ep93xx_pwm_write_tc(pwm, val);
ep93xx_pwm_write_dc(pwm, duty);
} else {
ep93xx_pwm_write_dc(pwm, duty);
ep93xx_pwm_write_tc(pwm, val);
}
if (!ep93xx_pwm_is_enabled(pwm))
ep93xx_pwm_enable(pwm);
} else {
return -EINVAL;
}
return count;
}
static ssize_t ep93xx_pwm_get_duty_percent(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
return sprintf(buf, "%d\n", pwm->duty_percent);
}
static ssize_t ep93xx_pwm_set_duty_percent(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
long val;
int err;
err = strict_strtol(buf, 10, &val);
if (err)
return -EINVAL;
if (val > 0 && val < 100) {
u32 term = ep93xx_pwm_read_tc(pwm);
ep93xx_pwm_write_dc(pwm, ((term + 1) * val / 100) - 1);
pwm->duty_percent = val;
return count;
}
return -EINVAL;
}
static ssize_t ep93xx_pwm_get_invert(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
return sprintf(buf, "%d\n", ep93xx_pwm_is_inverted(pwm));
}
static ssize_t ep93xx_pwm_set_invert(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
long val;
int err;
err = strict_strtol(buf, 10, &val);
if (err)
return -EINVAL;
if (val == 0)
ep93xx_pwm_normal(pwm);
else if (val == 1)
ep93xx_pwm_invert(pwm);
else
return -EINVAL;
return count;
}
static DEVICE_ATTR(min_freq, S_IRUGO, ep93xx_pwm_get_min_freq, NULL);
static DEVICE_ATTR(max_freq, S_IRUGO, ep93xx_pwm_get_max_freq, NULL);
static DEVICE_ATTR(freq, S_IWUGO | S_IRUGO,
ep93xx_pwm_get_freq, ep93xx_pwm_set_freq);
static DEVICE_ATTR(duty_percent, S_IWUGO | S_IRUGO,
ep93xx_pwm_get_duty_percent, ep93xx_pwm_set_duty_percent);
static DEVICE_ATTR(invert, S_IWUGO | S_IRUGO,
ep93xx_pwm_get_invert, ep93xx_pwm_set_invert);
static struct attribute *ep93xx_pwm_attrs[] = {
&dev_attr_min_freq.attr,
&dev_attr_max_freq.attr,
&dev_attr_freq.attr,
&dev_attr_duty_percent.attr,
&dev_attr_invert.attr,
NULL
};
static const struct attribute_group ep93xx_pwm_sysfs_files = {
.attrs = ep93xx_pwm_attrs,
};
static int __init ep93xx_pwm_probe(struct platform_device *pdev)
{
struct ep93xx_pwm *pwm;
struct resource *res;
int err;
err = ep93xx_pwm_acquire_gpio(pdev);
if (err)
return err;
pwm = kzalloc(sizeof(struct ep93xx_pwm), GFP_KERNEL);
if (!pwm) {
err = -ENOMEM;
goto fail_no_mem;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
err = -ENXIO;
goto fail_no_mem_resource;
}
res = request_mem_region(res->start, resource_size(res), pdev->name);
if (res == NULL) {
err = -EBUSY;
goto fail_no_mem_resource;
}
pwm->mmio_base = ioremap(res->start, resource_size(res));
if (pwm->mmio_base == NULL) {
err = -ENXIO;
goto fail_no_ioremap;
}
err = sysfs_create_group(&pdev->dev.kobj, &ep93xx_pwm_sysfs_files);
if (err)
goto fail_no_sysfs;
pwm->clk = clk_get(&pdev->dev, "pwm_clk");
if (IS_ERR(pwm->clk)) {
err = PTR_ERR(pwm->clk);
goto fail_no_clk;
}
pwm->duty_percent = 50;
platform_set_drvdata(pdev, pwm);
/* disable pwm at startup. Avoids zero value. */
ep93xx_pwm_disable(pwm);
ep93xx_pwm_write_tc(pwm, EP93XX_PWM_MAX_COUNT);
ep93xx_pwm_write_dc(pwm, EP93XX_PWM_MAX_COUNT / 2);
clk_enable(pwm->clk);
return 0;
fail_no_clk:
sysfs_remove_group(&pdev->dev.kobj, &ep93xx_pwm_sysfs_files);
fail_no_sysfs:
iounmap(pwm->mmio_base);
fail_no_ioremap:
release_mem_region(res->start, resource_size(res));
fail_no_mem_resource:
kfree(pwm);
fail_no_mem:
ep93xx_pwm_release_gpio(pdev);
return err;
}
static int __exit ep93xx_pwm_remove(struct platform_device *pdev)
{
struct ep93xx_pwm *pwm = platform_get_drvdata(pdev);
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ep93xx_pwm_disable(pwm);
clk_disable(pwm->clk);
clk_put(pwm->clk);
platform_set_drvdata(pdev, NULL);
sysfs_remove_group(&pdev->dev.kobj, &ep93xx_pwm_sysfs_files);
iounmap(pwm->mmio_base);
release_mem_region(res->start, resource_size(res));
kfree(pwm);
ep93xx_pwm_release_gpio(pdev);
return 0;
}
static struct platform_driver ep93xx_pwm_driver = {
.driver = {
.name = "ep93xx-pwm",
.owner = THIS_MODULE,
},
.remove = __exit_p(ep93xx_pwm_remove),
};
static int __init ep93xx_pwm_init(void)
{
return platform_driver_probe(&ep93xx_pwm_driver, ep93xx_pwm_probe);
}
static void __exit ep93xx_pwm_exit(void)
{
platform_driver_unregister(&ep93xx_pwm_driver);
}
module_init(ep93xx_pwm_init);
module_exit(ep93xx_pwm_exit);
MODULE_AUTHOR("Matthieu Crapet <mcrapet@gmail.com>, "
"H Hartley Sweeten <hsweeten@visionengravers.com>");
MODULE_DESCRIPTION("EP93xx PWM driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:ep93xx-pwm");
| gpl-2.0 |
p350user/ICY-PECAN-KERNEL | arch/powerpc/platforms/8xx/m8xx_setup.c | 1048 | 6582 | /*
* Copyright (C) 1995 Linus Torvalds
* Adapted from 'alpha' version by Gary Thomas
* Modified by Cort Dougan (cort@cs.nmt.edu)
* Modified for MBX using prep/chrp/pmac functions by Dan (dmalek@jlc.net)
* Further modified for generic 8xx by Dan.
*/
/*
* bootup setup stuff..
*/
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/rtc.h>
#include <linux/fsl_devices.h>
#include <asm/io.h>
#include <asm/mpc8xx.h>
#include <asm/8xx_immap.h>
#include <asm/prom.h>
#include <asm/fs_pd.h>
#include <mm/mmu_decl.h>
#include <sysdev/mpc8xx_pic.h>
#include "mpc8xx.h"
struct mpc8xx_pcmcia_ops m8xx_pcmcia_ops;
extern int cpm_pic_init(void);
extern int cpm_get_irq(void);
/* A place holder for time base interrupts, if they are ever enabled. */
static irqreturn_t timebase_interrupt(int irq, void *dev)
{
printk ("timebase_interrupt()\n");
return IRQ_HANDLED;
}
static struct irqaction tbint_irqaction = {
.handler = timebase_interrupt,
.name = "tbint",
};
/* per-board overridable init_internal_rtc() function. */
void __init __attribute__ ((weak))
init_internal_rtc(void)
{
sit8xx_t __iomem *sys_tmr = immr_map(im_sit);
/* Disable the RTC one second and alarm interrupts. */
clrbits16(&sys_tmr->sit_rtcsc, (RTCSC_SIE | RTCSC_ALE));
/* Enable the RTC */
setbits16(&sys_tmr->sit_rtcsc, (RTCSC_RTF | RTCSC_RTE));
immr_unmap(sys_tmr);
}
static int __init get_freq(char *name, unsigned long *val)
{
struct device_node *cpu;
const unsigned int *fp;
int found = 0;
/* The cpu node should have timebase and clock frequency properties */
cpu = of_find_node_by_type(NULL, "cpu");
if (cpu) {
fp = of_get_property(cpu, name, NULL);
if (fp) {
found = 1;
*val = *fp;
}
of_node_put(cpu);
}
return found;
}
/* The decrementer counts at the system (internal) clock frequency divided by
* sixteen, or external oscillator divided by four. We force the processor
* to use system clock divided by sixteen.
*/
void __init mpc8xx_calibrate_decr(void)
{
struct device_node *cpu;
cark8xx_t __iomem *clk_r1;
car8xx_t __iomem *clk_r2;
sitk8xx_t __iomem *sys_tmr1;
sit8xx_t __iomem *sys_tmr2;
int irq, virq;
clk_r1 = immr_map(im_clkrstk);
/* Unlock the SCCR. */
out_be32(&clk_r1->cark_sccrk, ~KAPWR_KEY);
out_be32(&clk_r1->cark_sccrk, KAPWR_KEY);
immr_unmap(clk_r1);
/* Force all 8xx processors to use divide by 16 processor clock. */
clk_r2 = immr_map(im_clkrst);
setbits32(&clk_r2->car_sccr, 0x02000000);
immr_unmap(clk_r2);
/* Processor frequency is MHz.
*/
ppc_proc_freq = 50000000;
if (!get_freq("clock-frequency", &ppc_proc_freq))
printk(KERN_ERR "WARNING: Estimating processor frequency "
"(not found)\n");
ppc_tb_freq = ppc_proc_freq / 16;
printk("Decrementer Frequency = 0x%lx\n", ppc_tb_freq);
/* Perform some more timer/timebase initialization. This used
* to be done elsewhere, but other changes caused it to get
* called more than once....that is a bad thing.
*
* First, unlock all of the registers we are going to modify.
* To protect them from corruption during power down, registers
* that are maintained by keep alive power are "locked". To
* modify these registers we have to write the key value to
* the key location associated with the register.
* Some boards power up with these unlocked, while others
* are locked. Writing anything (including the unlock code?)
* to the unlocked registers will lock them again. So, here
* we guarantee the registers are locked, then we unlock them
* for our use.
*/
sys_tmr1 = immr_map(im_sitk);
out_be32(&sys_tmr1->sitk_tbscrk, ~KAPWR_KEY);
out_be32(&sys_tmr1->sitk_rtcsck, ~KAPWR_KEY);
out_be32(&sys_tmr1->sitk_tbk, ~KAPWR_KEY);
out_be32(&sys_tmr1->sitk_tbscrk, KAPWR_KEY);
out_be32(&sys_tmr1->sitk_rtcsck, KAPWR_KEY);
out_be32(&sys_tmr1->sitk_tbk, KAPWR_KEY);
immr_unmap(sys_tmr1);
init_internal_rtc();
/* Enabling the decrementer also enables the timebase interrupts
* (or from the other point of view, to get decrementer interrupts
* we have to enable the timebase). The decrementer interrupt
* is wired into the vector table, nothing to do here for that.
*/
cpu = of_find_node_by_type(NULL, "cpu");
virq= irq_of_parse_and_map(cpu, 0);
irq = irq_map[virq].hwirq;
sys_tmr2 = immr_map(im_sit);
out_be16(&sys_tmr2->sit_tbscr, ((1 << (7 - (irq/2))) << 8) |
(TBSCR_TBF | TBSCR_TBE));
immr_unmap(sys_tmr2);
if (setup_irq(virq, &tbint_irqaction))
panic("Could not allocate timer IRQ!");
}
/* The RTC on the MPC8xx is an internal register.
* We want to protect this during power down, so we need to unlock,
* modify, and re-lock.
*/
int mpc8xx_set_rtc_time(struct rtc_time *tm)
{
sitk8xx_t __iomem *sys_tmr1;
sit8xx_t __iomem *sys_tmr2;
int time;
sys_tmr1 = immr_map(im_sitk);
sys_tmr2 = immr_map(im_sit);
time = mktime(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
out_be32(&sys_tmr1->sitk_rtck, KAPWR_KEY);
out_be32(&sys_tmr2->sit_rtc, time);
out_be32(&sys_tmr1->sitk_rtck, ~KAPWR_KEY);
immr_unmap(sys_tmr2);
immr_unmap(sys_tmr1);
return 0;
}
void mpc8xx_get_rtc_time(struct rtc_time *tm)
{
unsigned long data;
sit8xx_t __iomem *sys_tmr = immr_map(im_sit);
/* Get time from the RTC. */
data = in_be32(&sys_tmr->sit_rtc);
to_tm(data, tm);
tm->tm_year -= 1900;
tm->tm_mon -= 1;
immr_unmap(sys_tmr);
return;
}
void mpc8xx_restart(char *cmd)
{
car8xx_t __iomem *clk_r = immr_map(im_clkrst);
local_irq_disable();
setbits32(&clk_r->car_plprcr, 0x00000080);
/* Clear the ME bit in MSR to cause checkstop on machine check
*/
mtmsr(mfmsr() & ~0x1000);
in_8(&clk_r->res[0]);
panic("Restart failed\n");
}
static void cpm_cascade(unsigned int irq, struct irq_desc *desc)
{
int cascade_irq;
if ((cascade_irq = cpm_get_irq()) >= 0) {
struct irq_desc *cdesc = irq_to_desc(cascade_irq);
generic_handle_irq(cascade_irq);
cdesc->chip->eoi(cascade_irq);
}
desc->chip->eoi(irq);
}
/* Initialize the internal interrupt controllers. The number of
* interrupts supported can vary with the processor type, and the
* 82xx family can have up to 64.
* External interrupts can be either edge or level triggered, and
* need to be initialized by the appropriate driver.
*/
void __init mpc8xx_pics_init(void)
{
int irq;
if (mpc8xx_pic_init()) {
printk(KERN_ERR "Failed interrupt 8xx controller initialization\n");
return;
}
irq = cpm_pic_init();
if (irq != NO_IRQ)
set_irq_chained_handler(irq, cpm_cascade);
}
| gpl-2.0 |
gchild320/flounder | drivers/mfd/wm8994-core.c | 2072 | 19648 | /*
* wm8994-core.c -- Device access for Wolfson WM8994
*
* Copyright 2009 Wolfson Microelectronics PLC.
*
* 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 as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/mfd/core.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/wm8994/core.h>
#include <linux/mfd/wm8994/pdata.h>
#include <linux/mfd/wm8994/registers.h>
#include "wm8994.h"
/**
* wm8994_reg_read: Read a single WM8994 register.
*
* @wm8994: Device to read from.
* @reg: Register to read.
*/
int wm8994_reg_read(struct wm8994 *wm8994, unsigned short reg)
{
unsigned int val;
int ret;
ret = regmap_read(wm8994->regmap, reg, &val);
if (ret < 0)
return ret;
else
return val;
}
EXPORT_SYMBOL_GPL(wm8994_reg_read);
/**
* wm8994_bulk_read: Read multiple WM8994 registers
*
* @wm8994: Device to read from
* @reg: First register
* @count: Number of registers
* @buf: Buffer to fill. The data will be returned big endian.
*/
int wm8994_bulk_read(struct wm8994 *wm8994, unsigned short reg,
int count, u16 *buf)
{
return regmap_bulk_read(wm8994->regmap, reg, buf, count);
}
/**
* wm8994_reg_write: Write a single WM8994 register.
*
* @wm8994: Device to write to.
* @reg: Register to write to.
* @val: Value to write.
*/
int wm8994_reg_write(struct wm8994 *wm8994, unsigned short reg,
unsigned short val)
{
return regmap_write(wm8994->regmap, reg, val);
}
EXPORT_SYMBOL_GPL(wm8994_reg_write);
/**
* wm8994_bulk_write: Write multiple WM8994 registers
*
* @wm8994: Device to write to
* @reg: First register
* @count: Number of registers
* @buf: Buffer to write from. Data must be big-endian formatted.
*/
int wm8994_bulk_write(struct wm8994 *wm8994, unsigned short reg,
int count, const u16 *buf)
{
return regmap_raw_write(wm8994->regmap, reg, buf, count * sizeof(u16));
}
EXPORT_SYMBOL_GPL(wm8994_bulk_write);
/**
* wm8994_set_bits: Set the value of a bitfield in a WM8994 register
*
* @wm8994: Device to write to.
* @reg: Register to write to.
* @mask: Mask of bits to set.
* @val: Value to set (unshifted)
*/
int wm8994_set_bits(struct wm8994 *wm8994, unsigned short reg,
unsigned short mask, unsigned short val)
{
return regmap_update_bits(wm8994->regmap, reg, mask, val);
}
EXPORT_SYMBOL_GPL(wm8994_set_bits);
static struct mfd_cell wm8994_regulator_devs[] = {
{
.name = "wm8994-ldo",
.id = 1,
.pm_runtime_no_callbacks = true,
},
{
.name = "wm8994-ldo",
.id = 2,
.pm_runtime_no_callbacks = true,
},
};
static struct resource wm8994_codec_resources[] = {
{
.start = WM8994_IRQ_TEMP_SHUT,
.end = WM8994_IRQ_TEMP_WARN,
.flags = IORESOURCE_IRQ,
},
};
static struct resource wm8994_gpio_resources[] = {
{
.start = WM8994_IRQ_GPIO(1),
.end = WM8994_IRQ_GPIO(11),
.flags = IORESOURCE_IRQ,
},
};
static struct mfd_cell wm8994_devs[] = {
{
.name = "wm8994-codec",
.num_resources = ARRAY_SIZE(wm8994_codec_resources),
.resources = wm8994_codec_resources,
},
{
.name = "wm8994-gpio",
.num_resources = ARRAY_SIZE(wm8994_gpio_resources),
.resources = wm8994_gpio_resources,
.pm_runtime_no_callbacks = true,
},
};
/*
* Supplies for the main bulk of CODEC; the LDO supplies are ignored
* and should be handled via the standard regulator API supply
* management.
*/
static const char *wm1811_main_supplies[] = {
"DBVDD1",
"DBVDD2",
"DBVDD3",
"DCVDD",
"AVDD1",
"AVDD2",
"CPVDD",
"SPKVDD1",
"SPKVDD2",
};
static const char *wm8994_main_supplies[] = {
"DBVDD",
"DCVDD",
"AVDD1",
"AVDD2",
"CPVDD",
"SPKVDD1",
"SPKVDD2",
};
static const char *wm8958_main_supplies[] = {
"DBVDD1",
"DBVDD2",
"DBVDD3",
"DCVDD",
"AVDD1",
"AVDD2",
"CPVDD",
"SPKVDD1",
"SPKVDD2",
};
#ifdef CONFIG_PM_RUNTIME
static int wm8994_suspend(struct device *dev)
{
struct wm8994 *wm8994 = dev_get_drvdata(dev);
int ret;
/* Don't actually go through with the suspend if the CODEC is
* still active (eg, for audio passthrough from CP. */
ret = wm8994_reg_read(wm8994, WM8994_POWER_MANAGEMENT_1);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & WM8994_VMID_SEL_MASK) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
ret = wm8994_reg_read(wm8994, WM8994_POWER_MANAGEMENT_4);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & (WM8994_AIF2ADCL_ENA | WM8994_AIF2ADCR_ENA |
WM8994_AIF1ADC2L_ENA | WM8994_AIF1ADC2R_ENA |
WM8994_AIF1ADC1L_ENA | WM8994_AIF1ADC1R_ENA)) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
ret = wm8994_reg_read(wm8994, WM8994_POWER_MANAGEMENT_5);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & (WM8994_AIF2DACL_ENA | WM8994_AIF2DACR_ENA |
WM8994_AIF1DAC2L_ENA | WM8994_AIF1DAC2R_ENA |
WM8994_AIF1DAC1L_ENA | WM8994_AIF1DAC1R_ENA)) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
switch (wm8994->type) {
case WM8958:
case WM1811:
ret = wm8994_reg_read(wm8994, WM8958_MIC_DETECT_1);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & WM8958_MICD_ENA) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
break;
default:
break;
}
switch (wm8994->type) {
case WM1811:
ret = wm8994_reg_read(wm8994, WM8994_ANTIPOP_2);
if (ret < 0) {
dev_err(dev, "Failed to read jackdet: %d\n", ret);
} else if (ret & WM1811_JACKDET_MODE_MASK) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
break;
default:
break;
}
switch (wm8994->type) {
case WM1811:
ret = wm8994_reg_read(wm8994, WM8994_ANTIPOP_2);
if (ret < 0) {
dev_err(dev, "Failed to read jackdet: %d\n", ret);
} else if (ret & WM1811_JACKDET_MODE_MASK) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
break;
default:
break;
}
/* Disable LDO pulldowns while the device is suspended if we
* don't know that something will be driving them. */
if (!wm8994->ldo_ena_always_driven)
wm8994_set_bits(wm8994, WM8994_PULL_CONTROL_2,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD);
/* Explicitly put the device into reset in case regulators
* don't get disabled in order to ensure consistent restart.
*/
wm8994_reg_write(wm8994, WM8994_SOFTWARE_RESET,
wm8994_reg_read(wm8994, WM8994_SOFTWARE_RESET));
regcache_mark_dirty(wm8994->regmap);
/* Restore GPIO registers to prevent problems with mismatched
* pin configurations.
*/
ret = regcache_sync_region(wm8994->regmap, WM8994_GPIO_1,
WM8994_GPIO_11);
if (ret != 0)
dev_err(dev, "Failed to restore GPIO registers: %d\n", ret);
/* In case one of the GPIOs is used as a wake input. */
ret = regcache_sync_region(wm8994->regmap,
WM8994_INTERRUPT_STATUS_1_MASK,
WM8994_INTERRUPT_STATUS_1_MASK);
if (ret != 0)
dev_err(dev, "Failed to restore interrupt mask: %d\n", ret);
regcache_cache_only(wm8994->regmap, true);
wm8994->suspended = true;
ret = regulator_bulk_disable(wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(dev, "Failed to disable supplies: %d\n", ret);
return ret;
}
return 0;
}
static int wm8994_resume(struct device *dev)
{
struct wm8994 *wm8994 = dev_get_drvdata(dev);
int ret;
/* We may have lied to the PM core about suspending */
if (!wm8994->suspended)
return 0;
ret = regulator_bulk_enable(wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(dev, "Failed to enable supplies: %d\n", ret);
return ret;
}
regcache_cache_only(wm8994->regmap, false);
ret = regcache_sync(wm8994->regmap);
if (ret != 0) {
dev_err(dev, "Failed to restore register map: %d\n", ret);
goto err_enable;
}
/* Disable LDO pulldowns while the device is active */
wm8994_set_bits(wm8994, WM8994_PULL_CONTROL_2,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD,
0);
wm8994->suspended = false;
return 0;
err_enable:
regulator_bulk_disable(wm8994->num_supplies, wm8994->supplies);
return ret;
}
#endif
#ifdef CONFIG_REGULATOR
static int wm8994_ldo_in_use(struct wm8994_pdata *pdata, int ldo)
{
struct wm8994_ldo_pdata *ldo_pdata;
if (!pdata)
return 0;
ldo_pdata = &pdata->ldo[ldo];
if (!ldo_pdata->init_data)
return 0;
return ldo_pdata->init_data->num_consumer_supplies != 0;
}
#else
static int wm8994_ldo_in_use(struct wm8994_pdata *pdata, int ldo)
{
return 0;
}
#endif
static const struct reg_default wm8994_revc_patch[] = {
{ 0x102, 0x3 },
{ 0x56, 0x3 },
{ 0x817, 0x0 },
{ 0x102, 0x0 },
};
static const struct reg_default wm8958_reva_patch[] = {
{ 0x102, 0x3 },
{ 0xcb, 0x81 },
{ 0x817, 0x0 },
{ 0x102, 0x0 },
};
static const struct reg_default wm1811_reva_patch[] = {
{ 0x102, 0x3 },
{ 0x56, 0xc07 },
{ 0x5d, 0x7e },
{ 0x5e, 0x0 },
{ 0x102, 0x0 },
};
#ifdef CONFIG_OF
static int wm8994_set_pdata_from_of(struct wm8994 *wm8994)
{
struct device_node *np = wm8994->dev->of_node;
struct wm8994_pdata *pdata = &wm8994->pdata;
int i;
if (!np)
return 0;
if (of_property_read_u32_array(np, "wlf,gpio-cfg", pdata->gpio_defaults,
ARRAY_SIZE(pdata->gpio_defaults)) >= 0) {
for (i = 0; i < ARRAY_SIZE(pdata->gpio_defaults); i++) {
if (wm8994->pdata.gpio_defaults[i] == 0)
pdata->gpio_defaults[i]
= WM8994_CONFIGURE_GPIO;
}
}
of_property_read_u32_array(np, "wlf,micbias-cfg", pdata->micbias,
ARRAY_SIZE(pdata->micbias));
pdata->lineout1_diff = true;
pdata->lineout2_diff = true;
if (of_find_property(np, "wlf,lineout1-se", NULL))
pdata->lineout1_diff = false;
if (of_find_property(np, "wlf,lineout2-se", NULL))
pdata->lineout2_diff = false;
if (of_find_property(np, "wlf,lineout1-feedback", NULL))
pdata->lineout1fb = true;
if (of_find_property(np, "wlf,lineout2-feedback", NULL))
pdata->lineout2fb = true;
if (of_find_property(np, "wlf,ldoena-always-driven", NULL))
pdata->lineout2fb = true;
pdata->ldo[0].enable = of_get_named_gpio(np, "wlf,ldo1ena", 0);
if (pdata->ldo[0].enable < 0)
pdata->ldo[0].enable = 0;
pdata->ldo[1].enable = of_get_named_gpio(np, "wlf,ldo2ena", 0);
if (pdata->ldo[1].enable < 0)
pdata->ldo[1].enable = 0;
return 0;
}
#else
static int wm8994_set_pdata_from_of(struct wm8994 *wm8994)
{
return 0;
}
#endif
/*
* Instantiate the generic non-control parts of the device.
*/
static int wm8994_device_init(struct wm8994 *wm8994, int irq)
{
struct wm8994_pdata *pdata;
struct regmap_config *regmap_config;
const struct reg_default *regmap_patch = NULL;
const char *devname;
int ret, i, patch_regs = 0;
int pulls = 0;
if (dev_get_platdata(wm8994->dev)) {
pdata = dev_get_platdata(wm8994->dev);
wm8994->pdata = *pdata;
}
pdata = &wm8994->pdata;
ret = wm8994_set_pdata_from_of(wm8994);
if (ret != 0)
return ret;
dev_set_drvdata(wm8994->dev, wm8994);
/* Add the on-chip regulators first for bootstrapping */
ret = mfd_add_devices(wm8994->dev, -1,
wm8994_regulator_devs,
ARRAY_SIZE(wm8994_regulator_devs),
NULL, 0, NULL);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to add children: %d\n", ret);
goto err;
}
switch (wm8994->type) {
case WM1811:
wm8994->num_supplies = ARRAY_SIZE(wm1811_main_supplies);
break;
case WM8994:
wm8994->num_supplies = ARRAY_SIZE(wm8994_main_supplies);
break;
case WM8958:
wm8994->num_supplies = ARRAY_SIZE(wm8958_main_supplies);
break;
default:
BUG();
goto err;
}
wm8994->supplies = devm_kzalloc(wm8994->dev,
sizeof(struct regulator_bulk_data) *
wm8994->num_supplies, GFP_KERNEL);
if (!wm8994->supplies) {
ret = -ENOMEM;
goto err;
}
switch (wm8994->type) {
case WM1811:
for (i = 0; i < ARRAY_SIZE(wm1811_main_supplies); i++)
wm8994->supplies[i].supply = wm1811_main_supplies[i];
break;
case WM8994:
for (i = 0; i < ARRAY_SIZE(wm8994_main_supplies); i++)
wm8994->supplies[i].supply = wm8994_main_supplies[i];
break;
case WM8958:
for (i = 0; i < ARRAY_SIZE(wm8958_main_supplies); i++)
wm8994->supplies[i].supply = wm8958_main_supplies[i];
break;
default:
BUG();
goto err;
}
ret = devm_regulator_bulk_get(wm8994->dev, wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to get supplies: %d\n", ret);
goto err;
}
ret = regulator_bulk_enable(wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to enable supplies: %d\n", ret);
goto err;
}
ret = wm8994_reg_read(wm8994, WM8994_SOFTWARE_RESET);
if (ret < 0) {
dev_err(wm8994->dev, "Failed to read ID register\n");
goto err_enable;
}
switch (ret) {
case 0x1811:
devname = "WM1811";
if (wm8994->type != WM1811)
dev_warn(wm8994->dev, "Device registered as type %d\n",
wm8994->type);
wm8994->type = WM1811;
break;
case 0x8994:
devname = "WM8994";
if (wm8994->type != WM8994)
dev_warn(wm8994->dev, "Device registered as type %d\n",
wm8994->type);
wm8994->type = WM8994;
break;
case 0x8958:
devname = "WM8958";
if (wm8994->type != WM8958)
dev_warn(wm8994->dev, "Device registered as type %d\n",
wm8994->type);
wm8994->type = WM8958;
break;
default:
dev_err(wm8994->dev, "Device is not a WM8994, ID is %x\n",
ret);
ret = -EINVAL;
goto err_enable;
}
ret = wm8994_reg_read(wm8994, WM8994_CHIP_REVISION);
if (ret < 0) {
dev_err(wm8994->dev, "Failed to read revision register: %d\n",
ret);
goto err_enable;
}
wm8994->revision = ret & WM8994_CHIP_REV_MASK;
wm8994->cust_id = (ret & WM8994_CUST_ID_MASK) >> WM8994_CUST_ID_SHIFT;
switch (wm8994->type) {
case WM8994:
switch (wm8994->revision) {
case 0:
case 1:
dev_warn(wm8994->dev,
"revision %c not fully supported\n",
'A' + wm8994->revision);
break;
case 2:
case 3:
default:
regmap_patch = wm8994_revc_patch;
patch_regs = ARRAY_SIZE(wm8994_revc_patch);
break;
}
break;
case WM8958:
switch (wm8994->revision) {
case 0:
regmap_patch = wm8958_reva_patch;
patch_regs = ARRAY_SIZE(wm8958_reva_patch);
break;
default:
break;
}
break;
case WM1811:
/* Revision C did not change the relevant layer */
if (wm8994->revision > 1)
wm8994->revision++;
regmap_patch = wm1811_reva_patch;
patch_regs = ARRAY_SIZE(wm1811_reva_patch);
break;
default:
break;
}
dev_info(wm8994->dev, "%s revision %c CUST_ID %02x\n", devname,
'A' + wm8994->revision, wm8994->cust_id);
switch (wm8994->type) {
case WM1811:
regmap_config = &wm1811_regmap_config;
break;
case WM8994:
regmap_config = &wm8994_regmap_config;
break;
case WM8958:
regmap_config = &wm8958_regmap_config;
break;
default:
dev_err(wm8994->dev, "Unknown device type %d\n", wm8994->type);
return -EINVAL;
}
ret = regmap_reinit_cache(wm8994->regmap, regmap_config);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to reinit register cache: %d\n",
ret);
return ret;
}
if (regmap_patch) {
ret = regmap_register_patch(wm8994->regmap, regmap_patch,
patch_regs);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to register patch: %d\n",
ret);
goto err;
}
}
wm8994->irq_base = pdata->irq_base;
wm8994->gpio_base = pdata->gpio_base;
/* GPIO configuration is only applied if it's non-zero */
for (i = 0; i < ARRAY_SIZE(pdata->gpio_defaults); i++) {
if (pdata->gpio_defaults[i]) {
wm8994_set_bits(wm8994, WM8994_GPIO_1 + i,
0xffff, pdata->gpio_defaults[i]);
}
}
wm8994->ldo_ena_always_driven = pdata->ldo_ena_always_driven;
if (pdata->spkmode_pu)
pulls |= WM8994_SPKMODE_PU;
/* Disable unneeded pulls */
wm8994_set_bits(wm8994, WM8994_PULL_CONTROL_2,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD |
WM8994_SPKMODE_PU | WM8994_CSNADDR_PD,
pulls);
/* In some system designs where the regulators are not in use,
* we can achieve a small reduction in leakage currents by
* floating LDO outputs. This bit makes no difference if the
* LDOs are enabled, it only affects cases where the LDOs were
* in operation and are then disabled.
*/
for (i = 0; i < WM8994_NUM_LDO_REGS; i++) {
if (wm8994_ldo_in_use(pdata, i))
wm8994_set_bits(wm8994, WM8994_LDO_1 + i,
WM8994_LDO1_DISCH, WM8994_LDO1_DISCH);
else
wm8994_set_bits(wm8994, WM8994_LDO_1 + i,
WM8994_LDO1_DISCH, 0);
}
wm8994_irq_init(wm8994);
ret = mfd_add_devices(wm8994->dev, -1,
wm8994_devs, ARRAY_SIZE(wm8994_devs),
NULL, 0, NULL);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to add children: %d\n", ret);
goto err_irq;
}
pm_runtime_enable(wm8994->dev);
pm_runtime_idle(wm8994->dev);
return 0;
err_irq:
wm8994_irq_exit(wm8994);
err_enable:
regulator_bulk_disable(wm8994->num_supplies,
wm8994->supplies);
err:
mfd_remove_devices(wm8994->dev);
return ret;
}
static void wm8994_device_exit(struct wm8994 *wm8994)
{
pm_runtime_disable(wm8994->dev);
mfd_remove_devices(wm8994->dev);
wm8994_irq_exit(wm8994);
regulator_bulk_disable(wm8994->num_supplies,
wm8994->supplies);
}
static const struct of_device_id wm8994_of_match[] = {
{ .compatible = "wlf,wm1811", .data = (void *)WM1811 },
{ .compatible = "wlf,wm8994", .data = (void *)WM8994 },
{ .compatible = "wlf,wm8958", .data = (void *)WM8958 },
{ }
};
MODULE_DEVICE_TABLE(of, wm8994_of_match);
static int wm8994_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
const struct of_device_id *of_id;
struct wm8994 *wm8994;
int ret;
wm8994 = devm_kzalloc(&i2c->dev, sizeof(struct wm8994), GFP_KERNEL);
if (wm8994 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8994);
wm8994->dev = &i2c->dev;
wm8994->irq = i2c->irq;
if (i2c->dev.of_node) {
of_id = of_match_device(wm8994_of_match, &i2c->dev);
if (of_id)
wm8994->type = (int)of_id->data;
} else {
wm8994->type = id->driver_data;
}
wm8994->regmap = devm_regmap_init_i2c(i2c, &wm8994_base_regmap_config);
if (IS_ERR(wm8994->regmap)) {
ret = PTR_ERR(wm8994->regmap);
dev_err(wm8994->dev, "Failed to allocate register map: %d\n",
ret);
return ret;
}
return wm8994_device_init(wm8994, i2c->irq);
}
static int wm8994_i2c_remove(struct i2c_client *i2c)
{
struct wm8994 *wm8994 = i2c_get_clientdata(i2c);
wm8994_device_exit(wm8994);
return 0;
}
static const struct i2c_device_id wm8994_i2c_id[] = {
{ "wm1811", WM1811 },
{ "wm1811a", WM1811 },
{ "wm8994", WM8994 },
{ "wm8958", WM8958 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8994_i2c_id);
static const struct dev_pm_ops wm8994_pm_ops = {
SET_RUNTIME_PM_OPS(wm8994_suspend, wm8994_resume, NULL)
};
static struct i2c_driver wm8994_i2c_driver = {
.driver = {
.name = "wm8994",
.owner = THIS_MODULE,
.pm = &wm8994_pm_ops,
.of_match_table = of_match_ptr(wm8994_of_match),
},
.probe = wm8994_i2c_probe,
.remove = wm8994_i2c_remove,
.id_table = wm8994_i2c_id,
};
module_i2c_driver(wm8994_i2c_driver);
MODULE_DESCRIPTION("Core support for the WM8994 audio CODEC");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
| gpl-2.0 |
sajal/mptcp-rpi | net/ipv4/ipconfig.c | 2328 | 40042 | /*
* Automatic Configuration of IP -- use DHCP, BOOTP, RARP, or
* user-supplied information to configure own IP address and routes.
*
* Copyright (C) 1996-1998 Martin Mares <mj@atrey.karlin.mff.cuni.cz>
*
* Derived from network configuration code in fs/nfs/nfsroot.c,
* originally Copyright (C) 1995, 1996 Gero Kuhlmann and me.
*
* BOOTP rewritten to construct and analyse packets itself instead
* of misusing the IP layer. num_bugs_causing_wrong_arp_replies--;
* -- MJ, December 1998
*
* Fixed ip_auto_config_setup calling at startup in the new "Linker Magic"
* initialization scheme.
* - Arnaldo Carvalho de Melo <acme@conectiva.com.br>, 08/11/1999
*
* DHCP support added. To users this looks like a whole separate
* protocol, but we know it's just a bag on the side of BOOTP.
* -- Chip Salzenberg <chip@valinux.com>, May 2000
*
* Ported DHCP support from 2.2.16 to 2.4.0-test4
* -- Eric Biederman <ebiederman@lnxi.com>, 30 Aug 2000
*
* Merged changes from 2.2.19 into 2.4.3
* -- Eric Biederman <ebiederman@lnxi.com>, 22 April Aug 2001
*
* Multiple Nameservers in /proc/net/pnp
* -- Josef Siemes <jsiemes@web.de>, Aug 2002
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/random.h>
#include <linux/init.h>
#include <linux/utsname.h>
#include <linux/in.h>
#include <linux/if.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/socket.h>
#include <linux/route.h>
#include <linux/udp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/major.h>
#include <linux/root_dev.h>
#include <linux/delay.h>
#include <linux/nfs_fs.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <net/net_namespace.h>
#include <net/arp.h>
#include <net/ip.h>
#include <net/ipconfig.h>
#include <net/route.h>
#include <asm/uaccess.h>
#include <net/checksum.h>
#include <asm/processor.h>
/* Define this to allow debugging output */
#undef IPCONFIG_DEBUG
#ifdef IPCONFIG_DEBUG
#define DBG(x) printk x
#else
#define DBG(x) do { } while(0)
#endif
#if defined(CONFIG_IP_PNP_DHCP)
#define IPCONFIG_DHCP
#endif
#if defined(CONFIG_IP_PNP_BOOTP) || defined(CONFIG_IP_PNP_DHCP)
#define IPCONFIG_BOOTP
#endif
#if defined(CONFIG_IP_PNP_RARP)
#define IPCONFIG_RARP
#endif
#if defined(IPCONFIG_BOOTP) || defined(IPCONFIG_RARP)
#define IPCONFIG_DYNAMIC
#endif
/* Define the friendly delay before and after opening net devices */
#define CONF_POST_OPEN 10 /* After opening: 10 msecs */
#define CONF_CARRIER_TIMEOUT 120000 /* Wait for carrier timeout */
/* Define the timeout for waiting for a DHCP/BOOTP/RARP reply */
#define CONF_OPEN_RETRIES 2 /* (Re)open devices twice */
#define CONF_SEND_RETRIES 6 /* Send six requests per open */
#define CONF_INTER_TIMEOUT (HZ/2) /* Inter-device timeout: 1/2 second */
#define CONF_BASE_TIMEOUT (HZ*2) /* Initial timeout: 2 seconds */
#define CONF_TIMEOUT_RANDOM (HZ) /* Maximum amount of randomization */
#define CONF_TIMEOUT_MULT *7/4 /* Rate of timeout growth */
#define CONF_TIMEOUT_MAX (HZ*30) /* Maximum allowed timeout */
#define CONF_NAMESERVERS_MAX 3 /* Maximum number of nameservers
- '3' from resolv.h */
#define NONE cpu_to_be32(INADDR_NONE)
#define ANY cpu_to_be32(INADDR_ANY)
/*
* Public IP configuration
*/
/* This is used by platforms which might be able to set the ipconfig
* variables using firmware environment vars. If this is set, it will
* ignore such firmware variables.
*/
int ic_set_manually __initdata = 0; /* IPconfig parameters set manually */
static int ic_enable __initdata = 0; /* IP config enabled? */
/* Protocol choice */
int ic_proto_enabled __initdata = 0
#ifdef IPCONFIG_BOOTP
| IC_BOOTP
#endif
#ifdef CONFIG_IP_PNP_DHCP
| IC_USE_DHCP
#endif
#ifdef IPCONFIG_RARP
| IC_RARP
#endif
;
static int ic_host_name_set __initdata = 0; /* Host name set by us? */
__be32 ic_myaddr = NONE; /* My IP address */
static __be32 ic_netmask = NONE; /* Netmask for local subnet */
__be32 ic_gateway = NONE; /* Gateway IP address */
__be32 ic_addrservaddr = NONE; /* IP Address of the IP addresses'server */
__be32 ic_servaddr = NONE; /* Boot server IP address */
__be32 root_server_addr = NONE; /* Address of NFS server */
u8 root_server_path[256] = { 0, }; /* Path to mount as root */
__be32 ic_dev_xid; /* Device under configuration */
/* vendor class identifier */
static char vendor_class_identifier[253] __initdata;
/* Persistent data: */
static int ic_proto_used; /* Protocol used, if any */
static __be32 ic_nameservers[CONF_NAMESERVERS_MAX]; /* DNS Server IP addresses */
static u8 ic_domain[64]; /* DNS (not NIS) domain name */
/*
* Private state.
*/
/* Name of user-selected boot device */
static char user_dev_name[IFNAMSIZ] __initdata = { 0, };
/* Protocols supported by available interfaces */
static int ic_proto_have_if __initdata = 0;
/* MTU for boot device */
static int ic_dev_mtu __initdata = 0;
#ifdef IPCONFIG_DYNAMIC
static DEFINE_SPINLOCK(ic_recv_lock);
static volatile int ic_got_reply __initdata = 0; /* Proto(s) that replied */
#endif
#ifdef IPCONFIG_DHCP
static int ic_dhcp_msgtype __initdata = 0; /* DHCP msg type received */
#endif
/*
* Network devices
*/
struct ic_device {
struct ic_device *next;
struct net_device *dev;
unsigned short flags;
short able;
__be32 xid;
};
static struct ic_device *ic_first_dev __initdata = NULL;/* List of open device */
static struct net_device *ic_dev __initdata = NULL; /* Selected device */
static bool __init ic_is_init_dev(struct net_device *dev)
{
if (dev->flags & IFF_LOOPBACK)
return false;
return user_dev_name[0] ? !strcmp(dev->name, user_dev_name) :
(!(dev->flags & IFF_LOOPBACK) &&
(dev->flags & (IFF_POINTOPOINT|IFF_BROADCAST)) &&
strncmp(dev->name, "dummy", 5));
}
static int __init ic_open_devs(void)
{
struct ic_device *d, **last;
struct net_device *dev;
unsigned short oflags;
unsigned long start, next_msg;
last = &ic_first_dev;
rtnl_lock();
/* bring loopback device up first */
for_each_netdev(&init_net, dev) {
if (!(dev->flags & IFF_LOOPBACK))
continue;
if (dev_change_flags(dev, dev->flags | IFF_UP) < 0)
pr_err("IP-Config: Failed to open %s\n", dev->name);
}
for_each_netdev(&init_net, dev) {
if (ic_is_init_dev(dev)) {
int able = 0;
if (dev->mtu >= 364)
able |= IC_BOOTP;
else
pr_warn("DHCP/BOOTP: Ignoring device %s, MTU %d too small",
dev->name, dev->mtu);
if (!(dev->flags & IFF_NOARP))
able |= IC_RARP;
able &= ic_proto_enabled;
if (ic_proto_enabled && !able)
continue;
oflags = dev->flags;
if (dev_change_flags(dev, oflags | IFF_UP) < 0) {
pr_err("IP-Config: Failed to open %s\n",
dev->name);
continue;
}
if (!(d = kmalloc(sizeof(struct ic_device), GFP_KERNEL))) {
rtnl_unlock();
return -ENOMEM;
}
d->dev = dev;
*last = d;
last = &d->next;
d->flags = oflags;
d->able = able;
if (able & IC_BOOTP)
get_random_bytes(&d->xid, sizeof(__be32));
else
d->xid = 0;
ic_proto_have_if |= able;
DBG(("IP-Config: %s UP (able=%d, xid=%08x)\n",
dev->name, able, d->xid));
}
}
/* no point in waiting if we could not bring up at least one device */
if (!ic_first_dev)
goto have_carrier;
/* wait for a carrier on at least one device */
start = jiffies;
next_msg = start + msecs_to_jiffies(CONF_CARRIER_TIMEOUT/12);
while (jiffies - start < msecs_to_jiffies(CONF_CARRIER_TIMEOUT)) {
int wait, elapsed;
for_each_netdev(&init_net, dev)
if (ic_is_init_dev(dev) && netif_carrier_ok(dev))
goto have_carrier;
msleep(1);
if time_before(jiffies, next_msg)
continue;
elapsed = jiffies_to_msecs(jiffies - start);
wait = (CONF_CARRIER_TIMEOUT - elapsed + 500)/1000;
pr_info("Waiting up to %d more seconds for network.\n", wait);
next_msg = jiffies + msecs_to_jiffies(CONF_CARRIER_TIMEOUT/12);
}
have_carrier:
rtnl_unlock();
*last = NULL;
if (!ic_first_dev) {
if (user_dev_name[0])
pr_err("IP-Config: Device `%s' not found\n",
user_dev_name);
else
pr_err("IP-Config: No network devices available\n");
return -ENODEV;
}
return 0;
}
static void __init ic_close_devs(void)
{
struct ic_device *d, *next;
struct net_device *dev;
rtnl_lock();
next = ic_first_dev;
while ((d = next)) {
next = d->next;
dev = d->dev;
if (dev != ic_dev) {
DBG(("IP-Config: Downing %s\n", dev->name));
dev_change_flags(dev, d->flags);
}
kfree(d);
}
rtnl_unlock();
}
/*
* Interface to various network functions.
*/
static inline void
set_sockaddr(struct sockaddr_in *sin, __be32 addr, __be16 port)
{
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = addr;
sin->sin_port = port;
}
static int __init ic_devinet_ioctl(unsigned int cmd, struct ifreq *arg)
{
int res;
mm_segment_t oldfs = get_fs();
set_fs(get_ds());
res = devinet_ioctl(&init_net, cmd, (struct ifreq __user *) arg);
set_fs(oldfs);
return res;
}
static int __init ic_dev_ioctl(unsigned int cmd, struct ifreq *arg)
{
int res;
mm_segment_t oldfs = get_fs();
set_fs(get_ds());
res = dev_ioctl(&init_net, cmd, (struct ifreq __user *) arg);
set_fs(oldfs);
return res;
}
static int __init ic_route_ioctl(unsigned int cmd, struct rtentry *arg)
{
int res;
mm_segment_t oldfs = get_fs();
set_fs(get_ds());
res = ip_rt_ioctl(&init_net, cmd, (void __user *) arg);
set_fs(oldfs);
return res;
}
/*
* Set up interface addresses and routes.
*/
static int __init ic_setup_if(void)
{
struct ifreq ir;
struct sockaddr_in *sin = (void *) &ir.ifr_ifru.ifru_addr;
int err;
memset(&ir, 0, sizeof(ir));
strcpy(ir.ifr_ifrn.ifrn_name, ic_dev->name);
set_sockaddr(sin, ic_myaddr, 0);
if ((err = ic_devinet_ioctl(SIOCSIFADDR, &ir)) < 0) {
pr_err("IP-Config: Unable to set interface address (%d)\n",
err);
return -1;
}
set_sockaddr(sin, ic_netmask, 0);
if ((err = ic_devinet_ioctl(SIOCSIFNETMASK, &ir)) < 0) {
pr_err("IP-Config: Unable to set interface netmask (%d)\n",
err);
return -1;
}
set_sockaddr(sin, ic_myaddr | ~ic_netmask, 0);
if ((err = ic_devinet_ioctl(SIOCSIFBRDADDR, &ir)) < 0) {
pr_err("IP-Config: Unable to set interface broadcast address (%d)\n",
err);
return -1;
}
/* Handle the case where we need non-standard MTU on the boot link (a network
* using jumbo frames, for instance). If we can't set the mtu, don't error
* out, we'll try to muddle along.
*/
if (ic_dev_mtu != 0) {
strcpy(ir.ifr_name, ic_dev->name);
ir.ifr_mtu = ic_dev_mtu;
if ((err = ic_dev_ioctl(SIOCSIFMTU, &ir)) < 0)
pr_err("IP-Config: Unable to set interface mtu to %d (%d)\n",
ic_dev_mtu, err);
}
return 0;
}
static int __init ic_setup_routes(void)
{
/* No need to setup device routes, only the default route... */
if (ic_gateway != NONE) {
struct rtentry rm;
int err;
memset(&rm, 0, sizeof(rm));
if ((ic_gateway ^ ic_myaddr) & ic_netmask) {
pr_err("IP-Config: Gateway not on directly connected network\n");
return -1;
}
set_sockaddr((struct sockaddr_in *) &rm.rt_dst, 0, 0);
set_sockaddr((struct sockaddr_in *) &rm.rt_genmask, 0, 0);
set_sockaddr((struct sockaddr_in *) &rm.rt_gateway, ic_gateway, 0);
rm.rt_flags = RTF_UP | RTF_GATEWAY;
if ((err = ic_route_ioctl(SIOCADDRT, &rm)) < 0) {
pr_err("IP-Config: Cannot add default route (%d)\n",
err);
return -1;
}
}
return 0;
}
/*
* Fill in default values for all missing parameters.
*/
static int __init ic_defaults(void)
{
/*
* At this point we have no userspace running so need not
* claim locks on system_utsname
*/
if (!ic_host_name_set)
sprintf(init_utsname()->nodename, "%pI4", &ic_myaddr);
if (root_server_addr == NONE)
root_server_addr = ic_servaddr;
if (ic_netmask == NONE) {
if (IN_CLASSA(ntohl(ic_myaddr)))
ic_netmask = htonl(IN_CLASSA_NET);
else if (IN_CLASSB(ntohl(ic_myaddr)))
ic_netmask = htonl(IN_CLASSB_NET);
else if (IN_CLASSC(ntohl(ic_myaddr)))
ic_netmask = htonl(IN_CLASSC_NET);
else {
pr_err("IP-Config: Unable to guess netmask for address %pI4\n",
&ic_myaddr);
return -1;
}
printk("IP-Config: Guessing netmask %pI4\n", &ic_netmask);
}
return 0;
}
/*
* RARP support.
*/
#ifdef IPCONFIG_RARP
static int ic_rarp_recv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev);
static struct packet_type rarp_packet_type __initdata = {
.type = cpu_to_be16(ETH_P_RARP),
.func = ic_rarp_recv,
};
static inline void __init ic_rarp_init(void)
{
dev_add_pack(&rarp_packet_type);
}
static inline void __init ic_rarp_cleanup(void)
{
dev_remove_pack(&rarp_packet_type);
}
/*
* Process received RARP packet.
*/
static int __init
ic_rarp_recv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
struct arphdr *rarp;
unsigned char *rarp_ptr;
__be32 sip, tip;
unsigned char *sha, *tha; /* s for "source", t for "target" */
struct ic_device *d;
if (!net_eq(dev_net(dev), &init_net))
goto drop;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
if (!pskb_may_pull(skb, sizeof(struct arphdr)))
goto drop;
/* Basic sanity checks can be done without the lock. */
rarp = (struct arphdr *)skb_transport_header(skb);
/* If this test doesn't pass, it's not IP, or we should
* ignore it anyway.
*/
if (rarp->ar_hln != dev->addr_len || dev->type != ntohs(rarp->ar_hrd))
goto drop;
/* If it's not a RARP reply, delete it. */
if (rarp->ar_op != htons(ARPOP_RREPLY))
goto drop;
/* If it's not Ethernet, delete it. */
if (rarp->ar_pro != htons(ETH_P_IP))
goto drop;
if (!pskb_may_pull(skb, arp_hdr_len(dev)))
goto drop;
/* OK, it is all there and looks valid, process... */
rarp = (struct arphdr *)skb_transport_header(skb);
rarp_ptr = (unsigned char *) (rarp + 1);
/* One reply at a time, please. */
spin_lock(&ic_recv_lock);
/* If we already have a reply, just drop the packet */
if (ic_got_reply)
goto drop_unlock;
/* Find the ic_device that the packet arrived on */
d = ic_first_dev;
while (d && d->dev != dev)
d = d->next;
if (!d)
goto drop_unlock; /* should never happen */
/* Extract variable-width fields */
sha = rarp_ptr;
rarp_ptr += dev->addr_len;
memcpy(&sip, rarp_ptr, 4);
rarp_ptr += 4;
tha = rarp_ptr;
rarp_ptr += dev->addr_len;
memcpy(&tip, rarp_ptr, 4);
/* Discard packets which are not meant for us. */
if (memcmp(tha, dev->dev_addr, dev->addr_len))
goto drop_unlock;
/* Discard packets which are not from specified server. */
if (ic_servaddr != NONE && ic_servaddr != sip)
goto drop_unlock;
/* We have a winner! */
ic_dev = dev;
if (ic_myaddr == NONE)
ic_myaddr = tip;
ic_servaddr = sip;
ic_addrservaddr = sip;
ic_got_reply = IC_RARP;
drop_unlock:
/* Show's over. Nothing to see here. */
spin_unlock(&ic_recv_lock);
drop:
/* Throw the packet out. */
kfree_skb(skb);
return 0;
}
/*
* Send RARP request packet over a single interface.
*/
static void __init ic_rarp_send_if(struct ic_device *d)
{
struct net_device *dev = d->dev;
arp_send(ARPOP_RREQUEST, ETH_P_RARP, 0, dev, 0, NULL,
dev->dev_addr, dev->dev_addr);
}
#endif
/*
* Predefine Nameservers
*/
static inline void __init ic_nameservers_predef(void)
{
int i;
for (i = 0; i < CONF_NAMESERVERS_MAX; i++)
ic_nameservers[i] = NONE;
}
/*
* DHCP/BOOTP support.
*/
#ifdef IPCONFIG_BOOTP
struct bootp_pkt { /* BOOTP packet format */
struct iphdr iph; /* IP header */
struct udphdr udph; /* UDP header */
u8 op; /* 1=request, 2=reply */
u8 htype; /* HW address type */
u8 hlen; /* HW address length */
u8 hops; /* Used only by gateways */
__be32 xid; /* Transaction ID */
__be16 secs; /* Seconds since we started */
__be16 flags; /* Just what it says */
__be32 client_ip; /* Client's IP address if known */
__be32 your_ip; /* Assigned IP address */
__be32 server_ip; /* (Next, e.g. NFS) Server's IP address */
__be32 relay_ip; /* IP address of BOOTP relay */
u8 hw_addr[16]; /* Client's HW address */
u8 serv_name[64]; /* Server host name */
u8 boot_file[128]; /* Name of boot file */
u8 exten[312]; /* DHCP options / BOOTP vendor extensions */
};
/* packet ops */
#define BOOTP_REQUEST 1
#define BOOTP_REPLY 2
/* DHCP message types */
#define DHCPDISCOVER 1
#define DHCPOFFER 2
#define DHCPREQUEST 3
#define DHCPDECLINE 4
#define DHCPACK 5
#define DHCPNAK 6
#define DHCPRELEASE 7
#define DHCPINFORM 8
static int ic_bootp_recv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev);
static struct packet_type bootp_packet_type __initdata = {
.type = cpu_to_be16(ETH_P_IP),
.func = ic_bootp_recv,
};
/*
* Initialize DHCP/BOOTP extension fields in the request.
*/
static const u8 ic_bootp_cookie[4] = { 99, 130, 83, 99 };
#ifdef IPCONFIG_DHCP
static void __init
ic_dhcp_init_options(u8 *options)
{
u8 mt = ((ic_servaddr == NONE)
? DHCPDISCOVER : DHCPREQUEST);
u8 *e = options;
int len;
#ifdef IPCONFIG_DEBUG
printk("DHCP: Sending message type %d\n", mt);
#endif
memcpy(e, ic_bootp_cookie, 4); /* RFC1048 Magic Cookie */
e += 4;
*e++ = 53; /* DHCP message type */
*e++ = 1;
*e++ = mt;
if (mt == DHCPREQUEST) {
*e++ = 54; /* Server ID (IP address) */
*e++ = 4;
memcpy(e, &ic_servaddr, 4);
e += 4;
*e++ = 50; /* Requested IP address */
*e++ = 4;
memcpy(e, &ic_myaddr, 4);
e += 4;
}
/* always? */
{
static const u8 ic_req_params[] = {
1, /* Subnet mask */
3, /* Default gateway */
6, /* DNS server */
12, /* Host name */
15, /* Domain name */
17, /* Boot path */
26, /* MTU */
40, /* NIS domain name */
};
*e++ = 55; /* Parameter request list */
*e++ = sizeof(ic_req_params);
memcpy(e, ic_req_params, sizeof(ic_req_params));
e += sizeof(ic_req_params);
if (ic_host_name_set) {
*e++ = 12; /* host-name */
len = strlen(utsname()->nodename);
*e++ = len;
memcpy(e, utsname()->nodename, len);
e += len;
}
if (*vendor_class_identifier) {
pr_info("DHCP: sending class identifier \"%s\"\n",
vendor_class_identifier);
*e++ = 60; /* Class-identifier */
len = strlen(vendor_class_identifier);
*e++ = len;
memcpy(e, vendor_class_identifier, len);
e += len;
}
}
*e++ = 255; /* End of the list */
}
#endif /* IPCONFIG_DHCP */
static void __init ic_bootp_init_ext(u8 *e)
{
memcpy(e, ic_bootp_cookie, 4); /* RFC1048 Magic Cookie */
e += 4;
*e++ = 1; /* Subnet mask request */
*e++ = 4;
e += 4;
*e++ = 3; /* Default gateway request */
*e++ = 4;
e += 4;
*e++ = 5; /* Name server request */
*e++ = 8;
e += 8;
*e++ = 12; /* Host name request */
*e++ = 32;
e += 32;
*e++ = 40; /* NIS Domain name request */
*e++ = 32;
e += 32;
*e++ = 17; /* Boot path */
*e++ = 40;
e += 40;
*e++ = 57; /* set extension buffer size for reply */
*e++ = 2;
*e++ = 1; /* 128+236+8+20+14, see dhcpd sources */
*e++ = 150;
*e++ = 255; /* End of the list */
}
/*
* Initialize the DHCP/BOOTP mechanism.
*/
static inline void __init ic_bootp_init(void)
{
ic_nameservers_predef();
dev_add_pack(&bootp_packet_type);
}
/*
* DHCP/BOOTP cleanup.
*/
static inline void __init ic_bootp_cleanup(void)
{
dev_remove_pack(&bootp_packet_type);
}
/*
* Send DHCP/BOOTP request to single interface.
*/
static void __init ic_bootp_send_if(struct ic_device *d, unsigned long jiffies_diff)
{
struct net_device *dev = d->dev;
struct sk_buff *skb;
struct bootp_pkt *b;
struct iphdr *h;
int hlen = LL_RESERVED_SPACE(dev);
int tlen = dev->needed_tailroom;
/* Allocate packet */
skb = alloc_skb(sizeof(struct bootp_pkt) + hlen + tlen + 15,
GFP_KERNEL);
if (!skb)
return;
skb_reserve(skb, hlen);
b = (struct bootp_pkt *) skb_put(skb, sizeof(struct bootp_pkt));
memset(b, 0, sizeof(struct bootp_pkt));
/* Construct IP header */
skb_reset_network_header(skb);
h = ip_hdr(skb);
h->version = 4;
h->ihl = 5;
h->tot_len = htons(sizeof(struct bootp_pkt));
h->frag_off = htons(IP_DF);
h->ttl = 64;
h->protocol = IPPROTO_UDP;
h->daddr = htonl(INADDR_BROADCAST);
h->check = ip_fast_csum((unsigned char *) h, h->ihl);
/* Construct UDP header */
b->udph.source = htons(68);
b->udph.dest = htons(67);
b->udph.len = htons(sizeof(struct bootp_pkt) - sizeof(struct iphdr));
/* UDP checksum not calculated -- explicitly allowed in BOOTP RFC */
/* Construct DHCP/BOOTP header */
b->op = BOOTP_REQUEST;
if (dev->type < 256) /* check for false types */
b->htype = dev->type;
else if (dev->type == ARPHRD_FDDI)
b->htype = ARPHRD_ETHER;
else {
printk("Unknown ARP type 0x%04x for device %s\n", dev->type, dev->name);
b->htype = dev->type; /* can cause undefined behavior */
}
/* server_ip and your_ip address are both already zero per RFC2131 */
b->hlen = dev->addr_len;
memcpy(b->hw_addr, dev->dev_addr, dev->addr_len);
b->secs = htons(jiffies_diff / HZ);
b->xid = d->xid;
/* add DHCP options or BOOTP extensions */
#ifdef IPCONFIG_DHCP
if (ic_proto_enabled & IC_USE_DHCP)
ic_dhcp_init_options(b->exten);
else
#endif
ic_bootp_init_ext(b->exten);
/* Chain packet down the line... */
skb->dev = dev;
skb->protocol = htons(ETH_P_IP);
if (dev_hard_header(skb, dev, ntohs(skb->protocol),
dev->broadcast, dev->dev_addr, skb->len) < 0) {
kfree_skb(skb);
printk("E");
return;
}
if (dev_queue_xmit(skb) < 0)
printk("E");
}
/*
* Copy BOOTP-supplied string if not already set.
*/
static int __init ic_bootp_string(char *dest, char *src, int len, int max)
{
if (!len)
return 0;
if (len > max-1)
len = max-1;
memcpy(dest, src, len);
dest[len] = '\0';
return 1;
}
/*
* Process BOOTP extensions.
*/
static void __init ic_do_bootp_ext(u8 *ext)
{
u8 servers;
int i;
__be16 mtu;
#ifdef IPCONFIG_DEBUG
u8 *c;
printk("DHCP/BOOTP: Got extension %d:",*ext);
for (c=ext+2; c<ext+2+ext[1]; c++)
printk(" %02x", *c);
printk("\n");
#endif
switch (*ext++) {
case 1: /* Subnet mask */
if (ic_netmask == NONE)
memcpy(&ic_netmask, ext+1, 4);
break;
case 3: /* Default gateway */
if (ic_gateway == NONE)
memcpy(&ic_gateway, ext+1, 4);
break;
case 6: /* DNS server */
servers= *ext/4;
if (servers > CONF_NAMESERVERS_MAX)
servers = CONF_NAMESERVERS_MAX;
for (i = 0; i < servers; i++) {
if (ic_nameservers[i] == NONE)
memcpy(&ic_nameservers[i], ext+1+4*i, 4);
}
break;
case 12: /* Host name */
ic_bootp_string(utsname()->nodename, ext+1, *ext,
__NEW_UTS_LEN);
ic_host_name_set = 1;
break;
case 15: /* Domain name (DNS) */
ic_bootp_string(ic_domain, ext+1, *ext, sizeof(ic_domain));
break;
case 17: /* Root path */
if (!root_server_path[0])
ic_bootp_string(root_server_path, ext+1, *ext,
sizeof(root_server_path));
break;
case 26: /* Interface MTU */
memcpy(&mtu, ext+1, sizeof(mtu));
ic_dev_mtu = ntohs(mtu);
break;
case 40: /* NIS Domain name (_not_ DNS) */
ic_bootp_string(utsname()->domainname, ext+1, *ext,
__NEW_UTS_LEN);
break;
}
}
/*
* Receive BOOTP reply.
*/
static int __init ic_bootp_recv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
struct bootp_pkt *b;
struct iphdr *h;
struct ic_device *d;
int len, ext_len;
if (!net_eq(dev_net(dev), &init_net))
goto drop;
/* Perform verifications before taking the lock. */
if (skb->pkt_type == PACKET_OTHERHOST)
goto drop;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
if (!pskb_may_pull(skb,
sizeof(struct iphdr) +
sizeof(struct udphdr)))
goto drop;
b = (struct bootp_pkt *)skb_network_header(skb);
h = &b->iph;
if (h->ihl != 5 || h->version != 4 || h->protocol != IPPROTO_UDP)
goto drop;
/* Fragments are not supported */
if (ip_is_fragment(h)) {
net_err_ratelimited("DHCP/BOOTP: Ignoring fragmented reply\n");
goto drop;
}
if (skb->len < ntohs(h->tot_len))
goto drop;
if (ip_fast_csum((char *) h, h->ihl))
goto drop;
if (b->udph.source != htons(67) || b->udph.dest != htons(68))
goto drop;
if (ntohs(h->tot_len) < ntohs(b->udph.len) + sizeof(struct iphdr))
goto drop;
len = ntohs(b->udph.len) - sizeof(struct udphdr);
ext_len = len - (sizeof(*b) -
sizeof(struct iphdr) -
sizeof(struct udphdr) -
sizeof(b->exten));
if (ext_len < 0)
goto drop;
/* Ok the front looks good, make sure we can get at the rest. */
if (!pskb_may_pull(skb, skb->len))
goto drop;
b = (struct bootp_pkt *)skb_network_header(skb);
h = &b->iph;
/* One reply at a time, please. */
spin_lock(&ic_recv_lock);
/* If we already have a reply, just drop the packet */
if (ic_got_reply)
goto drop_unlock;
/* Find the ic_device that the packet arrived on */
d = ic_first_dev;
while (d && d->dev != dev)
d = d->next;
if (!d)
goto drop_unlock; /* should never happen */
/* Is it a reply to our BOOTP request? */
if (b->op != BOOTP_REPLY ||
b->xid != d->xid) {
net_err_ratelimited("DHCP/BOOTP: Reply not for us, op[%x] xid[%x]\n",
b->op, b->xid);
goto drop_unlock;
}
/* Is it a reply for the device we are configuring? */
if (b->xid != ic_dev_xid) {
net_err_ratelimited("DHCP/BOOTP: Ignoring delayed packet\n");
goto drop_unlock;
}
/* Parse extensions */
if (ext_len >= 4 &&
!memcmp(b->exten, ic_bootp_cookie, 4)) { /* Check magic cookie */
u8 *end = (u8 *) b + ntohs(b->iph.tot_len);
u8 *ext;
#ifdef IPCONFIG_DHCP
if (ic_proto_enabled & IC_USE_DHCP) {
__be32 server_id = NONE;
int mt = 0;
ext = &b->exten[4];
while (ext < end && *ext != 0xff) {
u8 *opt = ext++;
if (*opt == 0) /* Padding */
continue;
ext += *ext + 1;
if (ext >= end)
break;
switch (*opt) {
case 53: /* Message type */
if (opt[1])
mt = opt[2];
break;
case 54: /* Server ID (IP address) */
if (opt[1] >= 4)
memcpy(&server_id, opt + 2, 4);
break;
}
}
#ifdef IPCONFIG_DEBUG
printk("DHCP: Got message type %d\n", mt);
#endif
switch (mt) {
case DHCPOFFER:
/* While in the process of accepting one offer,
* ignore all others.
*/
if (ic_myaddr != NONE)
goto drop_unlock;
/* Let's accept that offer. */
ic_myaddr = b->your_ip;
ic_servaddr = server_id;
#ifdef IPCONFIG_DEBUG
printk("DHCP: Offered address %pI4 by server %pI4\n",
&ic_myaddr, &b->iph.saddr);
#endif
/* The DHCP indicated server address takes
* precedence over the bootp header one if
* they are different.
*/
if ((server_id != NONE) &&
(b->server_ip != server_id))
b->server_ip = ic_servaddr;
break;
case DHCPACK:
if (memcmp(dev->dev_addr, b->hw_addr, dev->addr_len) != 0)
goto drop_unlock;
/* Yeah! */
break;
default:
/* Urque. Forget it*/
ic_myaddr = NONE;
ic_servaddr = NONE;
goto drop_unlock;
}
ic_dhcp_msgtype = mt;
}
#endif /* IPCONFIG_DHCP */
ext = &b->exten[4];
while (ext < end && *ext != 0xff) {
u8 *opt = ext++;
if (*opt == 0) /* Padding */
continue;
ext += *ext + 1;
if (ext < end)
ic_do_bootp_ext(opt);
}
}
/* We have a winner! */
ic_dev = dev;
ic_myaddr = b->your_ip;
ic_servaddr = b->server_ip;
ic_addrservaddr = b->iph.saddr;
if (ic_gateway == NONE && b->relay_ip)
ic_gateway = b->relay_ip;
if (ic_nameservers[0] == NONE)
ic_nameservers[0] = ic_servaddr;
ic_got_reply = IC_BOOTP;
drop_unlock:
/* Show's over. Nothing to see here. */
spin_unlock(&ic_recv_lock);
drop:
/* Throw the packet out. */
kfree_skb(skb);
return 0;
}
#endif
/*
* Dynamic IP configuration -- DHCP, BOOTP, RARP.
*/
#ifdef IPCONFIG_DYNAMIC
static int __init ic_dynamic(void)
{
int retries;
struct ic_device *d;
unsigned long start_jiffies, timeout, jiff;
int do_bootp = ic_proto_have_if & IC_BOOTP;
int do_rarp = ic_proto_have_if & IC_RARP;
/*
* If none of DHCP/BOOTP/RARP was selected, return with an error.
* This routine gets only called when some pieces of information
* are missing, and without DHCP/BOOTP/RARP we are unable to get it.
*/
if (!ic_proto_enabled) {
pr_err("IP-Config: Incomplete network configuration information\n");
return -1;
}
#ifdef IPCONFIG_BOOTP
if ((ic_proto_enabled ^ ic_proto_have_if) & IC_BOOTP)
pr_err("DHCP/BOOTP: No suitable device found\n");
#endif
#ifdef IPCONFIG_RARP
if ((ic_proto_enabled ^ ic_proto_have_if) & IC_RARP)
pr_err("RARP: No suitable device found\n");
#endif
if (!ic_proto_have_if)
/* Error message already printed */
return -1;
/*
* Setup protocols
*/
#ifdef IPCONFIG_BOOTP
if (do_bootp)
ic_bootp_init();
#endif
#ifdef IPCONFIG_RARP
if (do_rarp)
ic_rarp_init();
#endif
/*
* Send requests and wait, until we get an answer. This loop
* seems to be a terrible waste of CPU time, but actually there is
* only one process running at all, so we don't need to use any
* scheduler functions.
* [Actually we could now, but the nothing else running note still
* applies.. - AC]
*/
pr_notice("Sending %s%s%s requests .",
do_bootp
? ((ic_proto_enabled & IC_USE_DHCP) ? "DHCP" : "BOOTP") : "",
(do_bootp && do_rarp) ? " and " : "",
do_rarp ? "RARP" : "");
start_jiffies = jiffies;
d = ic_first_dev;
retries = CONF_SEND_RETRIES;
get_random_bytes(&timeout, sizeof(timeout));
timeout = CONF_BASE_TIMEOUT + (timeout % (unsigned int) CONF_TIMEOUT_RANDOM);
for (;;) {
/* Track the device we are configuring */
ic_dev_xid = d->xid;
#ifdef IPCONFIG_BOOTP
if (do_bootp && (d->able & IC_BOOTP))
ic_bootp_send_if(d, jiffies - start_jiffies);
#endif
#ifdef IPCONFIG_RARP
if (do_rarp && (d->able & IC_RARP))
ic_rarp_send_if(d);
#endif
jiff = jiffies + (d->next ? CONF_INTER_TIMEOUT : timeout);
while (time_before(jiffies, jiff) && !ic_got_reply)
schedule_timeout_uninterruptible(1);
#ifdef IPCONFIG_DHCP
/* DHCP isn't done until we get a DHCPACK. */
if ((ic_got_reply & IC_BOOTP) &&
(ic_proto_enabled & IC_USE_DHCP) &&
ic_dhcp_msgtype != DHCPACK) {
ic_got_reply = 0;
pr_cont(",");
continue;
}
#endif /* IPCONFIG_DHCP */
if (ic_got_reply) {
pr_cont(" OK\n");
break;
}
if ((d = d->next))
continue;
if (! --retries) {
pr_cont(" timed out!\n");
break;
}
d = ic_first_dev;
timeout = timeout CONF_TIMEOUT_MULT;
if (timeout > CONF_TIMEOUT_MAX)
timeout = CONF_TIMEOUT_MAX;
pr_cont(".");
}
#ifdef IPCONFIG_BOOTP
if (do_bootp)
ic_bootp_cleanup();
#endif
#ifdef IPCONFIG_RARP
if (do_rarp)
ic_rarp_cleanup();
#endif
if (!ic_got_reply) {
ic_myaddr = NONE;
return -1;
}
printk("IP-Config: Got %s answer from %pI4, ",
((ic_got_reply & IC_RARP) ? "RARP"
: (ic_proto_enabled & IC_USE_DHCP) ? "DHCP" : "BOOTP"),
&ic_addrservaddr);
pr_cont("my address is %pI4\n", &ic_myaddr);
return 0;
}
#endif /* IPCONFIG_DYNAMIC */
#ifdef CONFIG_PROC_FS
static int pnp_seq_show(struct seq_file *seq, void *v)
{
int i;
if (ic_proto_used & IC_PROTO)
seq_printf(seq, "#PROTO: %s\n",
(ic_proto_used & IC_RARP) ? "RARP"
: (ic_proto_used & IC_USE_DHCP) ? "DHCP" : "BOOTP");
else
seq_puts(seq, "#MANUAL\n");
if (ic_domain[0])
seq_printf(seq,
"domain %s\n", ic_domain);
for (i = 0; i < CONF_NAMESERVERS_MAX; i++) {
if (ic_nameservers[i] != NONE)
seq_printf(seq, "nameserver %pI4\n",
&ic_nameservers[i]);
}
if (ic_servaddr != NONE)
seq_printf(seq, "bootserver %pI4\n",
&ic_servaddr);
return 0;
}
static int pnp_seq_open(struct inode *indoe, struct file *file)
{
return single_open(file, pnp_seq_show, NULL);
}
static const struct file_operations pnp_seq_fops = {
.owner = THIS_MODULE,
.open = pnp_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_PROC_FS */
/*
* Extract IP address from the parameter string if needed. Note that we
* need to have root_server_addr set _before_ IPConfig gets called as it
* can override it.
*/
__be32 __init root_nfs_parse_addr(char *name)
{
__be32 addr;
int octets = 0;
char *cp, *cq;
cp = cq = name;
while (octets < 4) {
while (*cp >= '0' && *cp <= '9')
cp++;
if (cp == cq || cp - cq > 3)
break;
if (*cp == '.' || octets == 3)
octets++;
if (octets < 4)
cp++;
cq = cp;
}
if (octets == 4 && (*cp == ':' || *cp == '\0')) {
if (*cp == ':')
*cp++ = '\0';
addr = in_aton(name);
memmove(name, cp, strlen(cp) + 1);
} else
addr = NONE;
return addr;
}
#define DEVICE_WAIT_MAX 12 /* 12 seconds */
static int __init wait_for_devices(void)
{
int i;
for (i = 0; i < DEVICE_WAIT_MAX; i++) {
struct net_device *dev;
int found = 0;
rtnl_lock();
for_each_netdev(&init_net, dev) {
if (ic_is_init_dev(dev)) {
found = 1;
break;
}
}
rtnl_unlock();
if (found)
return 0;
ssleep(1);
}
return -ENODEV;
}
/*
* IP Autoconfig dispatcher.
*/
static int __init ip_auto_config(void)
{
__be32 addr;
#ifdef IPCONFIG_DYNAMIC
int retries = CONF_OPEN_RETRIES;
#endif
int err;
unsigned int i;
#ifdef CONFIG_PROC_FS
proc_create("pnp", S_IRUGO, init_net.proc_net, &pnp_seq_fops);
#endif /* CONFIG_PROC_FS */
if (!ic_enable)
return 0;
DBG(("IP-Config: Entered.\n"));
#ifdef IPCONFIG_DYNAMIC
try_try_again:
#endif
/* Wait for devices to appear */
err = wait_for_devices();
if (err)
return err;
/* Setup all network devices */
err = ic_open_devs();
if (err)
return err;
/* Give drivers a chance to settle */
msleep(CONF_POST_OPEN);
/*
* If the config information is insufficient (e.g., our IP address or
* IP address of the boot server is missing or we have multiple network
* interfaces and no default was set), use BOOTP or RARP to get the
* missing values.
*/
if (ic_myaddr == NONE ||
#ifdef CONFIG_ROOT_NFS
(root_server_addr == NONE &&
ic_servaddr == NONE &&
ROOT_DEV == Root_NFS) ||
#endif
ic_first_dev->next) {
#ifdef IPCONFIG_DYNAMIC
if (ic_dynamic() < 0) {
ic_close_devs();
/*
* I don't know why, but sometimes the
* eepro100 driver (at least) gets upset and
* doesn't work the first time it's opened.
* But then if you close it and reopen it, it
* works just fine. So we need to try that at
* least once before giving up.
*
* Also, if the root will be NFS-mounted, we
* have nowhere to go if DHCP fails. So we
* just have to keep trying forever.
*
* -- Chip
*/
#ifdef CONFIG_ROOT_NFS
if (ROOT_DEV == Root_NFS) {
pr_err("IP-Config: Retrying forever (NFS root)...\n");
goto try_try_again;
}
#endif
if (--retries) {
pr_err("IP-Config: Reopening network devices...\n");
goto try_try_again;
}
/* Oh, well. At least we tried. */
pr_err("IP-Config: Auto-configuration of network failed\n");
return -1;
}
#else /* !DYNAMIC */
pr_err("IP-Config: Incomplete network configuration information\n");
ic_close_devs();
return -1;
#endif /* IPCONFIG_DYNAMIC */
} else {
/* Device selected manually or only one device -> use it */
ic_dev = ic_first_dev->dev;
}
addr = root_nfs_parse_addr(root_server_path);
if (root_server_addr == NONE)
root_server_addr = addr;
/*
* Use defaults wherever applicable.
*/
if (ic_defaults() < 0)
return -1;
/*
* Close all network devices except the device we've
* autoconfigured and set up routes.
*/
ic_close_devs();
if (ic_setup_if() < 0 || ic_setup_routes() < 0)
return -1;
/*
* Record which protocol was actually used.
*/
#ifdef IPCONFIG_DYNAMIC
ic_proto_used = ic_got_reply | (ic_proto_enabled & IC_USE_DHCP);
#endif
#ifndef IPCONFIG_SILENT
/*
* Clue in the operator.
*/
pr_info("IP-Config: Complete:\n");
pr_info(" device=%s, hwaddr=%*phC, ipaddr=%pI4, mask=%pI4, gw=%pI4\n",
ic_dev->name, ic_dev->addr_len, ic_dev->dev_addr,
&ic_myaddr, &ic_netmask, &ic_gateway);
pr_info(" host=%s, domain=%s, nis-domain=%s\n",
utsname()->nodename, ic_domain, utsname()->domainname);
pr_info(" bootserver=%pI4, rootserver=%pI4, rootpath=%s",
&ic_servaddr, &root_server_addr, root_server_path);
if (ic_dev_mtu)
pr_cont(", mtu=%d", ic_dev_mtu);
for (i = 0; i < CONF_NAMESERVERS_MAX; i++)
if (ic_nameservers[i] != NONE) {
pr_info(" nameserver%u=%pI4",
i, &ic_nameservers[i]);
break;
}
for (i++; i < CONF_NAMESERVERS_MAX; i++)
if (ic_nameservers[i] != NONE)
pr_cont(", nameserver%u=%pI4", i, &ic_nameservers[i]);
pr_cont("\n");
#endif /* !SILENT */
return 0;
}
late_initcall(ip_auto_config);
/*
* Decode any IP configuration options in the "ip=" or "nfsaddrs=" kernel
* command line parameter. See Documentation/filesystems/nfs/nfsroot.txt.
*/
static int __init ic_proto_name(char *name)
{
if (!strcmp(name, "on") || !strcmp(name, "any")) {
return 1;
}
if (!strcmp(name, "off") || !strcmp(name, "none")) {
return 0;
}
#ifdef CONFIG_IP_PNP_DHCP
else if (!strcmp(name, "dhcp")) {
ic_proto_enabled &= ~IC_RARP;
return 1;
}
#endif
#ifdef CONFIG_IP_PNP_BOOTP
else if (!strcmp(name, "bootp")) {
ic_proto_enabled &= ~(IC_RARP | IC_USE_DHCP);
return 1;
}
#endif
#ifdef CONFIG_IP_PNP_RARP
else if (!strcmp(name, "rarp")) {
ic_proto_enabled &= ~(IC_BOOTP | IC_USE_DHCP);
return 1;
}
#endif
#ifdef IPCONFIG_DYNAMIC
else if (!strcmp(name, "both")) {
ic_proto_enabled &= ~IC_USE_DHCP; /* backward compat :-( */
return 1;
}
#endif
return 0;
}
static int __init ip_auto_config_setup(char *addrs)
{
char *cp, *ip, *dp;
int num = 0;
ic_set_manually = 1;
ic_enable = 1;
/*
* If any dhcp, bootp etc options are set, leave autoconfig on
* and skip the below static IP processing.
*/
if (ic_proto_name(addrs))
return 1;
/* If no static IP is given, turn off autoconfig and bail. */
if (*addrs == 0 ||
strcmp(addrs, "off") == 0 ||
strcmp(addrs, "none") == 0) {
ic_enable = 0;
return 1;
}
ic_nameservers_predef();
/* Parse string for static IP assignment. */
ip = addrs;
while (ip && *ip) {
if ((cp = strchr(ip, ':')))
*cp++ = '\0';
if (strlen(ip) > 0) {
DBG(("IP-Config: Parameter #%d: `%s'\n", num, ip));
switch (num) {
case 0:
if ((ic_myaddr = in_aton(ip)) == ANY)
ic_myaddr = NONE;
break;
case 1:
if ((ic_servaddr = in_aton(ip)) == ANY)
ic_servaddr = NONE;
break;
case 2:
if ((ic_gateway = in_aton(ip)) == ANY)
ic_gateway = NONE;
break;
case 3:
if ((ic_netmask = in_aton(ip)) == ANY)
ic_netmask = NONE;
break;
case 4:
if ((dp = strchr(ip, '.'))) {
*dp++ = '\0';
strlcpy(utsname()->domainname, dp,
sizeof(utsname()->domainname));
}
strlcpy(utsname()->nodename, ip,
sizeof(utsname()->nodename));
ic_host_name_set = 1;
break;
case 5:
strlcpy(user_dev_name, ip, sizeof(user_dev_name));
break;
case 6:
if (ic_proto_name(ip) == 0 &&
ic_myaddr == NONE) {
ic_enable = 0;
}
break;
case 7:
if (CONF_NAMESERVERS_MAX >= 1) {
ic_nameservers[0] = in_aton(ip);
if (ic_nameservers[0] == ANY)
ic_nameservers[0] = NONE;
}
break;
case 8:
if (CONF_NAMESERVERS_MAX >= 2) {
ic_nameservers[1] = in_aton(ip);
if (ic_nameservers[1] == ANY)
ic_nameservers[1] = NONE;
}
break;
}
}
ip = cp;
num++;
}
return 1;
}
__setup("ip=", ip_auto_config_setup);
static int __init nfsaddrs_config_setup(char *addrs)
{
return ip_auto_config_setup(addrs);
}
__setup("nfsaddrs=", nfsaddrs_config_setup);
static int __init vendor_class_identifier_setup(char *addrs)
{
if (strlcpy(vendor_class_identifier, addrs,
sizeof(vendor_class_identifier))
>= sizeof(vendor_class_identifier))
pr_warn("DHCP: vendorclass too long, truncated to \"%s\"",
vendor_class_identifier);
return 1;
}
__setup("dhcpclass=", vendor_class_identifier_setup);
| gpl-2.0 |
Jackeagle/kernel_samsung | drivers/regulator/mc13xxx-regulator-core.c | 2584 | 6653 | /*
* Regulator Driver for Freescale MC13xxx PMIC
*
* Copyright 2010 Yong Shen <yong.shen@linaro.org>
*
* Based on mc13783 regulator driver :
* Copyright (C) 2008 Sascha Hauer, Pengutronix <s.hauer@pengutronix.de>
* Copyright 2009 Alberto Panizzo <maramaopercheseimorto@gmail.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.
*
* Regs infos taken from mc13xxx drivers from freescale and mc13xxx.pdf file
* from freescale
*/
#include <linux/mfd/mc13xxx.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/of_regulator.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/of.h>
#include "mc13xxx.h"
static int mc13xxx_regulator_enable(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
int ret;
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_rmw(priv->mc13xxx, mc13xxx_regulators[id].reg,
mc13xxx_regulators[id].enable_bit,
mc13xxx_regulators[id].enable_bit);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_regulator_disable(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
int ret;
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_rmw(priv->mc13xxx, mc13xxx_regulators[id].reg,
mc13xxx_regulators[id].enable_bit, 0);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_regulator_is_enabled(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int ret, id = rdev_get_id(rdev);
unsigned int val;
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_read(priv->mc13xxx, mc13xxx_regulators[id].reg, &val);
mc13xxx_unlock(priv->mc13xxx);
if (ret)
return ret;
return (val & mc13xxx_regulators[id].enable_bit) != 0;
}
static int mc13xxx_regulator_set_voltage_sel(struct regulator_dev *rdev,
unsigned selector)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int id = rdev_get_id(rdev);
int ret;
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_rmw(priv->mc13xxx, mc13xxx_regulators[id].vsel_reg,
mc13xxx_regulators[id].vsel_mask,
selector << mc13xxx_regulators[id].vsel_shift);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_regulator_get_voltage(struct regulator_dev *rdev)
{
struct mc13xxx_regulator_priv *priv = rdev_get_drvdata(rdev);
struct mc13xxx_regulator *mc13xxx_regulators = priv->mc13xxx_regulators;
int ret, id = rdev_get_id(rdev);
unsigned int val;
dev_dbg(rdev_get_dev(rdev), "%s id: %d\n", __func__, id);
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_read(priv->mc13xxx,
mc13xxx_regulators[id].vsel_reg, &val);
mc13xxx_unlock(priv->mc13xxx);
if (ret)
return ret;
val = (val & mc13xxx_regulators[id].vsel_mask)
>> mc13xxx_regulators[id].vsel_shift;
dev_dbg(rdev_get_dev(rdev), "%s id: %d val: %d\n", __func__, id, val);
BUG_ON(val >= mc13xxx_regulators[id].desc.n_voltages);
return rdev->desc->volt_table[val];
}
struct regulator_ops mc13xxx_regulator_ops = {
.enable = mc13xxx_regulator_enable,
.disable = mc13xxx_regulator_disable,
.is_enabled = mc13xxx_regulator_is_enabled,
.list_voltage = regulator_list_voltage_table,
.set_voltage_sel = mc13xxx_regulator_set_voltage_sel,
.get_voltage = mc13xxx_regulator_get_voltage,
};
EXPORT_SYMBOL_GPL(mc13xxx_regulator_ops);
int mc13xxx_fixed_regulator_set_voltage(struct regulator_dev *rdev, int min_uV,
int max_uV, unsigned *selector)
{
int id = rdev_get_id(rdev);
dev_dbg(rdev_get_dev(rdev), "%s id: %d min_uV: %d max_uV: %d\n",
__func__, id, min_uV, max_uV);
if (min_uV <= rdev->desc->volt_table[0] &&
rdev->desc->volt_table[0] <= max_uV) {
*selector = 0;
return 0;
} else {
return -EINVAL;
}
}
EXPORT_SYMBOL_GPL(mc13xxx_fixed_regulator_set_voltage);
struct regulator_ops mc13xxx_fixed_regulator_ops = {
.enable = mc13xxx_regulator_enable,
.disable = mc13xxx_regulator_disable,
.is_enabled = mc13xxx_regulator_is_enabled,
.list_voltage = regulator_list_voltage_table,
.set_voltage = mc13xxx_fixed_regulator_set_voltage,
};
EXPORT_SYMBOL_GPL(mc13xxx_fixed_regulator_ops);
#ifdef CONFIG_OF
int mc13xxx_get_num_regulators_dt(struct platform_device *pdev)
{
struct device_node *parent;
int num;
of_node_get(pdev->dev.parent->of_node);
parent = of_find_node_by_name(pdev->dev.parent->of_node, "regulators");
if (!parent)
return -ENODEV;
num = of_get_child_count(parent);
of_node_put(parent);
return num;
}
EXPORT_SYMBOL_GPL(mc13xxx_get_num_regulators_dt);
struct mc13xxx_regulator_init_data *mc13xxx_parse_regulators_dt(
struct platform_device *pdev, struct mc13xxx_regulator *regulators,
int num_regulators)
{
struct mc13xxx_regulator_priv *priv = platform_get_drvdata(pdev);
struct mc13xxx_regulator_init_data *data, *p;
struct device_node *parent, *child;
int i, parsed = 0;
of_node_get(pdev->dev.parent->of_node);
parent = of_find_node_by_name(pdev->dev.parent->of_node, "regulators");
if (!parent)
return NULL;
data = devm_kzalloc(&pdev->dev, sizeof(*data) * priv->num_regulators,
GFP_KERNEL);
if (!data) {
of_node_put(parent);
return NULL;
}
p = data;
for_each_child_of_node(parent, child) {
int found = 0;
for (i = 0; i < num_regulators; i++) {
if (!regulators[i].desc.name)
continue;
if (!of_node_cmp(child->name,
regulators[i].desc.name)) {
p->id = i;
p->init_data = of_get_regulator_init_data(
&pdev->dev, child);
p->node = child;
p++;
parsed++;
found = 1;
break;
}
}
if (!found)
dev_warn(&pdev->dev,
"Unknown regulator: %s\n", child->name);
}
of_node_put(parent);
priv->num_regulators = parsed;
return data;
}
EXPORT_SYMBOL_GPL(mc13xxx_parse_regulators_dt);
#endif
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Yong Shen <yong.shen@linaro.org>");
MODULE_DESCRIPTION("Regulator Driver for Freescale MC13xxx PMIC");
MODULE_ALIAS("mc13xxx-regulator-core");
| gpl-2.0 |
WesternStar/tilinux | drivers/misc/sgi-gru/grufile.c | 2584 | 15342 | /*
* SN Platform GRU Driver
*
* FILE OPERATIONS & DRIVER INITIALIZATION
*
* This file supports the user system call for file open, close, mmap, etc.
* This also incudes the driver initialization code.
*
* Copyright (c) 2008 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; 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/errno.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#ifdef CONFIG_X86_64
#include <asm/uv/uv_irq.h>
#endif
#include <asm/uv/uv.h>
#include "gru.h"
#include "grulib.h"
#include "grutables.h"
#include <asm/uv/uv_hub.h>
#include <asm/uv/uv_mmrs.h>
struct gru_blade_state *gru_base[GRU_MAX_BLADES] __read_mostly;
unsigned long gru_start_paddr __read_mostly;
void *gru_start_vaddr __read_mostly;
unsigned long gru_end_paddr __read_mostly;
unsigned int gru_max_gids __read_mostly;
struct gru_stats_s gru_stats;
/* Guaranteed user available resources on each node */
static int max_user_cbrs, max_user_dsr_bytes;
static struct miscdevice gru_miscdev;
/*
* gru_vma_close
*
* Called when unmapping a device mapping. Frees all gru resources
* and tables belonging to the vma.
*/
static void gru_vma_close(struct vm_area_struct *vma)
{
struct gru_vma_data *vdata;
struct gru_thread_state *gts;
struct list_head *entry, *next;
if (!vma->vm_private_data)
return;
vdata = vma->vm_private_data;
vma->vm_private_data = NULL;
gru_dbg(grudev, "vma %p, file %p, vdata %p\n", vma, vma->vm_file,
vdata);
list_for_each_safe(entry, next, &vdata->vd_head) {
gts =
list_entry(entry, struct gru_thread_state, ts_next);
list_del(>s->ts_next);
mutex_lock(>s->ts_ctxlock);
if (gts->ts_gru)
gru_unload_context(gts, 0);
mutex_unlock(>s->ts_ctxlock);
gts_drop(gts);
}
kfree(vdata);
STAT(vdata_free);
}
/*
* gru_file_mmap
*
* Called when mmapping the device. Initializes the vma with a fault handler
* and private data structure necessary to allocate, track, and free the
* underlying pages.
*/
static int gru_file_mmap(struct file *file, struct vm_area_struct *vma)
{
if ((vma->vm_flags & (VM_SHARED | VM_WRITE)) != (VM_SHARED | VM_WRITE))
return -EPERM;
if (vma->vm_start & (GRU_GSEG_PAGESIZE - 1) ||
vma->vm_end & (GRU_GSEG_PAGESIZE - 1))
return -EINVAL;
vma->vm_flags |= VM_IO | VM_PFNMAP | VM_LOCKED |
VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
vma->vm_page_prot = PAGE_SHARED;
vma->vm_ops = &gru_vm_ops;
vma->vm_private_data = gru_alloc_vma_data(vma, 0);
if (!vma->vm_private_data)
return -ENOMEM;
gru_dbg(grudev, "file %p, vaddr 0x%lx, vma %p, vdata %p\n",
file, vma->vm_start, vma, vma->vm_private_data);
return 0;
}
/*
* Create a new GRU context
*/
static int gru_create_new_context(unsigned long arg)
{
struct gru_create_context_req req;
struct vm_area_struct *vma;
struct gru_vma_data *vdata;
int ret = -EINVAL;
if (copy_from_user(&req, (void __user *)arg, sizeof(req)))
return -EFAULT;
if (req.data_segment_bytes > max_user_dsr_bytes)
return -EINVAL;
if (req.control_blocks > max_user_cbrs || !req.maximum_thread_count)
return -EINVAL;
if (!(req.options & GRU_OPT_MISS_MASK))
req.options |= GRU_OPT_MISS_FMM_INTR;
down_write(¤t->mm->mmap_sem);
vma = gru_find_vma(req.gseg);
if (vma) {
vdata = vma->vm_private_data;
vdata->vd_user_options = req.options;
vdata->vd_dsr_au_count =
GRU_DS_BYTES_TO_AU(req.data_segment_bytes);
vdata->vd_cbr_au_count = GRU_CB_COUNT_TO_AU(req.control_blocks);
vdata->vd_tlb_preload_count = req.tlb_preload_count;
ret = 0;
}
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Get GRU configuration info (temp - for emulator testing)
*/
static long gru_get_config_info(unsigned long arg)
{
struct gru_config_info info;
int nodesperblade;
if (num_online_nodes() > 1 &&
(uv_node_to_blade_id(1) == uv_node_to_blade_id(0)))
nodesperblade = 2;
else
nodesperblade = 1;
memset(&info, 0, sizeof(info));
info.cpus = num_online_cpus();
info.nodes = num_online_nodes();
info.blades = info.nodes / nodesperblade;
info.chiplets = GRU_CHIPLETS_PER_BLADE * info.blades;
if (copy_to_user((void __user *)arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/*
* gru_file_unlocked_ioctl
*
* Called to update file attributes via IOCTL calls.
*/
static long gru_file_unlocked_ioctl(struct file *file, unsigned int req,
unsigned long arg)
{
int err = -EBADRQC;
gru_dbg(grudev, "file %p, req 0x%x, 0x%lx\n", file, req, arg);
switch (req) {
case GRU_CREATE_CONTEXT:
err = gru_create_new_context(arg);
break;
case GRU_SET_CONTEXT_OPTION:
err = gru_set_context_option(arg);
break;
case GRU_USER_GET_EXCEPTION_DETAIL:
err = gru_get_exception_detail(arg);
break;
case GRU_USER_UNLOAD_CONTEXT:
err = gru_user_unload_context(arg);
break;
case GRU_USER_FLUSH_TLB:
err = gru_user_flush_tlb(arg);
break;
case GRU_USER_CALL_OS:
err = gru_handle_user_call_os(arg);
break;
case GRU_GET_GSEG_STATISTICS:
err = gru_get_gseg_statistics(arg);
break;
case GRU_KTEST:
err = gru_ktest(arg);
break;
case GRU_GET_CONFIG_INFO:
err = gru_get_config_info(arg);
break;
case GRU_DUMP_CHIPLET_STATE:
err = gru_dump_chiplet_request(arg);
break;
}
return err;
}
/*
* Called at init time to build tables for all GRUs that are present in the
* system.
*/
static void gru_init_chiplet(struct gru_state *gru, unsigned long paddr,
void *vaddr, int blade_id, int chiplet_id)
{
spin_lock_init(&gru->gs_lock);
spin_lock_init(&gru->gs_asid_lock);
gru->gs_gru_base_paddr = paddr;
gru->gs_gru_base_vaddr = vaddr;
gru->gs_gid = blade_id * GRU_CHIPLETS_PER_BLADE + chiplet_id;
gru->gs_blade = gru_base[blade_id];
gru->gs_blade_id = blade_id;
gru->gs_chiplet_id = chiplet_id;
gru->gs_cbr_map = (GRU_CBR_AU == 64) ? ~0 : (1UL << GRU_CBR_AU) - 1;
gru->gs_dsr_map = (1UL << GRU_DSR_AU) - 1;
gru->gs_asid_limit = MAX_ASID;
gru_tgh_flush_init(gru);
if (gru->gs_gid >= gru_max_gids)
gru_max_gids = gru->gs_gid + 1;
gru_dbg(grudev, "bid %d, gid %d, vaddr %p (0x%lx)\n",
blade_id, gru->gs_gid, gru->gs_gru_base_vaddr,
gru->gs_gru_base_paddr);
}
static int gru_init_tables(unsigned long gru_base_paddr, void *gru_base_vaddr)
{
int pnode, nid, bid, chip;
int cbrs, dsrbytes, n;
int order = get_order(sizeof(struct gru_blade_state));
struct page *page;
struct gru_state *gru;
unsigned long paddr;
void *vaddr;
max_user_cbrs = GRU_NUM_CB;
max_user_dsr_bytes = GRU_NUM_DSR_BYTES;
for_each_possible_blade(bid) {
pnode = uv_blade_to_pnode(bid);
nid = uv_blade_to_memory_nid(bid);/* -1 if no memory on blade */
page = alloc_pages_node(nid, GFP_KERNEL, order);
if (!page)
goto fail;
gru_base[bid] = page_address(page);
memset(gru_base[bid], 0, sizeof(struct gru_blade_state));
gru_base[bid]->bs_lru_gru = &gru_base[bid]->bs_grus[0];
spin_lock_init(&gru_base[bid]->bs_lock);
init_rwsem(&gru_base[bid]->bs_kgts_sema);
dsrbytes = 0;
cbrs = 0;
for (gru = gru_base[bid]->bs_grus, chip = 0;
chip < GRU_CHIPLETS_PER_BLADE;
chip++, gru++) {
paddr = gru_chiplet_paddr(gru_base_paddr, pnode, chip);
vaddr = gru_chiplet_vaddr(gru_base_vaddr, pnode, chip);
gru_init_chiplet(gru, paddr, vaddr, bid, chip);
n = hweight64(gru->gs_cbr_map) * GRU_CBR_AU_SIZE;
cbrs = max(cbrs, n);
n = hweight64(gru->gs_dsr_map) * GRU_DSR_AU_BYTES;
dsrbytes = max(dsrbytes, n);
}
max_user_cbrs = min(max_user_cbrs, cbrs);
max_user_dsr_bytes = min(max_user_dsr_bytes, dsrbytes);
}
return 0;
fail:
for (bid--; bid >= 0; bid--)
free_pages((unsigned long)gru_base[bid], order);
return -ENOMEM;
}
static void gru_free_tables(void)
{
int bid;
int order = get_order(sizeof(struct gru_state) *
GRU_CHIPLETS_PER_BLADE);
for (bid = 0; bid < GRU_MAX_BLADES; bid++)
free_pages((unsigned long)gru_base[bid], order);
}
static unsigned long gru_chiplet_cpu_to_mmr(int chiplet, int cpu, int *corep)
{
unsigned long mmr = 0;
int core;
/*
* We target the cores of a blade and not the hyperthreads themselves.
* There is a max of 8 cores per socket and 2 sockets per blade,
* making for a max total of 16 cores (i.e., 16 CPUs without
* hyperthreading and 32 CPUs with hyperthreading).
*/
core = uv_cpu_core_number(cpu) + UV_MAX_INT_CORES * uv_cpu_socket_number(cpu);
if (core >= GRU_NUM_TFM || uv_cpu_ht_number(cpu))
return 0;
if (chiplet == 0) {
mmr = UVH_GR0_TLB_INT0_CONFIG +
core * (UVH_GR0_TLB_INT1_CONFIG - UVH_GR0_TLB_INT0_CONFIG);
} else if (chiplet == 1) {
mmr = UVH_GR1_TLB_INT0_CONFIG +
core * (UVH_GR1_TLB_INT1_CONFIG - UVH_GR1_TLB_INT0_CONFIG);
} else {
BUG();
}
*corep = core;
return mmr;
}
#ifdef CONFIG_IA64
static int gru_irq_count[GRU_CHIPLETS_PER_BLADE];
static void gru_noop(struct irq_data *d)
{
}
static struct irq_chip gru_chip[GRU_CHIPLETS_PER_BLADE] = {
[0 ... GRU_CHIPLETS_PER_BLADE - 1] {
.irq_mask = gru_noop,
.irq_unmask = gru_noop,
.irq_ack = gru_noop
}
};
static int gru_chiplet_setup_tlb_irq(int chiplet, char *irq_name,
irq_handler_t irq_handler, int cpu, int blade)
{
unsigned long mmr;
int irq = IRQ_GRU + chiplet;
int ret, core;
mmr = gru_chiplet_cpu_to_mmr(chiplet, cpu, &core);
if (mmr == 0)
return 0;
if (gru_irq_count[chiplet] == 0) {
gru_chip[chiplet].name = irq_name;
ret = irq_set_chip(irq, &gru_chip[chiplet]);
if (ret) {
printk(KERN_ERR "%s: set_irq_chip failed, errno=%d\n",
GRU_DRIVER_ID_STR, -ret);
return ret;
}
ret = request_irq(irq, irq_handler, 0, irq_name, NULL);
if (ret) {
printk(KERN_ERR "%s: request_irq failed, errno=%d\n",
GRU_DRIVER_ID_STR, -ret);
return ret;
}
}
gru_irq_count[chiplet]++;
return 0;
}
static void gru_chiplet_teardown_tlb_irq(int chiplet, int cpu, int blade)
{
unsigned long mmr;
int core, irq = IRQ_GRU + chiplet;
if (gru_irq_count[chiplet] == 0)
return;
mmr = gru_chiplet_cpu_to_mmr(chiplet, cpu, &core);
if (mmr == 0)
return;
if (--gru_irq_count[chiplet] == 0)
free_irq(irq, NULL);
}
#elif defined CONFIG_X86_64
static int gru_chiplet_setup_tlb_irq(int chiplet, char *irq_name,
irq_handler_t irq_handler, int cpu, int blade)
{
unsigned long mmr;
int irq, core;
int ret;
mmr = gru_chiplet_cpu_to_mmr(chiplet, cpu, &core);
if (mmr == 0)
return 0;
irq = uv_setup_irq(irq_name, cpu, blade, mmr, UV_AFFINITY_CPU);
if (irq < 0) {
printk(KERN_ERR "%s: uv_setup_irq failed, errno=%d\n",
GRU_DRIVER_ID_STR, -irq);
return irq;
}
ret = request_irq(irq, irq_handler, 0, irq_name, NULL);
if (ret) {
uv_teardown_irq(irq);
printk(KERN_ERR "%s: request_irq failed, errno=%d\n",
GRU_DRIVER_ID_STR, -ret);
return ret;
}
gru_base[blade]->bs_grus[chiplet].gs_irq[core] = irq;
return 0;
}
static void gru_chiplet_teardown_tlb_irq(int chiplet, int cpu, int blade)
{
int irq, core;
unsigned long mmr;
mmr = gru_chiplet_cpu_to_mmr(chiplet, cpu, &core);
if (mmr) {
irq = gru_base[blade]->bs_grus[chiplet].gs_irq[core];
if (irq) {
free_irq(irq, NULL);
uv_teardown_irq(irq);
}
}
}
#endif
static void gru_teardown_tlb_irqs(void)
{
int blade;
int cpu;
for_each_online_cpu(cpu) {
blade = uv_cpu_to_blade_id(cpu);
gru_chiplet_teardown_tlb_irq(0, cpu, blade);
gru_chiplet_teardown_tlb_irq(1, cpu, blade);
}
for_each_possible_blade(blade) {
if (uv_blade_nr_possible_cpus(blade))
continue;
gru_chiplet_teardown_tlb_irq(0, 0, blade);
gru_chiplet_teardown_tlb_irq(1, 0, blade);
}
}
static int gru_setup_tlb_irqs(void)
{
int blade;
int cpu;
int ret;
for_each_online_cpu(cpu) {
blade = uv_cpu_to_blade_id(cpu);
ret = gru_chiplet_setup_tlb_irq(0, "GRU0_TLB", gru0_intr, cpu, blade);
if (ret != 0)
goto exit1;
ret = gru_chiplet_setup_tlb_irq(1, "GRU1_TLB", gru1_intr, cpu, blade);
if (ret != 0)
goto exit1;
}
for_each_possible_blade(blade) {
if (uv_blade_nr_possible_cpus(blade))
continue;
ret = gru_chiplet_setup_tlb_irq(0, "GRU0_TLB", gru_intr_mblade, 0, blade);
if (ret != 0)
goto exit1;
ret = gru_chiplet_setup_tlb_irq(1, "GRU1_TLB", gru_intr_mblade, 0, blade);
if (ret != 0)
goto exit1;
}
return 0;
exit1:
gru_teardown_tlb_irqs();
return ret;
}
/*
* gru_init
*
* Called at boot or module load time to initialize the GRUs.
*/
static int __init gru_init(void)
{
int ret;
if (!is_uv_system() || (is_uvx_hub() && !is_uv2_hub()))
return 0;
#if defined CONFIG_IA64
gru_start_paddr = 0xd000000000UL; /* ZZZZZZZZZZZZZZZZZZZ fixme */
#else
gru_start_paddr = uv_read_local_mmr(UVH_RH_GAM_GRU_OVERLAY_CONFIG_MMR) &
0x7fffffffffffUL;
#endif
gru_start_vaddr = __va(gru_start_paddr);
gru_end_paddr = gru_start_paddr + GRU_MAX_BLADES * GRU_SIZE;
printk(KERN_INFO "GRU space: 0x%lx - 0x%lx\n",
gru_start_paddr, gru_end_paddr);
ret = misc_register(&gru_miscdev);
if (ret) {
printk(KERN_ERR "%s: misc_register failed\n",
GRU_DRIVER_ID_STR);
goto exit0;
}
ret = gru_proc_init();
if (ret) {
printk(KERN_ERR "%s: proc init failed\n", GRU_DRIVER_ID_STR);
goto exit1;
}
ret = gru_init_tables(gru_start_paddr, gru_start_vaddr);
if (ret) {
printk(KERN_ERR "%s: init tables failed\n", GRU_DRIVER_ID_STR);
goto exit2;
}
ret = gru_setup_tlb_irqs();
if (ret != 0)
goto exit3;
gru_kservices_init();
printk(KERN_INFO "%s: v%s\n", GRU_DRIVER_ID_STR,
GRU_DRIVER_VERSION_STR);
return 0;
exit3:
gru_free_tables();
exit2:
gru_proc_exit();
exit1:
misc_deregister(&gru_miscdev);
exit0:
return ret;
}
static void __exit gru_exit(void)
{
if (!is_uv_system())
return;
gru_teardown_tlb_irqs();
gru_kservices_exit();
gru_free_tables();
misc_deregister(&gru_miscdev);
gru_proc_exit();
}
static const struct file_operations gru_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = gru_file_unlocked_ioctl,
.mmap = gru_file_mmap,
.llseek = noop_llseek,
};
static struct miscdevice gru_miscdev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "gru",
.fops = &gru_fops,
};
const struct vm_operations_struct gru_vm_ops = {
.close = gru_vma_close,
.fault = gru_fault,
};
#ifndef MODULE
fs_initcall(gru_init);
#else
module_init(gru_init);
#endif
module_exit(gru_exit);
module_param(gru_options, ulong, 0644);
MODULE_PARM_DESC(gru_options, "Various debug options");
MODULE_AUTHOR("Silicon Graphics, Inc.");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION(GRU_DRIVER_ID_STR GRU_DRIVER_VERSION_STR);
MODULE_VERSION(GRU_DRIVER_VERSION_STR);
| gpl-2.0 |
NX511J-dev/kernel_zte_nx511j | drivers/leds/leds-max8997.c | 2840 | 8225 | /*
* leds-max8997.c - LED class driver for MAX8997 LEDs.
*
* Copyright (C) 2011 Samsung Electronics
* Donggeun Kim <dg77.kim@samsung.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/err.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/leds.h>
#include <linux/mfd/max8997.h>
#include <linux/mfd/max8997-private.h>
#include <linux/platform_device.h>
#define MAX8997_LED_FLASH_SHIFT 3
#define MAX8997_LED_FLASH_CUR_MASK 0xf8
#define MAX8997_LED_MOVIE_SHIFT 4
#define MAX8997_LED_MOVIE_CUR_MASK 0xf0
#define MAX8997_LED_FLASH_MAX_BRIGHTNESS 0x1f
#define MAX8997_LED_MOVIE_MAX_BRIGHTNESS 0xf
#define MAX8997_LED_NONE_MAX_BRIGHTNESS 0
#define MAX8997_LED0_FLASH_MASK 0x1
#define MAX8997_LED0_FLASH_PIN_MASK 0x5
#define MAX8997_LED0_MOVIE_MASK 0x8
#define MAX8997_LED0_MOVIE_PIN_MASK 0x28
#define MAX8997_LED1_FLASH_MASK 0x2
#define MAX8997_LED1_FLASH_PIN_MASK 0x6
#define MAX8997_LED1_MOVIE_MASK 0x10
#define MAX8997_LED1_MOVIE_PIN_MASK 0x30
#define MAX8997_LED_BOOST_ENABLE_MASK (1 << 6)
struct max8997_led {
struct max8997_dev *iodev;
struct led_classdev cdev;
bool enabled;
int id;
enum max8997_led_mode led_mode;
struct mutex mutex;
};
static void max8997_led_set_mode(struct max8997_led *led,
enum max8997_led_mode mode)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 mask = 0, val;
switch (mode) {
case MAX8997_FLASH_MODE:
mask = MAX8997_LED1_FLASH_MASK | MAX8997_LED0_FLASH_MASK;
val = led->id ?
MAX8997_LED1_FLASH_MASK : MAX8997_LED0_FLASH_MASK;
led->cdev.max_brightness = MAX8997_LED_FLASH_MAX_BRIGHTNESS;
break;
case MAX8997_MOVIE_MODE:
mask = MAX8997_LED1_MOVIE_MASK | MAX8997_LED0_MOVIE_MASK;
val = led->id ?
MAX8997_LED1_MOVIE_MASK : MAX8997_LED0_MOVIE_MASK;
led->cdev.max_brightness = MAX8997_LED_MOVIE_MAX_BRIGHTNESS;
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
mask = MAX8997_LED1_FLASH_PIN_MASK |
MAX8997_LED0_FLASH_PIN_MASK;
val = led->id ?
MAX8997_LED1_FLASH_PIN_MASK : MAX8997_LED0_FLASH_PIN_MASK;
led->cdev.max_brightness = MAX8997_LED_FLASH_MAX_BRIGHTNESS;
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
mask = MAX8997_LED1_MOVIE_PIN_MASK |
MAX8997_LED0_MOVIE_PIN_MASK;
val = led->id ?
MAX8997_LED1_MOVIE_PIN_MASK : MAX8997_LED0_MOVIE_PIN_MASK;
led->cdev.max_brightness = MAX8997_LED_MOVIE_MAX_BRIGHTNESS;
break;
default:
led->cdev.max_brightness = MAX8997_LED_NONE_MAX_BRIGHTNESS;
break;
}
if (mask) {
ret = max8997_update_reg(client, MAX8997_REG_LEN_CNTL, val,
mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
led->led_mode = mode;
}
static void max8997_led_enable(struct max8997_led *led, bool enable)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = MAX8997_LED_BOOST_ENABLE_MASK;
if (led->enabled == enable)
return;
val = enable ? MAX8997_LED_BOOST_ENABLE_MASK : 0;
ret = max8997_update_reg(client, MAX8997_REG_BOOST_CNTL, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
led->enabled = enable;
}
static void max8997_led_set_current(struct max8997_led *led,
enum led_brightness value)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = 0, reg = 0;
switch (led->led_mode) {
case MAX8997_FLASH_MODE:
case MAX8997_FLASH_PIN_CONTROL_MODE:
val = value << MAX8997_LED_FLASH_SHIFT;
mask = MAX8997_LED_FLASH_CUR_MASK;
reg = led->id ? MAX8997_REG_FLASH2_CUR : MAX8997_REG_FLASH1_CUR;
break;
case MAX8997_MOVIE_MODE:
case MAX8997_MOVIE_PIN_CONTROL_MODE:
val = value << MAX8997_LED_MOVIE_SHIFT;
mask = MAX8997_LED_MOVIE_CUR_MASK;
reg = MAX8997_REG_MOVIE_CUR;
break;
default:
break;
}
if (mask) {
ret = max8997_update_reg(client, reg, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
}
static void max8997_led_brightness_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
if (value) {
max8997_led_set_current(led, value);
max8997_led_enable(led, true);
} else {
max8997_led_set_current(led, value);
max8997_led_enable(led, false);
}
}
static ssize_t max8997_led_show_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
ssize_t ret = 0;
mutex_lock(&led->mutex);
switch (led->led_mode) {
case MAX8997_FLASH_MODE:
ret += sprintf(buf, "FLASH\n");
break;
case MAX8997_MOVIE_MODE:
ret += sprintf(buf, "MOVIE\n");
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
ret += sprintf(buf, "FLASH_PIN_CONTROL\n");
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
ret += sprintf(buf, "MOVIE_PIN_CONTROL\n");
break;
default:
ret += sprintf(buf, "NONE\n");
break;
}
mutex_unlock(&led->mutex);
return ret;
}
static ssize_t max8997_led_store_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
enum max8997_led_mode mode;
mutex_lock(&led->mutex);
if (!strncmp(buf, "FLASH_PIN_CONTROL", 17))
mode = MAX8997_FLASH_PIN_CONTROL_MODE;
else if (!strncmp(buf, "MOVIE_PIN_CONTROL", 17))
mode = MAX8997_MOVIE_PIN_CONTROL_MODE;
else if (!strncmp(buf, "FLASH", 5))
mode = MAX8997_FLASH_MODE;
else if (!strncmp(buf, "MOVIE", 5))
mode = MAX8997_MOVIE_MODE;
else
mode = MAX8997_NONE;
max8997_led_set_mode(led, mode);
mutex_unlock(&led->mutex);
return size;
}
static DEVICE_ATTR(mode, 0644, max8997_led_show_mode, max8997_led_store_mode);
static int max8997_led_probe(struct platform_device *pdev)
{
struct max8997_dev *iodev = dev_get_drvdata(pdev->dev.parent);
struct max8997_platform_data *pdata = dev_get_platdata(iodev->dev);
struct max8997_led *led;
char name[20];
int ret = 0;
if (pdata == NULL) {
dev_err(&pdev->dev, "no platform data\n");
return -ENODEV;
}
led = devm_kzalloc(&pdev->dev, sizeof(*led), GFP_KERNEL);
if (led == NULL)
return -ENOMEM;
led->id = pdev->id;
snprintf(name, sizeof(name), "max8997-led%d", pdev->id);
led->cdev.name = name;
led->cdev.brightness_set = max8997_led_brightness_set;
led->cdev.flags |= LED_CORE_SUSPENDRESUME;
led->cdev.brightness = 0;
led->iodev = iodev;
/* initialize mode and brightness according to platform_data */
if (pdata->led_pdata) {
u8 mode = 0, brightness = 0;
mode = pdata->led_pdata->mode[led->id];
brightness = pdata->led_pdata->brightness[led->id];
max8997_led_set_mode(led, pdata->led_pdata->mode[led->id]);
if (brightness > led->cdev.max_brightness)
brightness = led->cdev.max_brightness;
max8997_led_set_current(led, brightness);
led->cdev.brightness = brightness;
} else {
max8997_led_set_mode(led, MAX8997_NONE);
max8997_led_set_current(led, 0);
}
mutex_init(&led->mutex);
platform_set_drvdata(pdev, led);
ret = led_classdev_register(&pdev->dev, &led->cdev);
if (ret < 0)
return ret;
ret = device_create_file(led->cdev.dev, &dev_attr_mode);
if (ret != 0) {
dev_err(&pdev->dev,
"failed to create file: %d\n", ret);
led_classdev_unregister(&led->cdev);
return ret;
}
return 0;
}
static int max8997_led_remove(struct platform_device *pdev)
{
struct max8997_led *led = platform_get_drvdata(pdev);
device_remove_file(led->cdev.dev, &dev_attr_mode);
led_classdev_unregister(&led->cdev);
return 0;
}
static struct platform_driver max8997_led_driver = {
.driver = {
.name = "max8997-led",
.owner = THIS_MODULE,
},
.probe = max8997_led_probe,
.remove = max8997_led_remove,
};
module_platform_driver(max8997_led_driver);
MODULE_AUTHOR("Donggeun Kim <dg77.kim@samsung.com>");
MODULE_DESCRIPTION("MAX8997 LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:max8997-led");
| gpl-2.0 |
dnkn/rk3188_tablet | fs/ext2/xattr_security.c | 2840 | 1895 | /*
* linux/fs/ext2/xattr_security.c
* Handler for storing security labels as extended attributes.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/ext2_fs.h>
#include <linux/security.h>
#include "xattr.h"
static size_t
ext2_xattr_security_list(struct dentry *dentry, char *list, size_t list_size,
const char *name, size_t name_len, int type)
{
const int prefix_len = XATTR_SECURITY_PREFIX_LEN;
const size_t total_len = prefix_len + name_len + 1;
if (list && total_len <= list_size) {
memcpy(list, XATTR_SECURITY_PREFIX, prefix_len);
memcpy(list+prefix_len, name, name_len);
list[prefix_len + name_len] = '\0';
}
return total_len;
}
static int
ext2_xattr_security_get(struct dentry *dentry, const char *name,
void *buffer, size_t size, int type)
{
if (strcmp(name, "") == 0)
return -EINVAL;
return ext2_xattr_get(dentry->d_inode, EXT2_XATTR_INDEX_SECURITY, name,
buffer, size);
}
static int
ext2_xattr_security_set(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags, int type)
{
if (strcmp(name, "") == 0)
return -EINVAL;
return ext2_xattr_set(dentry->d_inode, EXT2_XATTR_INDEX_SECURITY, name,
value, size, flags);
}
int
ext2_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
int err;
size_t len;
void *value;
char *name;
err = security_inode_init_security(inode, dir, qstr, &name, &value, &len);
if (err) {
if (err == -EOPNOTSUPP)
return 0;
return err;
}
err = ext2_xattr_set(inode, EXT2_XATTR_INDEX_SECURITY,
name, value, len, 0);
kfree(name);
kfree(value);
return err;
}
const struct xattr_handler ext2_xattr_security_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.list = ext2_xattr_security_list,
.get = ext2_xattr_security_get,
.set = ext2_xattr_security_set,
};
| gpl-2.0 |
nikybiasion/android_kernel_asus_me301t | drivers/block/paride/pd.c | 3096 | 24194 | /*
pd.c (c) 1997-8 Grant R. Guenther <grant@torque.net>
Under the terms of the GNU General Public License.
This is the high-level driver for parallel port IDE hard
drives based on chips supported by the paride module.
By default, the driver will autoprobe for a single parallel
port IDE drive, but if their individual parameters are
specified, the driver can handle up to 4 drives.
The behaviour of the pd driver can be altered by setting
some parameters from the insmod command line. The following
parameters are adjustable:
drive0 These four arguments can be arrays of
drive1 1-8 integers as follows:
drive2
drive3 <prt>,<pro>,<uni>,<mod>,<geo>,<sby>,<dly>,<slv>
Where,
<prt> is the base of the parallel port address for
the corresponding drive. (required)
<pro> is the protocol number for the adapter that
supports this drive. These numbers are
logged by 'paride' when the protocol modules
are initialised. (0 if not given)
<uni> for those adapters that support chained
devices, this is the unit selector for the
chain of devices on the given port. It should
be zero for devices that don't support chaining.
(0 if not given)
<mod> this can be -1 to choose the best mode, or one
of the mode numbers supported by the adapter.
(-1 if not given)
<geo> this defaults to 0 to indicate that the driver
should use the CHS geometry provided by the drive
itself. If set to 1, the driver will provide
a logical geometry with 64 heads and 32 sectors
per track, to be consistent with most SCSI
drivers. (0 if not given)
<sby> set this to zero to disable the power saving
standby mode, if needed. (1 if not given)
<dly> some parallel ports require the driver to
go more slowly. -1 sets a default value that
should work with the chosen protocol. Otherwise,
set this to a small integer, the larger it is
the slower the port i/o. In some cases, setting
this to zero will speed up the device. (default -1)
<slv> IDE disks can be jumpered to master or slave.
Set this to 0 to choose the master drive, 1 to
choose the slave, -1 (the default) to choose the
first drive found.
major You may use this parameter to overide the
default major number (45) that this driver
will use. Be sure to change the device
name as well.
name This parameter is a character string that
contains the name the kernel will use for this
device (in /proc output, for instance).
(default "pd")
cluster The driver will attempt to aggregate requests
for adjacent blocks into larger multi-block
clusters. The maximum cluster size (in 512
byte sectors) is set with this parameter.
(default 64)
verbose This parameter controls the amount of logging
that the driver will do. Set it to 0 for
normal operation, 1 to see autoprobe progress
messages, or 2 to see additional debugging
output. (default 0)
nice This parameter controls the driver's use of
idle CPU time, at the expense of some speed.
If this driver is built into the kernel, you can use kernel
the following command line parameters, with the same values
as the corresponding module parameters listed above:
pd.drive0
pd.drive1
pd.drive2
pd.drive3
pd.cluster
pd.nice
In addition, you can use the parameter pd.disable to disable
the driver entirely.
*/
/* Changes:
1.01 GRG 1997.01.24 Restored pd_reset()
Added eject ioctl
1.02 GRG 1998.05.06 SMP spinlock changes,
Added slave support
1.03 GRG 1998.06.16 Eliminate an Ugh.
1.04 GRG 1998.08.15 Extra debugging, use HZ in loop timing
1.05 GRG 1998.09.24 Added jumbo support
*/
#define PD_VERSION "1.05"
#define PD_MAJOR 45
#define PD_NAME "pd"
#define PD_UNITS 4
/* Here are things one can override from the insmod command.
Most are autoprobed by paride unless set here. Verbose is off
by default.
*/
static int verbose = 0;
static int major = PD_MAJOR;
static char *name = PD_NAME;
static int cluster = 64;
static int nice = 0;
static int disable = 0;
static int drive0[8] = { 0, 0, 0, -1, 0, 1, -1, -1 };
static int drive1[8] = { 0, 0, 0, -1, 0, 1, -1, -1 };
static int drive2[8] = { 0, 0, 0, -1, 0, 1, -1, -1 };
static int drive3[8] = { 0, 0, 0, -1, 0, 1, -1, -1 };
static int (*drives[4])[8] = {&drive0, &drive1, &drive2, &drive3};
enum {D_PRT, D_PRO, D_UNI, D_MOD, D_GEO, D_SBY, D_DLY, D_SLV};
/* end of parameters */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/hdreg.h>
#include <linux/cdrom.h> /* for the eject ioctl */
#include <linux/blkdev.h>
#include <linux/blkpg.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <linux/workqueue.h>
static DEFINE_MUTEX(pd_mutex);
static DEFINE_SPINLOCK(pd_lock);
module_param(verbose, bool, 0);
module_param(major, int, 0);
module_param(name, charp, 0);
module_param(cluster, int, 0);
module_param(nice, int, 0);
module_param_array(drive0, int, NULL, 0);
module_param_array(drive1, int, NULL, 0);
module_param_array(drive2, int, NULL, 0);
module_param_array(drive3, int, NULL, 0);
#include "paride.h"
#define PD_BITS 4
/* numbers for "SCSI" geometry */
#define PD_LOG_HEADS 64
#define PD_LOG_SECTS 32
#define PD_ID_OFF 54
#define PD_ID_LEN 14
#define PD_MAX_RETRIES 5
#define PD_TMO 800 /* interrupt timeout in jiffies */
#define PD_SPIN_DEL 50 /* spin delay in micro-seconds */
#define PD_SPIN (1000000*PD_TMO)/(HZ*PD_SPIN_DEL)
#define STAT_ERR 0x00001
#define STAT_INDEX 0x00002
#define STAT_ECC 0x00004
#define STAT_DRQ 0x00008
#define STAT_SEEK 0x00010
#define STAT_WRERR 0x00020
#define STAT_READY 0x00040
#define STAT_BUSY 0x00080
#define ERR_AMNF 0x00100
#define ERR_TK0NF 0x00200
#define ERR_ABRT 0x00400
#define ERR_MCR 0x00800
#define ERR_IDNF 0x01000
#define ERR_MC 0x02000
#define ERR_UNC 0x04000
#define ERR_TMO 0x10000
#define IDE_READ 0x20
#define IDE_WRITE 0x30
#define IDE_READ_VRFY 0x40
#define IDE_INIT_DEV_PARMS 0x91
#define IDE_STANDBY 0x96
#define IDE_ACKCHANGE 0xdb
#define IDE_DOORLOCK 0xde
#define IDE_DOORUNLOCK 0xdf
#define IDE_IDENTIFY 0xec
#define IDE_EJECT 0xed
#define PD_NAMELEN 8
struct pd_unit {
struct pi_adapter pia; /* interface to paride layer */
struct pi_adapter *pi;
int access; /* count of active opens ... */
int capacity; /* Size of this volume in sectors */
int heads; /* physical geometry */
int sectors;
int cylinders;
int can_lba;
int drive; /* master=0 slave=1 */
int changed; /* Have we seen a disk change ? */
int removable; /* removable media device ? */
int standby;
int alt_geom;
char name[PD_NAMELEN]; /* pda, pdb, etc ... */
struct gendisk *gd;
};
static struct pd_unit pd[PD_UNITS];
static char pd_scratch[512]; /* scratch block buffer */
static char *pd_errs[17] = { "ERR", "INDEX", "ECC", "DRQ", "SEEK", "WRERR",
"READY", "BUSY", "AMNF", "TK0NF", "ABRT", "MCR",
"IDNF", "MC", "UNC", "???", "TMO"
};
static inline int status_reg(struct pd_unit *disk)
{
return pi_read_regr(disk->pi, 1, 6);
}
static inline int read_reg(struct pd_unit *disk, int reg)
{
return pi_read_regr(disk->pi, 0, reg);
}
static inline void write_status(struct pd_unit *disk, int val)
{
pi_write_regr(disk->pi, 1, 6, val);
}
static inline void write_reg(struct pd_unit *disk, int reg, int val)
{
pi_write_regr(disk->pi, 0, reg, val);
}
static inline u8 DRIVE(struct pd_unit *disk)
{
return 0xa0+0x10*disk->drive;
}
/* ide command interface */
static void pd_print_error(struct pd_unit *disk, char *msg, int status)
{
int i;
printk("%s: %s: status = 0x%x =", disk->name, msg, status);
for (i = 0; i < ARRAY_SIZE(pd_errs); i++)
if (status & (1 << i))
printk(" %s", pd_errs[i]);
printk("\n");
}
static void pd_reset(struct pd_unit *disk)
{ /* called only for MASTER drive */
write_status(disk, 4);
udelay(50);
write_status(disk, 0);
udelay(250);
}
#define DBMSG(msg) ((verbose>1)?(msg):NULL)
static int pd_wait_for(struct pd_unit *disk, int w, char *msg)
{ /* polled wait */
int k, r, e;
k = 0;
while (k < PD_SPIN) {
r = status_reg(disk);
k++;
if (((r & w) == w) && !(r & STAT_BUSY))
break;
udelay(PD_SPIN_DEL);
}
e = (read_reg(disk, 1) << 8) + read_reg(disk, 7);
if (k >= PD_SPIN)
e |= ERR_TMO;
if ((e & (STAT_ERR | ERR_TMO)) && (msg != NULL))
pd_print_error(disk, msg, e);
return e;
}
static void pd_send_command(struct pd_unit *disk, int n, int s, int h, int c0, int c1, int func)
{
write_reg(disk, 6, DRIVE(disk) + h);
write_reg(disk, 1, 0); /* the IDE task file */
write_reg(disk, 2, n);
write_reg(disk, 3, s);
write_reg(disk, 4, c0);
write_reg(disk, 5, c1);
write_reg(disk, 7, func);
udelay(1);
}
static void pd_ide_command(struct pd_unit *disk, int func, int block, int count)
{
int c1, c0, h, s;
if (disk->can_lba) {
s = block & 255;
c0 = (block >>= 8) & 255;
c1 = (block >>= 8) & 255;
h = ((block >>= 8) & 15) + 0x40;
} else {
s = (block % disk->sectors) + 1;
h = (block /= disk->sectors) % disk->heads;
c0 = (block /= disk->heads) % 256;
c1 = (block >>= 8);
}
pd_send_command(disk, count, s, h, c0, c1, func);
}
/* The i/o request engine */
enum action {Fail = 0, Ok = 1, Hold, Wait};
static struct request *pd_req; /* current request */
static enum action (*phase)(void);
static void run_fsm(void);
static void ps_tq_int(struct work_struct *work);
static DECLARE_DELAYED_WORK(fsm_tq, ps_tq_int);
static void schedule_fsm(void)
{
if (!nice)
schedule_delayed_work(&fsm_tq, 0);
else
schedule_delayed_work(&fsm_tq, nice-1);
}
static void ps_tq_int(struct work_struct *work)
{
run_fsm();
}
static enum action do_pd_io_start(void);
static enum action pd_special(void);
static enum action do_pd_read_start(void);
static enum action do_pd_write_start(void);
static enum action do_pd_read_drq(void);
static enum action do_pd_write_done(void);
static struct request_queue *pd_queue;
static int pd_claimed;
static struct pd_unit *pd_current; /* current request's drive */
static PIA *pi_current; /* current request's PIA */
static void run_fsm(void)
{
while (1) {
enum action res;
unsigned long saved_flags;
int stop = 0;
if (!phase) {
pd_current = pd_req->rq_disk->private_data;
pi_current = pd_current->pi;
phase = do_pd_io_start;
}
switch (pd_claimed) {
case 0:
pd_claimed = 1;
if (!pi_schedule_claimed(pi_current, run_fsm))
return;
case 1:
pd_claimed = 2;
pi_current->proto->connect(pi_current);
}
switch(res = phase()) {
case Ok: case Fail:
pi_disconnect(pi_current);
pd_claimed = 0;
phase = NULL;
spin_lock_irqsave(&pd_lock, saved_flags);
if (!__blk_end_request_cur(pd_req,
res == Ok ? 0 : -EIO)) {
pd_req = blk_fetch_request(pd_queue);
if (!pd_req)
stop = 1;
}
spin_unlock_irqrestore(&pd_lock, saved_flags);
if (stop)
return;
case Hold:
schedule_fsm();
return;
case Wait:
pi_disconnect(pi_current);
pd_claimed = 0;
}
}
}
static int pd_retries = 0; /* i/o error retry count */
static int pd_block; /* address of next requested block */
static int pd_count; /* number of blocks still to do */
static int pd_run; /* sectors in current cluster */
static int pd_cmd; /* current command READ/WRITE */
static char *pd_buf; /* buffer for request in progress */
static enum action do_pd_io_start(void)
{
if (pd_req->cmd_type == REQ_TYPE_SPECIAL) {
phase = pd_special;
return pd_special();
}
pd_cmd = rq_data_dir(pd_req);
if (pd_cmd == READ || pd_cmd == WRITE) {
pd_block = blk_rq_pos(pd_req);
pd_count = blk_rq_cur_sectors(pd_req);
if (pd_block + pd_count > get_capacity(pd_req->rq_disk))
return Fail;
pd_run = blk_rq_sectors(pd_req);
pd_buf = pd_req->buffer;
pd_retries = 0;
if (pd_cmd == READ)
return do_pd_read_start();
else
return do_pd_write_start();
}
return Fail;
}
static enum action pd_special(void)
{
enum action (*func)(struct pd_unit *) = pd_req->special;
return func(pd_current);
}
static int pd_next_buf(void)
{
unsigned long saved_flags;
pd_count--;
pd_run--;
pd_buf += 512;
pd_block++;
if (!pd_run)
return 1;
if (pd_count)
return 0;
spin_lock_irqsave(&pd_lock, saved_flags);
__blk_end_request_cur(pd_req, 0);
pd_count = blk_rq_cur_sectors(pd_req);
pd_buf = pd_req->buffer;
spin_unlock_irqrestore(&pd_lock, saved_flags);
return 0;
}
static unsigned long pd_timeout;
static enum action do_pd_read_start(void)
{
if (pd_wait_for(pd_current, STAT_READY, "do_pd_read") & STAT_ERR) {
if (pd_retries < PD_MAX_RETRIES) {
pd_retries++;
return Wait;
}
return Fail;
}
pd_ide_command(pd_current, IDE_READ, pd_block, pd_run);
phase = do_pd_read_drq;
pd_timeout = jiffies + PD_TMO;
return Hold;
}
static enum action do_pd_write_start(void)
{
if (pd_wait_for(pd_current, STAT_READY, "do_pd_write") & STAT_ERR) {
if (pd_retries < PD_MAX_RETRIES) {
pd_retries++;
return Wait;
}
return Fail;
}
pd_ide_command(pd_current, IDE_WRITE, pd_block, pd_run);
while (1) {
if (pd_wait_for(pd_current, STAT_DRQ, "do_pd_write_drq") & STAT_ERR) {
if (pd_retries < PD_MAX_RETRIES) {
pd_retries++;
return Wait;
}
return Fail;
}
pi_write_block(pd_current->pi, pd_buf, 512);
if (pd_next_buf())
break;
}
phase = do_pd_write_done;
pd_timeout = jiffies + PD_TMO;
return Hold;
}
static inline int pd_ready(void)
{
return !(status_reg(pd_current) & STAT_BUSY);
}
static enum action do_pd_read_drq(void)
{
if (!pd_ready() && !time_after_eq(jiffies, pd_timeout))
return Hold;
while (1) {
if (pd_wait_for(pd_current, STAT_DRQ, "do_pd_read_drq") & STAT_ERR) {
if (pd_retries < PD_MAX_RETRIES) {
pd_retries++;
phase = do_pd_read_start;
return Wait;
}
return Fail;
}
pi_read_block(pd_current->pi, pd_buf, 512);
if (pd_next_buf())
break;
}
return Ok;
}
static enum action do_pd_write_done(void)
{
if (!pd_ready() && !time_after_eq(jiffies, pd_timeout))
return Hold;
if (pd_wait_for(pd_current, STAT_READY, "do_pd_write_done") & STAT_ERR) {
if (pd_retries < PD_MAX_RETRIES) {
pd_retries++;
phase = do_pd_write_start;
return Wait;
}
return Fail;
}
return Ok;
}
/* special io requests */
/* According to the ATA standard, the default CHS geometry should be
available following a reset. Some Western Digital drives come up
in a mode where only LBA addresses are accepted until the device
parameters are initialised.
*/
static void pd_init_dev_parms(struct pd_unit *disk)
{
pd_wait_for(disk, 0, DBMSG("before init_dev_parms"));
pd_send_command(disk, disk->sectors, 0, disk->heads - 1, 0, 0,
IDE_INIT_DEV_PARMS);
udelay(300);
pd_wait_for(disk, 0, "Initialise device parameters");
}
static enum action pd_door_lock(struct pd_unit *disk)
{
if (!(pd_wait_for(disk, STAT_READY, "Lock") & STAT_ERR)) {
pd_send_command(disk, 1, 0, 0, 0, 0, IDE_DOORLOCK);
pd_wait_for(disk, STAT_READY, "Lock done");
}
return Ok;
}
static enum action pd_door_unlock(struct pd_unit *disk)
{
if (!(pd_wait_for(disk, STAT_READY, "Lock") & STAT_ERR)) {
pd_send_command(disk, 1, 0, 0, 0, 0, IDE_DOORUNLOCK);
pd_wait_for(disk, STAT_READY, "Lock done");
}
return Ok;
}
static enum action pd_eject(struct pd_unit *disk)
{
pd_wait_for(disk, 0, DBMSG("before unlock on eject"));
pd_send_command(disk, 1, 0, 0, 0, 0, IDE_DOORUNLOCK);
pd_wait_for(disk, 0, DBMSG("after unlock on eject"));
pd_wait_for(disk, 0, DBMSG("before eject"));
pd_send_command(disk, 0, 0, 0, 0, 0, IDE_EJECT);
pd_wait_for(disk, 0, DBMSG("after eject"));
return Ok;
}
static enum action pd_media_check(struct pd_unit *disk)
{
int r = pd_wait_for(disk, STAT_READY, DBMSG("before media_check"));
if (!(r & STAT_ERR)) {
pd_send_command(disk, 1, 1, 0, 0, 0, IDE_READ_VRFY);
r = pd_wait_for(disk, STAT_READY, DBMSG("RDY after READ_VRFY"));
} else
disk->changed = 1; /* say changed if other error */
if (r & ERR_MC) {
disk->changed = 1;
pd_send_command(disk, 1, 0, 0, 0, 0, IDE_ACKCHANGE);
pd_wait_for(disk, STAT_READY, DBMSG("RDY after ACKCHANGE"));
pd_send_command(disk, 1, 1, 0, 0, 0, IDE_READ_VRFY);
r = pd_wait_for(disk, STAT_READY, DBMSG("RDY after VRFY"));
}
return Ok;
}
static void pd_standby_off(struct pd_unit *disk)
{
pd_wait_for(disk, 0, DBMSG("before STANDBY"));
pd_send_command(disk, 0, 0, 0, 0, 0, IDE_STANDBY);
pd_wait_for(disk, 0, DBMSG("after STANDBY"));
}
static enum action pd_identify(struct pd_unit *disk)
{
int j;
char id[PD_ID_LEN + 1];
/* WARNING: here there may be dragons. reset() applies to both drives,
but we call it only on probing the MASTER. This should allow most
common configurations to work, but be warned that a reset can clear
settings on the SLAVE drive.
*/
if (disk->drive == 0)
pd_reset(disk);
write_reg(disk, 6, DRIVE(disk));
pd_wait_for(disk, 0, DBMSG("before IDENT"));
pd_send_command(disk, 1, 0, 0, 0, 0, IDE_IDENTIFY);
if (pd_wait_for(disk, STAT_DRQ, DBMSG("IDENT DRQ")) & STAT_ERR)
return Fail;
pi_read_block(disk->pi, pd_scratch, 512);
disk->can_lba = pd_scratch[99] & 2;
disk->sectors = le16_to_cpu(*(__le16 *) (pd_scratch + 12));
disk->heads = le16_to_cpu(*(__le16 *) (pd_scratch + 6));
disk->cylinders = le16_to_cpu(*(__le16 *) (pd_scratch + 2));
if (disk->can_lba)
disk->capacity = le32_to_cpu(*(__le32 *) (pd_scratch + 120));
else
disk->capacity = disk->sectors * disk->heads * disk->cylinders;
for (j = 0; j < PD_ID_LEN; j++)
id[j ^ 1] = pd_scratch[j + PD_ID_OFF];
j = PD_ID_LEN - 1;
while ((j >= 0) && (id[j] <= 0x20))
j--;
j++;
id[j] = 0;
disk->removable = pd_scratch[0] & 0x80;
printk("%s: %s, %s, %d blocks [%dM], (%d/%d/%d), %s media\n",
disk->name, id,
disk->drive ? "slave" : "master",
disk->capacity, disk->capacity / 2048,
disk->cylinders, disk->heads, disk->sectors,
disk->removable ? "removable" : "fixed");
if (disk->capacity)
pd_init_dev_parms(disk);
if (!disk->standby)
pd_standby_off(disk);
return Ok;
}
/* end of io request engine */
static void do_pd_request(struct request_queue * q)
{
if (pd_req)
return;
pd_req = blk_fetch_request(q);
if (!pd_req)
return;
schedule_fsm();
}
static int pd_special_command(struct pd_unit *disk,
enum action (*func)(struct pd_unit *disk))
{
struct request *rq;
int err = 0;
rq = blk_get_request(disk->gd->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_SPECIAL;
rq->special = func;
err = blk_execute_rq(disk->gd->queue, disk->gd, rq, 0);
blk_put_request(rq);
return err;
}
/* kernel glue structures */
static int pd_open(struct block_device *bdev, fmode_t mode)
{
struct pd_unit *disk = bdev->bd_disk->private_data;
mutex_lock(&pd_mutex);
disk->access++;
if (disk->removable) {
pd_special_command(disk, pd_media_check);
pd_special_command(disk, pd_door_lock);
}
mutex_unlock(&pd_mutex);
return 0;
}
static int pd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct pd_unit *disk = bdev->bd_disk->private_data;
if (disk->alt_geom) {
geo->heads = PD_LOG_HEADS;
geo->sectors = PD_LOG_SECTS;
geo->cylinders = disk->capacity / (geo->heads * geo->sectors);
} else {
geo->heads = disk->heads;
geo->sectors = disk->sectors;
geo->cylinders = disk->cylinders;
}
return 0;
}
static int pd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct pd_unit *disk = bdev->bd_disk->private_data;
switch (cmd) {
case CDROMEJECT:
mutex_lock(&pd_mutex);
if (disk->access == 1)
pd_special_command(disk, pd_eject);
mutex_unlock(&pd_mutex);
return 0;
default:
return -EINVAL;
}
}
static int pd_release(struct gendisk *p, fmode_t mode)
{
struct pd_unit *disk = p->private_data;
mutex_lock(&pd_mutex);
if (!--disk->access && disk->removable)
pd_special_command(disk, pd_door_unlock);
mutex_unlock(&pd_mutex);
return 0;
}
static unsigned int pd_check_events(struct gendisk *p, unsigned int clearing)
{
struct pd_unit *disk = p->private_data;
int r;
if (!disk->removable)
return 0;
pd_special_command(disk, pd_media_check);
r = disk->changed;
disk->changed = 0;
return r ? DISK_EVENT_MEDIA_CHANGE : 0;
}
static int pd_revalidate(struct gendisk *p)
{
struct pd_unit *disk = p->private_data;
if (pd_special_command(disk, pd_identify) == 0)
set_capacity(p, disk->capacity);
else
set_capacity(p, 0);
return 0;
}
static const struct block_device_operations pd_fops = {
.owner = THIS_MODULE,
.open = pd_open,
.release = pd_release,
.ioctl = pd_ioctl,
.getgeo = pd_getgeo,
.check_events = pd_check_events,
.revalidate_disk= pd_revalidate
};
/* probing */
static void pd_probe_drive(struct pd_unit *disk)
{
struct gendisk *p = alloc_disk(1 << PD_BITS);
if (!p)
return;
strcpy(p->disk_name, disk->name);
p->fops = &pd_fops;
p->major = major;
p->first_minor = (disk - pd) << PD_BITS;
disk->gd = p;
p->private_data = disk;
p->queue = pd_queue;
if (disk->drive == -1) {
for (disk->drive = 0; disk->drive <= 1; disk->drive++)
if (pd_special_command(disk, pd_identify) == 0)
return;
} else if (pd_special_command(disk, pd_identify) == 0)
return;
disk->gd = NULL;
put_disk(p);
}
static int pd_detect(void)
{
int found = 0, unit, pd_drive_count = 0;
struct pd_unit *disk;
for (unit = 0; unit < PD_UNITS; unit++) {
int *parm = *drives[unit];
struct pd_unit *disk = pd + unit;
disk->pi = &disk->pia;
disk->access = 0;
disk->changed = 1;
disk->capacity = 0;
disk->drive = parm[D_SLV];
snprintf(disk->name, PD_NAMELEN, "%s%c", name, 'a'+unit);
disk->alt_geom = parm[D_GEO];
disk->standby = parm[D_SBY];
if (parm[D_PRT])
pd_drive_count++;
}
if (pd_drive_count == 0) { /* nothing spec'd - so autoprobe for 1 */
disk = pd;
if (pi_init(disk->pi, 1, -1, -1, -1, -1, -1, pd_scratch,
PI_PD, verbose, disk->name)) {
pd_probe_drive(disk);
if (!disk->gd)
pi_release(disk->pi);
}
} else {
for (unit = 0, disk = pd; unit < PD_UNITS; unit++, disk++) {
int *parm = *drives[unit];
if (!parm[D_PRT])
continue;
if (pi_init(disk->pi, 0, parm[D_PRT], parm[D_MOD],
parm[D_UNI], parm[D_PRO], parm[D_DLY],
pd_scratch, PI_PD, verbose, disk->name)) {
pd_probe_drive(disk);
if (!disk->gd)
pi_release(disk->pi);
}
}
}
for (unit = 0, disk = pd; unit < PD_UNITS; unit++, disk++) {
if (disk->gd) {
set_capacity(disk->gd, disk->capacity);
add_disk(disk->gd);
found = 1;
}
}
if (!found)
printk("%s: no valid drive found\n", name);
return found;
}
static int __init pd_init(void)
{
if (disable)
goto out1;
pd_queue = blk_init_queue(do_pd_request, &pd_lock);
if (!pd_queue)
goto out1;
blk_queue_max_hw_sectors(pd_queue, cluster);
if (register_blkdev(major, name))
goto out2;
printk("%s: %s version %s, major %d, cluster %d, nice %d\n",
name, name, PD_VERSION, major, cluster, nice);
if (!pd_detect())
goto out3;
return 0;
out3:
unregister_blkdev(major, name);
out2:
blk_cleanup_queue(pd_queue);
out1:
return -ENODEV;
}
static void __exit pd_exit(void)
{
struct pd_unit *disk;
int unit;
unregister_blkdev(major, name);
for (unit = 0, disk = pd; unit < PD_UNITS; unit++, disk++) {
struct gendisk *p = disk->gd;
if (p) {
disk->gd = NULL;
del_gendisk(p);
put_disk(p);
pi_release(disk->pi);
}
}
blk_cleanup_queue(pd_queue);
}
MODULE_LICENSE("GPL");
module_init(pd_init)
module_exit(pd_exit)
| gpl-2.0 |
VanirAOSP/kernel_samsung_skomer | drivers/rtc/rtc-bfin.c | 3096 | 13639 | /*
* Blackfin On-Chip Real Time Clock Driver
* Supports BF51x/BF52x/BF53[123]/BF53[467]/BF54x
*
* Copyright 2004-2010 Analog Devices Inc.
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
/* The biggest issue we deal with in this driver is that register writes are
* synced to the RTC frequency of 1Hz. So if you write to a register and
* attempt to write again before the first write has completed, the new write
* is simply discarded. This can easily be troublesome if userspace disables
* one event (say periodic) and then right after enables an event (say alarm).
* Since all events are maintained in the same interrupt mask register, if
* we wrote to it to disable the first event and then wrote to it again to
* enable the second event, that second event would not be enabled as the
* write would be discarded and things quickly fall apart.
*
* To keep this delay from significantly degrading performance (we, in theory,
* would have to sleep for up to 1 second every time we wanted to write a
* register), we only check the write pending status before we start to issue
* a new write. We bank on the idea that it doesn't matter when the sync
* happens so long as we don't attempt another write before it does. The only
* time userspace would take this penalty is when they try and do multiple
* operations right after another ... but in this case, they need to take the
* sync penalty, so we should be OK.
*
* Also note that the RTC_ISTAT register does not suffer this penalty; its
* writes to clear status registers complete immediately.
*/
/* It may seem odd that there is no SWCNT code in here (which would be exposed
* via the periodic interrupt event, or PIE). Since the Blackfin RTC peripheral
* runs in units of seconds (N/HZ) but the Linux framework runs in units of HZ
* (2^N HZ), there is no point in keeping code that only provides 1 HZ PIEs.
* The same exact behavior can be accomplished by using the update interrupt
* event (UIE). Maybe down the line the RTC peripheral will suck less in which
* case we can re-introduce PIE support.
*/
#include <linux/bcd.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <asm/blackfin.h>
#define dev_dbg_stamp(dev) dev_dbg(dev, "%s:%i: here i am\n", __func__, __LINE__)
struct bfin_rtc {
struct rtc_device *rtc_dev;
struct rtc_time rtc_alarm;
u16 rtc_wrote_regs;
};
/* Bit values for the ISTAT / ICTL registers */
#define RTC_ISTAT_WRITE_COMPLETE 0x8000
#define RTC_ISTAT_WRITE_PENDING 0x4000
#define RTC_ISTAT_ALARM_DAY 0x0040
#define RTC_ISTAT_24HR 0x0020
#define RTC_ISTAT_HOUR 0x0010
#define RTC_ISTAT_MIN 0x0008
#define RTC_ISTAT_SEC 0x0004
#define RTC_ISTAT_ALARM 0x0002
#define RTC_ISTAT_STOPWATCH 0x0001
/* Shift values for RTC_STAT register */
#define DAY_BITS_OFF 17
#define HOUR_BITS_OFF 12
#define MIN_BITS_OFF 6
#define SEC_BITS_OFF 0
/* Some helper functions to convert between the common RTC notion of time
* and the internal Blackfin notion that is encoded in 32bits.
*/
static inline u32 rtc_time_to_bfin(unsigned long now)
{
u32 sec = (now % 60);
u32 min = (now % (60 * 60)) / 60;
u32 hour = (now % (60 * 60 * 24)) / (60 * 60);
u32 days = (now / (60 * 60 * 24));
return (sec << SEC_BITS_OFF) +
(min << MIN_BITS_OFF) +
(hour << HOUR_BITS_OFF) +
(days << DAY_BITS_OFF);
}
static inline unsigned long rtc_bfin_to_time(u32 rtc_bfin)
{
return (((rtc_bfin >> SEC_BITS_OFF) & 0x003F)) +
(((rtc_bfin >> MIN_BITS_OFF) & 0x003F) * 60) +
(((rtc_bfin >> HOUR_BITS_OFF) & 0x001F) * 60 * 60) +
(((rtc_bfin >> DAY_BITS_OFF) & 0x7FFF) * 60 * 60 * 24);
}
static inline void rtc_bfin_to_tm(u32 rtc_bfin, struct rtc_time *tm)
{
rtc_time_to_tm(rtc_bfin_to_time(rtc_bfin), tm);
}
/**
* bfin_rtc_sync_pending - make sure pending writes have complete
*
* Wait for the previous write to a RTC register to complete.
* Unfortunately, we can't sleep here as that introduces a race condition when
* turning on interrupt events. Consider this:
* - process sets alarm
* - process enables alarm
* - process sleeps while waiting for rtc write to sync
* - interrupt fires while process is sleeping
* - interrupt acks the event by writing to ISTAT
* - interrupt sets the WRITE PENDING bit
* - interrupt handler finishes
* - process wakes up, sees WRITE PENDING bit set, goes to sleep
* - interrupt fires while process is sleeping
* If anyone can point out the obvious solution here, i'm listening :). This
* shouldn't be an issue on an SMP or preempt system as this function should
* only be called with the rtc lock held.
*
* Other options:
* - disable PREN so the sync happens at 32.768kHZ ... but this changes the
* inc rate for all RTC registers from 1HZ to 32.768kHZ ...
* - use the write complete IRQ
*/
/*
static void bfin_rtc_sync_pending_polled(void)
{
while (!(bfin_read_RTC_ISTAT() & RTC_ISTAT_WRITE_COMPLETE))
if (!(bfin_read_RTC_ISTAT() & RTC_ISTAT_WRITE_PENDING))
break;
bfin_write_RTC_ISTAT(RTC_ISTAT_WRITE_COMPLETE);
}
*/
static DECLARE_COMPLETION(bfin_write_complete);
static void bfin_rtc_sync_pending(struct device *dev)
{
dev_dbg_stamp(dev);
while (bfin_read_RTC_ISTAT() & RTC_ISTAT_WRITE_PENDING)
wait_for_completion_timeout(&bfin_write_complete, HZ * 5);
dev_dbg_stamp(dev);
}
/**
* bfin_rtc_reset - set RTC to sane/known state
*
* Initialize the RTC. Enable pre-scaler to scale RTC clock
* to 1Hz and clear interrupt/status registers.
*/
static void bfin_rtc_reset(struct device *dev, u16 rtc_ictl)
{
struct bfin_rtc *rtc = dev_get_drvdata(dev);
dev_dbg_stamp(dev);
bfin_rtc_sync_pending(dev);
bfin_write_RTC_PREN(0x1);
bfin_write_RTC_ICTL(rtc_ictl);
bfin_write_RTC_ALARM(0);
bfin_write_RTC_ISTAT(0xFFFF);
rtc->rtc_wrote_regs = 0;
}
/**
* bfin_rtc_interrupt - handle interrupt from RTC
*
* Since we handle all RTC events here, we have to make sure the requested
* interrupt is enabled (in RTC_ICTL) as the event status register (RTC_ISTAT)
* always gets updated regardless of the interrupt being enabled. So when one
* even we care about (e.g. stopwatch) goes off, we don't want to turn around
* and say that other events have happened as well (e.g. second). We do not
* have to worry about pending writes to the RTC_ICTL register as interrupts
* only fire if they are enabled in the RTC_ICTL register.
*/
static irqreturn_t bfin_rtc_interrupt(int irq, void *dev_id)
{
struct device *dev = dev_id;
struct bfin_rtc *rtc = dev_get_drvdata(dev);
unsigned long events = 0;
bool write_complete = false;
u16 rtc_istat, rtc_istat_clear, rtc_ictl, bits;
dev_dbg_stamp(dev);
rtc_istat = bfin_read_RTC_ISTAT();
rtc_ictl = bfin_read_RTC_ICTL();
rtc_istat_clear = 0;
bits = RTC_ISTAT_WRITE_COMPLETE;
if (rtc_istat & bits) {
rtc_istat_clear |= bits;
write_complete = true;
complete(&bfin_write_complete);
}
bits = (RTC_ISTAT_ALARM | RTC_ISTAT_ALARM_DAY);
if (rtc_ictl & bits) {
if (rtc_istat & bits) {
rtc_istat_clear |= bits;
events |= RTC_AF | RTC_IRQF;
}
}
bits = RTC_ISTAT_SEC;
if (rtc_ictl & bits) {
if (rtc_istat & bits) {
rtc_istat_clear |= bits;
events |= RTC_UF | RTC_IRQF;
}
}
if (events)
rtc_update_irq(rtc->rtc_dev, 1, events);
if (write_complete || events) {
bfin_write_RTC_ISTAT(rtc_istat_clear);
return IRQ_HANDLED;
} else
return IRQ_NONE;
}
static void bfin_rtc_int_set(u16 rtc_int)
{
bfin_write_RTC_ISTAT(rtc_int);
bfin_write_RTC_ICTL(bfin_read_RTC_ICTL() | rtc_int);
}
static void bfin_rtc_int_clear(u16 rtc_int)
{
bfin_write_RTC_ICTL(bfin_read_RTC_ICTL() & rtc_int);
}
static void bfin_rtc_int_set_alarm(struct bfin_rtc *rtc)
{
/* Blackfin has different bits for whether the alarm is
* more than 24 hours away.
*/
bfin_rtc_int_set(rtc->rtc_alarm.tm_yday == -1 ? RTC_ISTAT_ALARM : RTC_ISTAT_ALARM_DAY);
}
static int bfin_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct bfin_rtc *rtc = dev_get_drvdata(dev);
dev_dbg_stamp(dev);
if (enabled)
bfin_rtc_int_set_alarm(rtc);
else
bfin_rtc_int_clear(~(RTC_ISTAT_ALARM | RTC_ISTAT_ALARM_DAY));
return 0;
}
static int bfin_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct bfin_rtc *rtc = dev_get_drvdata(dev);
dev_dbg_stamp(dev);
if (rtc->rtc_wrote_regs & 0x1)
bfin_rtc_sync_pending(dev);
rtc_bfin_to_tm(bfin_read_RTC_STAT(), tm);
return 0;
}
static int bfin_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct bfin_rtc *rtc = dev_get_drvdata(dev);
int ret;
unsigned long now;
dev_dbg_stamp(dev);
ret = rtc_tm_to_time(tm, &now);
if (ret == 0) {
if (rtc->rtc_wrote_regs & 0x1)
bfin_rtc_sync_pending(dev);
bfin_write_RTC_STAT(rtc_time_to_bfin(now));
rtc->rtc_wrote_regs = 0x1;
}
return ret;
}
static int bfin_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct bfin_rtc *rtc = dev_get_drvdata(dev);
dev_dbg_stamp(dev);
alrm->time = rtc->rtc_alarm;
bfin_rtc_sync_pending(dev);
alrm->enabled = !!(bfin_read_RTC_ICTL() & (RTC_ISTAT_ALARM | RTC_ISTAT_ALARM_DAY));
return 0;
}
static int bfin_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct bfin_rtc *rtc = dev_get_drvdata(dev);
unsigned long rtc_alarm;
dev_dbg_stamp(dev);
if (rtc_tm_to_time(&alrm->time, &rtc_alarm))
return -EINVAL;
rtc->rtc_alarm = alrm->time;
bfin_rtc_sync_pending(dev);
bfin_write_RTC_ALARM(rtc_time_to_bfin(rtc_alarm));
if (alrm->enabled)
bfin_rtc_int_set_alarm(rtc);
return 0;
}
static int bfin_rtc_proc(struct device *dev, struct seq_file *seq)
{
#define yesno(x) ((x) ? "yes" : "no")
u16 ictl = bfin_read_RTC_ICTL();
dev_dbg_stamp(dev);
seq_printf(seq,
"alarm_IRQ\t: %s\n"
"wkalarm_IRQ\t: %s\n"
"seconds_IRQ\t: %s\n",
yesno(ictl & RTC_ISTAT_ALARM),
yesno(ictl & RTC_ISTAT_ALARM_DAY),
yesno(ictl & RTC_ISTAT_SEC));
return 0;
#undef yesno
}
static struct rtc_class_ops bfin_rtc_ops = {
.read_time = bfin_rtc_read_time,
.set_time = bfin_rtc_set_time,
.read_alarm = bfin_rtc_read_alarm,
.set_alarm = bfin_rtc_set_alarm,
.proc = bfin_rtc_proc,
.alarm_irq_enable = bfin_rtc_alarm_irq_enable,
};
static int __devinit bfin_rtc_probe(struct platform_device *pdev)
{
struct bfin_rtc *rtc;
struct device *dev = &pdev->dev;
int ret = 0;
unsigned long timeout = jiffies + HZ;
dev_dbg_stamp(dev);
/* Allocate memory for our RTC struct */
rtc = kzalloc(sizeof(*rtc), GFP_KERNEL);
if (unlikely(!rtc))
return -ENOMEM;
platform_set_drvdata(pdev, rtc);
device_init_wakeup(dev, 1);
/* Register our RTC with the RTC framework */
rtc->rtc_dev = rtc_device_register(pdev->name, dev, &bfin_rtc_ops,
THIS_MODULE);
if (unlikely(IS_ERR(rtc->rtc_dev))) {
ret = PTR_ERR(rtc->rtc_dev);
goto err;
}
/* Grab the IRQ and init the hardware */
ret = request_irq(IRQ_RTC, bfin_rtc_interrupt, 0, pdev->name, dev);
if (unlikely(ret))
goto err_reg;
/* sometimes the bootloader touched things, but the write complete was not
* enabled, so let's just do a quick timeout here since the IRQ will not fire ...
*/
while (bfin_read_RTC_ISTAT() & RTC_ISTAT_WRITE_PENDING)
if (time_after(jiffies, timeout))
break;
bfin_rtc_reset(dev, RTC_ISTAT_WRITE_COMPLETE);
bfin_write_RTC_SWCNT(0);
return 0;
err_reg:
rtc_device_unregister(rtc->rtc_dev);
err:
kfree(rtc);
return ret;
}
static int __devexit bfin_rtc_remove(struct platform_device *pdev)
{
struct bfin_rtc *rtc = platform_get_drvdata(pdev);
struct device *dev = &pdev->dev;
bfin_rtc_reset(dev, 0);
free_irq(IRQ_RTC, dev);
rtc_device_unregister(rtc->rtc_dev);
platform_set_drvdata(pdev, NULL);
kfree(rtc);
return 0;
}
#ifdef CONFIG_PM
static int bfin_rtc_suspend(struct platform_device *pdev, pm_message_t state)
{
struct device *dev = &pdev->dev;
dev_dbg_stamp(dev);
if (device_may_wakeup(dev)) {
enable_irq_wake(IRQ_RTC);
bfin_rtc_sync_pending(dev);
} else
bfin_rtc_int_clear(0);
return 0;
}
static int bfin_rtc_resume(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
dev_dbg_stamp(dev);
if (device_may_wakeup(dev))
disable_irq_wake(IRQ_RTC);
/*
* Since only some of the RTC bits are maintained externally in the
* Vbat domain, we need to wait for the RTC MMRs to be synced into
* the core after waking up. This happens every RTC 1HZ. Once that
* has happened, we can go ahead and re-enable the important write
* complete interrupt event.
*/
while (!(bfin_read_RTC_ISTAT() & RTC_ISTAT_SEC))
continue;
bfin_rtc_int_set(RTC_ISTAT_WRITE_COMPLETE);
return 0;
}
#else
# define bfin_rtc_suspend NULL
# define bfin_rtc_resume NULL
#endif
static struct platform_driver bfin_rtc_driver = {
.driver = {
.name = "rtc-bfin",
.owner = THIS_MODULE,
},
.probe = bfin_rtc_probe,
.remove = __devexit_p(bfin_rtc_remove),
.suspend = bfin_rtc_suspend,
.resume = bfin_rtc_resume,
};
static int __init bfin_rtc_init(void)
{
return platform_driver_register(&bfin_rtc_driver);
}
static void __exit bfin_rtc_exit(void)
{
platform_driver_unregister(&bfin_rtc_driver);
}
module_init(bfin_rtc_init);
module_exit(bfin_rtc_exit);
MODULE_DESCRIPTION("Blackfin On-Chip Real Time Clock Driver");
MODULE_AUTHOR("Mike Frysinger <vapier@gentoo.org>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:rtc-bfin");
| gpl-2.0 |
HeydayGuan/android-kernel-3.0 | drivers/mtd/ftl.c | 3096 | 32247 | /* This version ported to the Linux-MTD system by dwmw2@infradead.org
*
* Fixes: Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* - fixes some leaks on failure in build_maps and ftl_notify_add, cleanups
*
* Based on:
*/
/*======================================================================
A Flash Translation Layer memory card driver
This driver implements a disk-like block device driver with an
apparent block size of 512 bytes for flash memory cards.
ftl_cs.c 1.62 2000/02/01 00:59:04
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright © 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in
which case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
LEGAL NOTE: The FTL format is patented by M-Systems. They have
granted a license for its use with PCMCIA devices:
"M-Systems grants a royalty-free, non-exclusive license under
any presently existing M-Systems intellectual property rights
necessary for the design and development of FTL-compatible
drivers, file systems and utilities using the data formats with
PCMCIA PC Cards as described in the PCMCIA Flash Translation
Layer (FTL) Specification."
Use of the FTL format for non-PCMCIA applications may be an
infringement of these patents. For additional information,
contact M-Systems directly. M-Systems since acquired by Sandisk.
======================================================================*/
#include <linux/mtd/blktrans.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
/*#define PSYCHO_DEBUG */
#include <linux/kernel.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/major.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/hdreg.h>
#include <linux/vmalloc.h>
#include <linux/blkpg.h>
#include <asm/uaccess.h>
#include <linux/mtd/ftl.h>
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
static int shuffle_freq = 50;
module_param(shuffle_freq, int, 0);
/*====================================================================*/
/* Major device # for FTL device */
#ifndef FTL_MAJOR
#define FTL_MAJOR 44
#endif
/*====================================================================*/
/* Maximum number of separate memory devices we'll allow */
#define MAX_DEV 4
/* Maximum number of regions per device */
#define MAX_REGION 4
/* Maximum number of partitions in an FTL region */
#define PART_BITS 4
/* Maximum number of outstanding erase requests per socket */
#define MAX_ERASE 8
/* Sector size -- shouldn't need to change */
#define SECTOR_SIZE 512
/* Each memory region corresponds to a minor device */
typedef struct partition_t {
struct mtd_blktrans_dev mbd;
uint32_t state;
uint32_t *VirtualBlockMap;
uint32_t *VirtualPageMap;
uint32_t FreeTotal;
struct eun_info_t {
uint32_t Offset;
uint32_t EraseCount;
uint32_t Free;
uint32_t Deleted;
} *EUNInfo;
struct xfer_info_t {
uint32_t Offset;
uint32_t EraseCount;
uint16_t state;
} *XferInfo;
uint16_t bam_index;
uint32_t *bam_cache;
uint16_t DataUnits;
uint32_t BlocksPerUnit;
erase_unit_header_t header;
} partition_t;
/* Partition state flags */
#define FTL_FORMATTED 0x01
/* Transfer unit states */
#define XFER_UNKNOWN 0x00
#define XFER_ERASING 0x01
#define XFER_ERASED 0x02
#define XFER_PREPARED 0x03
#define XFER_FAILED 0x04
/*====================================================================*/
static void ftl_erase_callback(struct erase_info *done);
/*======================================================================
Scan_header() checks to see if a memory region contains an FTL
partition. build_maps() reads all the erase unit headers, builds
the erase unit map, and then builds the virtual page map.
======================================================================*/
static int scan_header(partition_t *part)
{
erase_unit_header_t header;
loff_t offset, max_offset;
size_t ret;
int err;
part->header.FormattedSize = 0;
max_offset = (0x100000<part->mbd.mtd->size)?0x100000:part->mbd.mtd->size;
/* Search first megabyte for a valid FTL header */
for (offset = 0;
(offset + sizeof(header)) < max_offset;
offset += part->mbd.mtd->erasesize ? : 0x2000) {
err = part->mbd.mtd->read(part->mbd.mtd, offset, sizeof(header), &ret,
(unsigned char *)&header);
if (err)
return err;
if (strcmp(header.DataOrgTuple+3, "FTL100") == 0) break;
}
if (offset == max_offset) {
printk(KERN_NOTICE "ftl_cs: FTL header not found.\n");
return -ENOENT;
}
if (header.BlockSize != 9 ||
(header.EraseUnitSize < 10) || (header.EraseUnitSize > 31) ||
(header.NumTransferUnits >= le16_to_cpu(header.NumEraseUnits))) {
printk(KERN_NOTICE "ftl_cs: FTL header corrupt!\n");
return -1;
}
if ((1 << header.EraseUnitSize) != part->mbd.mtd->erasesize) {
printk(KERN_NOTICE "ftl: FTL EraseUnitSize %x != MTD erasesize %x\n",
1 << header.EraseUnitSize,part->mbd.mtd->erasesize);
return -1;
}
part->header = header;
return 0;
}
static int build_maps(partition_t *part)
{
erase_unit_header_t header;
uint16_t xvalid, xtrans, i;
unsigned blocks, j;
int hdr_ok, ret = -1;
ssize_t retval;
loff_t offset;
/* Set up erase unit maps */
part->DataUnits = le16_to_cpu(part->header.NumEraseUnits) -
part->header.NumTransferUnits;
part->EUNInfo = kmalloc(part->DataUnits * sizeof(struct eun_info_t),
GFP_KERNEL);
if (!part->EUNInfo)
goto out;
for (i = 0; i < part->DataUnits; i++)
part->EUNInfo[i].Offset = 0xffffffff;
part->XferInfo =
kmalloc(part->header.NumTransferUnits * sizeof(struct xfer_info_t),
GFP_KERNEL);
if (!part->XferInfo)
goto out_EUNInfo;
xvalid = xtrans = 0;
for (i = 0; i < le16_to_cpu(part->header.NumEraseUnits); i++) {
offset = ((i + le16_to_cpu(part->header.FirstPhysicalEUN))
<< part->header.EraseUnitSize);
ret = part->mbd.mtd->read(part->mbd.mtd, offset, sizeof(header), &retval,
(unsigned char *)&header);
if (ret)
goto out_XferInfo;
ret = -1;
/* Is this a transfer partition? */
hdr_ok = (strcmp(header.DataOrgTuple+3, "FTL100") == 0);
if (hdr_ok && (le16_to_cpu(header.LogicalEUN) < part->DataUnits) &&
(part->EUNInfo[le16_to_cpu(header.LogicalEUN)].Offset == 0xffffffff)) {
part->EUNInfo[le16_to_cpu(header.LogicalEUN)].Offset = offset;
part->EUNInfo[le16_to_cpu(header.LogicalEUN)].EraseCount =
le32_to_cpu(header.EraseCount);
xvalid++;
} else {
if (xtrans == part->header.NumTransferUnits) {
printk(KERN_NOTICE "ftl_cs: format error: too many "
"transfer units!\n");
goto out_XferInfo;
}
if (hdr_ok && (le16_to_cpu(header.LogicalEUN) == 0xffff)) {
part->XferInfo[xtrans].state = XFER_PREPARED;
part->XferInfo[xtrans].EraseCount = le32_to_cpu(header.EraseCount);
} else {
part->XferInfo[xtrans].state = XFER_UNKNOWN;
/* Pick anything reasonable for the erase count */
part->XferInfo[xtrans].EraseCount =
le32_to_cpu(part->header.EraseCount);
}
part->XferInfo[xtrans].Offset = offset;
xtrans++;
}
}
/* Check for format trouble */
header = part->header;
if ((xtrans != header.NumTransferUnits) ||
(xvalid+xtrans != le16_to_cpu(header.NumEraseUnits))) {
printk(KERN_NOTICE "ftl_cs: format error: erase units "
"don't add up!\n");
goto out_XferInfo;
}
/* Set up virtual page map */
blocks = le32_to_cpu(header.FormattedSize) >> header.BlockSize;
part->VirtualBlockMap = vmalloc(blocks * sizeof(uint32_t));
if (!part->VirtualBlockMap)
goto out_XferInfo;
memset(part->VirtualBlockMap, 0xff, blocks * sizeof(uint32_t));
part->BlocksPerUnit = (1 << header.EraseUnitSize) >> header.BlockSize;
part->bam_cache = kmalloc(part->BlocksPerUnit * sizeof(uint32_t),
GFP_KERNEL);
if (!part->bam_cache)
goto out_VirtualBlockMap;
part->bam_index = 0xffff;
part->FreeTotal = 0;
for (i = 0; i < part->DataUnits; i++) {
part->EUNInfo[i].Free = 0;
part->EUNInfo[i].Deleted = 0;
offset = part->EUNInfo[i].Offset + le32_to_cpu(header.BAMOffset);
ret = part->mbd.mtd->read(part->mbd.mtd, offset,
part->BlocksPerUnit * sizeof(uint32_t), &retval,
(unsigned char *)part->bam_cache);
if (ret)
goto out_bam_cache;
for (j = 0; j < part->BlocksPerUnit; j++) {
if (BLOCK_FREE(le32_to_cpu(part->bam_cache[j]))) {
part->EUNInfo[i].Free++;
part->FreeTotal++;
} else if ((BLOCK_TYPE(le32_to_cpu(part->bam_cache[j])) == BLOCK_DATA) &&
(BLOCK_NUMBER(le32_to_cpu(part->bam_cache[j])) < blocks))
part->VirtualBlockMap[BLOCK_NUMBER(le32_to_cpu(part->bam_cache[j]))] =
(i << header.EraseUnitSize) + (j << header.BlockSize);
else if (BLOCK_DELETED(le32_to_cpu(part->bam_cache[j])))
part->EUNInfo[i].Deleted++;
}
}
ret = 0;
goto out;
out_bam_cache:
kfree(part->bam_cache);
out_VirtualBlockMap:
vfree(part->VirtualBlockMap);
out_XferInfo:
kfree(part->XferInfo);
out_EUNInfo:
kfree(part->EUNInfo);
out:
return ret;
} /* build_maps */
/*======================================================================
Erase_xfer() schedules an asynchronous erase operation for a
transfer unit.
======================================================================*/
static int erase_xfer(partition_t *part,
uint16_t xfernum)
{
int ret;
struct xfer_info_t *xfer;
struct erase_info *erase;
xfer = &part->XferInfo[xfernum];
DEBUG(1, "ftl_cs: erasing xfer unit at 0x%x\n", xfer->Offset);
xfer->state = XFER_ERASING;
/* Is there a free erase slot? Always in MTD. */
erase=kmalloc(sizeof(struct erase_info), GFP_KERNEL);
if (!erase)
return -ENOMEM;
erase->mtd = part->mbd.mtd;
erase->callback = ftl_erase_callback;
erase->addr = xfer->Offset;
erase->len = 1 << part->header.EraseUnitSize;
erase->priv = (u_long)part;
ret = part->mbd.mtd->erase(part->mbd.mtd, erase);
if (!ret)
xfer->EraseCount++;
else
kfree(erase);
return ret;
} /* erase_xfer */
/*======================================================================
Prepare_xfer() takes a freshly erased transfer unit and gives
it an appropriate header.
======================================================================*/
static void ftl_erase_callback(struct erase_info *erase)
{
partition_t *part;
struct xfer_info_t *xfer;
int i;
/* Look up the transfer unit */
part = (partition_t *)(erase->priv);
for (i = 0; i < part->header.NumTransferUnits; i++)
if (part->XferInfo[i].Offset == erase->addr) break;
if (i == part->header.NumTransferUnits) {
printk(KERN_NOTICE "ftl_cs: internal error: "
"erase lookup failed!\n");
return;
}
xfer = &part->XferInfo[i];
if (erase->state == MTD_ERASE_DONE)
xfer->state = XFER_ERASED;
else {
xfer->state = XFER_FAILED;
printk(KERN_NOTICE "ftl_cs: erase failed: state = %d\n",
erase->state);
}
kfree(erase);
} /* ftl_erase_callback */
static int prepare_xfer(partition_t *part, int i)
{
erase_unit_header_t header;
struct xfer_info_t *xfer;
int nbam, ret;
uint32_t ctl;
ssize_t retlen;
loff_t offset;
xfer = &part->XferInfo[i];
xfer->state = XFER_FAILED;
DEBUG(1, "ftl_cs: preparing xfer unit at 0x%x\n", xfer->Offset);
/* Write the transfer unit header */
header = part->header;
header.LogicalEUN = cpu_to_le16(0xffff);
header.EraseCount = cpu_to_le32(xfer->EraseCount);
ret = part->mbd.mtd->write(part->mbd.mtd, xfer->Offset, sizeof(header),
&retlen, (u_char *)&header);
if (ret) {
return ret;
}
/* Write the BAM stub */
nbam = (part->BlocksPerUnit * sizeof(uint32_t) +
le32_to_cpu(part->header.BAMOffset) + SECTOR_SIZE - 1) / SECTOR_SIZE;
offset = xfer->Offset + le32_to_cpu(part->header.BAMOffset);
ctl = cpu_to_le32(BLOCK_CONTROL);
for (i = 0; i < nbam; i++, offset += sizeof(uint32_t)) {
ret = part->mbd.mtd->write(part->mbd.mtd, offset, sizeof(uint32_t),
&retlen, (u_char *)&ctl);
if (ret)
return ret;
}
xfer->state = XFER_PREPARED;
return 0;
} /* prepare_xfer */
/*======================================================================
Copy_erase_unit() takes a full erase block and a transfer unit,
copies everything to the transfer unit, then swaps the block
pointers.
All data blocks are copied to the corresponding blocks in the
target unit, so the virtual block map does not need to be
updated.
======================================================================*/
static int copy_erase_unit(partition_t *part, uint16_t srcunit,
uint16_t xferunit)
{
u_char buf[SECTOR_SIZE];
struct eun_info_t *eun;
struct xfer_info_t *xfer;
uint32_t src, dest, free, i;
uint16_t unit;
int ret;
ssize_t retlen;
loff_t offset;
uint16_t srcunitswap = cpu_to_le16(srcunit);
eun = &part->EUNInfo[srcunit];
xfer = &part->XferInfo[xferunit];
DEBUG(2, "ftl_cs: copying block 0x%x to 0x%x\n",
eun->Offset, xfer->Offset);
/* Read current BAM */
if (part->bam_index != srcunit) {
offset = eun->Offset + le32_to_cpu(part->header.BAMOffset);
ret = part->mbd.mtd->read(part->mbd.mtd, offset,
part->BlocksPerUnit * sizeof(uint32_t),
&retlen, (u_char *) (part->bam_cache));
/* mark the cache bad, in case we get an error later */
part->bam_index = 0xffff;
if (ret) {
printk( KERN_WARNING "ftl: Failed to read BAM cache in copy_erase_unit()!\n");
return ret;
}
}
/* Write the LogicalEUN for the transfer unit */
xfer->state = XFER_UNKNOWN;
offset = xfer->Offset + 20; /* Bad! */
unit = cpu_to_le16(0x7fff);
ret = part->mbd.mtd->write(part->mbd.mtd, offset, sizeof(uint16_t),
&retlen, (u_char *) &unit);
if (ret) {
printk( KERN_WARNING "ftl: Failed to write back to BAM cache in copy_erase_unit()!\n");
return ret;
}
/* Copy all data blocks from source unit to transfer unit */
src = eun->Offset; dest = xfer->Offset;
free = 0;
ret = 0;
for (i = 0; i < part->BlocksPerUnit; i++) {
switch (BLOCK_TYPE(le32_to_cpu(part->bam_cache[i]))) {
case BLOCK_CONTROL:
/* This gets updated later */
break;
case BLOCK_DATA:
case BLOCK_REPLACEMENT:
ret = part->mbd.mtd->read(part->mbd.mtd, src, SECTOR_SIZE,
&retlen, (u_char *) buf);
if (ret) {
printk(KERN_WARNING "ftl: Error reading old xfer unit in copy_erase_unit\n");
return ret;
}
ret = part->mbd.mtd->write(part->mbd.mtd, dest, SECTOR_SIZE,
&retlen, (u_char *) buf);
if (ret) {
printk(KERN_WARNING "ftl: Error writing new xfer unit in copy_erase_unit\n");
return ret;
}
break;
default:
/* All other blocks must be free */
part->bam_cache[i] = cpu_to_le32(0xffffffff);
free++;
break;
}
src += SECTOR_SIZE;
dest += SECTOR_SIZE;
}
/* Write the BAM to the transfer unit */
ret = part->mbd.mtd->write(part->mbd.mtd, xfer->Offset + le32_to_cpu(part->header.BAMOffset),
part->BlocksPerUnit * sizeof(int32_t), &retlen,
(u_char *)part->bam_cache);
if (ret) {
printk( KERN_WARNING "ftl: Error writing BAM in copy_erase_unit\n");
return ret;
}
/* All clear? Then update the LogicalEUN again */
ret = part->mbd.mtd->write(part->mbd.mtd, xfer->Offset + 20, sizeof(uint16_t),
&retlen, (u_char *)&srcunitswap);
if (ret) {
printk(KERN_WARNING "ftl: Error writing new LogicalEUN in copy_erase_unit\n");
return ret;
}
/* Update the maps and usage stats*/
i = xfer->EraseCount;
xfer->EraseCount = eun->EraseCount;
eun->EraseCount = i;
i = xfer->Offset;
xfer->Offset = eun->Offset;
eun->Offset = i;
part->FreeTotal -= eun->Free;
part->FreeTotal += free;
eun->Free = free;
eun->Deleted = 0;
/* Now, the cache should be valid for the new block */
part->bam_index = srcunit;
return 0;
} /* copy_erase_unit */
/*======================================================================
reclaim_block() picks a full erase unit and a transfer unit and
then calls copy_erase_unit() to copy one to the other. Then, it
schedules an erase on the expired block.
What's a good way to decide which transfer unit and which erase
unit to use? Beats me. My way is to always pick the transfer
unit with the fewest erases, and usually pick the data unit with
the most deleted blocks. But with a small probability, pick the
oldest data unit instead. This means that we generally postpone
the next reclaimation as long as possible, but shuffle static
stuff around a bit for wear leveling.
======================================================================*/
static int reclaim_block(partition_t *part)
{
uint16_t i, eun, xfer;
uint32_t best;
int queued, ret;
DEBUG(0, "ftl_cs: reclaiming space...\n");
DEBUG(3, "NumTransferUnits == %x\n", part->header.NumTransferUnits);
/* Pick the least erased transfer unit */
best = 0xffffffff; xfer = 0xffff;
do {
queued = 0;
for (i = 0; i < part->header.NumTransferUnits; i++) {
int n=0;
if (part->XferInfo[i].state == XFER_UNKNOWN) {
DEBUG(3,"XferInfo[%d].state == XFER_UNKNOWN\n",i);
n=1;
erase_xfer(part, i);
}
if (part->XferInfo[i].state == XFER_ERASING) {
DEBUG(3,"XferInfo[%d].state == XFER_ERASING\n",i);
n=1;
queued = 1;
}
else if (part->XferInfo[i].state == XFER_ERASED) {
DEBUG(3,"XferInfo[%d].state == XFER_ERASED\n",i);
n=1;
prepare_xfer(part, i);
}
if (part->XferInfo[i].state == XFER_PREPARED) {
DEBUG(3,"XferInfo[%d].state == XFER_PREPARED\n",i);
n=1;
if (part->XferInfo[i].EraseCount <= best) {
best = part->XferInfo[i].EraseCount;
xfer = i;
}
}
if (!n)
DEBUG(3,"XferInfo[%d].state == %x\n",i, part->XferInfo[i].state);
}
if (xfer == 0xffff) {
if (queued) {
DEBUG(1, "ftl_cs: waiting for transfer "
"unit to be prepared...\n");
if (part->mbd.mtd->sync)
part->mbd.mtd->sync(part->mbd.mtd);
} else {
static int ne = 0;
if (++ne < 5)
printk(KERN_NOTICE "ftl_cs: reclaim failed: no "
"suitable transfer units!\n");
else
DEBUG(1, "ftl_cs: reclaim failed: no "
"suitable transfer units!\n");
return -EIO;
}
}
} while (xfer == 0xffff);
eun = 0;
if ((jiffies % shuffle_freq) == 0) {
DEBUG(1, "ftl_cs: recycling freshest block...\n");
best = 0xffffffff;
for (i = 0; i < part->DataUnits; i++)
if (part->EUNInfo[i].EraseCount <= best) {
best = part->EUNInfo[i].EraseCount;
eun = i;
}
} else {
best = 0;
for (i = 0; i < part->DataUnits; i++)
if (part->EUNInfo[i].Deleted >= best) {
best = part->EUNInfo[i].Deleted;
eun = i;
}
if (best == 0) {
static int ne = 0;
if (++ne < 5)
printk(KERN_NOTICE "ftl_cs: reclaim failed: "
"no free blocks!\n");
else
DEBUG(1,"ftl_cs: reclaim failed: "
"no free blocks!\n");
return -EIO;
}
}
ret = copy_erase_unit(part, eun, xfer);
if (!ret)
erase_xfer(part, xfer);
else
printk(KERN_NOTICE "ftl_cs: copy_erase_unit failed!\n");
return ret;
} /* reclaim_block */
/*======================================================================
Find_free() searches for a free block. If necessary, it updates
the BAM cache for the erase unit containing the free block. It
returns the block index -- the erase unit is just the currently
cached unit. If there are no free blocks, it returns 0 -- this
is never a valid data block because it contains the header.
======================================================================*/
#ifdef PSYCHO_DEBUG
static void dump_lists(partition_t *part)
{
int i;
printk(KERN_DEBUG "ftl_cs: Free total = %d\n", part->FreeTotal);
for (i = 0; i < part->DataUnits; i++)
printk(KERN_DEBUG "ftl_cs: unit %d: %d phys, %d free, "
"%d deleted\n", i,
part->EUNInfo[i].Offset >> part->header.EraseUnitSize,
part->EUNInfo[i].Free, part->EUNInfo[i].Deleted);
}
#endif
static uint32_t find_free(partition_t *part)
{
uint16_t stop, eun;
uint32_t blk;
size_t retlen;
int ret;
/* Find an erase unit with some free space */
stop = (part->bam_index == 0xffff) ? 0 : part->bam_index;
eun = stop;
do {
if (part->EUNInfo[eun].Free != 0) break;
/* Wrap around at end of table */
if (++eun == part->DataUnits) eun = 0;
} while (eun != stop);
if (part->EUNInfo[eun].Free == 0)
return 0;
/* Is this unit's BAM cached? */
if (eun != part->bam_index) {
/* Invalidate cache */
part->bam_index = 0xffff;
ret = part->mbd.mtd->read(part->mbd.mtd,
part->EUNInfo[eun].Offset + le32_to_cpu(part->header.BAMOffset),
part->BlocksPerUnit * sizeof(uint32_t),
&retlen, (u_char *) (part->bam_cache));
if (ret) {
printk(KERN_WARNING"ftl: Error reading BAM in find_free\n");
return 0;
}
part->bam_index = eun;
}
/* Find a free block */
for (blk = 0; blk < part->BlocksPerUnit; blk++)
if (BLOCK_FREE(le32_to_cpu(part->bam_cache[blk]))) break;
if (blk == part->BlocksPerUnit) {
#ifdef PSYCHO_DEBUG
static int ne = 0;
if (++ne == 1)
dump_lists(part);
#endif
printk(KERN_NOTICE "ftl_cs: bad free list!\n");
return 0;
}
DEBUG(2, "ftl_cs: found free block at %d in %d\n", blk, eun);
return blk;
} /* find_free */
/*======================================================================
Read a series of sectors from an FTL partition.
======================================================================*/
static int ftl_read(partition_t *part, caddr_t buffer,
u_long sector, u_long nblocks)
{
uint32_t log_addr, bsize;
u_long i;
int ret;
size_t offset, retlen;
DEBUG(2, "ftl_cs: ftl_read(0x%p, 0x%lx, %ld)\n",
part, sector, nblocks);
if (!(part->state & FTL_FORMATTED)) {
printk(KERN_NOTICE "ftl_cs: bad partition\n");
return -EIO;
}
bsize = 1 << part->header.EraseUnitSize;
for (i = 0; i < nblocks; i++) {
if (((sector+i) * SECTOR_SIZE) >= le32_to_cpu(part->header.FormattedSize)) {
printk(KERN_NOTICE "ftl_cs: bad read offset\n");
return -EIO;
}
log_addr = part->VirtualBlockMap[sector+i];
if (log_addr == 0xffffffff)
memset(buffer, 0, SECTOR_SIZE);
else {
offset = (part->EUNInfo[log_addr / bsize].Offset
+ (log_addr % bsize));
ret = part->mbd.mtd->read(part->mbd.mtd, offset, SECTOR_SIZE,
&retlen, (u_char *) buffer);
if (ret) {
printk(KERN_WARNING "Error reading MTD device in ftl_read()\n");
return ret;
}
}
buffer += SECTOR_SIZE;
}
return 0;
} /* ftl_read */
/*======================================================================
Write a series of sectors to an FTL partition
======================================================================*/
static int set_bam_entry(partition_t *part, uint32_t log_addr,
uint32_t virt_addr)
{
uint32_t bsize, blk, le_virt_addr;
#ifdef PSYCHO_DEBUG
uint32_t old_addr;
#endif
uint16_t eun;
int ret;
size_t retlen, offset;
DEBUG(2, "ftl_cs: set_bam_entry(0x%p, 0x%x, 0x%x)\n",
part, log_addr, virt_addr);
bsize = 1 << part->header.EraseUnitSize;
eun = log_addr / bsize;
blk = (log_addr % bsize) / SECTOR_SIZE;
offset = (part->EUNInfo[eun].Offset + blk * sizeof(uint32_t) +
le32_to_cpu(part->header.BAMOffset));
#ifdef PSYCHO_DEBUG
ret = part->mbd.mtd->read(part->mbd.mtd, offset, sizeof(uint32_t),
&retlen, (u_char *)&old_addr);
if (ret) {
printk(KERN_WARNING"ftl: Error reading old_addr in set_bam_entry: %d\n",ret);
return ret;
}
old_addr = le32_to_cpu(old_addr);
if (((virt_addr == 0xfffffffe) && !BLOCK_FREE(old_addr)) ||
((virt_addr == 0) && (BLOCK_TYPE(old_addr) != BLOCK_DATA)) ||
(!BLOCK_DELETED(virt_addr) && (old_addr != 0xfffffffe))) {
static int ne = 0;
if (++ne < 5) {
printk(KERN_NOTICE "ftl_cs: set_bam_entry() inconsistency!\n");
printk(KERN_NOTICE "ftl_cs: log_addr = 0x%x, old = 0x%x"
", new = 0x%x\n", log_addr, old_addr, virt_addr);
}
return -EIO;
}
#endif
le_virt_addr = cpu_to_le32(virt_addr);
if (part->bam_index == eun) {
#ifdef PSYCHO_DEBUG
if (le32_to_cpu(part->bam_cache[blk]) != old_addr) {
static int ne = 0;
if (++ne < 5) {
printk(KERN_NOTICE "ftl_cs: set_bam_entry() "
"inconsistency!\n");
printk(KERN_NOTICE "ftl_cs: log_addr = 0x%x, cache"
" = 0x%x\n",
le32_to_cpu(part->bam_cache[blk]), old_addr);
}
return -EIO;
}
#endif
part->bam_cache[blk] = le_virt_addr;
}
ret = part->mbd.mtd->write(part->mbd.mtd, offset, sizeof(uint32_t),
&retlen, (u_char *)&le_virt_addr);
if (ret) {
printk(KERN_NOTICE "ftl_cs: set_bam_entry() failed!\n");
printk(KERN_NOTICE "ftl_cs: log_addr = 0x%x, new = 0x%x\n",
log_addr, virt_addr);
}
return ret;
} /* set_bam_entry */
static int ftl_write(partition_t *part, caddr_t buffer,
u_long sector, u_long nblocks)
{
uint32_t bsize, log_addr, virt_addr, old_addr, blk;
u_long i;
int ret;
size_t retlen, offset;
DEBUG(2, "ftl_cs: ftl_write(0x%p, %ld, %ld)\n",
part, sector, nblocks);
if (!(part->state & FTL_FORMATTED)) {
printk(KERN_NOTICE "ftl_cs: bad partition\n");
return -EIO;
}
/* See if we need to reclaim space, before we start */
while (part->FreeTotal < nblocks) {
ret = reclaim_block(part);
if (ret)
return ret;
}
bsize = 1 << part->header.EraseUnitSize;
virt_addr = sector * SECTOR_SIZE | BLOCK_DATA;
for (i = 0; i < nblocks; i++) {
if (virt_addr >= le32_to_cpu(part->header.FormattedSize)) {
printk(KERN_NOTICE "ftl_cs: bad write offset\n");
return -EIO;
}
/* Grab a free block */
blk = find_free(part);
if (blk == 0) {
static int ne = 0;
if (++ne < 5)
printk(KERN_NOTICE "ftl_cs: internal error: "
"no free blocks!\n");
return -ENOSPC;
}
/* Tag the BAM entry, and write the new block */
log_addr = part->bam_index * bsize + blk * SECTOR_SIZE;
part->EUNInfo[part->bam_index].Free--;
part->FreeTotal--;
if (set_bam_entry(part, log_addr, 0xfffffffe))
return -EIO;
part->EUNInfo[part->bam_index].Deleted++;
offset = (part->EUNInfo[part->bam_index].Offset +
blk * SECTOR_SIZE);
ret = part->mbd.mtd->write(part->mbd.mtd, offset, SECTOR_SIZE, &retlen,
buffer);
if (ret) {
printk(KERN_NOTICE "ftl_cs: block write failed!\n");
printk(KERN_NOTICE "ftl_cs: log_addr = 0x%x, virt_addr"
" = 0x%x, Offset = 0x%zx\n", log_addr, virt_addr,
offset);
return -EIO;
}
/* Only delete the old entry when the new entry is ready */
old_addr = part->VirtualBlockMap[sector+i];
if (old_addr != 0xffffffff) {
part->VirtualBlockMap[sector+i] = 0xffffffff;
part->EUNInfo[old_addr/bsize].Deleted++;
if (set_bam_entry(part, old_addr, 0))
return -EIO;
}
/* Finally, set up the new pointers */
if (set_bam_entry(part, log_addr, virt_addr))
return -EIO;
part->VirtualBlockMap[sector+i] = log_addr;
part->EUNInfo[part->bam_index].Deleted--;
buffer += SECTOR_SIZE;
virt_addr += SECTOR_SIZE;
}
return 0;
} /* ftl_write */
static int ftl_getgeo(struct mtd_blktrans_dev *dev, struct hd_geometry *geo)
{
partition_t *part = (void *)dev;
u_long sect;
/* Sort of arbitrary: round size down to 4KiB boundary */
sect = le32_to_cpu(part->header.FormattedSize)/SECTOR_SIZE;
geo->heads = 1;
geo->sectors = 8;
geo->cylinders = sect >> 3;
return 0;
}
static int ftl_readsect(struct mtd_blktrans_dev *dev,
unsigned long block, char *buf)
{
return ftl_read((void *)dev, buf, block, 1);
}
static int ftl_writesect(struct mtd_blktrans_dev *dev,
unsigned long block, char *buf)
{
return ftl_write((void *)dev, buf, block, 1);
}
static int ftl_discardsect(struct mtd_blktrans_dev *dev,
unsigned long sector, unsigned nr_sects)
{
partition_t *part = (void *)dev;
uint32_t bsize = 1 << part->header.EraseUnitSize;
DEBUG(1, "FTL erase sector %ld for %d sectors\n",
sector, nr_sects);
while (nr_sects) {
uint32_t old_addr = part->VirtualBlockMap[sector];
if (old_addr != 0xffffffff) {
part->VirtualBlockMap[sector] = 0xffffffff;
part->EUNInfo[old_addr/bsize].Deleted++;
if (set_bam_entry(part, old_addr, 0))
return -EIO;
}
nr_sects--;
sector++;
}
return 0;
}
/*====================================================================*/
static void ftl_freepart(partition_t *part)
{
vfree(part->VirtualBlockMap);
part->VirtualBlockMap = NULL;
kfree(part->VirtualPageMap);
part->VirtualPageMap = NULL;
kfree(part->EUNInfo);
part->EUNInfo = NULL;
kfree(part->XferInfo);
part->XferInfo = NULL;
kfree(part->bam_cache);
part->bam_cache = NULL;
} /* ftl_freepart */
static void ftl_add_mtd(struct mtd_blktrans_ops *tr, struct mtd_info *mtd)
{
partition_t *partition;
partition = kzalloc(sizeof(partition_t), GFP_KERNEL);
if (!partition) {
printk(KERN_WARNING "No memory to scan for FTL on %s\n",
mtd->name);
return;
}
partition->mbd.mtd = mtd;
if ((scan_header(partition) == 0) &&
(build_maps(partition) == 0)) {
partition->state = FTL_FORMATTED;
#ifdef PCMCIA_DEBUG
printk(KERN_INFO "ftl_cs: opening %d KiB FTL partition\n",
le32_to_cpu(partition->header.FormattedSize) >> 10);
#endif
partition->mbd.size = le32_to_cpu(partition->header.FormattedSize) >> 9;
partition->mbd.tr = tr;
partition->mbd.devnum = -1;
if (!add_mtd_blktrans_dev((void *)partition))
return;
}
ftl_freepart(partition);
kfree(partition);
}
static void ftl_remove_dev(struct mtd_blktrans_dev *dev)
{
del_mtd_blktrans_dev(dev);
ftl_freepart((partition_t *)dev);
}
static struct mtd_blktrans_ops ftl_tr = {
.name = "ftl",
.major = FTL_MAJOR,
.part_bits = PART_BITS,
.blksize = SECTOR_SIZE,
.readsect = ftl_readsect,
.writesect = ftl_writesect,
.discard = ftl_discardsect,
.getgeo = ftl_getgeo,
.add_mtd = ftl_add_mtd,
.remove_dev = ftl_remove_dev,
.owner = THIS_MODULE,
};
static int __init init_ftl(void)
{
return register_mtd_blktrans(&ftl_tr);
}
static void __exit cleanup_ftl(void)
{
deregister_mtd_blktrans(&ftl_tr);
}
module_init(init_ftl);
module_exit(cleanup_ftl);
MODULE_LICENSE("Dual MPL/GPL");
MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>");
MODULE_DESCRIPTION("Support code for Flash Translation Layer, used on PCMCIA devices");
| gpl-2.0 |
yank555-lu/N3-KK-Sourcedrops | ipc/mqueue.c | 4632 | 31210 | /*
* POSIX message queues filesystem for Linux.
*
* Copyright (C) 2003,2004 Krzysztof Benedyczak (golbi@mat.uni.torun.pl)
* Michal Wronski (michal.wronski@gmail.com)
*
* Spinlocks: Mohamed Abbas (abbas.mohamed@intel.com)
* Lockless receive & send, fd based notify:
* Manfred Spraul (manfred@colorfullife.com)
*
* Audit: George Wilson (ltcgcw@us.ibm.com)
*
* This file is released under the GPL.
*/
#include <linux/capability.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/sysctl.h>
#include <linux/poll.h>
#include <linux/mqueue.h>
#include <linux/msg.h>
#include <linux/skbuff.h>
#include <linux/netlink.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <linux/signal.h>
#include <linux/mutex.h>
#include <linux/nsproxy.h>
#include <linux/pid.h>
#include <linux/ipc_namespace.h>
#include <linux/user_namespace.h>
#include <linux/slab.h>
#include <net/sock.h>
#include "util.h"
#define MQUEUE_MAGIC 0x19800202
#define DIRENT_SIZE 20
#define FILENT_SIZE 80
#define SEND 0
#define RECV 1
#define STATE_NONE 0
#define STATE_PENDING 1
#define STATE_READY 2
struct ext_wait_queue { /* queue of sleeping tasks */
struct task_struct *task;
struct list_head list;
struct msg_msg *msg; /* ptr of loaded message */
int state; /* one of STATE_* values */
};
struct mqueue_inode_info {
spinlock_t lock;
struct inode vfs_inode;
wait_queue_head_t wait_q;
struct msg_msg **messages;
struct mq_attr attr;
struct sigevent notify;
struct pid* notify_owner;
struct user_struct *user; /* user who created, for accounting */
struct sock *notify_sock;
struct sk_buff *notify_cookie;
/* for tasks waiting for free space and messages, respectively */
struct ext_wait_queue e_wait_q[2];
unsigned long qsize; /* size of queue in memory (sum of all msgs) */
};
static const struct inode_operations mqueue_dir_inode_operations;
static const struct file_operations mqueue_file_operations;
static const struct super_operations mqueue_super_ops;
static void remove_notification(struct mqueue_inode_info *info);
static struct kmem_cache *mqueue_inode_cachep;
static struct ctl_table_header * mq_sysctl_table;
static inline struct mqueue_inode_info *MQUEUE_I(struct inode *inode)
{
return container_of(inode, struct mqueue_inode_info, vfs_inode);
}
/*
* This routine should be called with the mq_lock held.
*/
static inline struct ipc_namespace *__get_ns_from_inode(struct inode *inode)
{
return get_ipc_ns(inode->i_sb->s_fs_info);
}
static struct ipc_namespace *get_ns_from_inode(struct inode *inode)
{
struct ipc_namespace *ns;
spin_lock(&mq_lock);
ns = __get_ns_from_inode(inode);
spin_unlock(&mq_lock);
return ns;
}
static struct inode *mqueue_get_inode(struct super_block *sb,
struct ipc_namespace *ipc_ns, umode_t mode,
struct mq_attr *attr)
{
struct user_struct *u = current_user();
struct inode *inode;
int ret = -ENOMEM;
inode = new_inode(sb);
if (!inode)
goto err;
inode->i_ino = get_next_ino();
inode->i_mode = mode;
inode->i_uid = current_fsuid();
inode->i_gid = current_fsgid();
inode->i_mtime = inode->i_ctime = inode->i_atime = CURRENT_TIME;
if (S_ISREG(mode)) {
struct mqueue_inode_info *info;
unsigned long mq_bytes, mq_msg_tblsz;
inode->i_fop = &mqueue_file_operations;
inode->i_size = FILENT_SIZE;
/* mqueue specific info */
info = MQUEUE_I(inode);
spin_lock_init(&info->lock);
init_waitqueue_head(&info->wait_q);
INIT_LIST_HEAD(&info->e_wait_q[0].list);
INIT_LIST_HEAD(&info->e_wait_q[1].list);
info->notify_owner = NULL;
info->qsize = 0;
info->user = NULL; /* set when all is ok */
memset(&info->attr, 0, sizeof(info->attr));
info->attr.mq_maxmsg = ipc_ns->mq_msg_max;
info->attr.mq_msgsize = ipc_ns->mq_msgsize_max;
if (attr) {
info->attr.mq_maxmsg = attr->mq_maxmsg;
info->attr.mq_msgsize = attr->mq_msgsize;
}
mq_msg_tblsz = info->attr.mq_maxmsg * sizeof(struct msg_msg *);
info->messages = kmalloc(mq_msg_tblsz, GFP_KERNEL);
if (!info->messages)
goto out_inode;
mq_bytes = (mq_msg_tblsz +
(info->attr.mq_maxmsg * info->attr.mq_msgsize));
spin_lock(&mq_lock);
if (u->mq_bytes + mq_bytes < u->mq_bytes ||
u->mq_bytes + mq_bytes > rlimit(RLIMIT_MSGQUEUE)) {
spin_unlock(&mq_lock);
/* mqueue_evict_inode() releases info->messages */
ret = -EMFILE;
goto out_inode;
}
u->mq_bytes += mq_bytes;
spin_unlock(&mq_lock);
/* all is ok */
info->user = get_uid(u);
} else if (S_ISDIR(mode)) {
inc_nlink(inode);
/* Some things misbehave if size == 0 on a directory */
inode->i_size = 2 * DIRENT_SIZE;
inode->i_op = &mqueue_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
}
return inode;
out_inode:
iput(inode);
err:
return ERR_PTR(ret);
}
static int mqueue_fill_super(struct super_block *sb, void *data, int silent)
{
struct inode *inode;
struct ipc_namespace *ns = data;
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
sb->s_magic = MQUEUE_MAGIC;
sb->s_op = &mqueue_super_ops;
inode = mqueue_get_inode(sb, ns, S_IFDIR | S_ISVTX | S_IRWXUGO, NULL);
if (IS_ERR(inode))
return PTR_ERR(inode);
sb->s_root = d_make_root(inode);
if (!sb->s_root)
return -ENOMEM;
return 0;
}
static struct dentry *mqueue_mount(struct file_system_type *fs_type,
int flags, const char *dev_name,
void *data)
{
if (!(flags & MS_KERNMOUNT))
data = current->nsproxy->ipc_ns;
return mount_ns(fs_type, flags, data, mqueue_fill_super);
}
static void init_once(void *foo)
{
struct mqueue_inode_info *p = (struct mqueue_inode_info *) foo;
inode_init_once(&p->vfs_inode);
}
static struct inode *mqueue_alloc_inode(struct super_block *sb)
{
struct mqueue_inode_info *ei;
ei = kmem_cache_alloc(mqueue_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
return &ei->vfs_inode;
}
static void mqueue_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(mqueue_inode_cachep, MQUEUE_I(inode));
}
static void mqueue_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, mqueue_i_callback);
}
static void mqueue_evict_inode(struct inode *inode)
{
struct mqueue_inode_info *info;
struct user_struct *user;
unsigned long mq_bytes;
int i;
struct ipc_namespace *ipc_ns;
end_writeback(inode);
if (S_ISDIR(inode->i_mode))
return;
ipc_ns = get_ns_from_inode(inode);
info = MQUEUE_I(inode);
spin_lock(&info->lock);
for (i = 0; i < info->attr.mq_curmsgs; i++)
free_msg(info->messages[i]);
kfree(info->messages);
spin_unlock(&info->lock);
/* Total amount of bytes accounted for the mqueue */
mq_bytes = info->attr.mq_maxmsg * (sizeof(struct msg_msg *)
+ info->attr.mq_msgsize);
user = info->user;
if (user) {
spin_lock(&mq_lock);
user->mq_bytes -= mq_bytes;
/*
* get_ns_from_inode() ensures that the
* (ipc_ns = sb->s_fs_info) is either a valid ipc_ns
* to which we now hold a reference, or it is NULL.
* We can't put it here under mq_lock, though.
*/
if (ipc_ns)
ipc_ns->mq_queues_count--;
spin_unlock(&mq_lock);
free_uid(user);
}
if (ipc_ns)
put_ipc_ns(ipc_ns);
}
static int mqueue_create(struct inode *dir, struct dentry *dentry,
umode_t mode, struct nameidata *nd)
{
struct inode *inode;
struct mq_attr *attr = dentry->d_fsdata;
int error;
struct ipc_namespace *ipc_ns;
spin_lock(&mq_lock);
ipc_ns = __get_ns_from_inode(dir);
if (!ipc_ns) {
error = -EACCES;
goto out_unlock;
}
if (ipc_ns->mq_queues_count >= ipc_ns->mq_queues_max &&
!capable(CAP_SYS_RESOURCE)) {
error = -ENOSPC;
goto out_unlock;
}
ipc_ns->mq_queues_count++;
spin_unlock(&mq_lock);
inode = mqueue_get_inode(dir->i_sb, ipc_ns, mode, attr);
if (IS_ERR(inode)) {
error = PTR_ERR(inode);
spin_lock(&mq_lock);
ipc_ns->mq_queues_count--;
goto out_unlock;
}
put_ipc_ns(ipc_ns);
dir->i_size += DIRENT_SIZE;
dir->i_ctime = dir->i_mtime = dir->i_atime = CURRENT_TIME;
d_instantiate(dentry, inode);
dget(dentry);
return 0;
out_unlock:
spin_unlock(&mq_lock);
if (ipc_ns)
put_ipc_ns(ipc_ns);
return error;
}
static int mqueue_unlink(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
dir->i_ctime = dir->i_mtime = dir->i_atime = CURRENT_TIME;
dir->i_size -= DIRENT_SIZE;
drop_nlink(inode);
dput(dentry);
return 0;
}
/*
* This is routine for system read from queue file.
* To avoid mess with doing here some sort of mq_receive we allow
* to read only queue size & notification info (the only values
* that are interesting from user point of view and aren't accessible
* through std routines)
*/
static ssize_t mqueue_read_file(struct file *filp, char __user *u_data,
size_t count, loff_t *off)
{
struct mqueue_inode_info *info = MQUEUE_I(filp->f_path.dentry->d_inode);
char buffer[FILENT_SIZE];
ssize_t ret;
spin_lock(&info->lock);
snprintf(buffer, sizeof(buffer),
"QSIZE:%-10lu NOTIFY:%-5d SIGNO:%-5d NOTIFY_PID:%-6d\n",
info->qsize,
info->notify_owner ? info->notify.sigev_notify : 0,
(info->notify_owner &&
info->notify.sigev_notify == SIGEV_SIGNAL) ?
info->notify.sigev_signo : 0,
pid_vnr(info->notify_owner));
spin_unlock(&info->lock);
buffer[sizeof(buffer)-1] = '\0';
ret = simple_read_from_buffer(u_data, count, off, buffer,
strlen(buffer));
if (ret <= 0)
return ret;
filp->f_path.dentry->d_inode->i_atime = filp->f_path.dentry->d_inode->i_ctime = CURRENT_TIME;
return ret;
}
static int mqueue_flush_file(struct file *filp, fl_owner_t id)
{
struct mqueue_inode_info *info = MQUEUE_I(filp->f_path.dentry->d_inode);
spin_lock(&info->lock);
if (task_tgid(current) == info->notify_owner)
remove_notification(info);
spin_unlock(&info->lock);
return 0;
}
static unsigned int mqueue_poll_file(struct file *filp, struct poll_table_struct *poll_tab)
{
struct mqueue_inode_info *info = MQUEUE_I(filp->f_path.dentry->d_inode);
int retval = 0;
poll_wait(filp, &info->wait_q, poll_tab);
spin_lock(&info->lock);
if (info->attr.mq_curmsgs)
retval = POLLIN | POLLRDNORM;
if (info->attr.mq_curmsgs < info->attr.mq_maxmsg)
retval |= POLLOUT | POLLWRNORM;
spin_unlock(&info->lock);
return retval;
}
/* Adds current to info->e_wait_q[sr] before element with smaller prio */
static void wq_add(struct mqueue_inode_info *info, int sr,
struct ext_wait_queue *ewp)
{
struct ext_wait_queue *walk;
ewp->task = current;
list_for_each_entry(walk, &info->e_wait_q[sr].list, list) {
if (walk->task->static_prio <= current->static_prio) {
list_add_tail(&ewp->list, &walk->list);
return;
}
}
list_add_tail(&ewp->list, &info->e_wait_q[sr].list);
}
/*
* Puts current task to sleep. Caller must hold queue lock. After return
* lock isn't held.
* sr: SEND or RECV
*/
static int wq_sleep(struct mqueue_inode_info *info, int sr,
ktime_t *timeout, struct ext_wait_queue *ewp)
{
int retval;
signed long time;
wq_add(info, sr, ewp);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock(&info->lock);
time = schedule_hrtimeout_range_clock(timeout, 0,
HRTIMER_MODE_ABS, CLOCK_REALTIME);
while (ewp->state == STATE_PENDING)
cpu_relax();
if (ewp->state == STATE_READY) {
retval = 0;
goto out;
}
spin_lock(&info->lock);
if (ewp->state == STATE_READY) {
retval = 0;
goto out_unlock;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (time == 0) {
retval = -ETIMEDOUT;
break;
}
}
list_del(&ewp->list);
out_unlock:
spin_unlock(&info->lock);
out:
return retval;
}
/*
* Returns waiting task that should be serviced first or NULL if none exists
*/
static struct ext_wait_queue *wq_get_first_waiter(
struct mqueue_inode_info *info, int sr)
{
struct list_head *ptr;
ptr = info->e_wait_q[sr].list.prev;
if (ptr == &info->e_wait_q[sr].list)
return NULL;
return list_entry(ptr, struct ext_wait_queue, list);
}
/* Auxiliary functions to manipulate messages' list */
static void msg_insert(struct msg_msg *ptr, struct mqueue_inode_info *info)
{
int k;
k = info->attr.mq_curmsgs - 1;
while (k >= 0 && info->messages[k]->m_type >= ptr->m_type) {
info->messages[k + 1] = info->messages[k];
k--;
}
info->attr.mq_curmsgs++;
info->qsize += ptr->m_ts;
info->messages[k + 1] = ptr;
}
static inline struct msg_msg *msg_get(struct mqueue_inode_info *info)
{
info->qsize -= info->messages[--info->attr.mq_curmsgs]->m_ts;
return info->messages[info->attr.mq_curmsgs];
}
static inline void set_cookie(struct sk_buff *skb, char code)
{
((char*)skb->data)[NOTIFY_COOKIE_LEN-1] = code;
}
/*
* The next function is only to split too long sys_mq_timedsend
*/
static void __do_notify(struct mqueue_inode_info *info)
{
/* notification
* invoked when there is registered process and there isn't process
* waiting synchronously for message AND state of queue changed from
* empty to not empty. Here we are sure that no one is waiting
* synchronously. */
if (info->notify_owner &&
info->attr.mq_curmsgs == 1) {
struct siginfo sig_i;
switch (info->notify.sigev_notify) {
case SIGEV_NONE:
break;
case SIGEV_SIGNAL:
/* sends signal */
sig_i.si_signo = info->notify.sigev_signo;
sig_i.si_errno = 0;
sig_i.si_code = SI_MESGQ;
sig_i.si_value = info->notify.sigev_value;
/* map current pid/uid into info->owner's namespaces */
rcu_read_lock();
sig_i.si_pid = task_tgid_nr_ns(current,
ns_of_pid(info->notify_owner));
sig_i.si_uid = user_ns_map_uid(info->user->user_ns,
current_cred(), current_uid());
rcu_read_unlock();
kill_pid_info(info->notify.sigev_signo,
&sig_i, info->notify_owner);
break;
case SIGEV_THREAD:
set_cookie(info->notify_cookie, NOTIFY_WOKENUP);
netlink_sendskb(info->notify_sock, info->notify_cookie);
break;
}
/* after notification unregisters process */
put_pid(info->notify_owner);
info->notify_owner = NULL;
}
wake_up(&info->wait_q);
}
static int prepare_timeout(const struct timespec __user *u_abs_timeout,
ktime_t *expires, struct timespec *ts)
{
if (copy_from_user(ts, u_abs_timeout, sizeof(struct timespec)))
return -EFAULT;
if (!timespec_valid(ts))
return -EINVAL;
*expires = timespec_to_ktime(*ts);
return 0;
}
static void remove_notification(struct mqueue_inode_info *info)
{
if (info->notify_owner != NULL &&
info->notify.sigev_notify == SIGEV_THREAD) {
set_cookie(info->notify_cookie, NOTIFY_REMOVED);
netlink_sendskb(info->notify_sock, info->notify_cookie);
}
put_pid(info->notify_owner);
info->notify_owner = NULL;
}
static int mq_attr_ok(struct ipc_namespace *ipc_ns, struct mq_attr *attr)
{
if (attr->mq_maxmsg <= 0 || attr->mq_msgsize <= 0)
return 0;
if (capable(CAP_SYS_RESOURCE)) {
if (attr->mq_maxmsg > HARD_MSGMAX)
return 0;
} else {
if (attr->mq_maxmsg > ipc_ns->mq_msg_max ||
attr->mq_msgsize > ipc_ns->mq_msgsize_max)
return 0;
}
/* check for overflow */
if (attr->mq_msgsize > ULONG_MAX/attr->mq_maxmsg)
return 0;
if ((unsigned long)(attr->mq_maxmsg * (attr->mq_msgsize
+ sizeof (struct msg_msg *))) <
(unsigned long)(attr->mq_maxmsg * attr->mq_msgsize))
return 0;
return 1;
}
/*
* Invoked when creating a new queue via sys_mq_open
*/
static struct file *do_create(struct ipc_namespace *ipc_ns, struct dentry *dir,
struct dentry *dentry, int oflag, umode_t mode,
struct mq_attr *attr)
{
const struct cred *cred = current_cred();
struct file *result;
int ret;
if (attr) {
if (!mq_attr_ok(ipc_ns, attr)) {
ret = -EINVAL;
goto out;
}
/* store for use during create */
dentry->d_fsdata = attr;
}
mode &= ~current_umask();
ret = mnt_want_write(ipc_ns->mq_mnt);
if (ret)
goto out;
ret = vfs_create(dir->d_inode, dentry, mode, NULL);
dentry->d_fsdata = NULL;
if (ret)
goto out_drop_write;
result = dentry_open(dentry, ipc_ns->mq_mnt, oflag, cred);
/*
* dentry_open() took a persistent mnt_want_write(),
* so we can now drop this one.
*/
mnt_drop_write(ipc_ns->mq_mnt);
return result;
out_drop_write:
mnt_drop_write(ipc_ns->mq_mnt);
out:
dput(dentry);
mntput(ipc_ns->mq_mnt);
return ERR_PTR(ret);
}
/* Opens existing queue */
static struct file *do_open(struct ipc_namespace *ipc_ns,
struct dentry *dentry, int oflag)
{
int ret;
const struct cred *cred = current_cred();
static const int oflag2acc[O_ACCMODE] = { MAY_READ, MAY_WRITE,
MAY_READ | MAY_WRITE };
if ((oflag & O_ACCMODE) == (O_RDWR | O_WRONLY)) {
ret = -EINVAL;
goto err;
}
if (inode_permission(dentry->d_inode, oflag2acc[oflag & O_ACCMODE])) {
ret = -EACCES;
goto err;
}
return dentry_open(dentry, ipc_ns->mq_mnt, oflag, cred);
err:
dput(dentry);
mntput(ipc_ns->mq_mnt);
return ERR_PTR(ret);
}
SYSCALL_DEFINE4(mq_open, const char __user *, u_name, int, oflag, umode_t, mode,
struct mq_attr __user *, u_attr)
{
struct dentry *dentry;
struct file *filp;
char *name;
struct mq_attr attr;
int fd, error;
struct ipc_namespace *ipc_ns = current->nsproxy->ipc_ns;
if (u_attr && copy_from_user(&attr, u_attr, sizeof(struct mq_attr)))
return -EFAULT;
audit_mq_open(oflag, mode, u_attr ? &attr : NULL);
if (IS_ERR(name = getname(u_name)))
return PTR_ERR(name);
fd = get_unused_fd_flags(O_CLOEXEC);
if (fd < 0)
goto out_putname;
mutex_lock(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex);
dentry = lookup_one_len(name, ipc_ns->mq_mnt->mnt_root, strlen(name));
if (IS_ERR(dentry)) {
error = PTR_ERR(dentry);
goto out_putfd;
}
mntget(ipc_ns->mq_mnt);
if (oflag & O_CREAT) {
if (dentry->d_inode) { /* entry already exists */
audit_inode(name, dentry);
if (oflag & O_EXCL) {
error = -EEXIST;
goto out;
}
filp = do_open(ipc_ns, dentry, oflag);
} else {
filp = do_create(ipc_ns, ipc_ns->mq_mnt->mnt_root,
dentry, oflag, mode,
u_attr ? &attr : NULL);
}
} else {
if (!dentry->d_inode) {
error = -ENOENT;
goto out;
}
audit_inode(name, dentry);
filp = do_open(ipc_ns, dentry, oflag);
}
if (IS_ERR(filp)) {
error = PTR_ERR(filp);
goto out_putfd;
}
fd_install(fd, filp);
goto out_upsem;
out:
dput(dentry);
mntput(ipc_ns->mq_mnt);
out_putfd:
put_unused_fd(fd);
fd = error;
out_upsem:
mutex_unlock(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex);
out_putname:
putname(name);
return fd;
}
SYSCALL_DEFINE1(mq_unlink, const char __user *, u_name)
{
int err;
char *name;
struct dentry *dentry;
struct inode *inode = NULL;
struct ipc_namespace *ipc_ns = current->nsproxy->ipc_ns;
name = getname(u_name);
if (IS_ERR(name))
return PTR_ERR(name);
mutex_lock_nested(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex,
I_MUTEX_PARENT);
dentry = lookup_one_len(name, ipc_ns->mq_mnt->mnt_root, strlen(name));
if (IS_ERR(dentry)) {
err = PTR_ERR(dentry);
goto out_unlock;
}
if (!dentry->d_inode) {
err = -ENOENT;
goto out_err;
}
inode = dentry->d_inode;
if (inode)
ihold(inode);
err = mnt_want_write(ipc_ns->mq_mnt);
if (err)
goto out_err;
err = vfs_unlink(dentry->d_parent->d_inode, dentry);
mnt_drop_write(ipc_ns->mq_mnt);
out_err:
dput(dentry);
out_unlock:
mutex_unlock(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex);
putname(name);
if (inode)
iput(inode);
return err;
}
/* Pipelined send and receive functions.
*
* If a receiver finds no waiting message, then it registers itself in the
* list of waiting receivers. A sender checks that list before adding the new
* message into the message array. If there is a waiting receiver, then it
* bypasses the message array and directly hands the message over to the
* receiver.
* The receiver accepts the message and returns without grabbing the queue
* spinlock. Therefore an intermediate STATE_PENDING state and memory barriers
* are necessary. The same algorithm is used for sysv semaphores, see
* ipc/sem.c for more details.
*
* The same algorithm is used for senders.
*/
/* pipelined_send() - send a message directly to the task waiting in
* sys_mq_timedreceive() (without inserting message into a queue).
*/
static inline void pipelined_send(struct mqueue_inode_info *info,
struct msg_msg *message,
struct ext_wait_queue *receiver)
{
receiver->msg = message;
list_del(&receiver->list);
receiver->state = STATE_PENDING;
wake_up_process(receiver->task);
smp_wmb();
receiver->state = STATE_READY;
}
/* pipelined_receive() - if there is task waiting in sys_mq_timedsend()
* gets its message and put to the queue (we have one free place for sure). */
static inline void pipelined_receive(struct mqueue_inode_info *info)
{
struct ext_wait_queue *sender = wq_get_first_waiter(info, SEND);
if (!sender) {
/* for poll */
wake_up_interruptible(&info->wait_q);
return;
}
msg_insert(sender->msg, info);
list_del(&sender->list);
sender->state = STATE_PENDING;
wake_up_process(sender->task);
smp_wmb();
sender->state = STATE_READY;
}
SYSCALL_DEFINE5(mq_timedsend, mqd_t, mqdes, const char __user *, u_msg_ptr,
size_t, msg_len, unsigned int, msg_prio,
const struct timespec __user *, u_abs_timeout)
{
struct file *filp;
struct inode *inode;
struct ext_wait_queue wait;
struct ext_wait_queue *receiver;
struct msg_msg *msg_ptr;
struct mqueue_inode_info *info;
ktime_t expires, *timeout = NULL;
struct timespec ts;
int ret;
if (u_abs_timeout) {
int res = prepare_timeout(u_abs_timeout, &expires, &ts);
if (res)
return res;
timeout = &expires;
}
if (unlikely(msg_prio >= (unsigned long) MQ_PRIO_MAX))
return -EINVAL;
audit_mq_sendrecv(mqdes, msg_len, msg_prio, timeout ? &ts : NULL);
filp = fget(mqdes);
if (unlikely(!filp)) {
ret = -EBADF;
goto out;
}
inode = filp->f_path.dentry->d_inode;
if (unlikely(filp->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
audit_inode(NULL, filp->f_path.dentry);
if (unlikely(!(filp->f_mode & FMODE_WRITE))) {
ret = -EBADF;
goto out_fput;
}
if (unlikely(msg_len > info->attr.mq_msgsize)) {
ret = -EMSGSIZE;
goto out_fput;
}
/* First try to allocate memory, before doing anything with
* existing queues. */
msg_ptr = load_msg(u_msg_ptr, msg_len);
if (IS_ERR(msg_ptr)) {
ret = PTR_ERR(msg_ptr);
goto out_fput;
}
msg_ptr->m_ts = msg_len;
msg_ptr->m_type = msg_prio;
spin_lock(&info->lock);
if (info->attr.mq_curmsgs == info->attr.mq_maxmsg) {
if (filp->f_flags & O_NONBLOCK) {
spin_unlock(&info->lock);
ret = -EAGAIN;
} else {
wait.task = current;
wait.msg = (void *) msg_ptr;
wait.state = STATE_NONE;
ret = wq_sleep(info, SEND, timeout, &wait);
}
if (ret < 0)
free_msg(msg_ptr);
} else {
receiver = wq_get_first_waiter(info, RECV);
if (receiver) {
pipelined_send(info, msg_ptr, receiver);
} else {
/* adds message to the queue */
msg_insert(msg_ptr, info);
__do_notify(info);
}
inode->i_atime = inode->i_mtime = inode->i_ctime =
CURRENT_TIME;
spin_unlock(&info->lock);
ret = 0;
}
out_fput:
fput(filp);
out:
return ret;
}
SYSCALL_DEFINE5(mq_timedreceive, mqd_t, mqdes, char __user *, u_msg_ptr,
size_t, msg_len, unsigned int __user *, u_msg_prio,
const struct timespec __user *, u_abs_timeout)
{
ssize_t ret;
struct msg_msg *msg_ptr;
struct file *filp;
struct inode *inode;
struct mqueue_inode_info *info;
struct ext_wait_queue wait;
ktime_t expires, *timeout = NULL;
struct timespec ts;
if (u_abs_timeout) {
int res = prepare_timeout(u_abs_timeout, &expires, &ts);
if (res)
return res;
timeout = &expires;
}
audit_mq_sendrecv(mqdes, msg_len, 0, timeout ? &ts : NULL);
filp = fget(mqdes);
if (unlikely(!filp)) {
ret = -EBADF;
goto out;
}
inode = filp->f_path.dentry->d_inode;
if (unlikely(filp->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
audit_inode(NULL, filp->f_path.dentry);
if (unlikely(!(filp->f_mode & FMODE_READ))) {
ret = -EBADF;
goto out_fput;
}
/* checks if buffer is big enough */
if (unlikely(msg_len < info->attr.mq_msgsize)) {
ret = -EMSGSIZE;
goto out_fput;
}
spin_lock(&info->lock);
if (info->attr.mq_curmsgs == 0) {
if (filp->f_flags & O_NONBLOCK) {
spin_unlock(&info->lock);
ret = -EAGAIN;
} else {
wait.task = current;
wait.state = STATE_NONE;
ret = wq_sleep(info, RECV, timeout, &wait);
msg_ptr = wait.msg;
}
} else {
msg_ptr = msg_get(info);
inode->i_atime = inode->i_mtime = inode->i_ctime =
CURRENT_TIME;
/* There is now free space in queue. */
pipelined_receive(info);
spin_unlock(&info->lock);
ret = 0;
}
if (ret == 0) {
ret = msg_ptr->m_ts;
if ((u_msg_prio && put_user(msg_ptr->m_type, u_msg_prio)) ||
store_msg(u_msg_ptr, msg_ptr, msg_ptr->m_ts)) {
ret = -EFAULT;
}
free_msg(msg_ptr);
}
out_fput:
fput(filp);
out:
return ret;
}
/*
* Notes: the case when user wants us to deregister (with NULL as pointer)
* and he isn't currently owner of notification, will be silently discarded.
* It isn't explicitly defined in the POSIX.
*/
SYSCALL_DEFINE2(mq_notify, mqd_t, mqdes,
const struct sigevent __user *, u_notification)
{
int ret;
struct file *filp;
struct sock *sock;
struct inode *inode;
struct sigevent notification;
struct mqueue_inode_info *info;
struct sk_buff *nc;
if (u_notification) {
if (copy_from_user(¬ification, u_notification,
sizeof(struct sigevent)))
return -EFAULT;
}
audit_mq_notify(mqdes, u_notification ? ¬ification : NULL);
nc = NULL;
sock = NULL;
if (u_notification != NULL) {
if (unlikely(notification.sigev_notify != SIGEV_NONE &&
notification.sigev_notify != SIGEV_SIGNAL &&
notification.sigev_notify != SIGEV_THREAD))
return -EINVAL;
if (notification.sigev_notify == SIGEV_SIGNAL &&
!valid_signal(notification.sigev_signo)) {
return -EINVAL;
}
if (notification.sigev_notify == SIGEV_THREAD) {
long timeo;
/* create the notify skb */
nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);
if (!nc) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(nc->data,
notification.sigev_value.sival_ptr,
NOTIFY_COOKIE_LEN)) {
ret = -EFAULT;
goto out;
}
/* TODO: add a header? */
skb_put(nc, NOTIFY_COOKIE_LEN);
/* and attach it to the socket */
retry:
filp = fget(notification.sigev_signo);
if (!filp) {
ret = -EBADF;
goto out;
}
sock = netlink_getsockbyfilp(filp);
fput(filp);
if (IS_ERR(sock)) {
ret = PTR_ERR(sock);
sock = NULL;
goto out;
}
timeo = MAX_SCHEDULE_TIMEOUT;
ret = netlink_attachskb(sock, nc, &timeo, NULL);
if (ret == 1)
goto retry;
if (ret) {
sock = NULL;
nc = NULL;
goto out;
}
}
}
filp = fget(mqdes);
if (!filp) {
ret = -EBADF;
goto out;
}
inode = filp->f_path.dentry->d_inode;
if (unlikely(filp->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
ret = 0;
spin_lock(&info->lock);
if (u_notification == NULL) {
if (info->notify_owner == task_tgid(current)) {
remove_notification(info);
inode->i_atime = inode->i_ctime = CURRENT_TIME;
}
} else if (info->notify_owner != NULL) {
ret = -EBUSY;
} else {
switch (notification.sigev_notify) {
case SIGEV_NONE:
info->notify.sigev_notify = SIGEV_NONE;
break;
case SIGEV_THREAD:
info->notify_sock = sock;
info->notify_cookie = nc;
sock = NULL;
nc = NULL;
info->notify.sigev_notify = SIGEV_THREAD;
break;
case SIGEV_SIGNAL:
info->notify.sigev_signo = notification.sigev_signo;
info->notify.sigev_value = notification.sigev_value;
info->notify.sigev_notify = SIGEV_SIGNAL;
break;
}
info->notify_owner = get_pid(task_tgid(current));
inode->i_atime = inode->i_ctime = CURRENT_TIME;
}
spin_unlock(&info->lock);
out_fput:
fput(filp);
out:
if (sock) {
netlink_detachskb(sock, nc);
} else if (nc) {
dev_kfree_skb(nc);
}
return ret;
}
SYSCALL_DEFINE3(mq_getsetattr, mqd_t, mqdes,
const struct mq_attr __user *, u_mqstat,
struct mq_attr __user *, u_omqstat)
{
int ret;
struct mq_attr mqstat, omqstat;
struct file *filp;
struct inode *inode;
struct mqueue_inode_info *info;
if (u_mqstat != NULL) {
if (copy_from_user(&mqstat, u_mqstat, sizeof(struct mq_attr)))
return -EFAULT;
if (mqstat.mq_flags & (~O_NONBLOCK))
return -EINVAL;
}
filp = fget(mqdes);
if (!filp) {
ret = -EBADF;
goto out;
}
inode = filp->f_path.dentry->d_inode;
if (unlikely(filp->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
spin_lock(&info->lock);
omqstat = info->attr;
omqstat.mq_flags = filp->f_flags & O_NONBLOCK;
if (u_mqstat) {
audit_mq_getsetattr(mqdes, &mqstat);
spin_lock(&filp->f_lock);
if (mqstat.mq_flags & O_NONBLOCK)
filp->f_flags |= O_NONBLOCK;
else
filp->f_flags &= ~O_NONBLOCK;
spin_unlock(&filp->f_lock);
inode->i_atime = inode->i_ctime = CURRENT_TIME;
}
spin_unlock(&info->lock);
ret = 0;
if (u_omqstat != NULL && copy_to_user(u_omqstat, &omqstat,
sizeof(struct mq_attr)))
ret = -EFAULT;
out_fput:
fput(filp);
out:
return ret;
}
static const struct inode_operations mqueue_dir_inode_operations = {
.lookup = simple_lookup,
.create = mqueue_create,
.unlink = mqueue_unlink,
};
static const struct file_operations mqueue_file_operations = {
.flush = mqueue_flush_file,
.poll = mqueue_poll_file,
.read = mqueue_read_file,
.llseek = default_llseek,
};
static const struct super_operations mqueue_super_ops = {
.alloc_inode = mqueue_alloc_inode,
.destroy_inode = mqueue_destroy_inode,
.evict_inode = mqueue_evict_inode,
.statfs = simple_statfs,
};
static struct file_system_type mqueue_fs_type = {
.name = "mqueue",
.mount = mqueue_mount,
.kill_sb = kill_litter_super,
};
int mq_init_ns(struct ipc_namespace *ns)
{
ns->mq_queues_count = 0;
ns->mq_queues_max = DFLT_QUEUESMAX;
ns->mq_msg_max = DFLT_MSGMAX;
ns->mq_msgsize_max = DFLT_MSGSIZEMAX;
ns->mq_mnt = kern_mount_data(&mqueue_fs_type, ns);
if (IS_ERR(ns->mq_mnt)) {
int err = PTR_ERR(ns->mq_mnt);
ns->mq_mnt = NULL;
return err;
}
return 0;
}
void mq_clear_sbinfo(struct ipc_namespace *ns)
{
ns->mq_mnt->mnt_sb->s_fs_info = NULL;
}
void mq_put_mnt(struct ipc_namespace *ns)
{
kern_unmount(ns->mq_mnt);
}
static int __init init_mqueue_fs(void)
{
int error;
mqueue_inode_cachep = kmem_cache_create("mqueue_inode_cache",
sizeof(struct mqueue_inode_info), 0,
SLAB_HWCACHE_ALIGN, init_once);
if (mqueue_inode_cachep == NULL)
return -ENOMEM;
/* ignore failures - they are not fatal */
mq_sysctl_table = mq_register_sysctl_table();
error = register_filesystem(&mqueue_fs_type);
if (error)
goto out_sysctl;
spin_lock_init(&mq_lock);
error = mq_init_ns(&init_ipc_ns);
if (error)
goto out_filesystem;
return 0;
out_filesystem:
unregister_filesystem(&mqueue_fs_type);
out_sysctl:
if (mq_sysctl_table)
unregister_sysctl_table(mq_sysctl_table);
kmem_cache_destroy(mqueue_inode_cachep);
return error;
}
__initcall(init_mqueue_fs);
| gpl-2.0 |
Biktorgj/Tizen_b2_Kernel | arch/sh/cchips/hd6446x/hd64461.c | 7448 | 2918 | /*
* Copyright (C) 2000 YAEGASHI Takeshi
* Hitachi HD64461 companion chip support
*/
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <asm/hd64461.h>
/* This belongs in cpu specific */
#define INTC_ICR1 0xA4140010UL
static void hd64461_mask_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
unsigned short nimr;
unsigned short mask = 1 << (irq - HD64461_IRQBASE);
nimr = __raw_readw(HD64461_NIMR);
nimr |= mask;
__raw_writew(nimr, HD64461_NIMR);
}
static void hd64461_unmask_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
unsigned short nimr;
unsigned short mask = 1 << (irq - HD64461_IRQBASE);
nimr = __raw_readw(HD64461_NIMR);
nimr &= ~mask;
__raw_writew(nimr, HD64461_NIMR);
}
static void hd64461_mask_and_ack_irq(struct irq_data *data)
{
hd64461_mask_irq(data);
#ifdef CONFIG_HD64461_ENABLER
if (data->irq == HD64461_IRQBASE + 13)
__raw_writeb(0x00, HD64461_PCC1CSCR);
#endif
}
static struct irq_chip hd64461_irq_chip = {
.name = "HD64461-IRQ",
.irq_mask = hd64461_mask_irq,
.irq_mask_ack = hd64461_mask_and_ack_irq,
.irq_unmask = hd64461_unmask_irq,
};
static void hd64461_irq_demux(unsigned int irq, struct irq_desc *desc)
{
unsigned short intv = __raw_readw(HD64461_NIRR);
unsigned int ext_irq = HD64461_IRQBASE;
intv &= (1 << HD64461_IRQ_NUM) - 1;
for (; intv; intv >>= 1, ext_irq++) {
if (!(intv & 1))
continue;
generic_handle_irq(ext_irq);
}
}
int __init setup_hd64461(void)
{
int i, nid = cpu_to_node(boot_cpu_data);
if (!MACH_HD64461)
return 0;
printk(KERN_INFO
"HD64461 configured at 0x%x on irq %d(mapped into %d to %d)\n",
HD64461_IOBASE, CONFIG_HD64461_IRQ, HD64461_IRQBASE,
HD64461_IRQBASE + 15);
/* Should be at processor specific part.. */
#if defined(CONFIG_CPU_SUBTYPE_SH7709)
__raw_writew(0x2240, INTC_ICR1);
#endif
__raw_writew(0xffff, HD64461_NIMR);
/* IRQ 80 -> 95 belongs to HD64461 */
for (i = HD64461_IRQBASE; i < HD64461_IRQBASE + 16; i++) {
unsigned int irq;
irq = create_irq_nr(i, nid);
if (unlikely(irq == 0)) {
pr_err("%s: failed hooking irq %d for HD64461\n",
__func__, i);
return -EBUSY;
}
if (unlikely(irq != i)) {
pr_err("%s: got irq %d but wanted %d, bailing.\n",
__func__, irq, i);
destroy_irq(irq);
return -EINVAL;
}
irq_set_chip_and_handler(i, &hd64461_irq_chip,
handle_level_irq);
}
irq_set_chained_handler(CONFIG_HD64461_IRQ, hd64461_irq_demux);
irq_set_irq_type(CONFIG_HD64461_IRQ, IRQ_TYPE_LEVEL_LOW);
#ifdef CONFIG_HD64461_ENABLER
printk(KERN_INFO "HD64461: enabling PCMCIA devices\n");
__raw_writeb(0x4c, HD64461_PCC1CSCIER);
__raw_writeb(0x00, HD64461_PCC1CSCR);
#endif
return 0;
}
module_init(setup_hd64461);
| gpl-2.0 |
IndieBeto/StockLP | drivers/pci/hotplug/rpaphp_core.c | 7448 | 11054 | /*
* PCI Hot Plug Controller Driver for RPA-compliant PPC64 platform.
* Copyright (C) 2003 Linda Xie <lxie@us.ibm.com>
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. 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.
*
* Send feedback to <lxie@us.ibm.com>
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <asm/eeh.h> /* for eeh_add_device() */
#include <asm/rtas.h> /* rtas_call */
#include <asm/pci-bridge.h> /* for pci_controller */
#include "../pci.h" /* for pci_add_new_bus */
/* and pci_do_scan_bus */
#include "rpaphp.h"
bool rpaphp_debug;
LIST_HEAD(rpaphp_slot_head);
#define DRIVER_VERSION "0.1"
#define DRIVER_AUTHOR "Linda Xie <lxie@us.ibm.com>"
#define DRIVER_DESC "RPA HOT Plug PCI Controller Driver"
#define MAX_LOC_CODE 128
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param_named(debug, rpaphp_debug, bool, 0644);
/**
* set_attention_status - set attention LED
* @hotplug_slot: target &hotplug_slot
* @value: LED control value
*
* echo 0 > attention -- set LED OFF
* echo 1 > attention -- set LED ON
* echo 2 > attention -- set LED ID(identify, light is blinking)
*/
static int set_attention_status(struct hotplug_slot *hotplug_slot, u8 value)
{
int rc;
struct slot *slot = (struct slot *)hotplug_slot->private;
switch (value) {
case 0:
case 1:
case 2:
break;
default:
value = 1;
break;
}
rc = rtas_set_indicator(DR_INDICATOR, slot->index, value);
if (!rc)
hotplug_slot->info->attention_status = value;
return rc;
}
/**
* get_power_status - get power status of a slot
* @hotplug_slot: slot to get status
* @value: pointer to store status
*/
static int get_power_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
int retval, level;
struct slot *slot = (struct slot *)hotplug_slot->private;
retval = rtas_get_power_level (slot->power_domain, &level);
if (!retval)
*value = level;
return retval;
}
/**
* get_attention_status - get attention LED status
* @hotplug_slot: slot to get status
* @value: pointer to store status
*/
static int get_attention_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
struct slot *slot = (struct slot *)hotplug_slot->private;
*value = slot->hotplug_slot->info->attention_status;
return 0;
}
static int get_adapter_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
struct slot *slot = (struct slot *)hotplug_slot->private;
int rc, state;
rc = rpaphp_get_sensor_state(slot, &state);
*value = NOT_VALID;
if (rc)
return rc;
if (state == EMPTY)
*value = EMPTY;
else if (state == PRESENT)
*value = slot->state;
return 0;
}
static enum pci_bus_speed get_max_bus_speed(struct slot *slot)
{
enum pci_bus_speed speed;
switch (slot->type) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
speed = PCI_SPEED_33MHz; /* speed for case 1-6 */
break;
case 7:
case 8:
speed = PCI_SPEED_66MHz;
break;
case 11:
case 14:
speed = PCI_SPEED_66MHz_PCIX;
break;
case 12:
case 15:
speed = PCI_SPEED_100MHz_PCIX;
break;
case 13:
case 16:
speed = PCI_SPEED_133MHz_PCIX;
break;
default:
speed = PCI_SPEED_UNKNOWN;
break;
}
return speed;
}
static int get_children_props(struct device_node *dn, const int **drc_indexes,
const int **drc_names, const int **drc_types,
const int **drc_power_domains)
{
const int *indexes, *names, *types, *domains;
indexes = of_get_property(dn, "ibm,drc-indexes", NULL);
names = of_get_property(dn, "ibm,drc-names", NULL);
types = of_get_property(dn, "ibm,drc-types", NULL);
domains = of_get_property(dn, "ibm,drc-power-domains", NULL);
if (!indexes || !names || !types || !domains) {
/* Slot does not have dynamically-removable children */
return -EINVAL;
}
if (drc_indexes)
*drc_indexes = indexes;
if (drc_names)
/* &drc_names[1] contains NULL terminated slot names */
*drc_names = names;
if (drc_types)
/* &drc_types[1] contains NULL terminated slot types */
*drc_types = types;
if (drc_power_domains)
*drc_power_domains = domains;
return 0;
}
/* To get the DRC props describing the current node, first obtain it's
* my-drc-index property. Next obtain the DRC list from it's parent. Use
* the my-drc-index for correlation, and obtain the requested properties.
*/
int rpaphp_get_drc_props(struct device_node *dn, int *drc_index,
char **drc_name, char **drc_type, int *drc_power_domain)
{
const int *indexes, *names;
const int *types, *domains;
const unsigned int *my_index;
char *name_tmp, *type_tmp;
int i, rc;
my_index = of_get_property(dn, "ibm,my-drc-index", NULL);
if (!my_index) {
/* Node isn't DLPAR/hotplug capable */
return -EINVAL;
}
rc = get_children_props(dn->parent, &indexes, &names, &types, &domains);
if (rc < 0) {
return -EINVAL;
}
name_tmp = (char *) &names[1];
type_tmp = (char *) &types[1];
/* Iterate through parent properties, looking for my-drc-index */
for (i = 0; i < indexes[0]; i++) {
if ((unsigned int) indexes[i + 1] == *my_index) {
if (drc_name)
*drc_name = name_tmp;
if (drc_type)
*drc_type = type_tmp;
if (drc_index)
*drc_index = *my_index;
if (drc_power_domain)
*drc_power_domain = domains[i+1];
return 0;
}
name_tmp += (strlen(name_tmp) + 1);
type_tmp += (strlen(type_tmp) + 1);
}
return -EINVAL;
}
static int is_php_type(char *drc_type)
{
unsigned long value;
char *endptr;
/* PCI Hotplug nodes have an integer for drc_type */
value = simple_strtoul(drc_type, &endptr, 10);
if (endptr == drc_type)
return 0;
return 1;
}
/**
* is_php_dn() - return 1 if this is a hotpluggable pci slot, else 0
* @dn: target &device_node
* @indexes: passed to get_children_props()
* @names: passed to get_children_props()
* @types: returned from get_children_props()
* @power_domains:
*
* This routine will return true only if the device node is
* a hotpluggable slot. This routine will return false
* for built-in pci slots (even when the built-in slots are
* dlparable.)
*/
static int is_php_dn(struct device_node *dn, const int **indexes,
const int **names, const int **types, const int **power_domains)
{
const int *drc_types;
int rc;
rc = get_children_props(dn, indexes, names, &drc_types, power_domains);
if (rc < 0)
return 0;
if (!is_php_type((char *) &drc_types[1]))
return 0;
*types = drc_types;
return 1;
}
/**
* rpaphp_add_slot -- declare a hotplug slot to the hotplug subsystem.
* @dn: device node of slot
*
* This subroutine will register a hotplugable slot with the
* PCI hotplug infrastructure. This routine is typically called
* during boot time, if the hotplug slots are present at boot time,
* or is called later, by the dlpar add code, if the slot is
* being dynamically added during runtime.
*
* If the device node points at an embedded (built-in) slot, this
* routine will just return without doing anything, since embedded
* slots cannot be hotplugged.
*
* To remove a slot, it suffices to call rpaphp_deregister_slot().
*/
int rpaphp_add_slot(struct device_node *dn)
{
struct slot *slot;
int retval = 0;
int i;
const int *indexes, *names, *types, *power_domains;
char *name, *type;
if (!dn->name || strcmp(dn->name, "pci"))
return 0;
/* If this is not a hotplug slot, return without doing anything. */
if (!is_php_dn(dn, &indexes, &names, &types, &power_domains))
return 0;
dbg("Entry %s: dn->full_name=%s\n", __func__, dn->full_name);
/* register PCI devices */
name = (char *) &names[1];
type = (char *) &types[1];
for (i = 0; i < indexes[0]; i++) {
slot = alloc_slot_struct(dn, indexes[i + 1], name, power_domains[i + 1]);
if (!slot)
return -ENOMEM;
slot->type = simple_strtoul(type, NULL, 10);
dbg("Found drc-index:0x%x drc-name:%s drc-type:%s\n",
indexes[i + 1], name, type);
retval = rpaphp_enable_slot(slot);
if (!retval)
retval = rpaphp_register_slot(slot);
if (retval)
dealloc_slot_struct(slot);
name += strlen(name) + 1;
type += strlen(type) + 1;
}
dbg("%s - Exit: rc[%d]\n", __func__, retval);
/* XXX FIXME: reports a failure only if last entry in loop failed */
return retval;
}
static void __exit cleanup_slots(void)
{
struct list_head *tmp, *n;
struct slot *slot;
/*
* Unregister all of our slots with the pci_hotplug subsystem,
* and free up all memory that we had allocated.
* memory will be freed in release_slot callback.
*/
list_for_each_safe(tmp, n, &rpaphp_slot_head) {
slot = list_entry(tmp, struct slot, rpaphp_slot_list);
list_del(&slot->rpaphp_slot_list);
pci_hp_deregister(slot->hotplug_slot);
}
return;
}
static int __init rpaphp_init(void)
{
struct device_node *dn = NULL;
info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
while ((dn = of_find_node_by_name(dn, "pci")))
rpaphp_add_slot(dn);
return 0;
}
static void __exit rpaphp_exit(void)
{
cleanup_slots();
}
static int enable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = (struct slot *)hotplug_slot->private;
int state;
int retval;
if (slot->state == CONFIGURED)
return 0;
retval = rpaphp_get_sensor_state(slot, &state);
if (retval)
return retval;
if (state == PRESENT) {
pcibios_add_pci_devices(slot->bus);
slot->state = CONFIGURED;
} else if (state == EMPTY) {
slot->state = EMPTY;
} else {
err("%s: slot[%s] is in invalid state\n", __func__, slot->name);
slot->state = NOT_VALID;
return -EINVAL;
}
slot->bus->max_bus_speed = get_max_bus_speed(slot);
return 0;
}
static int disable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = (struct slot *)hotplug_slot->private;
if (slot->state == NOT_CONFIGURED)
return -EINVAL;
pcibios_remove_pci_devices(slot->bus);
vm_unmap_aliases();
slot->state = NOT_CONFIGURED;
return 0;
}
struct hotplug_slot_ops rpaphp_hotplug_slot_ops = {
.enable_slot = enable_slot,
.disable_slot = disable_slot,
.set_attention_status = set_attention_status,
.get_power_status = get_power_status,
.get_attention_status = get_attention_status,
.get_adapter_status = get_adapter_status,
};
module_init(rpaphp_init);
module_exit(rpaphp_exit);
EXPORT_SYMBOL_GPL(rpaphp_add_slot);
EXPORT_SYMBOL_GPL(rpaphp_slot_head);
EXPORT_SYMBOL_GPL(rpaphp_get_drc_props);
| gpl-2.0 |
aimaletdinow/LABS | arch/x86/um/vdso/um_vdso.c | 10264 | 1618 | /*
* Copyright (C) 2011 Richard Weinberger <richrd@nod.at>
*
* 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 vDSO turns all calls into a syscall so that UML can trap them.
*/
/* Disable profiling for userspace code */
#define DISABLE_BRANCH_PROFILING
#include <linux/time.h>
#include <linux/getcpu.h>
#include <asm/unistd.h>
int __vdso_clock_gettime(clockid_t clock, struct timespec *ts)
{
long ret;
asm("syscall" : "=a" (ret) :
"0" (__NR_clock_gettime), "D" (clock), "S" (ts) : "memory");
return ret;
}
int clock_gettime(clockid_t, struct timespec *)
__attribute__((weak, alias("__vdso_clock_gettime")));
int __vdso_gettimeofday(struct timeval *tv, struct timezone *tz)
{
long ret;
asm("syscall" : "=a" (ret) :
"0" (__NR_gettimeofday), "D" (tv), "S" (tz) : "memory");
return ret;
}
int gettimeofday(struct timeval *, struct timezone *)
__attribute__((weak, alias("__vdso_gettimeofday")));
time_t __vdso_time(time_t *t)
{
long secs;
asm volatile("syscall"
: "=a" (secs)
: "0" (__NR_time), "D" (t) : "cc", "r11", "cx", "memory");
return secs;
}
int time(time_t *t) __attribute__((weak, alias("__vdso_time")));
long
__vdso_getcpu(unsigned *cpu, unsigned *node, struct getcpu_cache *unused)
{
/*
* UML does not support SMP, we can cheat here. :)
*/
if (cpu)
*cpu = 0;
if (node)
*node = 0;
return 0;
}
long getcpu(unsigned *cpu, unsigned *node, struct getcpu_cache *tcache)
__attribute__((weak, alias("__vdso_getcpu")));
| gpl-2.0 |
hillbeast/Kyorakernel-G3 | arch/mips/gt64120/wrppmc/time.c | 11544 | 1084 | /*
* time.c: MIPS CPU Count/Compare timer hookup
*
* Author: Mark.Zhan, <rongkai.zhan@windriver.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 1996, 1997, 2004 by Ralf Baechle (ralf@linux-mips.org)
* Copyright (C) 2006, Wind River System Inc.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/gt64120.h>
#include <asm/time.h>
#define WRPPMC_CPU_CLK_FREQ 40000000 /* 40MHZ */
/*
* Estimate CPU frequency. Sets mips_hpt_frequency as a side-effect
*
* NOTE: We disable all GT64120 timers, and use MIPS processor internal
* timer as the source of kernel clock tick.
*/
void __init plat_time_init(void)
{
/* Disable GT64120 timers */
GT_WRITE(GT_TC_CONTROL_OFS, 0x00);
GT_WRITE(GT_TC0_OFS, 0x00);
GT_WRITE(GT_TC1_OFS, 0x00);
GT_WRITE(GT_TC2_OFS, 0x00);
GT_WRITE(GT_TC3_OFS, 0x00);
/* Use MIPS compare/count internal timer */
mips_hpt_frequency = WRPPMC_CPU_CLK_FREQ;
}
| gpl-2.0 |
wurikiji/ttFS | ulinux/linux-3.10.61/arch/sh/kernel/sys_sh.c | 12056 | 2311 | /*
* linux/arch/sh/kernel/sys_sh.c
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/SuperH
* platform.
*
* Taken from i386 version.
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/utsname.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/ipc.h>
#include <asm/syscalls.h>
#include <asm/uaccess.h>
#include <asm/unistd.h>
#include <asm/cacheflush.h>
#include <asm/cachectl.h>
asmlinkage int old_mmap(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
int fd, unsigned long off)
{
if (off & ~PAGE_MASK)
return -EINVAL;
return sys_mmap_pgoff(addr, len, prot, flags, fd, off>>PAGE_SHIFT);
}
asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
{
/*
* The shift for mmap2 is constant, regardless of PAGE_SIZE
* setting.
*/
if (pgoff & ((1 << (PAGE_SHIFT - 12)) - 1))
return -EINVAL;
pgoff >>= PAGE_SHIFT - 12;
return sys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
}
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int sys_cacheflush(unsigned long addr, unsigned long len, int op)
{
struct vm_area_struct *vma;
if ((op <= 0) || (op > (CACHEFLUSH_D_PURGE|CACHEFLUSH_I)))
return -EINVAL;
/*
* Verify that the specified address region actually belongs
* to this process.
*/
if (addr + len < addr)
return -EFAULT;
down_read(¤t->mm->mmap_sem);
vma = find_vma (current->mm, addr);
if (vma == NULL || addr < vma->vm_start || addr + len > vma->vm_end) {
up_read(¤t->mm->mmap_sem);
return -EFAULT;
}
switch (op & CACHEFLUSH_D_PURGE) {
case CACHEFLUSH_D_INVAL:
__flush_invalidate_region((void *)addr, len);
break;
case CACHEFLUSH_D_WB:
__flush_wback_region((void *)addr, len);
break;
case CACHEFLUSH_D_PURGE:
__flush_purge_region((void *)addr, len);
break;
}
if (op & CACHEFLUSH_I)
flush_icache_range(addr, addr+len);
up_read(¤t->mm->mmap_sem);
return 0;
}
| gpl-2.0 |
kgp700/nexroid-sgs4ltea-kk | arch/arm/mach-davinci/irq.c | 12568 | 3705 | /*
* Interrupt handler for DaVinci boards.
*
* Copyright (C) 2006 Texas Instruments.
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/cputype.h>
#include <mach/common.h>
#include <asm/mach/irq.h>
#define FIQ_REG0_OFFSET 0x0000
#define FIQ_REG1_OFFSET 0x0004
#define IRQ_REG0_OFFSET 0x0008
#define IRQ_REG1_OFFSET 0x000C
#define IRQ_ENT_REG0_OFFSET 0x0018
#define IRQ_ENT_REG1_OFFSET 0x001C
#define IRQ_INCTL_REG_OFFSET 0x0020
#define IRQ_EABASE_REG_OFFSET 0x0024
#define IRQ_INTPRI0_REG_OFFSET 0x0030
#define IRQ_INTPRI7_REG_OFFSET 0x004C
static inline void davinci_irq_writel(unsigned long value, int offset)
{
__raw_writel(value, davinci_intc_base + offset);
}
static __init void
davinci_alloc_gc(void __iomem *base, unsigned int irq_start, unsigned int num)
{
struct irq_chip_generic *gc;
struct irq_chip_type *ct;
gc = irq_alloc_generic_chip("AINTC", 1, irq_start, base, handle_edge_irq);
if (!gc) {
pr_err("%s: irq_alloc_generic_chip for IRQ %u failed\n",
__func__, irq_start);
return;
}
ct = gc->chip_types;
ct->chip.irq_ack = irq_gc_ack_set_bit;
ct->chip.irq_mask = irq_gc_mask_clr_bit;
ct->chip.irq_unmask = irq_gc_mask_set_bit;
ct->regs.ack = IRQ_REG0_OFFSET;
ct->regs.mask = IRQ_ENT_REG0_OFFSET;
irq_setup_generic_chip(gc, IRQ_MSK(num), IRQ_GC_INIT_MASK_CACHE,
IRQ_NOREQUEST | IRQ_NOPROBE, 0);
}
/* ARM Interrupt Controller Initialization */
void __init davinci_irq_init(void)
{
unsigned i, j;
const u8 *davinci_def_priorities = davinci_soc_info.intc_irq_prios;
davinci_intc_type = DAVINCI_INTC_TYPE_AINTC;
davinci_intc_base = ioremap(davinci_soc_info.intc_base, SZ_4K);
if (WARN_ON(!davinci_intc_base))
return;
/* Clear all interrupt requests */
davinci_irq_writel(~0x0, FIQ_REG0_OFFSET);
davinci_irq_writel(~0x0, FIQ_REG1_OFFSET);
davinci_irq_writel(~0x0, IRQ_REG0_OFFSET);
davinci_irq_writel(~0x0, IRQ_REG1_OFFSET);
/* Disable all interrupts */
davinci_irq_writel(0x0, IRQ_ENT_REG0_OFFSET);
davinci_irq_writel(0x0, IRQ_ENT_REG1_OFFSET);
/* Interrupts disabled immediately, IRQ entry reflects all */
davinci_irq_writel(0x0, IRQ_INCTL_REG_OFFSET);
/* we don't use the hardware vector table, just its entry addresses */
davinci_irq_writel(0, IRQ_EABASE_REG_OFFSET);
/* Clear all interrupt requests */
davinci_irq_writel(~0x0, FIQ_REG0_OFFSET);
davinci_irq_writel(~0x0, FIQ_REG1_OFFSET);
davinci_irq_writel(~0x0, IRQ_REG0_OFFSET);
davinci_irq_writel(~0x0, IRQ_REG1_OFFSET);
for (i = IRQ_INTPRI0_REG_OFFSET; i <= IRQ_INTPRI7_REG_OFFSET; i += 4) {
u32 pri;
for (j = 0, pri = 0; j < 32; j += 4, davinci_def_priorities++)
pri |= (*davinci_def_priorities & 0x07) << j;
davinci_irq_writel(pri, i);
}
for (i = 0, j = 0; i < davinci_soc_info.intc_irq_num; i += 32, j += 0x04)
davinci_alloc_gc(davinci_intc_base + j, i, 32);
irq_set_handler(IRQ_TINT1_TINT34, handle_level_irq);
}
| gpl-2.0 |
roalex/sgs3-kernel | arch/powerpc/boot/cuboot-824x.c | 14104 | 1224 | /*
* Old U-boot compatibility for 824x
*
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "ops.h"
#include "stdio.h"
#include "cuboot.h"
#define TARGET_824x
#include "ppcboot.h"
static bd_t bd;
static void platform_fixups(void)
{
void *soc;
dt_fixup_memory(bd.bi_memstart, bd.bi_memsize);
dt_fixup_mac_addresses(bd.bi_enetaddr);
dt_fixup_cpu_clocks(bd.bi_intfreq, bd.bi_busfreq / 4, bd.bi_busfreq);
soc = find_node_by_devtype(NULL, "soc");
if (soc) {
void *serial = NULL;
setprop(soc, "bus-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
while ((serial = find_node_by_devtype(serial, "serial"))) {
if (get_parent(serial) != soc)
continue;
setprop(serial, "clock-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
}
}
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7)
{
CUBOOT_INIT();
fdt_init(_dtb_start);
serial_console_init();
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
fernandog/xbmc | xbmc/network/httprequesthandler/HTTPWebinterfaceAddonsHandler.cpp | 25 | 2153 | /*
* Copyright (C) 2011-2013 Team XBMC
* http://xbmc.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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "HTTPWebinterfaceAddonsHandler.h"
#include "addons/AddonManager.h"
#include "network/WebServer.h"
#define ADDON_HEADER "<html><head><title>Add-on List</title></head><body>\n<h1>Available web interfaces:</h1>\n<ul>\n"
bool CHTTPWebinterfaceAddonsHandler::CanHandleRequest(const HTTPRequest &request)
{
return (request.pathUrl.compare("/addons") == 0 || request.pathUrl.compare("/addons/") == 0);
}
int CHTTPWebinterfaceAddonsHandler::HandleRequest()
{
m_responseData = ADDON_HEADER;
ADDON::VECADDONS addons;
if (!ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_WEB_INTERFACE, addons) || addons.empty())
{
m_response.type = HTTPError;
m_response.status = MHD_HTTP_INTERNAL_SERVER_ERROR;
return MHD_YES;
}
for (ADDON::IVECADDONS addon = addons.begin(); addon != addons.end(); ++addon)
m_responseData += "<li><a href=/addons/" + (*addon)->ID() + "/>" + (*addon)->Name() + "</a></li>\n";
m_responseData += "</ul>\n</body></html>";
m_responseRange.SetData(m_responseData.c_str(), m_responseData.size());
m_response.type = HTTPMemoryDownloadNoFreeCopy;
m_response.status = MHD_HTTP_OK;
m_response.contentType = "text/html";
m_response.totalLength = m_responseData.size();
return MHD_YES;
}
HttpResponseRanges CHTTPWebinterfaceAddonsHandler::GetResponseData() const
{
HttpResponseRanges ranges;
ranges.push_back(m_responseRange);
return ranges;
}
| gpl-2.0 |
chunkeey/LEDE-IPQ40XX | package/kernel/lantiq/ltq-ptm/src/ifxmips_ptm_vdsl.c | 25 | 35204 | /******************************************************************************
**
** FILE NAME : ifxmips_ptm_vdsl.c
** PROJECT : UEIP
** MODULES : PTM
**
** DATE : 7 Jul 2009
** AUTHOR : Xu Liang
** DESCRIPTION : PTM driver common source file (core functions for VR9)
** COPYRIGHT : Copyright (c) 2006
** Infineon Technologies AG
** Am Campeon 1-12, 85579 Neubiberg, Germany
**
** 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.
**
** HISTORY
** $Date $Author $Comment
** 07 JUL 2009 Xu Liang Init Version
*******************************************************************************/
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/ioctl.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include "ifxmips_ptm_vdsl.h"
#include <lantiq_soc.h>
#define MODULE_PARM_ARRAY(a, b) module_param_array(a, int, NULL, 0)
#define MODULE_PARM(a, b) module_param(a, int, 0)
static int wanqos_en = 0;
static int queue_gamma_map[4] = {0xFE, 0x01, 0x00, 0x00};
MODULE_PARM(wanqos_en, "i");
MODULE_PARM_DESC(wanqos_en, "WAN QoS support, 1 - enabled, 0 - disabled.");
MODULE_PARM_ARRAY(queue_gamma_map, "4-4i");
MODULE_PARM_DESC(queue_gamma_map, "TX QoS queues mapping to 4 TX Gamma interfaces.");
extern int (*ifx_mei_atm_showtime_enter)(struct port_cell_info *, void *);
extern int (*ifx_mei_atm_showtime_exit)(void);
extern int ifx_mei_atm_showtime_check(int *is_showtime, struct port_cell_info *port_cell, void **xdata_addr);
static int g_showtime = 0;
static void *g_xdata_addr = NULL;
#define ENABLE_TMP_DBG 0
unsigned long cgu_get_pp32_clock(void)
{
struct clk *c = clk_get_ppe();
unsigned long rate = clk_get_rate(c);
clk_put(c);
return rate;
}
static void ptm_setup(struct net_device *, int);
static struct net_device_stats *ptm_get_stats(struct net_device *);
static int ptm_open(struct net_device *);
static int ptm_stop(struct net_device *);
static unsigned int ptm_poll(int, unsigned int);
static int ptm_napi_poll(struct napi_struct *, int);
static int ptm_hard_start_xmit(struct sk_buff *, struct net_device *);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(4,10,0))
static int ptm_change_mtu(struct net_device *, int);
#endif
static int ptm_ioctl(struct net_device *, struct ifreq *, int);
static void ptm_tx_timeout(struct net_device *);
static inline struct sk_buff* alloc_skb_rx(void);
static inline struct sk_buff* alloc_skb_tx(unsigned int);
static inline struct sk_buff *get_skb_pointer(unsigned int);
static inline int get_tx_desc(unsigned int, unsigned int *);
/*
* Mailbox handler and signal function
*/
static irqreturn_t mailbox_irq_handler(int, void *);
/*
* Tasklet to Handle Swap Descriptors
*/
static void do_swap_desc_tasklet(unsigned long);
/*
* Init & clean-up functions
*/
static inline int init_priv_data(void);
static inline void clear_priv_data(void);
static inline int init_tables(void);
static inline void clear_tables(void);
static int g_wanqos_en = 0;
static int g_queue_gamma_map[4];
static struct ptm_priv_data g_ptm_priv_data;
static struct net_device_ops g_ptm_netdev_ops = {
.ndo_get_stats = ptm_get_stats,
.ndo_open = ptm_open,
.ndo_stop = ptm_stop,
.ndo_start_xmit = ptm_hard_start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
#if (LINUX_VERSION_CODE < KERNEL_VERSION(4,10,0))
.ndo_change_mtu = ptm_change_mtu,
#endif
.ndo_do_ioctl = ptm_ioctl,
.ndo_tx_timeout = ptm_tx_timeout,
};
static struct net_device *g_net_dev[1] = {0};
static char *g_net_dev_name[1] = {"dsl0"};
static int g_ptm_prio_queue_map[8];
static DECLARE_TASKLET(g_swap_desc_tasklet, do_swap_desc_tasklet, 0);
unsigned int ifx_ptm_dbg_enable = DBG_ENABLE_MASK_ERR;
/*
* ####################################
* Local Function
* ####################################
*/
static void ptm_setup(struct net_device *dev, int ndev)
{
netif_carrier_off(dev);
dev->netdev_ops = &g_ptm_netdev_ops;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4,10,0))
/* Allow up to 1508 bytes, for RFC4638 */
dev->max_mtu = ETH_DATA_LEN + 8;
#endif
netif_napi_add(dev, &g_ptm_priv_data.itf[ndev].napi, ptm_napi_poll, 16);
dev->watchdog_timeo = ETH_WATCHDOG_TIMEOUT;
dev->dev_addr[0] = 0x00;
dev->dev_addr[1] = 0x20;
dev->dev_addr[2] = 0xda;
dev->dev_addr[3] = 0x86;
dev->dev_addr[4] = 0x23;
dev->dev_addr[5] = 0x75 + ndev;
}
static struct net_device_stats *ptm_get_stats(struct net_device *dev)
{
struct net_device_stats *s;
if ( dev != g_net_dev[0] )
return NULL;
s = &g_ptm_priv_data.itf[0].stats;
return s;
}
static int ptm_open(struct net_device *dev)
{
ASSERT(dev == g_net_dev[0], "incorrect device");
napi_enable(&g_ptm_priv_data.itf[0].napi);
IFX_REG_W32_MASK(0, 1, MBOX_IGU1_IER);
netif_start_queue(dev);
return 0;
}
static int ptm_stop(struct net_device *dev)
{
ASSERT(dev == g_net_dev[0], "incorrect device");
IFX_REG_W32_MASK(1 | (1 << 17), 0, MBOX_IGU1_IER);
napi_disable(&g_ptm_priv_data.itf[0].napi);
netif_stop_queue(dev);
return 0;
}
static unsigned int ptm_poll(int ndev, unsigned int work_to_do)
{
unsigned int work_done = 0;
volatile struct rx_descriptor *desc;
struct rx_descriptor reg_desc;
struct sk_buff *skb, *new_skb;
ASSERT(ndev >= 0 && ndev < ARRAY_SIZE(g_net_dev), "ndev = %d (wrong value)", ndev);
while ( work_done < work_to_do ) {
desc = &WAN_RX_DESC_BASE[g_ptm_priv_data.itf[0].rx_desc_pos];
if ( desc->own /* || !desc->c */ ) // if PP32 hold descriptor or descriptor not completed
break;
if ( ++g_ptm_priv_data.itf[0].rx_desc_pos == WAN_RX_DESC_NUM )
g_ptm_priv_data.itf[0].rx_desc_pos = 0;
reg_desc = *desc;
skb = get_skb_pointer(reg_desc.dataptr);
ASSERT(skb != NULL, "invalid pointer skb == NULL");
new_skb = alloc_skb_rx();
if ( new_skb != NULL ) {
skb_reserve(skb, reg_desc.byteoff);
skb_put(skb, reg_desc.datalen);
// parse protocol header
skb->dev = g_net_dev[0];
skb->protocol = eth_type_trans(skb, skb->dev);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(4,11,0))
g_net_dev[0]->last_rx = jiffies;
#endif
netif_receive_skb(skb);
g_ptm_priv_data.itf[0].stats.rx_packets++;
g_ptm_priv_data.itf[0].stats.rx_bytes += reg_desc.datalen;
reg_desc.dataptr = (unsigned int)new_skb->data & 0x0FFFFFFF;
reg_desc.byteoff = RX_HEAD_MAC_ADDR_ALIGNMENT;
}
reg_desc.datalen = RX_MAX_BUFFER_SIZE - RX_HEAD_MAC_ADDR_ALIGNMENT;
reg_desc.own = 1;
reg_desc.c = 0;
/* write discriptor to memory */
*((volatile unsigned int *)desc + 1) = *((unsigned int *)®_desc + 1);
wmb();
*(volatile unsigned int *)desc = *(unsigned int *)®_desc;
work_done++;
}
return work_done;
}
static int ptm_napi_poll(struct napi_struct *napi, int budget)
{
int ndev = 0;
unsigned int work_done;
work_done = ptm_poll(ndev, budget);
// interface down
if ( !netif_running(napi->dev) ) {
napi_complete(napi);
return work_done;
}
// clear interrupt
IFX_REG_W32_MASK(0, 1, MBOX_IGU1_ISRC);
// no more traffic
if (work_done < budget) {
napi_complete(napi);
IFX_REG_W32_MASK(0, 1, MBOX_IGU1_IER);
return work_done;
}
// next round
return work_done;
}
static int ptm_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
unsigned int f_full;
int desc_base;
volatile struct tx_descriptor *desc;
struct tx_descriptor reg_desc = {0};
struct sk_buff *skb_to_free;
unsigned int byteoff;
ASSERT(dev == g_net_dev[0], "incorrect device");
if ( !g_showtime ) {
err("not in showtime");
goto PTM_HARD_START_XMIT_FAIL;
}
/* allocate descriptor */
desc_base = get_tx_desc(0, &f_full);
if ( f_full ) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,7,0)
netif_trans_update(dev);
#else
dev->trans_start = jiffies;
#endif
netif_stop_queue(dev);
IFX_REG_W32_MASK(0, 1 << 17, MBOX_IGU1_ISRC);
IFX_REG_W32_MASK(0, 1 << 17, MBOX_IGU1_IER);
}
if ( desc_base < 0 )
goto PTM_HARD_START_XMIT_FAIL;
desc = &CPU_TO_WAN_TX_DESC_BASE[desc_base];
byteoff = (unsigned int)skb->data & (DATA_BUFFER_ALIGNMENT - 1);
if ( skb_headroom(skb) < sizeof(struct sk_buff *) + byteoff || skb_cloned(skb) ) {
struct sk_buff *new_skb;
ASSERT(skb_headroom(skb) >= sizeof(struct sk_buff *) + byteoff, "skb_headroom(skb) < sizeof(struct sk_buff *) + byteoff");
ASSERT(!skb_cloned(skb), "skb is cloned");
new_skb = alloc_skb_tx(skb->len);
if ( new_skb == NULL ) {
dbg("no memory");
goto ALLOC_SKB_TX_FAIL;
}
skb_put(new_skb, skb->len);
memcpy(new_skb->data, skb->data, skb->len);
dev_kfree_skb_any(skb);
skb = new_skb;
byteoff = (unsigned int)skb->data & (DATA_BUFFER_ALIGNMENT - 1);
/* write back to physical memory */
dma_cache_wback((unsigned long)skb->data, skb->len);
}
*(struct sk_buff **)((unsigned int)skb->data - byteoff - sizeof(struct sk_buff *)) = skb;
/* write back to physical memory */
dma_cache_wback((unsigned long)skb->data - byteoff - sizeof(struct sk_buff *), skb->len + byteoff + sizeof(struct sk_buff *));
/* free previous skb */
skb_to_free = get_skb_pointer(desc->dataptr);
if ( skb_to_free != NULL )
dev_kfree_skb_any(skb_to_free);
/* update descriptor */
reg_desc.small = 0;
reg_desc.dataptr = (unsigned int)skb->data & (0x0FFFFFFF ^ (DATA_BUFFER_ALIGNMENT - 1));
reg_desc.datalen = skb->len < ETH_ZLEN ? ETH_ZLEN : skb->len;
reg_desc.qid = g_ptm_prio_queue_map[skb->priority > 7 ? 7 : skb->priority];
reg_desc.byteoff = byteoff;
reg_desc.own = 1;
reg_desc.c = 1;
reg_desc.sop = reg_desc.eop = 1;
/* update MIB */
g_ptm_priv_data.itf[0].stats.tx_packets++;
g_ptm_priv_data.itf[0].stats.tx_bytes += reg_desc.datalen;
/* write discriptor to memory */
*((volatile unsigned int *)desc + 1) = *((unsigned int *)®_desc + 1);
wmb();
*(volatile unsigned int *)desc = *(unsigned int *)®_desc;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,7,0)
netif_trans_update(dev);
#else
dev->trans_start = jiffies;
#endif
return 0;
ALLOC_SKB_TX_FAIL:
PTM_HARD_START_XMIT_FAIL:
dev_kfree_skb_any(skb);
g_ptm_priv_data.itf[0].stats.tx_dropped++;
return 0;
}
#if (LINUX_VERSION_CODE < KERNEL_VERSION(4,10,0))
static int ptm_change_mtu(struct net_device *dev, int mtu)
{
/* Allow up to 1508 bytes, for RFC4638 */
if (mtu < 68 || mtu > ETH_DATA_LEN + 8)
return -EINVAL;
dev->mtu = mtu;
return 0;
}
#endif
static int ptm_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
ASSERT(dev == g_net_dev[0], "incorrect device");
switch ( cmd )
{
case IFX_PTM_MIB_CW_GET:
((PTM_CW_IF_ENTRY_T *)ifr->ifr_data)->ifRxNoIdleCodewords = IFX_REG_R32(DREG_AR_CELL0) + IFX_REG_R32(DREG_AR_CELL1);
((PTM_CW_IF_ENTRY_T *)ifr->ifr_data)->ifRxIdleCodewords = IFX_REG_R32(DREG_AR_IDLE_CNT0) + IFX_REG_R32(DREG_AR_IDLE_CNT1);
((PTM_CW_IF_ENTRY_T *)ifr->ifr_data)->ifRxCodingViolation = IFX_REG_R32(DREG_AR_CVN_CNT0) + IFX_REG_R32(DREG_AR_CVN_CNT1) + IFX_REG_R32(DREG_AR_CVNP_CNT0) + IFX_REG_R32(DREG_AR_CVNP_CNT1);
((PTM_CW_IF_ENTRY_T *)ifr->ifr_data)->ifTxNoIdleCodewords = IFX_REG_R32(DREG_AT_CELL0) + IFX_REG_R32(DREG_AT_CELL1);
((PTM_CW_IF_ENTRY_T *)ifr->ifr_data)->ifTxIdleCodewords = IFX_REG_R32(DREG_AT_IDLE_CNT0) + IFX_REG_R32(DREG_AT_IDLE_CNT1);
break;
case IFX_PTM_MIB_FRAME_GET:
{
PTM_FRAME_MIB_T data = {0};
int i;
data.RxCorrect = IFX_REG_R32(DREG_AR_HEC_CNT0) + IFX_REG_R32(DREG_AR_HEC_CNT1) + IFX_REG_R32(DREG_AR_AIIDLE_CNT0) + IFX_REG_R32(DREG_AR_AIIDLE_CNT1);
for ( i = 0; i < 4; i++ )
data.RxDropped += WAN_RX_MIB_TABLE(i)->wrx_dropdes_pdu;
for ( i = 0; i < 8; i++ )
data.TxSend += WAN_TX_MIB_TABLE(i)->wtx_total_pdu;
*((PTM_FRAME_MIB_T *)ifr->ifr_data) = data;
}
break;
case IFX_PTM_CFG_GET:
// use bear channel 0 preemption gamma interface settings
((IFX_PTM_CFG_T *)ifr->ifr_data)->RxEthCrcPresent = 1;
((IFX_PTM_CFG_T *)ifr->ifr_data)->RxEthCrcCheck = RX_GAMMA_ITF_CFG(0)->rx_eth_fcs_ver_dis == 0 ? 1 : 0;
((IFX_PTM_CFG_T *)ifr->ifr_data)->RxTcCrcCheck = RX_GAMMA_ITF_CFG(0)->rx_tc_crc_ver_dis == 0 ? 1 : 0;;
((IFX_PTM_CFG_T *)ifr->ifr_data)->RxTcCrcLen = RX_GAMMA_ITF_CFG(0)->rx_tc_crc_size == 0 ? 0 : (RX_GAMMA_ITF_CFG(0)->rx_tc_crc_size * 16);
((IFX_PTM_CFG_T *)ifr->ifr_data)->TxEthCrcGen = TX_GAMMA_ITF_CFG(0)->tx_eth_fcs_gen_dis == 0 ? 1 : 0;
((IFX_PTM_CFG_T *)ifr->ifr_data)->TxTcCrcGen = TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size == 0 ? 0 : 1;
((IFX_PTM_CFG_T *)ifr->ifr_data)->TxTcCrcLen = TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size == 0 ? 0 : (TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size * 16);
break;
case IFX_PTM_CFG_SET:
{
int i;
for ( i = 0; i < 4; i++ ) {
RX_GAMMA_ITF_CFG(i)->rx_eth_fcs_ver_dis = ((IFX_PTM_CFG_T *)ifr->ifr_data)->RxEthCrcCheck ? 0 : 1;
RX_GAMMA_ITF_CFG(0)->rx_tc_crc_ver_dis = ((IFX_PTM_CFG_T *)ifr->ifr_data)->RxTcCrcCheck ? 0 : 1;
switch ( ((IFX_PTM_CFG_T *)ifr->ifr_data)->RxTcCrcLen ) {
case 16: RX_GAMMA_ITF_CFG(0)->rx_tc_crc_size = 1; break;
case 32: RX_GAMMA_ITF_CFG(0)->rx_tc_crc_size = 2; break;
default: RX_GAMMA_ITF_CFG(0)->rx_tc_crc_size = 0;
}
TX_GAMMA_ITF_CFG(0)->tx_eth_fcs_gen_dis = ((IFX_PTM_CFG_T *)ifr->ifr_data)->TxEthCrcGen ? 0 : 1;
if ( ((IFX_PTM_CFG_T *)ifr->ifr_data)->TxTcCrcGen ) {
switch ( ((IFX_PTM_CFG_T *)ifr->ifr_data)->TxTcCrcLen ) {
case 16: TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size = 1; break;
case 32: TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size = 2; break;
default: TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size = 0;
}
}
else
TX_GAMMA_ITF_CFG(0)->tx_tc_crc_size = 0;
}
}
break;
case IFX_PTM_MAP_PKT_PRIO_TO_Q:
{
struct ppe_prio_q_map cmd;
if ( copy_from_user(&cmd, ifr->ifr_data, sizeof(cmd)) )
return -EFAULT;
if ( cmd.pkt_prio < 0 || cmd.pkt_prio >= ARRAY_SIZE(g_ptm_prio_queue_map) )
return -EINVAL;
if ( cmd.qid < 0 || cmd.qid >= g_wanqos_en )
return -EINVAL;
g_ptm_prio_queue_map[cmd.pkt_prio] = cmd.qid;
}
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static void ptm_tx_timeout(struct net_device *dev)
{
ASSERT(dev == g_net_dev[0], "incorrect device");
/* disable TX irq, release skb when sending new packet */
IFX_REG_W32_MASK(1 << 17, 0, MBOX_IGU1_IER);
/* wake up TX queue */
netif_wake_queue(dev);
return;
}
static inline struct sk_buff* alloc_skb_rx(void)
{
struct sk_buff *skb;
/* allocate memroy including trailer and padding */
skb = dev_alloc_skb(RX_MAX_BUFFER_SIZE + DATA_BUFFER_ALIGNMENT);
if ( skb != NULL ) {
/* must be burst length alignment and reserve two more bytes for MAC address alignment */
if ( ((unsigned int)skb->data & (DATA_BUFFER_ALIGNMENT - 1)) != 0 )
skb_reserve(skb, ~((unsigned int)skb->data + (DATA_BUFFER_ALIGNMENT - 1)) & (DATA_BUFFER_ALIGNMENT - 1));
/* pub skb in reserved area "skb->data - 4" */
*((struct sk_buff **)skb->data - 1) = skb;
wmb();
/* write back and invalidate cache */
dma_cache_wback_inv((unsigned long)skb->data - sizeof(skb), sizeof(skb));
/* invalidate cache */
dma_cache_inv((unsigned long)skb->data, (unsigned int)skb->end - (unsigned int)skb->data);
}
return skb;
}
static inline struct sk_buff* alloc_skb_tx(unsigned int size)
{
struct sk_buff *skb;
/* allocate memory including padding */
size = RX_MAX_BUFFER_SIZE;
size = (size + DATA_BUFFER_ALIGNMENT - 1) & ~(DATA_BUFFER_ALIGNMENT - 1);
skb = dev_alloc_skb(size + DATA_BUFFER_ALIGNMENT);
/* must be burst length alignment */
if ( skb != NULL )
skb_reserve(skb, ~((unsigned int)skb->data + (DATA_BUFFER_ALIGNMENT - 1)) & (DATA_BUFFER_ALIGNMENT - 1));
return skb;
}
static inline struct sk_buff *get_skb_pointer(unsigned int dataptr)
{
unsigned int skb_dataptr;
struct sk_buff *skb;
// usually, CPE memory is less than 256M bytes
// so NULL means invalid pointer
if ( dataptr == 0 ) {
dbg("dataptr is 0, it's supposed to be invalid pointer");
return NULL;
}
skb_dataptr = (dataptr - 4) | KSEG1;
skb = *(struct sk_buff **)skb_dataptr;
ASSERT((unsigned int)skb >= KSEG0, "invalid skb - skb = %#08x, dataptr = %#08x", (unsigned int)skb, dataptr);
ASSERT((((unsigned int)skb->data & (0x0FFFFFFF ^ (DATA_BUFFER_ALIGNMENT - 1))) | KSEG1) == (dataptr | KSEG1), "invalid skb - skb = %#08x, skb->data = %#08x, dataptr = %#08x", (unsigned int)skb, (unsigned int)skb->data, dataptr);
return skb;
}
static inline int get_tx_desc(unsigned int itf, unsigned int *f_full)
{
int desc_base = -1;
struct ptm_itf *p_itf = &g_ptm_priv_data.itf[0];
// assume TX is serial operation
// no protection provided
*f_full = 1;
if ( CPU_TO_WAN_TX_DESC_BASE[p_itf->tx_desc_pos].own == 0 ) {
desc_base = p_itf->tx_desc_pos;
if ( ++(p_itf->tx_desc_pos) == CPU_TO_WAN_TX_DESC_NUM )
p_itf->tx_desc_pos = 0;
if ( CPU_TO_WAN_TX_DESC_BASE[p_itf->tx_desc_pos].own == 0 )
*f_full = 0;
}
return desc_base;
}
static irqreturn_t mailbox_irq_handler(int irq, void *dev_id)
{
unsigned int isr;
int i;
isr = IFX_REG_R32(MBOX_IGU1_ISR);
IFX_REG_W32(isr, MBOX_IGU1_ISRC);
isr &= IFX_REG_R32(MBOX_IGU1_IER);
if (isr & BIT(0)) {
IFX_REG_W32_MASK(1, 0, MBOX_IGU1_IER);
napi_schedule(&g_ptm_priv_data.itf[0].napi);
#if defined(ENABLE_TMP_DBG) && ENABLE_TMP_DBG
{
volatile struct rx_descriptor *desc = &WAN_RX_DESC_BASE[g_ptm_priv_data.itf[0].rx_desc_pos];
if ( desc->own ) { // PP32 hold
err("invalid interrupt");
}
}
#endif
}
if (isr & BIT(16)) {
IFX_REG_W32_MASK(1 << 16, 0, MBOX_IGU1_IER);
tasklet_hi_schedule(&g_swap_desc_tasklet);
}
if (isr & BIT(17)) {
IFX_REG_W32_MASK(1 << 17, 0, MBOX_IGU1_IER);
netif_wake_queue(g_net_dev[0]);
}
return IRQ_HANDLED;
}
static void do_swap_desc_tasklet(unsigned long arg)
{
int budget = 32;
volatile struct tx_descriptor *desc;
struct sk_buff *skb;
unsigned int byteoff;
while ( budget-- > 0 ) {
if ( WAN_SWAP_DESC_BASE[g_ptm_priv_data.itf[0].tx_swap_desc_pos].own ) // if PP32 hold descriptor
break;
desc = &WAN_SWAP_DESC_BASE[g_ptm_priv_data.itf[0].tx_swap_desc_pos];
if ( ++g_ptm_priv_data.itf[0].tx_swap_desc_pos == WAN_SWAP_DESC_NUM )
g_ptm_priv_data.itf[0].tx_swap_desc_pos = 0;
skb = get_skb_pointer(desc->dataptr);
if ( skb != NULL )
dev_kfree_skb_any(skb);
skb = alloc_skb_tx(RX_MAX_BUFFER_SIZE);
if ( skb == NULL )
panic("can't allocate swap buffer for PPE firmware use\n");
byteoff = (unsigned int)skb->data & (DATA_BUFFER_ALIGNMENT - 1);
*(struct sk_buff **)((unsigned int)skb->data - byteoff - sizeof(struct sk_buff *)) = skb;
desc->dataptr = (unsigned int)skb->data & 0x0FFFFFFF;
desc->own = 1;
}
// clear interrupt
IFX_REG_W32_MASK(0, 16, MBOX_IGU1_ISRC);
// no more skb to be replaced
if ( WAN_SWAP_DESC_BASE[g_ptm_priv_data.itf[0].tx_swap_desc_pos].own ) { // if PP32 hold descriptor
IFX_REG_W32_MASK(0, 1 << 16, MBOX_IGU1_IER);
return;
}
tasklet_hi_schedule(&g_swap_desc_tasklet);
return;
}
static inline int ifx_ptm_version(char *buf)
{
int len = 0;
unsigned int major, minor;
ifx_ptm_get_fw_ver(&major, &minor);
len += sprintf(buf + len, "PTM %d.%d.%d", IFX_PTM_VER_MAJOR, IFX_PTM_VER_MID, IFX_PTM_VER_MINOR);
len += sprintf(buf + len, " PTM (E1) firmware version %d.%d\n", major, minor);
return len;
}
static inline int init_priv_data(void)
{
int i, j;
g_wanqos_en = wanqos_en ? wanqos_en : 8;
if ( g_wanqos_en > 8 )
g_wanqos_en = 8;
for ( i = 0; i < ARRAY_SIZE(g_queue_gamma_map); i++ )
{
g_queue_gamma_map[i] = queue_gamma_map[i] & ((1 << g_wanqos_en) - 1);
for ( j = 0; j < i; j++ )
g_queue_gamma_map[i] &= ~g_queue_gamma_map[j];
}
memset(&g_ptm_priv_data, 0, sizeof(g_ptm_priv_data));
{
int max_packet_priority = ARRAY_SIZE(g_ptm_prio_queue_map);
int tx_num_q;
int q_step, q_accum, p_step;
tx_num_q = __ETH_WAN_TX_QUEUE_NUM;
q_step = tx_num_q - 1;
p_step = max_packet_priority - 1;
for ( j = 0, q_accum = 0; j < max_packet_priority; j++, q_accum += q_step )
g_ptm_prio_queue_map[j] = q_step - (q_accum + (p_step >> 1)) / p_step;
}
return 0;
}
static inline void clear_priv_data(void)
{
}
static inline int init_tables(void)
{
struct sk_buff *skb_pool[WAN_RX_DESC_NUM] = {0};
struct cfg_std_data_len cfg_std_data_len = {0};
struct tx_qos_cfg tx_qos_cfg = {0};
struct psave_cfg psave_cfg = {0};
struct eg_bwctrl_cfg eg_bwctrl_cfg = {0};
struct test_mode test_mode = {0};
struct rx_bc_cfg rx_bc_cfg = {0};
struct tx_bc_cfg tx_bc_cfg = {0};
struct gpio_mode gpio_mode = {0};
struct gpio_wm_cfg gpio_wm_cfg = {0};
struct rx_gamma_itf_cfg rx_gamma_itf_cfg = {0};
struct tx_gamma_itf_cfg tx_gamma_itf_cfg = {0};
struct wtx_qos_q_desc_cfg wtx_qos_q_desc_cfg = {0};
struct rx_descriptor rx_desc = {0};
struct tx_descriptor tx_desc = {0};
int i;
for ( i = 0; i < WAN_RX_DESC_NUM; i++ ) {
skb_pool[i] = alloc_skb_rx();
if ( skb_pool[i] == NULL )
goto ALLOC_SKB_RX_FAIL;
}
cfg_std_data_len.byte_off = RX_HEAD_MAC_ADDR_ALIGNMENT; // this field replaces byte_off in rx descriptor of VDSL ingress
cfg_std_data_len.data_len = 1600;
*CFG_STD_DATA_LEN = cfg_std_data_len;
tx_qos_cfg.time_tick = cgu_get_pp32_clock() / 62500; // 16 * (cgu_get_pp32_clock() / 1000000)
tx_qos_cfg.overhd_bytes = 0;
tx_qos_cfg.eth1_eg_qnum = __ETH_WAN_TX_QUEUE_NUM;
tx_qos_cfg.eth1_burst_chk = 1;
tx_qos_cfg.eth1_qss = 0;
tx_qos_cfg.shape_en = 0; // disable
tx_qos_cfg.wfq_en = 0; // strict priority
*TX_QOS_CFG = tx_qos_cfg;
psave_cfg.start_state = 0;
psave_cfg.sleep_en = 1; // enable sleep mode
*PSAVE_CFG = psave_cfg;
eg_bwctrl_cfg.fdesc_wm = 16;
eg_bwctrl_cfg.class_len = 128;
*EG_BWCTRL_CFG = eg_bwctrl_cfg;
//*GPIO_ADDR = (unsigned int)IFX_GPIO_P0_OUT;
*GPIO_ADDR = (unsigned int)0x00000000; // disabled by default
gpio_mode.gpio_bit_bc1 = 2;
gpio_mode.gpio_bit_bc0 = 1;
gpio_mode.gpio_bc1_en = 0;
gpio_mode.gpio_bc0_en = 0;
*GPIO_MODE = gpio_mode;
gpio_wm_cfg.stop_wm_bc1 = 2;
gpio_wm_cfg.start_wm_bc1 = 4;
gpio_wm_cfg.stop_wm_bc0 = 2;
gpio_wm_cfg.start_wm_bc0 = 4;
*GPIO_WM_CFG = gpio_wm_cfg;
test_mode.mib_clear_mode = 0;
test_mode.test_mode = 0;
*TEST_MODE = test_mode;
rx_bc_cfg.local_state = 0;
rx_bc_cfg.remote_state = 0;
rx_bc_cfg.to_false_th = 7;
rx_bc_cfg.to_looking_th = 3;
*RX_BC_CFG(0) = rx_bc_cfg;
*RX_BC_CFG(1) = rx_bc_cfg;
tx_bc_cfg.fill_wm = 2;
tx_bc_cfg.uflw_wm = 2;
*TX_BC_CFG(0) = tx_bc_cfg;
*TX_BC_CFG(1) = tx_bc_cfg;
rx_gamma_itf_cfg.receive_state = 0;
rx_gamma_itf_cfg.rx_min_len = 60;
rx_gamma_itf_cfg.rx_pad_en = 1;
rx_gamma_itf_cfg.rx_eth_fcs_ver_dis = 0;
rx_gamma_itf_cfg.rx_rm_eth_fcs = 1;
rx_gamma_itf_cfg.rx_tc_crc_ver_dis = 0;
rx_gamma_itf_cfg.rx_tc_crc_size = 1;
rx_gamma_itf_cfg.rx_eth_fcs_result = 0xC704DD7B;
rx_gamma_itf_cfg.rx_tc_crc_result = 0x1D0F1D0F;
rx_gamma_itf_cfg.rx_crc_cfg = 0x2500;
rx_gamma_itf_cfg.rx_eth_fcs_init_value = 0xFFFFFFFF;
rx_gamma_itf_cfg.rx_tc_crc_init_value = 0x0000FFFF;
rx_gamma_itf_cfg.rx_max_len_sel = 0;
rx_gamma_itf_cfg.rx_edit_num2 = 0;
rx_gamma_itf_cfg.rx_edit_pos2 = 0;
rx_gamma_itf_cfg.rx_edit_type2 = 0;
rx_gamma_itf_cfg.rx_edit_en2 = 0;
rx_gamma_itf_cfg.rx_edit_num1 = 0;
rx_gamma_itf_cfg.rx_edit_pos1 = 0;
rx_gamma_itf_cfg.rx_edit_type1 = 0;
rx_gamma_itf_cfg.rx_edit_en1 = 0;
rx_gamma_itf_cfg.rx_inserted_bytes_1l = 0;
rx_gamma_itf_cfg.rx_inserted_bytes_1h = 0;
rx_gamma_itf_cfg.rx_inserted_bytes_2l = 0;
rx_gamma_itf_cfg.rx_inserted_bytes_2h = 0;
rx_gamma_itf_cfg.rx_len_adj = -6;
for ( i = 0; i < 4; i++ )
*RX_GAMMA_ITF_CFG(i) = rx_gamma_itf_cfg;
tx_gamma_itf_cfg.tx_len_adj = 6;
tx_gamma_itf_cfg.tx_crc_off_adj = 6;
tx_gamma_itf_cfg.tx_min_len = 0;
tx_gamma_itf_cfg.tx_eth_fcs_gen_dis = 0;
tx_gamma_itf_cfg.tx_tc_crc_size = 1;
tx_gamma_itf_cfg.tx_crc_cfg = 0x2F00;
tx_gamma_itf_cfg.tx_eth_fcs_init_value = 0xFFFFFFFF;
tx_gamma_itf_cfg.tx_tc_crc_init_value = 0x0000FFFF;
for ( i = 0; i < ARRAY_SIZE(g_queue_gamma_map); i++ ) {
tx_gamma_itf_cfg.queue_mapping = g_queue_gamma_map[i];
*TX_GAMMA_ITF_CFG(i) = tx_gamma_itf_cfg;
}
for ( i = 0; i < __ETH_WAN_TX_QUEUE_NUM; i++ ) {
wtx_qos_q_desc_cfg.length = WAN_TX_DESC_NUM;
wtx_qos_q_desc_cfg.addr = __ETH_WAN_TX_DESC_BASE(i);
*WTX_QOS_Q_DESC_CFG(i) = wtx_qos_q_desc_cfg;
}
// default TX queue QoS config is all ZERO
// TX Ctrl K Table
IFX_REG_W32(0x90111293, TX_CTRL_K_TABLE(0));
IFX_REG_W32(0x14959617, TX_CTRL_K_TABLE(1));
IFX_REG_W32(0x18999A1B, TX_CTRL_K_TABLE(2));
IFX_REG_W32(0x9C1D1E9F, TX_CTRL_K_TABLE(3));
IFX_REG_W32(0xA02122A3, TX_CTRL_K_TABLE(4));
IFX_REG_W32(0x24A5A627, TX_CTRL_K_TABLE(5));
IFX_REG_W32(0x28A9AA2B, TX_CTRL_K_TABLE(6));
IFX_REG_W32(0xAC2D2EAF, TX_CTRL_K_TABLE(7));
IFX_REG_W32(0x30B1B233, TX_CTRL_K_TABLE(8));
IFX_REG_W32(0xB43536B7, TX_CTRL_K_TABLE(9));
IFX_REG_W32(0xB8393ABB, TX_CTRL_K_TABLE(10));
IFX_REG_W32(0x3CBDBE3F, TX_CTRL_K_TABLE(11));
IFX_REG_W32(0xC04142C3, TX_CTRL_K_TABLE(12));
IFX_REG_W32(0x44C5C647, TX_CTRL_K_TABLE(13));
IFX_REG_W32(0x48C9CA4B, TX_CTRL_K_TABLE(14));
IFX_REG_W32(0xCC4D4ECF, TX_CTRL_K_TABLE(15));
// init RX descriptor
rx_desc.own = 1;
rx_desc.c = 0;
rx_desc.sop = 1;
rx_desc.eop = 1;
rx_desc.byteoff = RX_HEAD_MAC_ADDR_ALIGNMENT;
rx_desc.datalen = RX_MAX_BUFFER_SIZE - RX_HEAD_MAC_ADDR_ALIGNMENT;
for ( i = 0; i < WAN_RX_DESC_NUM; i++ ) {
rx_desc.dataptr = (unsigned int)skb_pool[i]->data & 0x0FFFFFFF;
WAN_RX_DESC_BASE[i] = rx_desc;
}
// init TX descriptor
tx_desc.own = 0;
tx_desc.c = 0;
tx_desc.sop = 1;
tx_desc.eop = 1;
tx_desc.byteoff = 0;
tx_desc.qid = 0;
tx_desc.datalen = 0;
tx_desc.small = 0;
tx_desc.dataptr = 0;
for ( i = 0; i < CPU_TO_WAN_TX_DESC_NUM; i++ )
CPU_TO_WAN_TX_DESC_BASE[i] = tx_desc;
for ( i = 0; i < WAN_TX_DESC_NUM_TOTAL; i++ )
WAN_TX_DESC_BASE(0)[i] = tx_desc;
// init Swap descriptor
for ( i = 0; i < WAN_SWAP_DESC_NUM; i++ )
WAN_SWAP_DESC_BASE[i] = tx_desc;
// init fastpath TX descriptor
tx_desc.own = 1;
for ( i = 0; i < FASTPATH_TO_WAN_TX_DESC_NUM; i++ )
FASTPATH_TO_WAN_TX_DESC_BASE[i] = tx_desc;
return 0;
ALLOC_SKB_RX_FAIL:
while ( i-- > 0 )
dev_kfree_skb_any(skb_pool[i]);
return -1;
}
static inline void clear_tables(void)
{
struct sk_buff *skb;
int i, j;
for ( i = 0; i < WAN_RX_DESC_NUM; i++ ) {
skb = get_skb_pointer(WAN_RX_DESC_BASE[i].dataptr);
if ( skb != NULL )
dev_kfree_skb_any(skb);
}
for ( i = 0; i < CPU_TO_WAN_TX_DESC_NUM; i++ ) {
skb = get_skb_pointer(CPU_TO_WAN_TX_DESC_BASE[i].dataptr);
if ( skb != NULL )
dev_kfree_skb_any(skb);
}
for ( j = 0; j < 8; j++ )
for ( i = 0; i < WAN_TX_DESC_NUM; i++ ) {
skb = get_skb_pointer(WAN_TX_DESC_BASE(j)[i].dataptr);
if ( skb != NULL )
dev_kfree_skb_any(skb);
}
for ( i = 0; i < WAN_SWAP_DESC_NUM; i++ ) {
skb = get_skb_pointer(WAN_SWAP_DESC_BASE[i].dataptr);
if ( skb != NULL )
dev_kfree_skb_any(skb);
}
for ( i = 0; i < FASTPATH_TO_WAN_TX_DESC_NUM; i++ ) {
skb = get_skb_pointer(FASTPATH_TO_WAN_TX_DESC_BASE[i].dataptr);
if ( skb != NULL )
dev_kfree_skb_any(skb);
}
}
static int ptm_showtime_enter(struct port_cell_info *port_cell, void *xdata_addr)
{
int i;
ASSERT(port_cell != NULL, "port_cell is NULL");
ASSERT(xdata_addr != NULL, "xdata_addr is NULL");
// TODO: ReTX set xdata_addr
g_xdata_addr = xdata_addr;
g_showtime = 1;
for ( i = 0; i < ARRAY_SIZE(g_net_dev); i++ )
netif_carrier_on(g_net_dev[i]);
IFX_REG_W32(0x0F, UTP_CFG);
//#ifdef CONFIG_VR9
// IFX_REG_W32_MASK(1 << 17, 0, FFSM_CFG0);
//#endif
printk("enter showtime\n");
return 0;
}
static int ptm_showtime_exit(void)
{
int i;
if ( !g_showtime )
return -1;
//#ifdef CONFIG_VR9
// IFX_REG_W32_MASK(0, 1 << 17, FFSM_CFG0);
//#endif
IFX_REG_W32(0x00, UTP_CFG);
for ( i = 0; i < ARRAY_SIZE(g_net_dev); i++ )
netif_carrier_off(g_net_dev[i]);
g_showtime = 0;
// TODO: ReTX clean state
g_xdata_addr = NULL;
printk("leave showtime\n");
return 0;
}
static int ifx_ptm_init(void)
{
int ret;
int i;
char ver_str[128];
struct port_cell_info port_cell = {0};
ret = init_priv_data();
if ( ret != 0 ) {
err("INIT_PRIV_DATA_FAIL");
goto INIT_PRIV_DATA_FAIL;
}
ifx_ptm_init_chip();
ret = init_tables();
if ( ret != 0 ) {
err("INIT_TABLES_FAIL");
goto INIT_TABLES_FAIL;
}
for ( i = 0; i < ARRAY_SIZE(g_net_dev); i++ ) {
g_net_dev[i] = alloc_netdev(0, g_net_dev_name[i], NET_NAME_UNKNOWN, ether_setup);
if ( g_net_dev[i] == NULL )
goto ALLOC_NETDEV_FAIL;
ptm_setup(g_net_dev[i], i);
}
for ( i = 0; i < ARRAY_SIZE(g_net_dev); i++ ) {
ret = register_netdev(g_net_dev[i]);
if ( ret != 0 )
goto REGISTER_NETDEV_FAIL;
}
/* register interrupt handler */
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,1,0)
ret = request_irq(PPE_MAILBOX_IGU1_INT, mailbox_irq_handler, 0, "ptm_mailbox_isr", &g_ptm_priv_data);
#else
ret = request_irq(PPE_MAILBOX_IGU1_INT, mailbox_irq_handler, IRQF_DISABLED, "ptm_mailbox_isr", &g_ptm_priv_data);
#endif
if ( ret ) {
if ( ret == -EBUSY ) {
err("IRQ may be occupied by other driver, please reconfig to disable it.");
}
else {
err("request_irq fail");
}
goto REQUEST_IRQ_PPE_MAILBOX_IGU1_INT_FAIL;
}
disable_irq(PPE_MAILBOX_IGU1_INT);
ret = ifx_pp32_start(0);
if ( ret ) {
err("ifx_pp32_start fail!");
goto PP32_START_FAIL;
}
IFX_REG_W32(1 << 16, MBOX_IGU1_IER); // enable SWAP interrupt
IFX_REG_W32(~0, MBOX_IGU1_ISRC);
enable_irq(PPE_MAILBOX_IGU1_INT);
ifx_mei_atm_showtime_check(&g_showtime, &port_cell, &g_xdata_addr);
if ( g_showtime ) {
ptm_showtime_enter(&port_cell, &g_xdata_addr);
}
ifx_mei_atm_showtime_enter = ptm_showtime_enter;
ifx_mei_atm_showtime_exit = ptm_showtime_exit;
ifx_ptm_version(ver_str);
printk(KERN_INFO "%s", ver_str);
printk("ifxmips_ptm: PTM init succeed\n");
return 0;
PP32_START_FAIL:
free_irq(PPE_MAILBOX_IGU1_INT, &g_ptm_priv_data);
REQUEST_IRQ_PPE_MAILBOX_IGU1_INT_FAIL:
i = ARRAY_SIZE(g_net_dev);
REGISTER_NETDEV_FAIL:
while ( i-- )
unregister_netdev(g_net_dev[i]);
i = ARRAY_SIZE(g_net_dev);
ALLOC_NETDEV_FAIL:
while ( i-- ) {
free_netdev(g_net_dev[i]);
g_net_dev[i] = NULL;
}
INIT_TABLES_FAIL:
INIT_PRIV_DATA_FAIL:
clear_priv_data();
printk("ifxmips_ptm: PTM init failed\n");
return ret;
}
static void __exit ifx_ptm_exit(void)
{
int i;
ifx_mei_atm_showtime_enter = NULL;
ifx_mei_atm_showtime_exit = NULL;
ifx_pp32_stop(0);
free_irq(PPE_MAILBOX_IGU1_INT, &g_ptm_priv_data);
for ( i = 0; i < ARRAY_SIZE(g_net_dev); i++ )
unregister_netdev(g_net_dev[i]);
for ( i = 0; i < ARRAY_SIZE(g_net_dev); i++ ) {
free_netdev(g_net_dev[i]);
g_net_dev[i] = NULL;
}
clear_tables();
ifx_ptm_uninit_chip();
clear_priv_data();
}
#ifndef MODULE
static int __init wanqos_en_setup(char *line)
{
wanqos_en = simple_strtoul(line, NULL, 0);
if ( wanqos_en < 1 || wanqos_en > 8 )
wanqos_en = 0;
return 0;
}
static int __init queue_gamma_map_setup(char *line)
{
char *p;
int i;
for ( i = 0, p = line; i < ARRAY_SIZE(queue_gamma_map) && isxdigit(*p); i++ )
{
queue_gamma_map[i] = simple_strtoul(p, &p, 0);
if ( *p == ',' || *p == ';' || *p == ':' )
p++;
}
return 0;
}
#endif
module_init(ifx_ptm_init);
module_exit(ifx_ptm_exit);
#ifndef MODULE
__setup("wanqos_en=", wanqos_en_setup);
__setup("queue_gamma_map=", queue_gamma_map_setup);
#endif
MODULE_LICENSE("GPL");
| gpl-2.0 |
CSE3320/kernel-code | linux-5.8/arch/arm/mach-davinci/dm365.c | 281 | 30826 | /*
* TI DaVinci DM365 chip specific setup
*
* Copyright (C) 2009 Texas Instruments
*
* 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.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk-provider.h>
#include <linux/clk/davinci.h>
#include <linux/clkdev.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/irqchip/irq-davinci-aintc.h>
#include <linux/platform_data/edma.h>
#include <linux/platform_data/gpio-davinci.h>
#include <linux/platform_data/keyscan-davinci.h>
#include <linux/platform_data/spi-davinci.h>
#include <linux/platform_device.h>
#include <linux/serial_8250.h>
#include <linux/spi/spi.h>
#include <asm/mach/map.h>
#include <mach/common.h>
#include <mach/cputype.h>
#include <mach/mux.h>
#include <mach/serial.h>
#include <clocksource/timer-davinci.h>
#include "asp.h"
#include "davinci.h"
#include "irqs.h"
#include "mux.h"
#define DM365_REF_FREQ 24000000 /* 24 MHz on the DM365 EVM */
#define DM365_RTC_BASE 0x01c69000
#define DM365_KEYSCAN_BASE 0x01c69400
#define DM365_OSD_BASE 0x01c71c00
#define DM365_VENC_BASE 0x01c71e00
#define DAVINCI_DM365_VC_BASE 0x01d0c000
#define DAVINCI_DMA_VC_TX 2
#define DAVINCI_DMA_VC_RX 3
#define DM365_EMAC_BASE 0x01d07000
#define DM365_EMAC_MDIO_BASE (DM365_EMAC_BASE + 0x4000)
#define DM365_EMAC_CNTRL_OFFSET 0x0000
#define DM365_EMAC_CNTRL_MOD_OFFSET 0x3000
#define DM365_EMAC_CNTRL_RAM_OFFSET 0x1000
#define DM365_EMAC_CNTRL_RAM_SIZE 0x2000
#define INTMUX 0x18
#define EVTMUX 0x1c
static const struct mux_config dm365_pins[] = {
#ifdef CONFIG_DAVINCI_MUX
MUX_CFG(DM365, MMCSD0, 0, 24, 1, 0, false)
MUX_CFG(DM365, SD1_CLK, 0, 16, 3, 1, false)
MUX_CFG(DM365, SD1_CMD, 4, 30, 3, 1, false)
MUX_CFG(DM365, SD1_DATA3, 4, 28, 3, 1, false)
MUX_CFG(DM365, SD1_DATA2, 4, 26, 3, 1, false)
MUX_CFG(DM365, SD1_DATA1, 4, 24, 3, 1, false)
MUX_CFG(DM365, SD1_DATA0, 4, 22, 3, 1, false)
MUX_CFG(DM365, I2C_SDA, 3, 23, 3, 2, false)
MUX_CFG(DM365, I2C_SCL, 3, 21, 3, 2, false)
MUX_CFG(DM365, AEMIF_AR_A14, 2, 0, 3, 1, false)
MUX_CFG(DM365, AEMIF_AR_BA0, 2, 0, 3, 2, false)
MUX_CFG(DM365, AEMIF_A3, 2, 2, 3, 1, false)
MUX_CFG(DM365, AEMIF_A7, 2, 4, 3, 1, false)
MUX_CFG(DM365, AEMIF_D15_8, 2, 6, 1, 1, false)
MUX_CFG(DM365, AEMIF_CE0, 2, 7, 1, 0, false)
MUX_CFG(DM365, AEMIF_CE1, 2, 8, 1, 0, false)
MUX_CFG(DM365, AEMIF_WE_OE, 2, 9, 1, 0, false)
MUX_CFG(DM365, MCBSP0_BDX, 0, 23, 1, 1, false)
MUX_CFG(DM365, MCBSP0_X, 0, 22, 1, 1, false)
MUX_CFG(DM365, MCBSP0_BFSX, 0, 21, 1, 1, false)
MUX_CFG(DM365, MCBSP0_BDR, 0, 20, 1, 1, false)
MUX_CFG(DM365, MCBSP0_R, 0, 19, 1, 1, false)
MUX_CFG(DM365, MCBSP0_BFSR, 0, 18, 1, 1, false)
MUX_CFG(DM365, SPI0_SCLK, 3, 28, 1, 1, false)
MUX_CFG(DM365, SPI0_SDI, 3, 26, 3, 1, false)
MUX_CFG(DM365, SPI0_SDO, 3, 25, 1, 1, false)
MUX_CFG(DM365, SPI0_SDENA0, 3, 29, 3, 1, false)
MUX_CFG(DM365, SPI0_SDENA1, 3, 26, 3, 2, false)
MUX_CFG(DM365, UART0_RXD, 3, 20, 1, 1, false)
MUX_CFG(DM365, UART0_TXD, 3, 19, 1, 1, false)
MUX_CFG(DM365, UART1_RXD, 3, 17, 3, 2, false)
MUX_CFG(DM365, UART1_TXD, 3, 15, 3, 2, false)
MUX_CFG(DM365, UART1_RTS, 3, 23, 3, 1, false)
MUX_CFG(DM365, UART1_CTS, 3, 21, 3, 1, false)
MUX_CFG(DM365, EMAC_TX_EN, 3, 17, 3, 1, false)
MUX_CFG(DM365, EMAC_TX_CLK, 3, 15, 3, 1, false)
MUX_CFG(DM365, EMAC_COL, 3, 14, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD3, 3, 13, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD2, 3, 12, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD1, 3, 11, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD0, 3, 10, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD3, 3, 9, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD2, 3, 8, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD1, 3, 7, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD0, 3, 6, 1, 1, false)
MUX_CFG(DM365, EMAC_RX_CLK, 3, 5, 1, 1, false)
MUX_CFG(DM365, EMAC_RX_DV, 3, 4, 1, 1, false)
MUX_CFG(DM365, EMAC_RX_ER, 3, 3, 1, 1, false)
MUX_CFG(DM365, EMAC_CRS, 3, 2, 1, 1, false)
MUX_CFG(DM365, EMAC_MDIO, 3, 1, 1, 1, false)
MUX_CFG(DM365, EMAC_MDCLK, 3, 0, 1, 1, false)
MUX_CFG(DM365, KEYSCAN, 2, 0, 0x3f, 0x3f, false)
MUX_CFG(DM365, PWM0, 1, 0, 3, 2, false)
MUX_CFG(DM365, PWM0_G23, 3, 26, 3, 3, false)
MUX_CFG(DM365, PWM1, 1, 2, 3, 2, false)
MUX_CFG(DM365, PWM1_G25, 3, 29, 3, 2, false)
MUX_CFG(DM365, PWM2_G87, 1, 10, 3, 2, false)
MUX_CFG(DM365, PWM2_G88, 1, 8, 3, 2, false)
MUX_CFG(DM365, PWM2_G89, 1, 6, 3, 2, false)
MUX_CFG(DM365, PWM2_G90, 1, 4, 3, 2, false)
MUX_CFG(DM365, PWM3_G80, 1, 20, 3, 3, false)
MUX_CFG(DM365, PWM3_G81, 1, 18, 3, 3, false)
MUX_CFG(DM365, PWM3_G85, 1, 14, 3, 2, false)
MUX_CFG(DM365, PWM3_G86, 1, 12, 3, 2, false)
MUX_CFG(DM365, SPI1_SCLK, 4, 2, 3, 1, false)
MUX_CFG(DM365, SPI1_SDI, 3, 31, 1, 1, false)
MUX_CFG(DM365, SPI1_SDO, 4, 0, 3, 1, false)
MUX_CFG(DM365, SPI1_SDENA0, 4, 4, 3, 1, false)
MUX_CFG(DM365, SPI1_SDENA1, 4, 0, 3, 2, false)
MUX_CFG(DM365, SPI2_SCLK, 4, 10, 3, 1, false)
MUX_CFG(DM365, SPI2_SDI, 4, 6, 3, 1, false)
MUX_CFG(DM365, SPI2_SDO, 4, 8, 3, 1, false)
MUX_CFG(DM365, SPI2_SDENA0, 4, 12, 3, 1, false)
MUX_CFG(DM365, SPI2_SDENA1, 4, 8, 3, 2, false)
MUX_CFG(DM365, SPI3_SCLK, 0, 0, 3, 2, false)
MUX_CFG(DM365, SPI3_SDI, 0, 2, 3, 2, false)
MUX_CFG(DM365, SPI3_SDO, 0, 6, 3, 2, false)
MUX_CFG(DM365, SPI3_SDENA0, 0, 4, 3, 2, false)
MUX_CFG(DM365, SPI3_SDENA1, 0, 6, 3, 3, false)
MUX_CFG(DM365, SPI4_SCLK, 4, 18, 3, 1, false)
MUX_CFG(DM365, SPI4_SDI, 4, 14, 3, 1, false)
MUX_CFG(DM365, SPI4_SDO, 4, 16, 3, 1, false)
MUX_CFG(DM365, SPI4_SDENA0, 4, 20, 3, 1, false)
MUX_CFG(DM365, SPI4_SDENA1, 4, 16, 3, 2, false)
MUX_CFG(DM365, CLKOUT0, 4, 20, 3, 3, false)
MUX_CFG(DM365, CLKOUT1, 4, 16, 3, 3, false)
MUX_CFG(DM365, CLKOUT2, 4, 8, 3, 3, false)
MUX_CFG(DM365, GPIO20, 3, 21, 3, 0, false)
MUX_CFG(DM365, GPIO30, 4, 6, 3, 0, false)
MUX_CFG(DM365, GPIO31, 4, 8, 3, 0, false)
MUX_CFG(DM365, GPIO32, 4, 10, 3, 0, false)
MUX_CFG(DM365, GPIO33, 4, 12, 3, 0, false)
MUX_CFG(DM365, GPIO40, 4, 26, 3, 0, false)
MUX_CFG(DM365, GPIO64_57, 2, 6, 1, 0, false)
MUX_CFG(DM365, VOUT_FIELD, 1, 18, 3, 1, false)
MUX_CFG(DM365, VOUT_FIELD_G81, 1, 18, 3, 0, false)
MUX_CFG(DM365, VOUT_HVSYNC, 1, 16, 1, 0, false)
MUX_CFG(DM365, VOUT_COUTL_EN, 1, 0, 0xff, 0x55, false)
MUX_CFG(DM365, VOUT_COUTH_EN, 1, 8, 0xff, 0x55, false)
MUX_CFG(DM365, VIN_CAM_WEN, 0, 14, 3, 0, false)
MUX_CFG(DM365, VIN_CAM_VD, 0, 13, 1, 0, false)
MUX_CFG(DM365, VIN_CAM_HD, 0, 12, 1, 0, false)
MUX_CFG(DM365, VIN_YIN4_7_EN, 0, 0, 0xff, 0, false)
MUX_CFG(DM365, VIN_YIN0_3_EN, 0, 8, 0xf, 0, false)
INT_CFG(DM365, INT_EDMA_CC, 2, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC0_ERR, 3, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC1_ERR, 4, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC2_ERR, 22, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC3_ERR, 23, 1, 1, false)
INT_CFG(DM365, INT_PRTCSS, 10, 1, 1, false)
INT_CFG(DM365, INT_EMAC_RXTHRESH, 14, 1, 1, false)
INT_CFG(DM365, INT_EMAC_RXPULSE, 15, 1, 1, false)
INT_CFG(DM365, INT_EMAC_TXPULSE, 16, 1, 1, false)
INT_CFG(DM365, INT_EMAC_MISCPULSE, 17, 1, 1, false)
INT_CFG(DM365, INT_IMX0_ENABLE, 0, 1, 0, false)
INT_CFG(DM365, INT_IMX0_DISABLE, 0, 1, 1, false)
INT_CFG(DM365, INT_HDVICP_ENABLE, 0, 1, 1, false)
INT_CFG(DM365, INT_HDVICP_DISABLE, 0, 1, 0, false)
INT_CFG(DM365, INT_IMX1_ENABLE, 24, 1, 1, false)
INT_CFG(DM365, INT_IMX1_DISABLE, 24, 1, 0, false)
INT_CFG(DM365, INT_NSF_ENABLE, 25, 1, 1, false)
INT_CFG(DM365, INT_NSF_DISABLE, 25, 1, 0, false)
EVT_CFG(DM365, EVT2_ASP_TX, 0, 1, 0, false)
EVT_CFG(DM365, EVT3_ASP_RX, 1, 1, 0, false)
EVT_CFG(DM365, EVT2_VC_TX, 0, 1, 1, false)
EVT_CFG(DM365, EVT3_VC_RX, 1, 1, 1, false)
#endif
};
static u64 dm365_spi0_dma_mask = DMA_BIT_MASK(32);
static struct davinci_spi_platform_data dm365_spi0_pdata = {
.version = SPI_VERSION_1,
.num_chipselect = 2,
.dma_event_q = EVENTQ_3,
.prescaler_limit = 1,
};
static struct resource dm365_spi0_resources[] = {
{
.start = 0x01c66000,
.end = 0x01c667ff,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_SPIINT0_0),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_spi0_device = {
.name = "spi_davinci",
.id = 0,
.dev = {
.dma_mask = &dm365_spi0_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &dm365_spi0_pdata,
},
.num_resources = ARRAY_SIZE(dm365_spi0_resources),
.resource = dm365_spi0_resources,
};
void __init dm365_init_spi0(unsigned chipselect_mask,
const struct spi_board_info *info, unsigned len)
{
davinci_cfg_reg(DM365_SPI0_SCLK);
davinci_cfg_reg(DM365_SPI0_SDI);
davinci_cfg_reg(DM365_SPI0_SDO);
/* not all slaves will be wired up */
if (chipselect_mask & BIT(0))
davinci_cfg_reg(DM365_SPI0_SDENA0);
if (chipselect_mask & BIT(1))
davinci_cfg_reg(DM365_SPI0_SDENA1);
spi_register_board_info(info, len);
platform_device_register(&dm365_spi0_device);
}
static struct resource dm365_gpio_resources[] = {
{ /* registers */
.start = DAVINCI_GPIO_BASE,
.end = DAVINCI_GPIO_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{ /* interrupt */
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO0),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO0),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO1),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO1),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO2),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO2),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO3),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO3),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO4),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO4),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO5),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO5),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO6),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO6),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO7),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_GPIO7),
.flags = IORESOURCE_IRQ,
},
};
static struct davinci_gpio_platform_data dm365_gpio_platform_data = {
.no_auto_base = true,
.base = 0,
.ngpio = 104,
.gpio_unbanked = 8,
};
int __init dm365_gpio_register(void)
{
return davinci_gpio_register(dm365_gpio_resources,
ARRAY_SIZE(dm365_gpio_resources),
&dm365_gpio_platform_data);
}
static struct emac_platform_data dm365_emac_pdata = {
.ctrl_reg_offset = DM365_EMAC_CNTRL_OFFSET,
.ctrl_mod_reg_offset = DM365_EMAC_CNTRL_MOD_OFFSET,
.ctrl_ram_offset = DM365_EMAC_CNTRL_RAM_OFFSET,
.ctrl_ram_size = DM365_EMAC_CNTRL_RAM_SIZE,
.version = EMAC_VERSION_2,
};
static struct resource dm365_emac_resources[] = {
{
.start = DM365_EMAC_BASE,
.end = DM365_EMAC_BASE + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_RXTHRESH),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_RXTHRESH),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_RXPULSE),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_RXPULSE),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_TXPULSE),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_TXPULSE),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_MISCPULSE),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_EMAC_MISCPULSE),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_emac_device = {
.name = "davinci_emac",
.id = 1,
.dev = {
.platform_data = &dm365_emac_pdata,
},
.num_resources = ARRAY_SIZE(dm365_emac_resources),
.resource = dm365_emac_resources,
};
static struct resource dm365_mdio_resources[] = {
{
.start = DM365_EMAC_MDIO_BASE,
.end = DM365_EMAC_MDIO_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device dm365_mdio_device = {
.name = "davinci_mdio",
.id = 0,
.num_resources = ARRAY_SIZE(dm365_mdio_resources),
.resource = dm365_mdio_resources,
};
static u8 dm365_default_priorities[DAVINCI_N_AINTC_IRQ] = {
[IRQ_VDINT0] = 2,
[IRQ_VDINT1] = 6,
[IRQ_VDINT2] = 6,
[IRQ_HISTINT] = 6,
[IRQ_H3AINT] = 6,
[IRQ_PRVUINT] = 6,
[IRQ_RSZINT] = 6,
[IRQ_DM365_INSFINT] = 7,
[IRQ_VENCINT] = 6,
[IRQ_ASQINT] = 6,
[IRQ_IMXINT] = 6,
[IRQ_DM365_IMCOPINT] = 4,
[IRQ_USBINT] = 4,
[IRQ_DM365_RTOINT] = 7,
[IRQ_DM365_TINT5] = 7,
[IRQ_DM365_TINT6] = 5,
[IRQ_CCINT0] = 5,
[IRQ_CCERRINT] = 5,
[IRQ_TCERRINT0] = 5,
[IRQ_TCERRINT] = 7,
[IRQ_PSCIN] = 4,
[IRQ_DM365_SPINT2_1] = 7,
[IRQ_DM365_TINT7] = 7,
[IRQ_DM365_SDIOINT0] = 7,
[IRQ_MBXINT] = 7,
[IRQ_MBRINT] = 7,
[IRQ_MMCINT] = 7,
[IRQ_DM365_MMCINT1] = 7,
[IRQ_DM365_PWMINT3] = 7,
[IRQ_AEMIFINT] = 2,
[IRQ_DM365_SDIOINT1] = 2,
[IRQ_TINT0_TINT12] = 7,
[IRQ_TINT0_TINT34] = 7,
[IRQ_TINT1_TINT12] = 7,
[IRQ_TINT1_TINT34] = 7,
[IRQ_PWMINT0] = 7,
[IRQ_PWMINT1] = 3,
[IRQ_PWMINT2] = 3,
[IRQ_I2C] = 3,
[IRQ_UARTINT0] = 3,
[IRQ_UARTINT1] = 3,
[IRQ_DM365_RTCINT] = 3,
[IRQ_DM365_SPIINT0_0] = 3,
[IRQ_DM365_SPIINT3_0] = 3,
[IRQ_DM365_GPIO0] = 3,
[IRQ_DM365_GPIO1] = 7,
[IRQ_DM365_GPIO2] = 4,
[IRQ_DM365_GPIO3] = 4,
[IRQ_DM365_GPIO4] = 7,
[IRQ_DM365_GPIO5] = 7,
[IRQ_DM365_GPIO6] = 7,
[IRQ_DM365_GPIO7] = 7,
[IRQ_DM365_EMAC_RXTHRESH] = 7,
[IRQ_DM365_EMAC_RXPULSE] = 7,
[IRQ_DM365_EMAC_TXPULSE] = 7,
[IRQ_DM365_EMAC_MISCPULSE] = 7,
[IRQ_DM365_GPIO12] = 7,
[IRQ_DM365_GPIO13] = 7,
[IRQ_DM365_GPIO14] = 7,
[IRQ_DM365_GPIO15] = 7,
[IRQ_DM365_KEYINT] = 7,
[IRQ_DM365_TCERRINT2] = 7,
[IRQ_DM365_TCERRINT3] = 7,
[IRQ_DM365_EMUINT] = 7,
};
/* Four Transfer Controllers on DM365 */
static s8 dm365_queue_priority_mapping[][2] = {
/* {event queue no, Priority} */
{0, 7},
{1, 7},
{2, 7},
{3, 0},
{-1, -1},
};
static const struct dma_slave_map dm365_edma_map[] = {
{ "davinci-mcbsp", "tx", EDMA_FILTER_PARAM(0, 2) },
{ "davinci-mcbsp", "rx", EDMA_FILTER_PARAM(0, 3) },
{ "davinci_voicecodec", "tx", EDMA_FILTER_PARAM(0, 2) },
{ "davinci_voicecodec", "rx", EDMA_FILTER_PARAM(0, 3) },
{ "spi_davinci.2", "tx", EDMA_FILTER_PARAM(0, 10) },
{ "spi_davinci.2", "rx", EDMA_FILTER_PARAM(0, 11) },
{ "spi_davinci.1", "tx", EDMA_FILTER_PARAM(0, 14) },
{ "spi_davinci.1", "rx", EDMA_FILTER_PARAM(0, 15) },
{ "spi_davinci.0", "tx", EDMA_FILTER_PARAM(0, 16) },
{ "spi_davinci.0", "rx", EDMA_FILTER_PARAM(0, 17) },
{ "spi_davinci.3", "tx", EDMA_FILTER_PARAM(0, 18) },
{ "spi_davinci.3", "rx", EDMA_FILTER_PARAM(0, 19) },
{ "da830-mmc.0", "rx", EDMA_FILTER_PARAM(0, 26) },
{ "da830-mmc.0", "tx", EDMA_FILTER_PARAM(0, 27) },
{ "da830-mmc.1", "rx", EDMA_FILTER_PARAM(0, 30) },
{ "da830-mmc.1", "tx", EDMA_FILTER_PARAM(0, 31) },
};
static struct edma_soc_info dm365_edma_pdata = {
.queue_priority_mapping = dm365_queue_priority_mapping,
.default_queue = EVENTQ_3,
.slave_map = dm365_edma_map,
.slavecnt = ARRAY_SIZE(dm365_edma_map),
};
static struct resource edma_resources[] = {
{
.name = "edma3_cc",
.start = 0x01c00000,
.end = 0x01c00000 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma3_tc0",
.start = 0x01c10000,
.end = 0x01c10000 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma3_tc1",
.start = 0x01c10400,
.end = 0x01c10400 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma3_tc2",
.start = 0x01c10800,
.end = 0x01c10800 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma3_tc3",
.start = 0x01c10c00,
.end = 0x01c10c00 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma3_ccint",
.start = DAVINCI_INTC_IRQ(IRQ_CCINT0),
.flags = IORESOURCE_IRQ,
},
{
.name = "edma3_ccerrint",
.start = DAVINCI_INTC_IRQ(IRQ_CCERRINT),
.flags = IORESOURCE_IRQ,
},
/* not using TC*_ERR */
};
static const struct platform_device_info dm365_edma_device __initconst = {
.name = "edma",
.id = 0,
.dma_mask = DMA_BIT_MASK(32),
.res = edma_resources,
.num_res = ARRAY_SIZE(edma_resources),
.data = &dm365_edma_pdata,
.size_data = sizeof(dm365_edma_pdata),
};
static struct resource dm365_asp_resources[] = {
{
.name = "mpu",
.start = DAVINCI_DM365_ASP0_BASE,
.end = DAVINCI_DM365_ASP0_BASE + SZ_8K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_DMA_ASP0_TX,
.end = DAVINCI_DMA_ASP0_TX,
.flags = IORESOURCE_DMA,
},
{
.start = DAVINCI_DMA_ASP0_RX,
.end = DAVINCI_DMA_ASP0_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device dm365_asp_device = {
.name = "davinci-mcbsp",
.id = -1,
.num_resources = ARRAY_SIZE(dm365_asp_resources),
.resource = dm365_asp_resources,
};
static struct resource dm365_vc_resources[] = {
{
.start = DAVINCI_DM365_VC_BASE,
.end = DAVINCI_DM365_VC_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_DMA_VC_TX,
.end = DAVINCI_DMA_VC_TX,
.flags = IORESOURCE_DMA,
},
{
.start = DAVINCI_DMA_VC_RX,
.end = DAVINCI_DMA_VC_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device dm365_vc_device = {
.name = "davinci_voicecodec",
.id = -1,
.num_resources = ARRAY_SIZE(dm365_vc_resources),
.resource = dm365_vc_resources,
};
static struct resource dm365_rtc_resources[] = {
{
.start = DM365_RTC_BASE,
.end = DM365_RTC_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_DM365_RTCINT),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_rtc_device = {
.name = "rtc_davinci",
.id = 0,
.num_resources = ARRAY_SIZE(dm365_rtc_resources),
.resource = dm365_rtc_resources,
};
static struct map_desc dm365_io_desc[] = {
{
.virtual = IO_VIRT,
.pfn = __phys_to_pfn(IO_PHYS),
.length = IO_SIZE,
.type = MT_DEVICE
},
};
static struct resource dm365_ks_resources[] = {
{
/* registers */
.start = DM365_KEYSCAN_BASE,
.end = DM365_KEYSCAN_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
/* interrupt */
.start = DAVINCI_INTC_IRQ(IRQ_DM365_KEYINT),
.end = DAVINCI_INTC_IRQ(IRQ_DM365_KEYINT),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_ks_device = {
.name = "davinci_keyscan",
.id = 0,
.num_resources = ARRAY_SIZE(dm365_ks_resources),
.resource = dm365_ks_resources,
};
/* Contents of JTAG ID register used to identify exact cpu type */
static struct davinci_id dm365_ids[] = {
{
.variant = 0x0,
.part_no = 0xb83e,
.manufacturer = 0x017,
.cpu_id = DAVINCI_CPU_ID_DM365,
.name = "dm365_rev1.1",
},
{
.variant = 0x8,
.part_no = 0xb83e,
.manufacturer = 0x017,
.cpu_id = DAVINCI_CPU_ID_DM365,
.name = "dm365_rev1.2",
},
};
/*
* Bottom half of timer0 is used for clockevent, top half is used for
* clocksource.
*/
static const struct davinci_timer_cfg dm365_timer_cfg = {
.reg = DEFINE_RES_IO(DAVINCI_TIMER0_BASE, SZ_128),
.irq = {
DEFINE_RES_IRQ(DAVINCI_INTC_IRQ(IRQ_TINT0_TINT12)),
DEFINE_RES_IRQ(DAVINCI_INTC_IRQ(IRQ_TINT0_TINT34)),
},
};
#define DM365_UART1_BASE (IO_PHYS + 0x106000)
static struct plat_serial8250_port dm365_serial0_platform_data[] = {
{
.mapbase = DAVINCI_UART0_BASE,
.irq = DAVINCI_INTC_IRQ(IRQ_UARTINT0),
.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST |
UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 2,
},
{
.flags = 0,
}
};
static struct plat_serial8250_port dm365_serial1_platform_data[] = {
{
.mapbase = DM365_UART1_BASE,
.irq = DAVINCI_INTC_IRQ(IRQ_UARTINT1),
.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST |
UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 2,
},
{
.flags = 0,
}
};
struct platform_device dm365_serial_device[] = {
{
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = dm365_serial0_platform_data,
}
},
{
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM1,
.dev = {
.platform_data = dm365_serial1_platform_data,
}
},
{
}
};
static const struct davinci_soc_info davinci_soc_info_dm365 = {
.io_desc = dm365_io_desc,
.io_desc_num = ARRAY_SIZE(dm365_io_desc),
.jtag_id_reg = 0x01c40028,
.ids = dm365_ids,
.ids_num = ARRAY_SIZE(dm365_ids),
.pinmux_base = DAVINCI_SYSTEM_MODULE_BASE,
.pinmux_pins = dm365_pins,
.pinmux_pins_num = ARRAY_SIZE(dm365_pins),
.emac_pdata = &dm365_emac_pdata,
.sram_dma = 0x00010000,
.sram_len = SZ_32K,
};
void __init dm365_init_asp(void)
{
davinci_cfg_reg(DM365_MCBSP0_BDX);
davinci_cfg_reg(DM365_MCBSP0_X);
davinci_cfg_reg(DM365_MCBSP0_BFSX);
davinci_cfg_reg(DM365_MCBSP0_BDR);
davinci_cfg_reg(DM365_MCBSP0_R);
davinci_cfg_reg(DM365_MCBSP0_BFSR);
davinci_cfg_reg(DM365_EVT2_ASP_TX);
davinci_cfg_reg(DM365_EVT3_ASP_RX);
platform_device_register(&dm365_asp_device);
}
void __init dm365_init_vc(void)
{
davinci_cfg_reg(DM365_EVT2_VC_TX);
davinci_cfg_reg(DM365_EVT3_VC_RX);
platform_device_register(&dm365_vc_device);
}
void __init dm365_init_ks(struct davinci_ks_platform_data *pdata)
{
dm365_ks_device.dev.platform_data = pdata;
platform_device_register(&dm365_ks_device);
}
void __init dm365_init_rtc(void)
{
davinci_cfg_reg(DM365_INT_PRTCSS);
platform_device_register(&dm365_rtc_device);
}
void __init dm365_init(void)
{
davinci_common_init(&davinci_soc_info_dm365);
davinci_map_sysmod();
}
void __init dm365_init_time(void)
{
void __iomem *pll1, *pll2, *psc;
struct clk *clk;
int rv;
clk_register_fixed_rate(NULL, "ref_clk", NULL, 0, DM365_REF_FREQ);
pll1 = ioremap(DAVINCI_PLL1_BASE, SZ_1K);
dm365_pll1_init(NULL, pll1, NULL);
pll2 = ioremap(DAVINCI_PLL2_BASE, SZ_1K);
dm365_pll2_init(NULL, pll2, NULL);
psc = ioremap(DAVINCI_PWR_SLEEP_CNTRL_BASE, SZ_4K);
dm365_psc_init(NULL, psc);
clk = clk_get(NULL, "timer0");
if (WARN_ON(IS_ERR(clk))) {
pr_err("Unable to get the timer clock\n");
return;
}
rv = davinci_timer_register(clk, &dm365_timer_cfg);
WARN(rv, "Unable to register the timer: %d\n", rv);
}
void __init dm365_register_clocks(void)
{
/* all clocks are currently registered in dm365_init_time() */
}
static struct resource dm365_vpss_resources[] = {
{
/* VPSS ISP5 Base address */
.name = "isp5",
.start = 0x01c70000,
.end = 0x01c70000 + 0xff,
.flags = IORESOURCE_MEM,
},
{
/* VPSS CLK Base address */
.name = "vpss",
.start = 0x01c70200,
.end = 0x01c70200 + 0xff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device dm365_vpss_device = {
.name = "vpss",
.id = -1,
.dev.platform_data = "dm365_vpss",
.num_resources = ARRAY_SIZE(dm365_vpss_resources),
.resource = dm365_vpss_resources,
};
static struct resource vpfe_resources[] = {
{
.start = DAVINCI_INTC_IRQ(IRQ_VDINT0),
.end = DAVINCI_INTC_IRQ(IRQ_VDINT0),
.flags = IORESOURCE_IRQ,
},
{
.start = DAVINCI_INTC_IRQ(IRQ_VDINT1),
.end = DAVINCI_INTC_IRQ(IRQ_VDINT1),
.flags = IORESOURCE_IRQ,
},
};
static u64 vpfe_capture_dma_mask = DMA_BIT_MASK(32);
static struct platform_device vpfe_capture_dev = {
.name = CAPTURE_DRV_NAME,
.id = -1,
.num_resources = ARRAY_SIZE(vpfe_resources),
.resource = vpfe_resources,
.dev = {
.dma_mask = &vpfe_capture_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static void dm365_isif_setup_pinmux(void)
{
davinci_cfg_reg(DM365_VIN_CAM_WEN);
davinci_cfg_reg(DM365_VIN_CAM_VD);
davinci_cfg_reg(DM365_VIN_CAM_HD);
davinci_cfg_reg(DM365_VIN_YIN4_7_EN);
davinci_cfg_reg(DM365_VIN_YIN0_3_EN);
}
static struct resource isif_resource[] = {
/* ISIF Base address */
{
.start = 0x01c71000,
.end = 0x01c71000 + 0x1ff,
.flags = IORESOURCE_MEM,
},
/* ISIF Linearization table 0 */
{
.start = 0x1C7C000,
.end = 0x1C7C000 + 0x2ff,
.flags = IORESOURCE_MEM,
},
/* ISIF Linearization table 1 */
{
.start = 0x1C7C400,
.end = 0x1C7C400 + 0x2ff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device dm365_isif_dev = {
.name = "isif",
.id = -1,
.num_resources = ARRAY_SIZE(isif_resource),
.resource = isif_resource,
.dev = {
.dma_mask = &vpfe_capture_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = dm365_isif_setup_pinmux,
},
};
static struct resource dm365_osd_resources[] = {
{
.start = DM365_OSD_BASE,
.end = DM365_OSD_BASE + 0xff,
.flags = IORESOURCE_MEM,
},
};
static u64 dm365_video_dma_mask = DMA_BIT_MASK(32);
static struct platform_device dm365_osd_dev = {
.name = DM365_VPBE_OSD_SUBDEV_NAME,
.id = -1,
.num_resources = ARRAY_SIZE(dm365_osd_resources),
.resource = dm365_osd_resources,
.dev = {
.dma_mask = &dm365_video_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct resource dm365_venc_resources[] = {
{
.start = DAVINCI_INTC_IRQ(IRQ_VENCINT),
.end = DAVINCI_INTC_IRQ(IRQ_VENCINT),
.flags = IORESOURCE_IRQ,
},
/* venc registers io space */
{
.start = DM365_VENC_BASE,
.end = DM365_VENC_BASE + 0x177,
.flags = IORESOURCE_MEM,
},
/* vdaccfg registers io space */
{
.start = DAVINCI_SYSTEM_MODULE_BASE + SYSMOD_VDAC_CONFIG,
.end = DAVINCI_SYSTEM_MODULE_BASE + SYSMOD_VDAC_CONFIG + 3,
.flags = IORESOURCE_MEM,
},
};
static struct resource dm365_v4l2_disp_resources[] = {
{
.start = DAVINCI_INTC_IRQ(IRQ_VENCINT),
.end = DAVINCI_INTC_IRQ(IRQ_VENCINT),
.flags = IORESOURCE_IRQ,
},
/* venc registers io space */
{
.start = DM365_VENC_BASE,
.end = DM365_VENC_BASE + 0x177,
.flags = IORESOURCE_MEM,
},
};
static int dm365_vpbe_setup_pinmux(u32 if_type, int field)
{
switch (if_type) {
case MEDIA_BUS_FMT_SGRBG8_1X8:
davinci_cfg_reg(DM365_VOUT_FIELD_G81);
davinci_cfg_reg(DM365_VOUT_COUTL_EN);
davinci_cfg_reg(DM365_VOUT_COUTH_EN);
break;
case MEDIA_BUS_FMT_YUYV10_1X20:
if (field)
davinci_cfg_reg(DM365_VOUT_FIELD);
else
davinci_cfg_reg(DM365_VOUT_FIELD_G81);
davinci_cfg_reg(DM365_VOUT_COUTL_EN);
davinci_cfg_reg(DM365_VOUT_COUTH_EN);
break;
default:
return -EINVAL;
}
return 0;
}
static int dm365_venc_setup_clock(enum vpbe_enc_timings_type type,
unsigned int pclock)
{
void __iomem *vpss_clkctl_reg;
u32 val;
vpss_clkctl_reg = DAVINCI_SYSMOD_VIRT(SYSMOD_VPSS_CLKCTL);
switch (type) {
case VPBE_ENC_STD:
val = VPSS_VENCCLKEN_ENABLE | VPSS_DACCLKEN_ENABLE;
break;
case VPBE_ENC_DV_TIMINGS:
if (pclock <= 27000000) {
val = VPSS_VENCCLKEN_ENABLE | VPSS_DACCLKEN_ENABLE;
} else {
/* set sysclk4 to output 74.25 MHz from pll1 */
val = VPSS_PLLC2SYSCLK5_ENABLE | VPSS_DACCLKEN_ENABLE |
VPSS_VENCCLKEN_ENABLE;
}
break;
default:
return -EINVAL;
}
writel(val, vpss_clkctl_reg);
return 0;
}
static struct platform_device dm365_vpbe_display = {
.name = "vpbe-v4l2",
.id = -1,
.num_resources = ARRAY_SIZE(dm365_v4l2_disp_resources),
.resource = dm365_v4l2_disp_resources,
.dev = {
.dma_mask = &dm365_video_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct venc_platform_data dm365_venc_pdata = {
.setup_pinmux = dm365_vpbe_setup_pinmux,
.setup_clock = dm365_venc_setup_clock,
};
static struct platform_device dm365_venc_dev = {
.name = DM365_VPBE_VENC_SUBDEV_NAME,
.id = -1,
.num_resources = ARRAY_SIZE(dm365_venc_resources),
.resource = dm365_venc_resources,
.dev = {
.dma_mask = &dm365_video_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = (void *)&dm365_venc_pdata,
},
};
static struct platform_device dm365_vpbe_dev = {
.name = "vpbe_controller",
.id = -1,
.dev = {
.dma_mask = &dm365_video_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
int __init dm365_init_video(struct vpfe_config *vpfe_cfg,
struct vpbe_config *vpbe_cfg)
{
if (vpfe_cfg || vpbe_cfg)
platform_device_register(&dm365_vpss_device);
if (vpfe_cfg) {
vpfe_capture_dev.dev.platform_data = vpfe_cfg;
platform_device_register(&dm365_isif_dev);
platform_device_register(&vpfe_capture_dev);
}
if (vpbe_cfg) {
dm365_vpbe_dev.dev.platform_data = vpbe_cfg;
platform_device_register(&dm365_osd_dev);
platform_device_register(&dm365_venc_dev);
platform_device_register(&dm365_vpbe_dev);
platform_device_register(&dm365_vpbe_display);
}
return 0;
}
static const struct davinci_aintc_config dm365_aintc_config = {
.reg = {
.start = DAVINCI_ARM_INTC_BASE,
.end = DAVINCI_ARM_INTC_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
.num_irqs = 64,
.prios = dm365_default_priorities,
};
void __init dm365_init_irq(void)
{
davinci_aintc_init(&dm365_aintc_config);
}
static int __init dm365_init_devices(void)
{
struct platform_device *edma_pdev;
int ret = 0;
if (!cpu_is_davinci_dm365())
return 0;
davinci_cfg_reg(DM365_INT_EDMA_CC);
edma_pdev = platform_device_register_full(&dm365_edma_device);
if (IS_ERR(edma_pdev)) {
pr_warn("%s: Failed to register eDMA\n", __func__);
return PTR_ERR(edma_pdev);
}
platform_device_register(&dm365_mdio_device);
platform_device_register(&dm365_emac_device);
ret = davinci_init_wdt();
if (ret)
pr_warn("%s: watchdog init failed: %d\n", __func__, ret);
return ret;
}
postcore_initcall(dm365_init_devices);
| gpl-2.0 |
WereCatf/source | target/linux/ar71xx/files/arch/mips/ath79/mach-tew-732br.c | 537 | 3406 | /*
* TRENDnet TEW-732BR board support
*
* Copyright (C) 2013 Gabor Juhos <juhosg@openwrt.org>
*
* 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/platform_device.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-m25p80.h"
#include "dev-wmac.h"
#include "machtypes.h"
#define TEW_732BR_GPIO_BTN_WPS 16
#define TEW_732BR_GPIO_BTN_RESET 17
#define TEW_732BR_GPIO_LED_POWER_GREEN 4
#define TEW_732BR_GPIO_LED_POWER_AMBER 14
#define TEW_732BR_GPIO_LED_PLANET_GREEN 12
#define TEW_732BR_GPIO_LED_PLANET_AMBER 22
#define TEW_732BR_KEYS_POLL_INTERVAL 20 /* msecs */
#define TEW_732BR_KEYS_DEBOUNCE_INTERVAL (3 * TEW_732BR_KEYS_POLL_INTERVAL)
#define TEW_732BR_ART_ADDRESS 0x1fff0000
#define TEW_732BR_CALDATA_OFFSET 0x1000
#define TEW_732BR_LAN_MAC_OFFSET 0xffa0
#define TEW_732BR_WAN_MAC_OFFSET 0xffb4
static struct gpio_led tew_732br_leds_gpio[] __initdata = {
{
.name = "trendnet:green:power",
.gpio = TEW_732BR_GPIO_LED_POWER_GREEN,
.active_low = 0,
},
{
.name = "trendnet:amber:power",
.gpio = TEW_732BR_GPIO_LED_POWER_AMBER,
.active_low = 0,
},
{
.name = "trendnet:green:wan",
.gpio = TEW_732BR_GPIO_LED_PLANET_GREEN,
.active_low = 1,
},
{
.name = "trendnet:amber:wan",
.gpio = TEW_732BR_GPIO_LED_PLANET_AMBER,
.active_low = 0,
},
};
static struct gpio_keys_button tew_732br_gpio_keys[] __initdata = {
{
.desc = "Reset button",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = TEW_732BR_KEYS_DEBOUNCE_INTERVAL,
.gpio = TEW_732BR_GPIO_BTN_RESET,
.active_low = 1,
},
{
.desc = "WPS button",
.type = EV_KEY,
.code = KEY_WPS_BUTTON,
.debounce_interval = TEW_732BR_KEYS_DEBOUNCE_INTERVAL,
.gpio = TEW_732BR_GPIO_BTN_WPS,
.active_low = 1,
},
};
static void __init tew_732br_setup(void)
{
u8 *art = (u8 *) KSEG1ADDR(TEW_732BR_ART_ADDRESS);
u8 lan_mac[ETH_ALEN];
u8 wan_mac[ETH_ALEN];
ath79_register_leds_gpio(-1, ARRAY_SIZE(tew_732br_leds_gpio),
tew_732br_leds_gpio);
ath79_register_gpio_keys_polled(1, TEW_732BR_KEYS_POLL_INTERVAL,
ARRAY_SIZE(tew_732br_gpio_keys),
tew_732br_gpio_keys);
ath79_register_m25p80(NULL);
ath79_parse_ascii_mac(art + TEW_732BR_LAN_MAC_OFFSET, lan_mac);
ath79_parse_ascii_mac(art + TEW_732BR_WAN_MAC_OFFSET, wan_mac);
ath79_register_wmac(art + TEW_732BR_CALDATA_OFFSET, lan_mac);
ath79_register_mdio(1, 0x0);
ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_SW_ONLY_MODE);
/* LAN: GMAC1 is connected to the internal switch */
ath79_init_mac(ath79_eth1_data.mac_addr, lan_mac, 0);
ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_GMII;
ath79_register_eth(1);
/* WAN: GMAC0 is connected to the PHY4 of the internal switch */
ath79_init_mac(ath79_eth0_data.mac_addr, wan_mac, 0);
ath79_switch_data.phy4_mii_en = 1;
ath79_switch_data.phy_poll_mask = BIT(4);
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII;
ath79_eth0_data.phy_mask = BIT(4);
ath79_eth0_data.mii_bus_dev = &ath79_mdio1_device.dev;
ath79_register_eth(0);
}
MIPS_MACHINE(ATH79_MACH_TEW_732BR, "TEW-732BR", "TRENDnet TEW-732BR",
tew_732br_setup);
| gpl-2.0 |
haggaie/rxe-dev | arch/mips/kernel/ftrace.c | 1561 | 11206 | /*
* Code for replacing ftrace calls with jumps.
*
* Copyright (C) 2007-2008 Steven Rostedt <srostedt@redhat.com>
* Copyright (C) 2009, 2010 DSLab, Lanzhou University, China
* Author: Wu Zhangjin <wuzhangjin@gmail.com>
*
* Thanks goes to Steven Rostedt for writing the original x86 version.
*/
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/ftrace.h>
#include <linux/syscalls.h>
#include <asm/asm.h>
#include <asm/asm-offsets.h>
#include <asm/cacheflush.h>
#include <asm/syscall.h>
#include <asm/uasm.h>
#include <asm/unistd.h>
#include <asm-generic/sections.h>
#if defined(KBUILD_MCOUNT_RA_ADDRESS) && defined(CONFIG_32BIT)
#define MCOUNT_OFFSET_INSNS 5
#else
#define MCOUNT_OFFSET_INSNS 4
#endif
#ifdef CONFIG_DYNAMIC_FTRACE
/* Arch override because MIPS doesn't need to run this from stop_machine() */
void arch_ftrace_update_code(int command)
{
ftrace_modify_all_code(command);
}
#endif
/*
* Check if the address is in kernel space
*
* Clone core_kernel_text() from kernel/extable.c, but doesn't call
* init_kernel_text() for Ftrace doesn't trace functions in init sections.
*/
static inline int in_kernel_space(unsigned long ip)
{
if (ip >= (unsigned long)_stext &&
ip <= (unsigned long)_etext)
return 1;
return 0;
}
#ifdef CONFIG_DYNAMIC_FTRACE
#define JAL 0x0c000000 /* jump & link: ip --> ra, jump to target */
#define ADDR_MASK 0x03ffffff /* op_code|addr : 31...26|25 ....0 */
#define JUMP_RANGE_MASK ((1UL << 28) - 1)
#define INSN_NOP 0x00000000 /* nop */
#define INSN_JAL(addr) \
((unsigned int)(JAL | (((addr) >> 2) & ADDR_MASK)))
static unsigned int insn_jal_ftrace_caller __read_mostly;
static unsigned int insn_la_mcount[2] __read_mostly;
static unsigned int insn_j_ftrace_graph_caller __maybe_unused __read_mostly;
static inline void ftrace_dyn_arch_init_insns(void)
{
u32 *buf;
unsigned int v1;
/* la v1, _mcount */
v1 = 3;
buf = (u32 *)&insn_la_mcount[0];
UASM_i_LA(&buf, v1, MCOUNT_ADDR);
/* jal (ftrace_caller + 8), jump over the first two instruction */
buf = (u32 *)&insn_jal_ftrace_caller;
uasm_i_jal(&buf, (FTRACE_ADDR + 8) & JUMP_RANGE_MASK);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
/* j ftrace_graph_caller */
buf = (u32 *)&insn_j_ftrace_graph_caller;
uasm_i_j(&buf, (unsigned long)ftrace_graph_caller & JUMP_RANGE_MASK);
#endif
}
static int ftrace_modify_code(unsigned long ip, unsigned int new_code)
{
int faulted;
mm_segment_t old_fs;
/* *(unsigned int *)ip = new_code; */
safe_store_code(new_code, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
old_fs = get_fs();
set_fs(get_ds());
flush_icache_range(ip, ip + 8);
set_fs(old_fs);
return 0;
}
#ifndef CONFIG_64BIT
static int ftrace_modify_code_2(unsigned long ip, unsigned int new_code1,
unsigned int new_code2)
{
int faulted;
mm_segment_t old_fs;
safe_store_code(new_code1, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
ip += 4;
safe_store_code(new_code2, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
ip -= 4;
old_fs = get_fs();
set_fs(get_ds());
flush_icache_range(ip, ip + 8);
set_fs(old_fs);
return 0;
}
static int ftrace_modify_code_2r(unsigned long ip, unsigned int new_code1,
unsigned int new_code2)
{
int faulted;
mm_segment_t old_fs;
ip += 4;
safe_store_code(new_code2, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
ip -= 4;
safe_store_code(new_code1, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
old_fs = get_fs();
set_fs(get_ds());
flush_icache_range(ip, ip + 8);
set_fs(old_fs);
return 0;
}
#endif
/*
* The details about the calling site of mcount on MIPS
*
* 1. For kernel:
*
* move at, ra
* jal _mcount --> nop
* sub sp, sp, 8 --> nop (CONFIG_32BIT)
*
* 2. For modules:
*
* 2.1 For KBUILD_MCOUNT_RA_ADDRESS and CONFIG_32BIT
*
* lui v1, hi_16bit_of_mcount --> b 1f (0x10000005)
* addiu v1, v1, low_16bit_of_mcount --> nop (CONFIG_32BIT)
* move at, ra
* move $12, ra_address
* jalr v1
* sub sp, sp, 8
* 1: offset = 5 instructions
* 2.2 For the Other situations
*
* lui v1, hi_16bit_of_mcount --> b 1f (0x10000004)
* addiu v1, v1, low_16bit_of_mcount --> nop (CONFIG_32BIT)
* move at, ra
* jalr v1
* nop | move $12, ra_address | sub sp, sp, 8
* 1: offset = 4 instructions
*/
#define INSN_B_1F (0x10000000 | MCOUNT_OFFSET_INSNS)
int ftrace_make_nop(struct module *mod,
struct dyn_ftrace *rec, unsigned long addr)
{
unsigned int new;
unsigned long ip = rec->ip;
/*
* If ip is in kernel space, no long call, otherwise, long call is
* needed.
*/
new = in_kernel_space(ip) ? INSN_NOP : INSN_B_1F;
#ifdef CONFIG_64BIT
return ftrace_modify_code(ip, new);
#else
/*
* On 32 bit MIPS platforms, gcc adds a stack adjust
* instruction in the delay slot after the branch to
* mcount and expects mcount to restore the sp on return.
* This is based on a legacy API and does nothing but
* waste instructions so it's being removed at runtime.
*/
return ftrace_modify_code_2(ip, new, INSN_NOP);
#endif
}
int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr)
{
unsigned int new;
unsigned long ip = rec->ip;
new = in_kernel_space(ip) ? insn_jal_ftrace_caller : insn_la_mcount[0];
#ifdef CONFIG_64BIT
return ftrace_modify_code(ip, new);
#else
return ftrace_modify_code_2r(ip, new, in_kernel_space(ip) ?
INSN_NOP : insn_la_mcount[1]);
#endif
}
#define FTRACE_CALL_IP ((unsigned long)(&ftrace_call))
int ftrace_update_ftrace_func(ftrace_func_t func)
{
unsigned int new;
new = INSN_JAL((unsigned long)func);
return ftrace_modify_code(FTRACE_CALL_IP, new);
}
int __init ftrace_dyn_arch_init(void)
{
/* Encode the instructions when booting */
ftrace_dyn_arch_init_insns();
/* Remove "b ftrace_stub" to ensure ftrace_caller() is executed */
ftrace_modify_code(MCOUNT_ADDR, INSN_NOP);
return 0;
}
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
#ifdef CONFIG_DYNAMIC_FTRACE
extern void ftrace_graph_call(void);
#define FTRACE_GRAPH_CALL_IP ((unsigned long)(&ftrace_graph_call))
int ftrace_enable_ftrace_graph_caller(void)
{
return ftrace_modify_code(FTRACE_GRAPH_CALL_IP,
insn_j_ftrace_graph_caller);
}
int ftrace_disable_ftrace_graph_caller(void)
{
return ftrace_modify_code(FTRACE_GRAPH_CALL_IP, INSN_NOP);
}
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifndef KBUILD_MCOUNT_RA_ADDRESS
#define S_RA_SP (0xafbf << 16) /* s{d,w} ra, offset(sp) */
#define S_R_SP (0xafb0 << 16) /* s{d,w} R, offset(sp) */
#define OFFSET_MASK 0xffff /* stack offset range: 0 ~ PT_SIZE */
unsigned long ftrace_get_parent_ra_addr(unsigned long self_ra, unsigned long
old_parent_ra, unsigned long parent_ra_addr, unsigned long fp)
{
unsigned long sp, ip, tmp;
unsigned int code;
int faulted;
/*
* For module, move the ip from the return address after the
* instruction "lui v1, hi_16bit_of_mcount"(offset is 24), but for
* kernel, move after the instruction "move ra, at"(offset is 16)
*/
ip = self_ra - (in_kernel_space(self_ra) ? 16 : 24);
/*
* search the text until finding the non-store instruction or "s{d,w}
* ra, offset(sp)" instruction
*/
do {
/* get the code at "ip": code = *(unsigned int *)ip; */
safe_load_code(code, ip, faulted);
if (unlikely(faulted))
return 0;
/*
* If we hit the non-store instruction before finding where the
* ra is stored, then this is a leaf function and it does not
* store the ra on the stack
*/
if ((code & S_R_SP) != S_R_SP)
return parent_ra_addr;
/* Move to the next instruction */
ip -= 4;
} while ((code & S_RA_SP) != S_RA_SP);
sp = fp + (code & OFFSET_MASK);
/* tmp = *(unsigned long *)sp; */
safe_load_stack(tmp, sp, faulted);
if (unlikely(faulted))
return 0;
if (tmp == old_parent_ra)
return sp;
return 0;
}
#endif /* !KBUILD_MCOUNT_RA_ADDRESS */
/*
* Hook the return address and push it in the stack of return addrs
* in current thread info.
*/
void prepare_ftrace_return(unsigned long *parent_ra_addr, unsigned long self_ra,
unsigned long fp)
{
unsigned long old_parent_ra;
struct ftrace_graph_ent trace;
unsigned long return_hooker = (unsigned long)
&return_to_handler;
int faulted, insns;
if (unlikely(ftrace_graph_is_dead()))
return;
if (unlikely(atomic_read(¤t->tracing_graph_pause)))
return;
/*
* "parent_ra_addr" is the stack address saved the return address of
* the caller of _mcount.
*
* if the gcc < 4.5, a leaf function does not save the return address
* in the stack address, so, we "emulate" one in _mcount's stack space,
* and hijack it directly, but for a non-leaf function, it save the
* return address to the its own stack space, we can not hijack it
* directly, but need to find the real stack address,
* ftrace_get_parent_addr() does it!
*
* if gcc>= 4.5, with the new -mmcount-ra-address option, for a
* non-leaf function, the location of the return address will be saved
* to $12 for us, and for a leaf function, only put a zero into $12. we
* do it in ftrace_graph_caller of mcount.S.
*/
/* old_parent_ra = *parent_ra_addr; */
safe_load_stack(old_parent_ra, parent_ra_addr, faulted);
if (unlikely(faulted))
goto out;
#ifndef KBUILD_MCOUNT_RA_ADDRESS
parent_ra_addr = (unsigned long *)ftrace_get_parent_ra_addr(self_ra,
old_parent_ra, (unsigned long)parent_ra_addr, fp);
/*
* If fails when getting the stack address of the non-leaf function's
* ra, stop function graph tracer and return
*/
if (parent_ra_addr == 0)
goto out;
#endif
/* *parent_ra_addr = return_hooker; */
safe_store_stack(return_hooker, parent_ra_addr, faulted);
if (unlikely(faulted))
goto out;
if (ftrace_push_return_trace(old_parent_ra, self_ra, &trace.depth, fp)
== -EBUSY) {
*parent_ra_addr = old_parent_ra;
return;
}
/*
* Get the recorded ip of the current mcount calling site in the
* __mcount_loc section, which will be used to filter the function
* entries configured through the tracing/set_graph_function interface.
*/
insns = in_kernel_space(self_ra) ? 2 : MCOUNT_OFFSET_INSNS + 1;
trace.func = self_ra - (MCOUNT_INSN_SIZE * insns);
/* Only trace if the calling function expects to */
if (!ftrace_graph_entry(&trace)) {
current->curr_ret_stack--;
*parent_ra_addr = old_parent_ra;
}
return;
out:
ftrace_graph_stop();
WARN_ON(1);
}
#endif /* CONFIG_FUNCTION_GRAPH_TRACER */
#ifdef CONFIG_FTRACE_SYSCALLS
#ifdef CONFIG_32BIT
unsigned long __init arch_syscall_addr(int nr)
{
return (unsigned long)sys_call_table[nr - __NR_O32_Linux];
}
#endif
#ifdef CONFIG_64BIT
unsigned long __init arch_syscall_addr(int nr)
{
#ifdef CONFIG_MIPS32_N32
if (nr >= __NR_N32_Linux && nr <= __NR_N32_Linux + __NR_N32_Linux_syscalls)
return (unsigned long)sysn32_call_table[nr - __NR_N32_Linux];
#endif
if (nr >= __NR_64_Linux && nr <= __NR_64_Linux + __NR_64_Linux_syscalls)
return (unsigned long)sys_call_table[nr - __NR_64_Linux];
#ifdef CONFIG_MIPS32_O32
if (nr >= __NR_O32_Linux && nr <= __NR_O32_Linux + __NR_O32_Linux_syscalls)
return (unsigned long)sys32_call_table[nr - __NR_O32_Linux];
#endif
return (unsigned long) &sys_ni_syscall;
}
#endif
#endif /* CONFIG_FTRACE_SYSCALLS */
| gpl-2.0 |
akshay4/android_old_kernel_htc_pico | drivers/rtc/rtc-wm8350.c | 3097 | 12389 | /*
* Real Time Clock driver for Wolfson Microelectronics WM8350
*
* Copyright (C) 2007, 2008 Wolfson Microelectronics PLC.
*
* Author: Liam Girdwood
* 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/kernel.h>
#include <linux/time.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <linux/interrupt.h>
#include <linux/ioctl.h>
#include <linux/completion.h>
#include <linux/mfd/wm8350/rtc.h>
#include <linux/mfd/wm8350/core.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#define WM8350_SET_ALM_RETRIES 5
#define WM8350_SET_TIME_RETRIES 5
#define WM8350_GET_TIME_RETRIES 5
#define to_wm8350_from_rtc_dev(d) container_of(d, struct wm8350, rtc.pdev.dev)
/*
* Read current time and date in RTC
*/
static int wm8350_rtc_readtime(struct device *dev, struct rtc_time *tm)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
u16 time1[4], time2[4];
int retries = WM8350_GET_TIME_RETRIES, ret;
/*
* Read the time twice and compare.
* If time1 == time2, then time is valid else retry.
*/
do {
ret = wm8350_block_read(wm8350, WM8350_RTC_SECONDS_MINUTES,
4, time1);
if (ret < 0)
return ret;
ret = wm8350_block_read(wm8350, WM8350_RTC_SECONDS_MINUTES,
4, time2);
if (ret < 0)
return ret;
if (memcmp(time1, time2, sizeof(time1)) == 0) {
tm->tm_sec = time1[0] & WM8350_RTC_SECS_MASK;
tm->tm_min = (time1[0] & WM8350_RTC_MINS_MASK)
>> WM8350_RTC_MINS_SHIFT;
tm->tm_hour = time1[1] & WM8350_RTC_HRS_MASK;
tm->tm_wday = ((time1[1] >> WM8350_RTC_DAY_SHIFT)
& 0x7) - 1;
tm->tm_mon = ((time1[2] & WM8350_RTC_MTH_MASK)
>> WM8350_RTC_MTH_SHIFT) - 1;
tm->tm_mday = (time1[2] & WM8350_RTC_DATE_MASK);
tm->tm_year = ((time1[3] & WM8350_RTC_YHUNDREDS_MASK)
>> WM8350_RTC_YHUNDREDS_SHIFT) * 100;
tm->tm_year += time1[3] & WM8350_RTC_YUNITS_MASK;
tm->tm_yday = rtc_year_days(tm->tm_mday, tm->tm_mon,
tm->tm_year);
tm->tm_year -= 1900;
dev_dbg(dev, "Read (%d left): %04x %04x %04x %04x\n",
retries,
time1[0], time1[1], time1[2], time1[3]);
return 0;
}
} while (retries--);
dev_err(dev, "timed out reading RTC time\n");
return -EIO;
}
/*
* Set current time and date in RTC
*/
static int wm8350_rtc_settime(struct device *dev, struct rtc_time *tm)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
u16 time[4];
u16 rtc_ctrl;
int ret, retries = WM8350_SET_TIME_RETRIES;
time[0] = tm->tm_sec;
time[0] |= tm->tm_min << WM8350_RTC_MINS_SHIFT;
time[1] = tm->tm_hour;
time[1] |= (tm->tm_wday + 1) << WM8350_RTC_DAY_SHIFT;
time[2] = tm->tm_mday;
time[2] |= (tm->tm_mon + 1) << WM8350_RTC_MTH_SHIFT;
time[3] = ((tm->tm_year + 1900) / 100) << WM8350_RTC_YHUNDREDS_SHIFT;
time[3] |= (tm->tm_year + 1900) % 100;
dev_dbg(dev, "Setting: %04x %04x %04x %04x\n",
time[0], time[1], time[2], time[3]);
/* Set RTC_SET to stop the clock */
ret = wm8350_set_bits(wm8350, WM8350_RTC_TIME_CONTROL, WM8350_RTC_SET);
if (ret < 0)
return ret;
/* Wait until confirmation of stopping */
do {
rtc_ctrl = wm8350_reg_read(wm8350, WM8350_RTC_TIME_CONTROL);
schedule_timeout_uninterruptible(msecs_to_jiffies(1));
} while (--retries && !(rtc_ctrl & WM8350_RTC_STS));
if (!retries) {
dev_err(dev, "timed out on set confirmation\n");
return -EIO;
}
/* Write time to RTC */
ret = wm8350_block_write(wm8350, WM8350_RTC_SECONDS_MINUTES, 4, time);
if (ret < 0)
return ret;
/* Clear RTC_SET to start the clock */
ret = wm8350_clear_bits(wm8350, WM8350_RTC_TIME_CONTROL,
WM8350_RTC_SET);
return ret;
}
/*
* Read alarm time and date in RTC
*/
static int wm8350_rtc_readalarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
struct rtc_time *tm = &alrm->time;
u16 time[4];
int ret;
ret = wm8350_block_read(wm8350, WM8350_ALARM_SECONDS_MINUTES, 4, time);
if (ret < 0)
return ret;
tm->tm_sec = time[0] & WM8350_RTC_ALMSECS_MASK;
if (tm->tm_sec == WM8350_RTC_ALMSECS_MASK)
tm->tm_sec = -1;
tm->tm_min = time[0] & WM8350_RTC_ALMMINS_MASK;
if (tm->tm_min == WM8350_RTC_ALMMINS_MASK)
tm->tm_min = -1;
else
tm->tm_min >>= WM8350_RTC_ALMMINS_SHIFT;
tm->tm_hour = time[1] & WM8350_RTC_ALMHRS_MASK;
if (tm->tm_hour == WM8350_RTC_ALMHRS_MASK)
tm->tm_hour = -1;
tm->tm_wday = ((time[1] >> WM8350_RTC_ALMDAY_SHIFT) & 0x7) - 1;
if (tm->tm_wday > 7)
tm->tm_wday = -1;
tm->tm_mon = time[2] & WM8350_RTC_ALMMTH_MASK;
if (tm->tm_mon == WM8350_RTC_ALMMTH_MASK)
tm->tm_mon = -1;
else
tm->tm_mon = (tm->tm_mon >> WM8350_RTC_ALMMTH_SHIFT) - 1;
tm->tm_mday = (time[2] & WM8350_RTC_ALMDATE_MASK);
if (tm->tm_mday == WM8350_RTC_ALMDATE_MASK)
tm->tm_mday = -1;
tm->tm_year = -1;
alrm->enabled = !(time[3] & WM8350_RTC_ALMSTS);
return 0;
}
static int wm8350_rtc_stop_alarm(struct wm8350 *wm8350)
{
int retries = WM8350_SET_ALM_RETRIES;
u16 rtc_ctrl;
int ret;
/* Set RTC_SET to stop the clock */
ret = wm8350_set_bits(wm8350, WM8350_RTC_TIME_CONTROL,
WM8350_RTC_ALMSET);
if (ret < 0)
return ret;
/* Wait until confirmation of stopping */
do {
rtc_ctrl = wm8350_reg_read(wm8350, WM8350_RTC_TIME_CONTROL);
schedule_timeout_uninterruptible(msecs_to_jiffies(1));
} while (retries-- && !(rtc_ctrl & WM8350_RTC_ALMSTS));
if (!(rtc_ctrl & WM8350_RTC_ALMSTS))
return -ETIMEDOUT;
return 0;
}
static int wm8350_rtc_start_alarm(struct wm8350 *wm8350)
{
int ret;
int retries = WM8350_SET_ALM_RETRIES;
u16 rtc_ctrl;
ret = wm8350_clear_bits(wm8350, WM8350_RTC_TIME_CONTROL,
WM8350_RTC_ALMSET);
if (ret < 0)
return ret;
/* Wait until confirmation */
do {
rtc_ctrl = wm8350_reg_read(wm8350, WM8350_RTC_TIME_CONTROL);
schedule_timeout_uninterruptible(msecs_to_jiffies(1));
} while (retries-- && rtc_ctrl & WM8350_RTC_ALMSTS);
if (rtc_ctrl & WM8350_RTC_ALMSTS)
return -ETIMEDOUT;
return 0;
}
static int wm8350_rtc_alarm_irq_enable(struct device *dev,
unsigned int enabled)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
if (enabled)
return wm8350_rtc_start_alarm(wm8350);
else
return wm8350_rtc_stop_alarm(wm8350);
}
static int wm8350_rtc_setalarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
struct rtc_time *tm = &alrm->time;
u16 time[3];
int ret;
memset(time, 0, sizeof(time));
if (tm->tm_sec != -1)
time[0] |= tm->tm_sec;
else
time[0] |= WM8350_RTC_ALMSECS_MASK;
if (tm->tm_min != -1)
time[0] |= tm->tm_min << WM8350_RTC_ALMMINS_SHIFT;
else
time[0] |= WM8350_RTC_ALMMINS_MASK;
if (tm->tm_hour != -1)
time[1] |= tm->tm_hour;
else
time[1] |= WM8350_RTC_ALMHRS_MASK;
if (tm->tm_wday != -1)
time[1] |= (tm->tm_wday + 1) << WM8350_RTC_ALMDAY_SHIFT;
else
time[1] |= WM8350_RTC_ALMDAY_MASK;
if (tm->tm_mday != -1)
time[2] |= tm->tm_mday;
else
time[2] |= WM8350_RTC_ALMDATE_MASK;
if (tm->tm_mon != -1)
time[2] |= (tm->tm_mon + 1) << WM8350_RTC_ALMMTH_SHIFT;
else
time[2] |= WM8350_RTC_ALMMTH_MASK;
ret = wm8350_rtc_stop_alarm(wm8350);
if (ret < 0)
return ret;
/* Write time to RTC */
ret = wm8350_block_write(wm8350, WM8350_ALARM_SECONDS_MINUTES,
3, time);
if (ret < 0)
return ret;
if (alrm->enabled)
ret = wm8350_rtc_start_alarm(wm8350);
return ret;
}
static irqreturn_t wm8350_rtc_alarm_handler(int irq, void *data)
{
struct wm8350 *wm8350 = data;
struct rtc_device *rtc = wm8350->rtc.rtc;
int ret;
rtc_update_irq(rtc, 1, RTC_IRQF | RTC_AF);
/* Make it one shot */
ret = wm8350_set_bits(wm8350, WM8350_RTC_TIME_CONTROL,
WM8350_RTC_ALMSET);
if (ret != 0) {
dev_err(&(wm8350->rtc.pdev->dev),
"Failed to disable alarm: %d\n", ret);
}
return IRQ_HANDLED;
}
static irqreturn_t wm8350_rtc_update_handler(int irq, void *data)
{
struct wm8350 *wm8350 = data;
struct rtc_device *rtc = wm8350->rtc.rtc;
rtc_update_irq(rtc, 1, RTC_IRQF | RTC_UF);
return IRQ_HANDLED;
}
static const struct rtc_class_ops wm8350_rtc_ops = {
.read_time = wm8350_rtc_readtime,
.set_time = wm8350_rtc_settime,
.read_alarm = wm8350_rtc_readalarm,
.set_alarm = wm8350_rtc_setalarm,
.alarm_irq_enable = wm8350_rtc_alarm_irq_enable,
};
#ifdef CONFIG_PM
static int wm8350_rtc_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct wm8350 *wm8350 = dev_get_drvdata(&pdev->dev);
int ret = 0;
u16 reg;
reg = wm8350_reg_read(wm8350, WM8350_RTC_TIME_CONTROL);
if (device_may_wakeup(&wm8350->rtc.pdev->dev) &&
reg & WM8350_RTC_ALMSTS) {
ret = wm8350_rtc_stop_alarm(wm8350);
if (ret != 0)
dev_err(&pdev->dev, "Failed to stop RTC alarm: %d\n",
ret);
}
return ret;
}
static int wm8350_rtc_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct wm8350 *wm8350 = dev_get_drvdata(&pdev->dev);
int ret;
if (wm8350->rtc.alarm_enabled) {
ret = wm8350_rtc_start_alarm(wm8350);
if (ret != 0)
dev_err(&pdev->dev,
"Failed to restart RTC alarm: %d\n", ret);
}
return 0;
}
#else
#define wm8350_rtc_suspend NULL
#define wm8350_rtc_resume NULL
#endif
static int wm8350_rtc_probe(struct platform_device *pdev)
{
struct wm8350 *wm8350 = platform_get_drvdata(pdev);
struct wm8350_rtc *wm_rtc = &wm8350->rtc;
int ret = 0;
u16 timectl, power5;
timectl = wm8350_reg_read(wm8350, WM8350_RTC_TIME_CONTROL);
if (timectl & WM8350_RTC_BCD) {
dev_err(&pdev->dev, "RTC BCD mode not supported\n");
return -EINVAL;
}
if (timectl & WM8350_RTC_12HR) {
dev_err(&pdev->dev, "RTC 12 hour mode not supported\n");
return -EINVAL;
}
/* enable the RTC if it's not already enabled */
power5 = wm8350_reg_read(wm8350, WM8350_POWER_MGMT_5);
if (!(power5 & WM8350_RTC_TICK_ENA)) {
dev_info(wm8350->dev, "Starting RTC\n");
wm8350_reg_unlock(wm8350);
ret = wm8350_set_bits(wm8350, WM8350_POWER_MGMT_5,
WM8350_RTC_TICK_ENA);
if (ret < 0) {
dev_err(&pdev->dev, "failed to enable RTC: %d\n", ret);
return ret;
}
wm8350_reg_lock(wm8350);
}
if (timectl & WM8350_RTC_STS) {
int retries;
ret = wm8350_clear_bits(wm8350, WM8350_RTC_TIME_CONTROL,
WM8350_RTC_SET);
if (ret < 0) {
dev_err(&pdev->dev, "failed to start: %d\n", ret);
return ret;
}
retries = WM8350_SET_TIME_RETRIES;
do {
timectl = wm8350_reg_read(wm8350,
WM8350_RTC_TIME_CONTROL);
} while (timectl & WM8350_RTC_STS && --retries);
if (retries == 0) {
dev_err(&pdev->dev, "failed to start: timeout\n");
return -ENODEV;
}
}
device_init_wakeup(&pdev->dev, 1);
wm_rtc->rtc = rtc_device_register("wm8350", &pdev->dev,
&wm8350_rtc_ops, THIS_MODULE);
if (IS_ERR(wm_rtc->rtc)) {
ret = PTR_ERR(wm_rtc->rtc);
dev_err(&pdev->dev, "failed to register RTC: %d\n", ret);
return ret;
}
wm8350_register_irq(wm8350, WM8350_IRQ_RTC_SEC,
wm8350_rtc_update_handler, 0,
"RTC Seconds", wm8350);
wm8350_mask_irq(wm8350, WM8350_IRQ_RTC_SEC);
wm8350_register_irq(wm8350, WM8350_IRQ_RTC_ALM,
wm8350_rtc_alarm_handler, 0,
"RTC Alarm", wm8350);
return 0;
}
static int __devexit wm8350_rtc_remove(struct platform_device *pdev)
{
struct wm8350 *wm8350 = platform_get_drvdata(pdev);
struct wm8350_rtc *wm_rtc = &wm8350->rtc;
wm8350_free_irq(wm8350, WM8350_IRQ_RTC_SEC, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_RTC_ALM, wm8350);
rtc_device_unregister(wm_rtc->rtc);
return 0;
}
static struct dev_pm_ops wm8350_rtc_pm_ops = {
.suspend = wm8350_rtc_suspend,
.resume = wm8350_rtc_resume,
};
static struct platform_driver wm8350_rtc_driver = {
.probe = wm8350_rtc_probe,
.remove = __devexit_p(wm8350_rtc_remove),
.driver = {
.name = "wm8350-rtc",
.pm = &wm8350_rtc_pm_ops,
},
};
static int __init wm8350_rtc_init(void)
{
return platform_driver_register(&wm8350_rtc_driver);
}
module_init(wm8350_rtc_init);
static void __exit wm8350_rtc_exit(void)
{
platform_driver_unregister(&wm8350_rtc_driver);
}
module_exit(wm8350_rtc_exit);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("RTC driver for the WM8350");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm8350-rtc");
| gpl-2.0 |
EmmanuelU/wild_kernel_htc_msm8660 | drivers/char/hw_random/picoxcell-rng.c | 3097 | 5031 | /*
* Copyright (c) 2010-2011 Picochip Ltd., Jamie Iles
*
* 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.
*
* All enquiries to support@picochip.com
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/hw_random.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#define DATA_REG_OFFSET 0x0200
#define CSR_REG_OFFSET 0x0278
#define CSR_OUT_EMPTY_MASK (1 << 24)
#define CSR_FAULT_MASK (1 << 1)
#define TRNG_BLOCK_RESET_MASK (1 << 0)
#define TAI_REG_OFFSET 0x0380
/*
* The maximum amount of time in microseconds to spend waiting for data if the
* core wants us to wait. The TRNG should generate 32 bits every 320ns so a
* timeout of 20us seems reasonable. The TRNG does builtin tests of the data
* for randomness so we can't always assume there is data present.
*/
#define PICO_TRNG_TIMEOUT 20
static void __iomem *rng_base;
static struct clk *rng_clk;
struct device *rng_dev;
static inline u32 picoxcell_trng_read_csr(void)
{
return __raw_readl(rng_base + CSR_REG_OFFSET);
}
static inline bool picoxcell_trng_is_empty(void)
{
return picoxcell_trng_read_csr() & CSR_OUT_EMPTY_MASK;
}
/*
* Take the random number generator out of reset and make sure the interrupts
* are masked. We shouldn't need to get large amounts of random bytes so just
* poll the status register. The hardware generates 32 bits every 320ns so we
* shouldn't have to wait long enough to warrant waiting for an IRQ.
*/
static void picoxcell_trng_start(void)
{
__raw_writel(0, rng_base + TAI_REG_OFFSET);
__raw_writel(0, rng_base + CSR_REG_OFFSET);
}
static void picoxcell_trng_reset(void)
{
__raw_writel(TRNG_BLOCK_RESET_MASK, rng_base + CSR_REG_OFFSET);
__raw_writel(TRNG_BLOCK_RESET_MASK, rng_base + TAI_REG_OFFSET);
picoxcell_trng_start();
}
/*
* Get some random data from the random number generator. The hw_random core
* layer provides us with locking.
*/
static int picoxcell_trng_read(struct hwrng *rng, void *buf, size_t max,
bool wait)
{
int i;
/* Wait for some data to become available. */
for (i = 0; i < PICO_TRNG_TIMEOUT && picoxcell_trng_is_empty(); ++i) {
if (!wait)
return 0;
udelay(1);
}
if (picoxcell_trng_read_csr() & CSR_FAULT_MASK) {
dev_err(rng_dev, "fault detected, resetting TRNG\n");
picoxcell_trng_reset();
return -EIO;
}
if (i == PICO_TRNG_TIMEOUT)
return 0;
*(u32 *)buf = __raw_readl(rng_base + DATA_REG_OFFSET);
return sizeof(u32);
}
static struct hwrng picoxcell_trng = {
.name = "picoxcell",
.read = picoxcell_trng_read,
};
static int picoxcell_trng_probe(struct platform_device *pdev)
{
int ret;
struct resource *mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_warn(&pdev->dev, "no memory resource\n");
return -ENOMEM;
}
if (!devm_request_mem_region(&pdev->dev, mem->start, resource_size(mem),
"picoxcell_trng")) {
dev_warn(&pdev->dev, "unable to request io mem\n");
return -EBUSY;
}
rng_base = devm_ioremap(&pdev->dev, mem->start, resource_size(mem));
if (!rng_base) {
dev_warn(&pdev->dev, "unable to remap io mem\n");
return -ENOMEM;
}
rng_clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(rng_clk)) {
dev_warn(&pdev->dev, "no clk\n");
return PTR_ERR(rng_clk);
}
ret = clk_enable(rng_clk);
if (ret) {
dev_warn(&pdev->dev, "unable to enable clk\n");
goto err_enable;
}
picoxcell_trng_start();
ret = hwrng_register(&picoxcell_trng);
if (ret)
goto err_register;
rng_dev = &pdev->dev;
dev_info(&pdev->dev, "pixoxcell random number generator active\n");
return 0;
err_register:
clk_disable(rng_clk);
err_enable:
clk_put(rng_clk);
return ret;
}
static int __devexit picoxcell_trng_remove(struct platform_device *pdev)
{
hwrng_unregister(&picoxcell_trng);
clk_disable(rng_clk);
clk_put(rng_clk);
return 0;
}
#ifdef CONFIG_PM
static int picoxcell_trng_suspend(struct device *dev)
{
clk_disable(rng_clk);
return 0;
}
static int picoxcell_trng_resume(struct device *dev)
{
return clk_enable(rng_clk);
}
static const struct dev_pm_ops picoxcell_trng_pm_ops = {
.suspend = picoxcell_trng_suspend,
.resume = picoxcell_trng_resume,
};
#endif /* CONFIG_PM */
static struct platform_driver picoxcell_trng_driver = {
.probe = picoxcell_trng_probe,
.remove = __devexit_p(picoxcell_trng_remove),
.driver = {
.name = "picoxcell-trng",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &picoxcell_trng_pm_ops,
#endif /* CONFIG_PM */
},
};
static int __init picoxcell_trng_init(void)
{
return platform_driver_register(&picoxcell_trng_driver);
}
module_init(picoxcell_trng_init);
static void __exit picoxcell_trng_exit(void)
{
platform_driver_unregister(&picoxcell_trng_driver);
}
module_exit(picoxcell_trng_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jamie Iles");
MODULE_DESCRIPTION("Picochip picoXcell TRNG driver");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.