repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
CyanogenMod/android_kernel_zte_msm8994 | drivers/media/rc/keymaps/rc-budget-ci-old.c | 7637 | 2550 | /* budget-ci-old.h - Keytable for budget_ci_old 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>
#include <linux/module.h>
/*
* From reading the following remotes:
* Zenith Universal 7 / TV Mode 807 / VCR Mode 837
* Hauppauge (from NOVA-CI-s box product)
* This is a "middle of the road" approach, differences are noted
*/
static struct rc_map_table budget_ci_old[] = {
{ 0x00, KEY_0 },
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
{ 0x03, KEY_3 },
{ 0x04, KEY_4 },
{ 0x05, KEY_5 },
{ 0x06, KEY_6 },
{ 0x07, KEY_7 },
{ 0x08, KEY_8 },
{ 0x09, KEY_9 },
{ 0x0a, KEY_ENTER },
{ 0x0b, KEY_RED },
{ 0x0c, KEY_POWER }, /* RADIO on Hauppauge */
{ 0x0d, KEY_MUTE },
{ 0x0f, KEY_A }, /* TV on Hauppauge */
{ 0x10, KEY_VOLUMEUP },
{ 0x11, KEY_VOLUMEDOWN },
{ 0x14, KEY_B },
{ 0x1c, KEY_UP },
{ 0x1d, KEY_DOWN },
{ 0x1e, KEY_OPTION }, /* RESERVED on Hauppauge */
{ 0x1f, KEY_BREAK },
{ 0x20, KEY_CHANNELUP },
{ 0x21, KEY_CHANNELDOWN },
{ 0x22, KEY_PREVIOUS }, /* Prev Ch on Zenith, SOURCE on Hauppauge */
{ 0x24, KEY_RESTART },
{ 0x25, KEY_OK },
{ 0x26, KEY_CYCLEWINDOWS }, /* MINIMIZE on Hauppauge */
{ 0x28, KEY_ENTER }, /* VCR mode on Zenith */
{ 0x29, KEY_PAUSE },
{ 0x2b, KEY_RIGHT },
{ 0x2c, KEY_LEFT },
{ 0x2e, KEY_MENU }, /* FULL SCREEN on Hauppauge */
{ 0x30, KEY_SLOW },
{ 0x31, KEY_PREVIOUS }, /* VCR mode on Zenith */
{ 0x32, KEY_REWIND },
{ 0x34, KEY_FASTFORWARD },
{ 0x35, KEY_PLAY },
{ 0x36, KEY_STOP },
{ 0x37, KEY_RECORD },
{ 0x38, KEY_TUNER }, /* TV/VCR on Zenith */
{ 0x3a, KEY_C },
{ 0x3c, KEY_EXIT },
{ 0x3d, KEY_POWER2 },
{ 0x3e, KEY_TUNER },
};
static struct rc_map_list budget_ci_old_map = {
.map = {
.scan = budget_ci_old,
.size = ARRAY_SIZE(budget_ci_old),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_BUDGET_CI_OLD,
}
};
static int __init init_rc_map_budget_ci_old(void)
{
return rc_map_register(&budget_ci_old_map);
}
static void __exit exit_rc_map_budget_ci_old(void)
{
rc_map_unregister(&budget_ci_old_map);
}
module_init(init_rc_map_budget_ci_old)
module_exit(exit_rc_map_budget_ci_old)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
ryrzy/LG-D802-G2-_Android_KK_D802_v20b | drivers/media/rc/keymaps/rc-avermedia-m733a-rm-k6.c | 7637 | 2493 | /* avermedia-m733a-rm-k6.h - Keytable for avermedia_m733a_rm_k6 Remote Controller
*
* Copyright (c) 2010 by Herton Ronaldo Krzesinski <herton@mandriva.com.br>
*
* 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>
#include <linux/module.h>
/*
* Avermedia M733A with IR model RM-K6
* This is the stock remote controller used with Positivo machines with M733A
* Herton Ronaldo Krzesinski <herton@mandriva.com.br>
*/
static struct rc_map_table avermedia_m733a_rm_k6[] = {
{ 0x0401, KEY_POWER2 },
{ 0x0406, KEY_MUTE },
{ 0x0408, KEY_MODE }, /* TV/FM */
{ 0x0409, KEY_1 },
{ 0x040a, KEY_2 },
{ 0x040b, KEY_3 },
{ 0x040c, KEY_4 },
{ 0x040d, KEY_5 },
{ 0x040e, KEY_6 },
{ 0x040f, KEY_7 },
{ 0x0410, KEY_8 },
{ 0x0411, KEY_9 },
{ 0x044c, KEY_DOT }, /* '.' */
{ 0x0412, KEY_0 },
{ 0x0407, KEY_REFRESH }, /* Refresh/Reload */
{ 0x0413, KEY_AUDIO },
{ 0x0440, KEY_SCREEN }, /* Full Screen toggle */
{ 0x0441, KEY_HOME },
{ 0x0442, KEY_BACK },
{ 0x0447, KEY_UP },
{ 0x0448, KEY_DOWN },
{ 0x0449, KEY_LEFT },
{ 0x044a, KEY_RIGHT },
{ 0x044b, KEY_OK },
{ 0x0404, KEY_VOLUMEUP },
{ 0x0405, KEY_VOLUMEDOWN },
{ 0x0402, KEY_CHANNELUP },
{ 0x0403, KEY_CHANNELDOWN },
{ 0x0443, KEY_RED },
{ 0x0444, KEY_GREEN },
{ 0x0445, KEY_YELLOW },
{ 0x0446, KEY_BLUE },
{ 0x0414, KEY_TEXT },
{ 0x0415, KEY_EPG },
{ 0x041a, KEY_TV2 }, /* PIP */
{ 0x041b, KEY_CAMERA }, /* Snapshot */
{ 0x0417, KEY_RECORD },
{ 0x0416, KEY_PLAYPAUSE },
{ 0x0418, KEY_STOP },
{ 0x0419, KEY_PAUSE },
{ 0x041f, KEY_PREVIOUS },
{ 0x041c, KEY_REWIND },
{ 0x041d, KEY_FORWARD },
{ 0x041e, KEY_NEXT },
};
static struct rc_map_list avermedia_m733a_rm_k6_map = {
.map = {
.scan = avermedia_m733a_rm_k6,
.size = ARRAY_SIZE(avermedia_m733a_rm_k6),
.rc_type = RC_TYPE_NEC,
.name = RC_MAP_AVERMEDIA_M733A_RM_K6,
}
};
static int __init init_rc_map_avermedia_m733a_rm_k6(void)
{
return rc_map_register(&avermedia_m733a_rm_k6_map);
}
static void __exit exit_rc_map_avermedia_m733a_rm_k6(void)
{
rc_map_unregister(&avermedia_m733a_rm_k6_map);
}
module_init(init_rc_map_avermedia_m733a_rm_k6)
module_exit(exit_rc_map_avermedia_m733a_rm_k6)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
Albinoman887/pyramid-3.4.10 | drivers/staging/comedi/drivers/adl_pci6208.c | 8149 | 13009 | /*
comedi/drivers/adl_pci6208.c
Hardware driver for ADLink 6208 series cards:
card | voltage output | current output
-------------+-------------------+---------------
PCI-6208V | 8 channels | -
PCI-6216V | 16 channels | -
PCI-6208A | 8 channels | 8 channels
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: adl_pci6208
Description: ADLink PCI-6208A
Devices: [ADLink] PCI-6208A (adl_pci6208)
Author: nsyeow <nsyeow@pd.jaring.my>
Updated: Fri, 30 Jan 2004 14:44:27 +0800
Status: untested
Configuration Options:
none
References:
- ni_660x.c
- adl_pci9111.c copied the entire pci setup section
- adl_pci9118.c
*/
/*
* These headers should be followed by a blank line, and any comments
* you wish to say about the driver. The comment area is the place
* to put any known bugs, limitations, unsupported features, supported
* command triggers, whether or not commands are supported on particular
* subdevices, etc.
*
* Somewhere in the comment should be information about configuration
* options that are used with comedi_config.
*/
#include "../comedidev.h"
#include "comedi_pci.h"
#define PCI6208_DRIVER_NAME "adl_pci6208"
/* Board descriptions */
struct pci6208_board {
const char *name;
unsigned short dev_id; /* `lspci` will show you this */
int ao_chans;
/* int ao_bits; */
};
static const struct pci6208_board pci6208_boards[] = {
/*{
.name = "pci6208v",
.dev_id = 0x6208, // not sure
.ao_chans = 8
// , .ao_bits = 16
},
{
.name = "pci6216v",
.dev_id = 0x6208, // not sure
.ao_chans = 16
// , .ao_bits = 16
}, */
{
.name = "pci6208a",
.dev_id = 0x6208,
.ao_chans = 8
/* , .ao_bits = 16 */
}
};
/* This is used by modprobe to translate PCI IDs to drivers. Should
* only be used for PCI and ISA-PnP devices */
static DEFINE_PCI_DEVICE_TABLE(pci6208_pci_table) = {
/* { PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, */
/* { PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, */
{ PCI_DEVICE(PCI_VENDOR_ID_ADLINK, 0x6208) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, pci6208_pci_table);
/* Will be initialized in pci6208_find device(). */
#define thisboard ((const struct pci6208_board *)dev->board_ptr)
struct pci6208_private {
int data;
struct pci_dev *pci_dev; /* for a PCI device */
unsigned int ao_readback[2]; /* Used for AO readback */
};
#define devpriv ((struct pci6208_private *)dev->private)
static int pci6208_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int pci6208_detach(struct comedi_device *dev);
static struct comedi_driver driver_pci6208 = {
.driver_name = PCI6208_DRIVER_NAME,
.module = THIS_MODULE,
.attach = pci6208_attach,
.detach = pci6208_detach,
};
static int __devinit driver_pci6208_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_pci6208.driver_name);
}
static void __devexit driver_pci6208_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_pci6208_pci_driver = {
.id_table = pci6208_pci_table,
.probe = &driver_pci6208_pci_probe,
.remove = __devexit_p(&driver_pci6208_pci_remove)
};
static int __init driver_pci6208_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_pci6208);
if (retval < 0)
return retval;
driver_pci6208_pci_driver.name = (char *)driver_pci6208.driver_name;
return pci_register_driver(&driver_pci6208_pci_driver);
}
static void __exit driver_pci6208_cleanup_module(void)
{
pci_unregister_driver(&driver_pci6208_pci_driver);
comedi_driver_unregister(&driver_pci6208);
}
module_init(driver_pci6208_init_module);
module_exit(driver_pci6208_cleanup_module);
static int pci6208_find_device(struct comedi_device *dev, int bus, int slot);
static int
pci6208_pci_setup(struct pci_dev *pci_dev, unsigned long *io_base_ptr,
int dev_minor);
/*read/write functions*/
static int pci6208_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int pci6208_ao_rinsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int pci6208_dio_insn_bits (struct comedi_device *dev,
* struct comedi_subdevice *s, */
/* struct comedi_insn *insn,unsigned int *data); */
/* static int pci6208_dio_insn_config(struct comedi_device *dev,
* struct comedi_subdevice *s, */
/* struct comedi_insn *insn,unsigned int *data); */
/*
* Attach is called by the Comedi core to configure the driver
* for a particular board. If you specified a board_name array
* in the driver structure, dev->board_ptr contains that
* address.
*/
static int pci6208_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
int retval;
unsigned long io_base;
printk(KERN_INFO "comedi%d: pci6208: ", dev->minor);
retval = alloc_private(dev, sizeof(struct pci6208_private));
if (retval < 0)
return retval;
retval = pci6208_find_device(dev, it->options[0], it->options[1]);
if (retval < 0)
return retval;
retval = pci6208_pci_setup(devpriv->pci_dev, &io_base, dev->minor);
if (retval < 0)
return retval;
dev->iobase = io_base;
dev->board_name = thisboard->name;
/*
* Allocate the subdevice structures. alloc_subdevice() is a
* convenient macro defined in comedidev.h.
*/
if (alloc_subdevices(dev, 2) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE; /* anything else to add here?? */
s->n_chan = thisboard->ao_chans;
s->maxdata = 0xffff; /* 16-bit DAC */
s->range_table = &range_bipolar10; /* this needs to be checked. */
s->insn_write = pci6208_ao_winsn;
s->insn_read = pci6208_ao_rinsn;
/* s=dev->subdevices+1; */
/* digital i/o subdevice */
/* s->type=COMEDI_SUBD_DIO; */
/* s->subdev_flags=SDF_READABLE|SDF_WRITABLE; */
/* s->n_chan=16; */
/* s->maxdata=1; */
/* s->range_table=&range_digital; */
/* s->insn_bits = pci6208_dio_insn_bits; */
/* s->insn_config = pci6208_dio_insn_config; */
printk(KERN_INFO "attached\n");
return 1;
}
/*
* _detach is called to deconfigure a device. It should deallocate
* resources.
* This function is also called when _attach() fails, so it should be
* careful not to release resources that were not necessarily
* allocated by _attach(). dev->private and dev->subdevices are
* deallocated automatically by the core.
*/
static int pci6208_detach(struct comedi_device *dev)
{
printk(KERN_INFO "comedi%d: pci6208: remove\n", dev->minor);
if (devpriv && devpriv->pci_dev) {
if (dev->iobase)
comedi_pci_disable(devpriv->pci_dev);
pci_dev_put(devpriv->pci_dev);
}
return 0;
}
static int pci6208_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i = 0, Data_Read;
unsigned short chan = CR_CHAN(insn->chanspec);
unsigned long invert = 1 << (16 - 1);
unsigned long out_value;
/* Writing a list of values to an AO channel is probably not
* very useful, but that's how the interface is defined. */
for (i = 0; i < insn->n; i++) {
out_value = data[i] ^ invert;
/* a typical programming sequence */
do {
Data_Read = (inw(dev->iobase) & 1);
} while (Data_Read);
outw(out_value, dev->iobase + (0x02 * chan));
devpriv->ao_readback[chan] = out_value;
}
/* return the number of samples read/written */
return i;
}
/* AO subdevices should have a read insn as well as a write insn.
* Usually this means copying a value stored in devpriv. */
static int pci6208_ao_rinsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
int chan = CR_CHAN(insn->chanspec);
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ao_readback[chan];
return i;
}
/* DIO devices are slightly special. Although it is possible to
* implement the insn_read/insn_write interface, it is much more
* useful to applications if you implement the insn_bits interface.
* This allows packed reading/writing of the DIO channels. The
* comedi core can convert between insn_bits and insn_read/write */
/* static int pci6208_dio_insn_bits(struct comedi_device *dev,
* struct comedi_subdevice *s, */
/* struct comedi_insn *insn,unsigned int *data) */
/* { */
/* if(insn->n!=2)return -EINVAL; */
/* The insn data is a mask in data[0] and the new data
* in data[1], each channel cooresponding to a bit. */
/* if(data[0]){ */
/* s->state &= ~data[0]; */
/* s->state |= data[0]&data[1]; */
/* Write out the new digital output lines */
/* outw(s->state,dev->iobase + SKEL_DIO); */
/* } */
/* on return, data[1] contains the value of the digital
* input and output lines. */
/* data[1]=inw(dev->iobase + SKEL_DIO); */
/* or we could just return the software copy of the output values if
* it was a purely digital output subdevice */
/* data[1]=s->state; */
/* return 2; */
/* } */
/* static int pci6208_dio_insn_config(struct comedi_device *dev,
* struct comedi_subdevice *s, */
/* struct comedi_insn *insn,unsigned int *data) */
/* { */
/* int chan=CR_CHAN(insn->chanspec); */
/* The input or output configuration of each digital line is
* configured by a special insn_config instruction. chanspec
* contains the channel to be changed, and data[0] contains the
* value COMEDI_INPUT or COMEDI_OUTPUT. */
/* if(data[0]==COMEDI_OUTPUT){ */
/* s->io_bits |= 1<<chan; */
/* }else{ */
/* s->io_bits &= ~(1<<chan); */
/* } */
/* outw(s->io_bits,dev->iobase + SKEL_DIO_CONFIG); */
/* return 1; */
/* } */
static int pci6208_find_device(struct comedi_device *dev, int bus, int slot)
{
struct pci_dev *pci_dev = NULL;
int i;
for_each_pci_dev(pci_dev) {
if (pci_dev->vendor == PCI_VENDOR_ID_ADLINK) {
for (i = 0; i < ARRAY_SIZE(pci6208_boards); i++) {
if (pci6208_boards[i].dev_id ==
pci_dev->device) {
/*
* was a particular bus/slot requested?
*/
if ((bus != 0) || (slot != 0)) {
/*
* are we on the
* wrong bus/slot?
*/
if (pci_dev->bus->number
!= bus ||
PCI_SLOT(pci_dev->devfn)
!= slot) {
continue;
}
}
dev->board_ptr = pci6208_boards + i;
goto found;
}
}
}
}
printk(KERN_ERR "comedi%d: no supported board found! "
"(req. bus/slot : %d/%d)\n",
dev->minor, bus, slot);
return -EIO;
found:
printk("comedi%d: found %s (b:s:f=%d:%d:%d) , irq=%d\n",
dev->minor,
pci6208_boards[i].name,
pci_dev->bus->number,
PCI_SLOT(pci_dev->devfn),
PCI_FUNC(pci_dev->devfn), pci_dev->irq);
/* TODO: Warn about non-tested boards. */
/* switch(board->device_id) */
/* { */
/* }; */
devpriv->pci_dev = pci_dev;
return 0;
}
static int
pci6208_pci_setup(struct pci_dev *pci_dev, unsigned long *io_base_ptr,
int dev_minor)
{
unsigned long io_base, io_range, lcr_io_base, lcr_io_range;
/* Enable PCI device and request regions */
if (comedi_pci_enable(pci_dev, PCI6208_DRIVER_NAME) < 0) {
printk(KERN_ERR "comedi%d: Failed to enable PCI device "
"and request regions\n",
dev_minor);
return -EIO;
}
/* Read local configuration register
* base address [PCI_BASE_ADDRESS #1].
*/
lcr_io_base = pci_resource_start(pci_dev, 1);
lcr_io_range = pci_resource_len(pci_dev, 1);
printk(KERN_INFO "comedi%d: local config registers at address"
" 0x%4lx [0x%4lx]\n",
dev_minor, lcr_io_base, lcr_io_range);
/* Read PCI6208 register base address [PCI_BASE_ADDRESS #2]. */
io_base = pci_resource_start(pci_dev, 2);
io_range = pci_resource_end(pci_dev, 2) - io_base + 1;
printk("comedi%d: 6208 registers at address 0x%4lx [0x%4lx]\n",
dev_minor, io_base, io_range);
*io_base_ptr = io_base;
/* devpriv->io_range = io_range; */
/* devpriv->is_valid=0; */
/* devpriv->lcr_io_base=lcr_io_base; */
/* devpriv->lcr_io_range=lcr_io_range; */
return 0;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Altaf-Mahdi/android_kernel_oneplus_msm8994 | sound/oss/trix.c | 8405 | 11131 | /*
* sound/oss/trix.c
*
* Low level driver for the MediaTrix AudioTrix Pro
* (MT-0002-PC Control Chip)
*
*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*
* Changes
* Alan Cox Modularisation, cleanup.
* Christoph Hellwig Adapted to module_init/module_exit
* Arnaldo C. de Melo Got rid of attach_uart401
*/
#include <linux/init.h>
#include <linux/module.h>
#include "sound_config.h"
#include "sb.h"
#include "sound_firmware.h"
#include "ad1848.h"
#include "mpu401.h"
#include "trix_boot.h"
static int mpu;
static bool joystick;
static unsigned char trix_read(int addr)
{
outb(((unsigned char) addr), 0x390); /* MT-0002-PC ASIC address */
return inb(0x391); /* MT-0002-PC ASIC data */
}
static void trix_write(int addr, int data)
{
outb(((unsigned char) addr), 0x390); /* MT-0002-PC ASIC address */
outb(((unsigned char) data), 0x391); /* MT-0002-PC ASIC data */
}
static void download_boot(int base)
{
int i = 0, n = trix_boot_len;
if (trix_boot_len == 0)
return;
trix_write(0xf8, 0x00); /* ??????? */
outb((0x01), base + 6); /* Clear the internal data pointer */
outb((0x00), base + 6); /* Restart */
/*
* Write the boot code to the RAM upload/download register.
* Each write increments the internal data pointer.
*/
outb((0x01), base + 6); /* Clear the internal data pointer */
outb((0x1A), 0x390); /* Select RAM download/upload port */
for (i = 0; i < n; i++)
outb((trix_boot[i]), 0x391);
for (i = n; i < 10016; i++) /* Clear up to first 16 bytes of data RAM */
outb((0x00), 0x391);
outb((0x00), base + 6); /* Reset */
outb((0x50), 0x390); /* ?????? */
}
static int trix_set_wss_port(struct address_info *hw_config)
{
unsigned char addr_bits;
if (trix_read(0x15) != 0x71) /* No ASIC signature */
{
MDB(printk(KERN_ERR "No AudioTrix ASIC signature found\n"));
return 0;
}
/*
* Reset some registers.
*/
trix_write(0x13, 0);
trix_write(0x14, 0);
/*
* Configure the ASIC to place the codec to the proper I/O location
*/
switch (hw_config->io_base)
{
case 0x530:
addr_bits = 0;
break;
case 0x604:
addr_bits = 1;
break;
case 0xE80:
addr_bits = 2;
break;
case 0xF40:
addr_bits = 3;
break;
default:
return 0;
}
trix_write(0x19, (trix_read(0x19) & 0x03) | addr_bits);
return 1;
}
/*
* Probe and attach routines for the Windows Sound System mode of
* AudioTrix Pro
*/
static int __init init_trix_wss(struct address_info *hw_config)
{
static unsigned char dma_bits[4] = {
1, 2, 0, 3
};
struct resource *ports;
int config_port = hw_config->io_base + 0;
int dma1 = hw_config->dma, dma2 = hw_config->dma2;
int old_num_mixers = num_mixers;
u8 config, bits;
int ret;
switch(hw_config->irq) {
case 7:
bits = 8;
break;
case 9:
bits = 0x10;
break;
case 10:
bits = 0x18;
break;
case 11:
bits = 0x20;
break;
default:
printk(KERN_ERR "AudioTrix: Bad WSS IRQ %d\n", hw_config->irq);
return 0;
}
switch (dma1) {
case 0:
case 1:
case 3:
break;
default:
printk(KERN_ERR "AudioTrix: Bad WSS DMA %d\n", dma1);
return 0;
}
switch (dma2) {
case -1:
case 0:
case 1:
case 3:
break;
default:
printk(KERN_ERR "AudioTrix: Bad capture DMA %d\n", dma2);
return 0;
}
/*
* Check if the IO port returns valid signature. The original MS Sound
* system returns 0x04 while some cards (AudioTrix Pro for example)
* return 0x00.
*/
ports = request_region(hw_config->io_base + 4, 4, "ad1848");
if (!ports) {
printk(KERN_ERR "AudioTrix: MSS I/O port conflict (%x)\n", hw_config->io_base);
return 0;
}
if (!request_region(hw_config->io_base, 4, "MSS config")) {
printk(KERN_ERR "AudioTrix: MSS I/O port conflict (%x)\n", hw_config->io_base);
release_region(hw_config->io_base + 4, 4);
return 0;
}
if (!trix_set_wss_port(hw_config))
goto fail;
config = inb(hw_config->io_base + 3);
if ((config & 0x3f) != 0x00)
{
MDB(printk(KERN_ERR "No MSS signature detected on port 0x%x\n", hw_config->io_base));
goto fail;
}
/*
* Check that DMA0 is not in use with a 8 bit board.
*/
if (dma1 == 0 && config & 0x80)
{
printk(KERN_ERR "AudioTrix: Can't use DMA0 with a 8 bit card slot\n");
goto fail;
}
if (hw_config->irq > 9 && config & 0x80)
{
printk(KERN_ERR "AudioTrix: Can't use IRQ%d with a 8 bit card slot\n", hw_config->irq);
goto fail;
}
ret = ad1848_detect(ports, NULL, hw_config->osp);
if (!ret)
goto fail;
if (joystick==1)
trix_write(0x15, 0x80);
/*
* Set the IRQ and DMA addresses.
*/
outb((bits | 0x40), config_port);
if (dma2 == -1 || dma2 == dma1)
{
bits |= dma_bits[dma1];
dma2 = dma1;
}
else
{
unsigned char tmp;
tmp = trix_read(0x13) & ~30;
trix_write(0x13, tmp | 0x80 | (dma1 << 4));
tmp = trix_read(0x14) & ~30;
trix_write(0x14, tmp | 0x80 | (dma2 << 4));
}
outb((bits), config_port); /* Write IRQ+DMA setup */
hw_config->slots[0] = ad1848_init("AudioTrix Pro", ports,
hw_config->irq,
dma1,
dma2,
0,
hw_config->osp,
THIS_MODULE);
if (num_mixers > old_num_mixers) /* Mixer got installed */
{
AD1848_REROUTE(SOUND_MIXER_LINE1, SOUND_MIXER_LINE); /* Line in */
AD1848_REROUTE(SOUND_MIXER_LINE2, SOUND_MIXER_CD);
AD1848_REROUTE(SOUND_MIXER_LINE3, SOUND_MIXER_SYNTH); /* OPL4 */
AD1848_REROUTE(SOUND_MIXER_SPEAKER, SOUND_MIXER_ALTPCM); /* SB */
}
return 1;
fail:
release_region(hw_config->io_base, 4);
release_region(hw_config->io_base + 4, 4);
return 0;
}
static int __init probe_trix_sb(struct address_info *hw_config)
{
int tmp;
unsigned char conf;
extern int sb_be_quiet;
int old_quiet;
static signed char irq_translate[] = {
-1, -1, -1, 0, 1, 2, -1, 3
};
if (trix_boot_len == 0)
return 0; /* No boot code -> no fun */
if ((hw_config->io_base & 0xffffff8f) != 0x200)
return 0;
tmp = hw_config->irq;
if (tmp > 7)
return 0;
if (irq_translate[tmp] == -1)
return 0;
tmp = hw_config->dma;
if (tmp != 1 && tmp != 3)
return 0;
if (!request_region(hw_config->io_base, 16, "soundblaster")) {
printk(KERN_ERR "AudioTrix: SB I/O port conflict (%x)\n", hw_config->io_base);
return 0;
}
conf = 0x84; /* DMA and IRQ enable */
conf |= hw_config->io_base & 0x70; /* I/O address bits */
conf |= irq_translate[hw_config->irq];
if (hw_config->dma == 3)
conf |= 0x08;
trix_write(0x1b, conf);
download_boot(hw_config->io_base);
hw_config->name = "AudioTrix SB";
if (!sb_dsp_detect(hw_config, 0, 0, NULL)) {
release_region(hw_config->io_base, 16);
return 0;
}
hw_config->driver_use_1 = SB_NO_MIDI | SB_NO_MIXER | SB_NO_RECORDING;
/* Prevent false alarms */
old_quiet = sb_be_quiet;
sb_be_quiet = 1;
sb_dsp_init(hw_config, THIS_MODULE);
sb_be_quiet = old_quiet;
return 1;
}
static int __init probe_trix_mpu(struct address_info *hw_config)
{
unsigned char conf;
static int irq_bits[] = {
-1, -1, -1, 1, 2, 3, -1, 4, -1, 5
};
if (hw_config->irq > 9)
{
printk(KERN_ERR "AudioTrix: Bad MPU IRQ %d\n", hw_config->irq);
return 0;
}
if (irq_bits[hw_config->irq] == -1)
{
printk(KERN_ERR "AudioTrix: Bad MPU IRQ %d\n", hw_config->irq);
return 0;
}
switch (hw_config->io_base)
{
case 0x330:
conf = 0x00;
break;
case 0x370:
conf = 0x04;
break;
case 0x3b0:
conf = 0x08;
break;
case 0x3f0:
conf = 0x0c;
break;
default:
return 0; /* Invalid port */
}
conf |= irq_bits[hw_config->irq] << 4;
trix_write(0x19, (trix_read(0x19) & 0x83) | conf);
hw_config->name = "AudioTrix Pro";
return probe_uart401(hw_config, THIS_MODULE);
}
static void __exit unload_trix_wss(struct address_info *hw_config)
{
int dma2 = hw_config->dma2;
if (dma2 == -1)
dma2 = hw_config->dma;
release_region(0x390, 2);
release_region(hw_config->io_base, 4);
ad1848_unload(hw_config->io_base + 4,
hw_config->irq,
hw_config->dma,
dma2,
0);
sound_unload_audiodev(hw_config->slots[0]);
}
static inline void __exit unload_trix_mpu(struct address_info *hw_config)
{
unload_uart401(hw_config);
}
static inline void __exit unload_trix_sb(struct address_info *hw_config)
{
sb_dsp_unload(hw_config, mpu);
}
static struct address_info cfg;
static struct address_info cfg2;
static struct address_info cfg_mpu;
static int sb;
static int fw_load;
static int __initdata io = -1;
static int __initdata irq = -1;
static int __initdata dma = -1;
static int __initdata dma2 = -1; /* Set this for modules that need it */
static int __initdata sb_io = -1;
static int __initdata sb_dma = -1;
static int __initdata sb_irq = -1;
static int __initdata mpu_io = -1;
static int __initdata mpu_irq = -1;
module_param(io, int, 0);
module_param(irq, int, 0);
module_param(dma, int, 0);
module_param(dma2, int, 0);
module_param(sb_io, int, 0);
module_param(sb_dma, int, 0);
module_param(sb_irq, int, 0);
module_param(mpu_io, int, 0);
module_param(mpu_irq, int, 0);
module_param(joystick, bool, 0);
static int __init init_trix(void)
{
printk(KERN_INFO "MediaTrix audio driver Copyright (C) by Hannu Savolainen 1993-1996\n");
cfg.io_base = io;
cfg.irq = irq;
cfg.dma = dma;
cfg.dma2 = dma2;
cfg2.io_base = sb_io;
cfg2.irq = sb_irq;
cfg2.dma = sb_dma;
cfg_mpu.io_base = mpu_io;
cfg_mpu.irq = mpu_irq;
if (cfg.io_base == -1 || cfg.dma == -1 || cfg.irq == -1) {
printk(KERN_INFO "I/O, IRQ, DMA and type are mandatory\n");
return -EINVAL;
}
if (cfg2.io_base != -1 && (cfg2.irq == -1 || cfg2.dma == -1)) {
printk(KERN_INFO "CONFIG_SB_IRQ and CONFIG_SB_DMA must be specified if SB_IO is set.\n");
return -EINVAL;
}
if (cfg_mpu.io_base != -1 && cfg_mpu.irq == -1) {
printk(KERN_INFO "CONFIG_MPU_IRQ must be specified if MPU_IO is set.\n");
return -EINVAL;
}
if (!trix_boot)
{
fw_load = 1;
trix_boot_len = mod_firmware_load("/etc/sound/trxpro.bin",
(char **) &trix_boot);
}
if (!request_region(0x390, 2, "AudioTrix")) {
printk(KERN_ERR "AudioTrix: Config port I/O conflict\n");
return -ENODEV;
}
if (!init_trix_wss(&cfg)) {
release_region(0x390, 2);
return -ENODEV;
}
/*
* We must attach in the right order to get the firmware
* loaded up in time.
*/
if (cfg2.io_base != -1) {
sb = probe_trix_sb(&cfg2);
}
if (cfg_mpu.io_base != -1)
mpu = probe_trix_mpu(&cfg_mpu);
return 0;
}
static void __exit cleanup_trix(void)
{
if (fw_load && trix_boot)
vfree(trix_boot);
if (sb)
unload_trix_sb(&cfg2);
if (mpu)
unload_trix_mpu(&cfg_mpu);
unload_trix_wss(&cfg);
}
module_init(init_trix);
module_exit(cleanup_trix);
#ifndef MODULE
static int __init setup_trix (char *str)
{
/* io, irq, dma, dma2, sb_io, sb_irq, sb_dma, mpu_io, mpu_irq */
int ints[9];
str = get_options(str, ARRAY_SIZE(ints), ints);
io = ints[1];
irq = ints[2];
dma = ints[3];
dma2 = ints[4];
sb_io = ints[5];
sb_irq = ints[6];
sb_dma = ints[6];
mpu_io = ints[7];
mpu_irq = ints[8];
return 1;
}
__setup("trix=", setup_trix);
#endif
MODULE_LICENSE("GPL");
| gpl-2.0 |
96boards-bubblegum/linux | drivers/staging/media/lirc/lirc_zilog.c | 214 | 41626 | /*
* i2c IR lirc driver for devices with zilog IR processors
*
* Copyright (c) 2000 Gerd Knorr <kraxel@goldbach.in-berlin.de>
* modified for PixelView (BT878P+W/FM) by
* Michal Kochanowicz <mkochano@pld.org.pl>
* Christoph Bartelmus <lirc@bartelmus.de>
* modified for KNC ONE TV Station/Anubis Typhoon TView Tuner by
* Ulrich Mueller <ulrich.mueller42@web.de>
* modified for Asus TV-Box and Creative/VisionTek BreakOut-Box by
* Stefan Jahn <stefan@lkcc.org>
* modified for inclusion into kernel sources by
* Jerome Brock <jbrock@users.sourceforge.net>
* modified for Leadtek Winfast PVR2000 by
* Thomas Reitmayr (treitmayr@yahoo.com)
* modified for Hauppauge PVR-150 IR TX device by
* Mark Weaver <mark@npsl.co.uk>
* changed name from lirc_pvr150 to lirc_zilog, works on more than pvr-150
* Jarod Wilson <jarod@redhat.com>
*
* parts are cut&pasted from the lirc_i2c.c driver
*
* Numerous changes updating lirc_zilog.c in kernel 2.6.38 and later are
* Copyright (C) 2011 Andy Walls <awalls@md.metrocast.net>
*
* 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/kmod.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/poll.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/firmware.h>
#include <linux/vmalloc.h>
#include <linux/mutex.h>
#include <linux/kthread.h>
#include <media/lirc_dev.h>
#include <media/lirc.h>
/* Max transfer size done by I2C transfer functions */
#define MAX_XFER_SIZE 64
struct IR;
struct IR_rx {
struct kref ref;
struct IR *ir;
/* RX device */
struct mutex client_lock;
struct i2c_client *c;
/* RX polling thread data */
struct task_struct *task;
/* RX read data */
unsigned char b[3];
bool hdpvr_data_fmt;
};
struct IR_tx {
struct kref ref;
struct IR *ir;
/* TX device */
struct mutex client_lock;
struct i2c_client *c;
/* TX additional actions needed */
int need_boot;
bool post_tx_ready_poll;
};
struct IR {
struct kref ref;
struct list_head list;
/* FIXME spinlock access to l.features */
struct lirc_driver l;
struct lirc_buffer rbuf;
struct mutex ir_lock;
atomic_t open_count;
struct i2c_adapter *adapter;
spinlock_t rx_ref_lock; /* struct IR_rx kref get()/put() */
struct IR_rx *rx;
spinlock_t tx_ref_lock; /* struct IR_tx kref get()/put() */
struct IR_tx *tx;
};
/* IR transceiver instance object list */
/*
* This lock is used for the following:
* a. ir_devices_list access, insertions, deletions
* b. struct IR kref get()s and put()s
* c. serialization of ir_probe() for the two i2c_clients for a Z8
*/
static DEFINE_MUTEX(ir_devices_lock);
static LIST_HEAD(ir_devices_list);
/* Block size for IR transmitter */
#define TX_BLOCK_SIZE 99
/* Hauppauge IR transmitter data */
struct tx_data_struct {
/* Boot block */
unsigned char *boot_data;
/* Start of binary data block */
unsigned char *datap;
/* End of binary data block */
unsigned char *endp;
/* Number of installed codesets */
unsigned int num_code_sets;
/* Pointers to codesets */
unsigned char **code_sets;
/* Global fixed data template */
int fixed[TX_BLOCK_SIZE];
};
static struct tx_data_struct *tx_data;
static struct mutex tx_data_lock;
/* module parameters */
static bool debug; /* debug output */
static bool tx_only; /* only handle the IR Tx function */
static int minor = -1; /* minor number */
/* struct IR reference counting */
static struct IR *get_ir_device(struct IR *ir, bool ir_devices_lock_held)
{
if (ir_devices_lock_held) {
kref_get(&ir->ref);
} else {
mutex_lock(&ir_devices_lock);
kref_get(&ir->ref);
mutex_unlock(&ir_devices_lock);
}
return ir;
}
static void release_ir_device(struct kref *ref)
{
struct IR *ir = container_of(ref, struct IR, ref);
/*
* Things should be in this state by now:
* ir->rx set to NULL and deallocated - happens before ir->rx->ir put()
* ir->rx->task kthread stopped - happens before ir->rx->ir put()
* ir->tx set to NULL and deallocated - happens before ir->tx->ir put()
* ir->open_count == 0 - happens on final close()
* ir_lock, tx_ref_lock, rx_ref_lock, all released
*/
if (ir->l.minor >= 0 && ir->l.minor < MAX_IRCTL_DEVICES) {
lirc_unregister_driver(ir->l.minor);
ir->l.minor = MAX_IRCTL_DEVICES;
}
if (kfifo_initialized(&ir->rbuf.fifo))
lirc_buffer_free(&ir->rbuf);
list_del(&ir->list);
kfree(ir);
}
static int put_ir_device(struct IR *ir, bool ir_devices_lock_held)
{
int released;
if (ir_devices_lock_held)
return kref_put(&ir->ref, release_ir_device);
mutex_lock(&ir_devices_lock);
released = kref_put(&ir->ref, release_ir_device);
mutex_unlock(&ir_devices_lock);
return released;
}
/* struct IR_rx reference counting */
static struct IR_rx *get_ir_rx(struct IR *ir)
{
struct IR_rx *rx;
spin_lock(&ir->rx_ref_lock);
rx = ir->rx;
if (rx != NULL)
kref_get(&rx->ref);
spin_unlock(&ir->rx_ref_lock);
return rx;
}
static void destroy_rx_kthread(struct IR_rx *rx, bool ir_devices_lock_held)
{
/* end up polling thread */
if (!IS_ERR_OR_NULL(rx->task)) {
kthread_stop(rx->task);
rx->task = NULL;
/* Put the ir ptr that ir_probe() gave to the rx poll thread */
put_ir_device(rx->ir, ir_devices_lock_held);
}
}
static void release_ir_rx(struct kref *ref)
{
struct IR_rx *rx = container_of(ref, struct IR_rx, ref);
struct IR *ir = rx->ir;
/*
* This release function can't do all the work, as we want
* to keep the rx_ref_lock a spinlock, and killing the poll thread
* and releasing the ir reference can cause a sleep. That work is
* performed by put_ir_rx()
*/
ir->l.features &= ~LIRC_CAN_REC_LIRCCODE;
/* Don't put_ir_device(rx->ir) here; lock can't be freed yet */
ir->rx = NULL;
/* Don't do the kfree(rx) here; we still need to kill the poll thread */
}
static int put_ir_rx(struct IR_rx *rx, bool ir_devices_lock_held)
{
int released;
struct IR *ir = rx->ir;
spin_lock(&ir->rx_ref_lock);
released = kref_put(&rx->ref, release_ir_rx);
spin_unlock(&ir->rx_ref_lock);
/* Destroy the rx kthread while not holding the spinlock */
if (released) {
destroy_rx_kthread(rx, ir_devices_lock_held);
kfree(rx);
/* Make sure we're not still in a poll_table somewhere */
wake_up_interruptible(&ir->rbuf.wait_poll);
}
/* Do a reference put() for the rx->ir reference, if we released rx */
if (released)
put_ir_device(ir, ir_devices_lock_held);
return released;
}
/* struct IR_tx reference counting */
static struct IR_tx *get_ir_tx(struct IR *ir)
{
struct IR_tx *tx;
spin_lock(&ir->tx_ref_lock);
tx = ir->tx;
if (tx != NULL)
kref_get(&tx->ref);
spin_unlock(&ir->tx_ref_lock);
return tx;
}
static void release_ir_tx(struct kref *ref)
{
struct IR_tx *tx = container_of(ref, struct IR_tx, ref);
struct IR *ir = tx->ir;
ir->l.features &= ~LIRC_CAN_SEND_PULSE;
/* Don't put_ir_device(tx->ir) here, so our lock doesn't get freed */
ir->tx = NULL;
kfree(tx);
}
static int put_ir_tx(struct IR_tx *tx, bool ir_devices_lock_held)
{
int released;
struct IR *ir = tx->ir;
spin_lock(&ir->tx_ref_lock);
released = kref_put(&tx->ref, release_ir_tx);
spin_unlock(&ir->tx_ref_lock);
/* Do a reference put() for the tx->ir reference, if we released tx */
if (released)
put_ir_device(ir, ir_devices_lock_held);
return released;
}
static int add_to_buf(struct IR *ir)
{
__u16 code;
unsigned char codes[2];
unsigned char keybuf[6];
int got_data = 0;
int ret;
int failures = 0;
unsigned char sendbuf[1] = { 0 };
struct lirc_buffer *rbuf = ir->l.rbuf;
struct IR_rx *rx;
struct IR_tx *tx;
if (lirc_buffer_full(rbuf)) {
dev_dbg(ir->l.dev, "buffer overflow\n");
return -EOVERFLOW;
}
rx = get_ir_rx(ir);
if (rx == NULL)
return -ENXIO;
/* Ensure our rx->c i2c_client remains valid for the duration */
mutex_lock(&rx->client_lock);
if (rx->c == NULL) {
mutex_unlock(&rx->client_lock);
put_ir_rx(rx, false);
return -ENXIO;
}
tx = get_ir_tx(ir);
/*
* service the device as long as it is returning
* data and we have space
*/
do {
if (kthread_should_stop()) {
ret = -ENODATA;
break;
}
/*
* Lock i2c bus for the duration. RX/TX chips interfere so
* this is worth it
*/
mutex_lock(&ir->ir_lock);
if (kthread_should_stop()) {
mutex_unlock(&ir->ir_lock);
ret = -ENODATA;
break;
}
/*
* Send random "poll command" (?) Windows driver does this
* and it is a good point to detect chip failure.
*/
ret = i2c_master_send(rx->c, sendbuf, 1);
if (ret != 1) {
dev_err(ir->l.dev, "i2c_master_send failed with %d\n",
ret);
if (failures >= 3) {
mutex_unlock(&ir->ir_lock);
dev_err(ir->l.dev,
"unable to read from the IR chip after 3 resets, giving up\n");
break;
}
/* Looks like the chip crashed, reset it */
dev_err(ir->l.dev,
"polling the IR receiver chip failed, trying reset\n");
set_current_state(TASK_UNINTERRUPTIBLE);
if (kthread_should_stop()) {
mutex_unlock(&ir->ir_lock);
ret = -ENODATA;
break;
}
schedule_timeout((100 * HZ + 999) / 1000);
if (tx != NULL)
tx->need_boot = 1;
++failures;
mutex_unlock(&ir->ir_lock);
ret = 0;
continue;
}
if (kthread_should_stop()) {
mutex_unlock(&ir->ir_lock);
ret = -ENODATA;
break;
}
ret = i2c_master_recv(rx->c, keybuf, sizeof(keybuf));
mutex_unlock(&ir->ir_lock);
if (ret != sizeof(keybuf)) {
dev_err(ir->l.dev,
"i2c_master_recv failed with %d -- keeping last read buffer\n",
ret);
} else {
rx->b[0] = keybuf[3];
rx->b[1] = keybuf[4];
rx->b[2] = keybuf[5];
dev_dbg(ir->l.dev,
"key (0x%02x/0x%02x)\n",
rx->b[0], rx->b[1]);
}
/* key pressed ? */
if (rx->hdpvr_data_fmt) {
if (got_data && (keybuf[0] == 0x80)) {
ret = 0;
break;
} else if (got_data && (keybuf[0] == 0x00)) {
ret = -ENODATA;
break;
}
} else if ((rx->b[0] & 0x80) == 0) {
ret = got_data ? 0 : -ENODATA;
break;
}
/* look what we have */
code = (((__u16)rx->b[0] & 0x7f) << 6) | (rx->b[1] >> 2);
codes[0] = (code >> 8) & 0xff;
codes[1] = code & 0xff;
/* return it */
lirc_buffer_write(rbuf, codes);
++got_data;
ret = 0;
} while (!lirc_buffer_full(rbuf));
mutex_unlock(&rx->client_lock);
if (tx != NULL)
put_ir_tx(tx, false);
put_ir_rx(rx, false);
return ret;
}
/*
* Main function of the polling thread -- from lirc_dev.
* We don't fit the LIRC model at all anymore. This is horrible, but
* basically we have a single RX/TX device with a nasty failure mode
* that needs to be accounted for across the pair. lirc lets us provide
* fops, but prevents us from using the internal polling, etc. if we do
* so. Hence the replication. Might be neater to extend the LIRC model
* to account for this but I'd think it's a very special case of seriously
* messed up hardware.
*/
static int lirc_thread(void *arg)
{
struct IR *ir = arg;
struct lirc_buffer *rbuf = ir->l.rbuf;
dev_dbg(ir->l.dev, "poll thread started\n");
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
/* if device not opened, we can sleep half a second */
if (atomic_read(&ir->open_count) == 0) {
schedule_timeout(HZ/2);
continue;
}
/*
* This is ~113*2 + 24 + jitter (2*repeat gap + code length).
* We use this interval as the chip resets every time you poll
* it (bad!). This is therefore just sufficient to catch all
* of the button presses. It makes the remote much more
* responsive. You can see the difference by running irw and
* holding down a button. With 100ms, the old polling
* interval, you'll notice breaks in the repeat sequence
* corresponding to lost keypresses.
*/
schedule_timeout((260 * HZ) / 1000);
if (kthread_should_stop())
break;
if (!add_to_buf(ir))
wake_up_interruptible(&rbuf->wait_poll);
}
dev_dbg(ir->l.dev, "poll thread ended\n");
return 0;
}
static int set_use_inc(void *data)
{
return 0;
}
static void set_use_dec(void *data)
{
}
/* safe read of a uint32 (always network byte order) */
static int read_uint32(unsigned char **data,
unsigned char *endp, unsigned int *val)
{
if (*data + 4 > endp)
return 0;
*val = ((*data)[0] << 24) | ((*data)[1] << 16) |
((*data)[2] << 8) | (*data)[3];
*data += 4;
return 1;
}
/* safe read of a uint8 */
static int read_uint8(unsigned char **data,
unsigned char *endp, unsigned char *val)
{
if (*data + 1 > endp)
return 0;
*val = *((*data)++);
return 1;
}
/* safe skipping of N bytes */
static int skip(unsigned char **data,
unsigned char *endp, unsigned int distance)
{
if (*data + distance > endp)
return 0;
*data += distance;
return 1;
}
/* decompress key data into the given buffer */
static int get_key_data(unsigned char *buf,
unsigned int codeset, unsigned int key)
{
unsigned char *data, *endp, *diffs, *key_block;
unsigned char keys, ndiffs, id;
unsigned int base, lim, pos, i;
/* Binary search for the codeset */
for (base = 0, lim = tx_data->num_code_sets; lim; lim >>= 1) {
pos = base + (lim >> 1);
data = tx_data->code_sets[pos];
if (!read_uint32(&data, tx_data->endp, &i))
goto corrupt;
if (i == codeset)
break;
else if (codeset > i) {
base = pos + 1;
--lim;
}
}
/* Not found? */
if (!lim)
return -EPROTO;
/* Set end of data block */
endp = pos < tx_data->num_code_sets - 1 ?
tx_data->code_sets[pos + 1] : tx_data->endp;
/* Read the block header */
if (!read_uint8(&data, endp, &keys) ||
!read_uint8(&data, endp, &ndiffs) ||
ndiffs > TX_BLOCK_SIZE || keys == 0)
goto corrupt;
/* Save diffs & skip */
diffs = data;
if (!skip(&data, endp, ndiffs))
goto corrupt;
/* Read the id of the first key */
if (!read_uint8(&data, endp, &id))
goto corrupt;
/* Unpack the first key's data */
for (i = 0; i < TX_BLOCK_SIZE; ++i) {
if (tx_data->fixed[i] == -1) {
if (!read_uint8(&data, endp, &buf[i]))
goto corrupt;
} else {
buf[i] = (unsigned char)tx_data->fixed[i];
}
}
/* Early out key found/not found */
if (key == id)
return 0;
if (keys == 1)
return -EPROTO;
/* Sanity check */
key_block = data;
if (!skip(&data, endp, (keys - 1) * (ndiffs + 1)))
goto corrupt;
/* Binary search for the key */
for (base = 0, lim = keys - 1; lim; lim >>= 1) {
/* Seek to block */
unsigned char *key_data;
pos = base + (lim >> 1);
key_data = key_block + (ndiffs + 1) * pos;
if (*key_data == key) {
/* skip key id */
++key_data;
/* found, so unpack the diffs */
for (i = 0; i < ndiffs; ++i) {
unsigned char val;
if (!read_uint8(&key_data, endp, &val) ||
diffs[i] >= TX_BLOCK_SIZE)
goto corrupt;
buf[diffs[i]] = val;
}
return 0;
} else if (key > *key_data) {
base = pos + 1;
--lim;
}
}
/* Key not found */
return -EPROTO;
corrupt:
pr_err("firmware is corrupt\n");
return -EFAULT;
}
/* send a block of data to the IR TX device */
static int send_data_block(struct IR_tx *tx, unsigned char *data_block)
{
int i, j, ret;
unsigned char buf[5];
for (i = 0; i < TX_BLOCK_SIZE;) {
int tosend = TX_BLOCK_SIZE - i;
if (tosend > 4)
tosend = 4;
buf[0] = (unsigned char)(i + 1);
for (j = 0; j < tosend; ++j)
buf[1 + j] = data_block[i + j];
dev_dbg(tx->ir->l.dev, "%*ph", 5, buf);
ret = i2c_master_send(tx->c, buf, tosend + 1);
if (ret != tosend + 1) {
dev_err(tx->ir->l.dev,
"i2c_master_send failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
i += tosend;
}
return 0;
}
/* send boot data to the IR TX device */
static int send_boot_data(struct IR_tx *tx)
{
int ret, i;
unsigned char buf[4];
/* send the boot block */
ret = send_data_block(tx, tx_data->boot_data);
if (ret != 0)
return ret;
/* Hit the go button to activate the new boot data */
buf[0] = 0x00;
buf[1] = 0x20;
ret = i2c_master_send(tx->c, buf, 2);
if (ret != 2) {
dev_err(tx->ir->l.dev, "i2c_master_send failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
/*
* Wait for zilog to settle after hitting go post boot block upload.
* Without this delay, the HD-PVR and HVR-1950 both return an -EIO
* upon attempting to get firmware revision, and tx probe thus fails.
*/
for (i = 0; i < 10; i++) {
ret = i2c_master_send(tx->c, buf, 1);
if (ret == 1)
break;
udelay(100);
}
if (ret != 1) {
dev_err(tx->ir->l.dev, "i2c_master_send failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
/* Here comes the firmware version... (hopefully) */
ret = i2c_master_recv(tx->c, buf, 4);
if (ret != 4) {
dev_err(tx->ir->l.dev, "i2c_master_recv failed with %d\n", ret);
return 0;
}
if ((buf[0] != 0x80) && (buf[0] != 0xa0)) {
dev_err(tx->ir->l.dev, "unexpected IR TX init response: %02x\n",
buf[0]);
return 0;
}
dev_notice(tx->ir->l.dev,
"Zilog/Hauppauge IR blaster firmware version %d.%d.%d loaded\n",
buf[1], buf[2], buf[3]);
return 0;
}
/* unload "firmware", lock held */
static void fw_unload_locked(void)
{
if (tx_data) {
vfree(tx_data->code_sets);
vfree(tx_data->datap);
vfree(tx_data);
tx_data = NULL;
pr_debug("successfully unloaded IR blaster firmware\n");
}
}
/* unload "firmware" for the IR TX device */
static void fw_unload(void)
{
mutex_lock(&tx_data_lock);
fw_unload_locked();
mutex_unlock(&tx_data_lock);
}
/* load "firmware" for the IR TX device */
static int fw_load(struct IR_tx *tx)
{
int ret;
unsigned int i;
unsigned char *data, version, num_global_fixed;
const struct firmware *fw_entry;
/* Already loaded? */
mutex_lock(&tx_data_lock);
if (tx_data) {
ret = 0;
goto out;
}
/* Request codeset data file */
ret = request_firmware(&fw_entry, "haup-ir-blaster.bin", tx->ir->l.dev);
if (ret != 0) {
dev_err(tx->ir->l.dev,
"firmware haup-ir-blaster.bin not available (%d)\n",
ret);
ret = ret < 0 ? ret : -EFAULT;
goto out;
}
dev_dbg(tx->ir->l.dev, "firmware of size %zu loaded\n", fw_entry->size);
/* Parse the file */
tx_data = vmalloc(sizeof(*tx_data));
if (tx_data == NULL) {
release_firmware(fw_entry);
ret = -ENOMEM;
goto out;
}
tx_data->code_sets = NULL;
/* Copy the data so hotplug doesn't get confused and timeout */
tx_data->datap = vmalloc(fw_entry->size);
if (tx_data->datap == NULL) {
release_firmware(fw_entry);
vfree(tx_data);
ret = -ENOMEM;
goto out;
}
memcpy(tx_data->datap, fw_entry->data, fw_entry->size);
tx_data->endp = tx_data->datap + fw_entry->size;
release_firmware(fw_entry); fw_entry = NULL;
/* Check version */
data = tx_data->datap;
if (!read_uint8(&data, tx_data->endp, &version))
goto corrupt;
if (version != 1) {
dev_err(tx->ir->l.dev,
"unsupported code set file version (%u, expected 1) -- please upgrade to a newer driver\n",
version);
fw_unload_locked();
ret = -EFAULT;
goto out;
}
/* Save boot block for later */
tx_data->boot_data = data;
if (!skip(&data, tx_data->endp, TX_BLOCK_SIZE))
goto corrupt;
if (!read_uint32(&data, tx_data->endp,
&tx_data->num_code_sets))
goto corrupt;
dev_dbg(tx->ir->l.dev, "%u IR blaster codesets loaded\n",
tx_data->num_code_sets);
tx_data->code_sets = vmalloc(
tx_data->num_code_sets * sizeof(char *));
if (tx_data->code_sets == NULL) {
fw_unload_locked();
ret = -ENOMEM;
goto out;
}
for (i = 0; i < TX_BLOCK_SIZE; ++i)
tx_data->fixed[i] = -1;
/* Read global fixed data template */
if (!read_uint8(&data, tx_data->endp, &num_global_fixed) ||
num_global_fixed > TX_BLOCK_SIZE)
goto corrupt;
for (i = 0; i < num_global_fixed; ++i) {
unsigned char pos, val;
if (!read_uint8(&data, tx_data->endp, &pos) ||
!read_uint8(&data, tx_data->endp, &val) ||
pos >= TX_BLOCK_SIZE)
goto corrupt;
tx_data->fixed[pos] = (int)val;
}
/* Filch out the position of each code set */
for (i = 0; i < tx_data->num_code_sets; ++i) {
unsigned int id;
unsigned char keys;
unsigned char ndiffs;
/* Save the codeset position */
tx_data->code_sets[i] = data;
/* Read header */
if (!read_uint32(&data, tx_data->endp, &id) ||
!read_uint8(&data, tx_data->endp, &keys) ||
!read_uint8(&data, tx_data->endp, &ndiffs) ||
ndiffs > TX_BLOCK_SIZE || keys == 0)
goto corrupt;
/* skip diff positions */
if (!skip(&data, tx_data->endp, ndiffs))
goto corrupt;
/*
* After the diffs we have the first key id + data -
* global fixed
*/
if (!skip(&data, tx_data->endp,
1 + TX_BLOCK_SIZE - num_global_fixed))
goto corrupt;
/* Then we have keys-1 blocks of key id+diffs */
if (!skip(&data, tx_data->endp,
(ndiffs + 1) * (keys - 1)))
goto corrupt;
}
ret = 0;
goto out;
corrupt:
dev_err(tx->ir->l.dev, "firmware is corrupt\n");
fw_unload_locked();
ret = -EFAULT;
out:
mutex_unlock(&tx_data_lock);
return ret;
}
/* copied from lirc_dev */
static ssize_t read(struct file *filep, char __user *outbuf, size_t n,
loff_t *ppos)
{
struct IR *ir = filep->private_data;
struct IR_rx *rx;
struct lirc_buffer *rbuf = ir->l.rbuf;
int ret = 0, written = 0, retries = 0;
unsigned int m;
DECLARE_WAITQUEUE(wait, current);
dev_dbg(ir->l.dev, "read called\n");
if (n % rbuf->chunk_size) {
dev_dbg(ir->l.dev, "read result = -EINVAL\n");
return -EINVAL;
}
rx = get_ir_rx(ir);
if (rx == NULL)
return -ENXIO;
/*
* we add ourselves to the task queue before buffer check
* to avoid losing scan code (in case when queue is awaken somewhere
* between while condition checking and scheduling)
*/
add_wait_queue(&rbuf->wait_poll, &wait);
set_current_state(TASK_INTERRUPTIBLE);
/*
* while we didn't provide 'length' bytes, device is opened in blocking
* mode and 'copy_to_user' is happy, wait for data.
*/
while (written < n && ret == 0) {
if (lirc_buffer_empty(rbuf)) {
/*
* According to the read(2) man page, 'written' can be
* returned as less than 'n', instead of blocking
* again, returning -EWOULDBLOCK, or returning
* -ERESTARTSYS
*/
if (written)
break;
if (filep->f_flags & O_NONBLOCK) {
ret = -EWOULDBLOCK;
break;
}
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
schedule();
set_current_state(TASK_INTERRUPTIBLE);
} else {
unsigned char buf[MAX_XFER_SIZE];
if (rbuf->chunk_size > sizeof(buf)) {
dev_err(ir->l.dev,
"chunk_size is too big (%d)!\n",
rbuf->chunk_size);
ret = -EINVAL;
break;
}
m = lirc_buffer_read(rbuf, buf);
if (m == rbuf->chunk_size) {
ret = copy_to_user(outbuf + written, buf,
rbuf->chunk_size);
written += rbuf->chunk_size;
} else {
retries++;
}
if (retries >= 5) {
dev_err(ir->l.dev, "Buffer read failed!\n");
ret = -EIO;
}
}
}
remove_wait_queue(&rbuf->wait_poll, &wait);
put_ir_rx(rx, false);
set_current_state(TASK_RUNNING);
dev_dbg(ir->l.dev, "read result = %d (%s)\n", ret,
ret ? "Error" : "OK");
return ret ? ret : written;
}
/* send a keypress to the IR TX device */
static int send_code(struct IR_tx *tx, unsigned int code, unsigned int key)
{
unsigned char data_block[TX_BLOCK_SIZE];
unsigned char buf[2];
int i, ret;
/* Get data for the codeset/key */
ret = get_key_data(data_block, code, key);
if (ret == -EPROTO) {
dev_err(tx->ir->l.dev,
"failed to get data for code %u, key %u -- check lircd.conf entries\n",
code, key);
return ret;
} else if (ret != 0)
return ret;
/* Send the data block */
ret = send_data_block(tx, data_block);
if (ret != 0)
return ret;
/* Send data block length? */
buf[0] = 0x00;
buf[1] = 0x40;
ret = i2c_master_send(tx->c, buf, 2);
if (ret != 2) {
dev_err(tx->ir->l.dev, "i2c_master_send failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
/* Give the z8 a moment to process data block */
for (i = 0; i < 10; i++) {
ret = i2c_master_send(tx->c, buf, 1);
if (ret == 1)
break;
udelay(100);
}
if (ret != 1) {
dev_err(tx->ir->l.dev, "i2c_master_send failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
/* Send finished download? */
ret = i2c_master_recv(tx->c, buf, 1);
if (ret != 1) {
dev_err(tx->ir->l.dev, "i2c_master_recv failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
if (buf[0] != 0xA0) {
dev_err(tx->ir->l.dev, "unexpected IR TX response #1: %02x\n",
buf[0]);
return -EFAULT;
}
/* Send prepare command? */
buf[0] = 0x00;
buf[1] = 0x80;
ret = i2c_master_send(tx->c, buf, 2);
if (ret != 2) {
dev_err(tx->ir->l.dev, "i2c_master_send failed with %d\n", ret);
return ret < 0 ? ret : -EFAULT;
}
/*
* The sleep bits aren't necessary on the HD PVR, and in fact, the
* last i2c_master_recv always fails with a -5, so for now, we're
* going to skip this whole mess and say we're done on the HD PVR
*/
if (!tx->post_tx_ready_poll) {
dev_dbg(tx->ir->l.dev, "sent code %u, key %u\n", code, key);
return 0;
}
/*
* This bit NAKs until the device is ready, so we retry it
* sleeping a bit each time. This seems to be what the windows
* driver does, approximately.
* Try for up to 1s.
*/
for (i = 0; i < 20; ++i) {
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout((50 * HZ + 999) / 1000);
ret = i2c_master_send(tx->c, buf, 1);
if (ret == 1)
break;
dev_dbg(tx->ir->l.dev,
"NAK expected: i2c_master_send failed with %d (try %d)\n",
ret, i+1);
}
if (ret != 1) {
dev_err(tx->ir->l.dev,
"IR TX chip never got ready: last i2c_master_send failed with %d\n",
ret);
return ret < 0 ? ret : -EFAULT;
}
/* Seems to be an 'ok' response */
i = i2c_master_recv(tx->c, buf, 1);
if (i != 1) {
dev_err(tx->ir->l.dev, "i2c_master_recv failed with %d\n", ret);
return -EFAULT;
}
if (buf[0] != 0x80) {
dev_err(tx->ir->l.dev, "unexpected IR TX response #2: %02x\n",
buf[0]);
return -EFAULT;
}
/* Oh good, it worked */
dev_dbg(tx->ir->l.dev, "sent code %u, key %u\n", code, key);
return 0;
}
/*
* Write a code to the device. We take in a 32-bit number (an int) and then
* decode this to a codeset/key index. The key data is then decompressed and
* sent to the device. We have a spin lock as per i2c documentation to prevent
* multiple concurrent sends which would probably cause the device to explode.
*/
static ssize_t write(struct file *filep, const char __user *buf, size_t n,
loff_t *ppos)
{
struct IR *ir = filep->private_data;
struct IR_tx *tx;
size_t i;
int failures = 0;
/* Validate user parameters */
if (n % sizeof(int))
return -EINVAL;
/* Get a struct IR_tx reference */
tx = get_ir_tx(ir);
if (tx == NULL)
return -ENXIO;
/* Ensure our tx->c i2c_client remains valid for the duration */
mutex_lock(&tx->client_lock);
if (tx->c == NULL) {
mutex_unlock(&tx->client_lock);
put_ir_tx(tx, false);
return -ENXIO;
}
/* Lock i2c bus for the duration */
mutex_lock(&ir->ir_lock);
/* Send each keypress */
for (i = 0; i < n;) {
int ret = 0;
int command;
if (copy_from_user(&command, buf + i, sizeof(command))) {
mutex_unlock(&ir->ir_lock);
mutex_unlock(&tx->client_lock);
put_ir_tx(tx, false);
return -EFAULT;
}
/* Send boot data first if required */
if (tx->need_boot == 1) {
/* Make sure we have the 'firmware' loaded, first */
ret = fw_load(tx);
if (ret != 0) {
mutex_unlock(&ir->ir_lock);
mutex_unlock(&tx->client_lock);
put_ir_tx(tx, false);
if (ret != -ENOMEM)
ret = -EIO;
return ret;
}
/* Prep the chip for transmitting codes */
ret = send_boot_data(tx);
if (ret == 0)
tx->need_boot = 0;
}
/* Send the code */
if (ret == 0) {
ret = send_code(tx, (unsigned)command >> 16,
(unsigned)command & 0xFFFF);
if (ret == -EPROTO) {
mutex_unlock(&ir->ir_lock);
mutex_unlock(&tx->client_lock);
put_ir_tx(tx, false);
return ret;
}
}
/*
* Hmm, a failure. If we've had a few then give up, otherwise
* try a reset
*/
if (ret != 0) {
/* Looks like the chip crashed, reset it */
dev_err(tx->ir->l.dev,
"sending to the IR transmitter chip failed, trying reset\n");
if (failures >= 3) {
dev_err(tx->ir->l.dev,
"unable to send to the IR chip after 3 resets, giving up\n");
mutex_unlock(&ir->ir_lock);
mutex_unlock(&tx->client_lock);
put_ir_tx(tx, false);
return ret;
}
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout((100 * HZ + 999) / 1000);
tx->need_boot = 1;
++failures;
} else
i += sizeof(int);
}
/* Release i2c bus */
mutex_unlock(&ir->ir_lock);
mutex_unlock(&tx->client_lock);
/* Give back our struct IR_tx reference */
put_ir_tx(tx, false);
/* All looks good */
return n;
}
/* copied from lirc_dev */
static unsigned int poll(struct file *filep, poll_table *wait)
{
struct IR *ir = filep->private_data;
struct IR_rx *rx;
struct lirc_buffer *rbuf = ir->l.rbuf;
unsigned int ret;
dev_dbg(ir->l.dev, "poll called\n");
rx = get_ir_rx(ir);
if (rx == NULL) {
/*
* Revisit this, if our poll function ever reports writeable
* status for Tx
*/
dev_dbg(ir->l.dev, "poll result = POLLERR\n");
return POLLERR;
}
/*
* Add our lirc_buffer's wait_queue to the poll_table. A wake up on
* that buffer's wait queue indicates we may have a new poll status.
*/
poll_wait(filep, &rbuf->wait_poll, wait);
/* Indicate what ops could happen immediately without blocking */
ret = lirc_buffer_empty(rbuf) ? 0 : (POLLIN|POLLRDNORM);
dev_dbg(ir->l.dev, "poll result = %s\n",
ret ? "POLLIN|POLLRDNORM" : "none");
return ret;
}
static long ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
{
struct IR *ir = filep->private_data;
unsigned long __user *uptr = (unsigned long __user *)arg;
int result;
unsigned long mode, features;
features = ir->l.features;
switch (cmd) {
case LIRC_GET_LENGTH:
result = put_user(13UL, uptr);
break;
case LIRC_GET_FEATURES:
result = put_user(features, uptr);
break;
case LIRC_GET_REC_MODE:
if (!(features&LIRC_CAN_REC_MASK))
return -ENOSYS;
result = put_user(LIRC_REC2MODE
(features&LIRC_CAN_REC_MASK),
uptr);
break;
case LIRC_SET_REC_MODE:
if (!(features&LIRC_CAN_REC_MASK))
return -ENOSYS;
result = get_user(mode, uptr);
if (!result && !(LIRC_MODE2REC(mode) & features))
result = -EINVAL;
break;
case LIRC_GET_SEND_MODE:
if (!(features&LIRC_CAN_SEND_MASK))
return -ENOSYS;
result = put_user(LIRC_MODE_PULSE, uptr);
break;
case LIRC_SET_SEND_MODE:
if (!(features&LIRC_CAN_SEND_MASK))
return -ENOSYS;
result = get_user(mode, uptr);
if (!result && mode != LIRC_MODE_PULSE)
return -EINVAL;
break;
default:
return -EINVAL;
}
return result;
}
static struct IR *get_ir_device_by_minor(unsigned int minor)
{
struct IR *ir;
struct IR *ret = NULL;
mutex_lock(&ir_devices_lock);
if (!list_empty(&ir_devices_list)) {
list_for_each_entry(ir, &ir_devices_list, list) {
if (ir->l.minor == minor) {
ret = get_ir_device(ir, true);
break;
}
}
}
mutex_unlock(&ir_devices_lock);
return ret;
}
/*
* Open the IR device. Get hold of our IR structure and
* stash it in private_data for the file
*/
static int open(struct inode *node, struct file *filep)
{
struct IR *ir;
unsigned int minor = MINOR(node->i_rdev);
/* find our IR struct */
ir = get_ir_device_by_minor(minor);
if (ir == NULL)
return -ENODEV;
atomic_inc(&ir->open_count);
/* stash our IR struct */
filep->private_data = ir;
nonseekable_open(node, filep);
return 0;
}
/* Close the IR device */
static int close(struct inode *node, struct file *filep)
{
/* find our IR struct */
struct IR *ir = filep->private_data;
if (ir == NULL) {
pr_err("ir: close: no private_data attached to the file!\n");
return -ENODEV;
}
atomic_dec(&ir->open_count);
put_ir_device(ir, false);
return 0;
}
static int ir_remove(struct i2c_client *client);
static int ir_probe(struct i2c_client *client, const struct i2c_device_id *id);
#define ID_FLAG_TX 0x01
#define ID_FLAG_HDPVR 0x02
static const struct i2c_device_id ir_transceiver_id[] = {
{ "ir_tx_z8f0811_haup", ID_FLAG_TX },
{ "ir_rx_z8f0811_haup", 0 },
{ "ir_tx_z8f0811_hdpvr", ID_FLAG_HDPVR | ID_FLAG_TX },
{ "ir_rx_z8f0811_hdpvr", ID_FLAG_HDPVR },
{ }
};
MODULE_DEVICE_TABLE(i2c, ir_transceiver_id);
static struct i2c_driver driver = {
.driver = {
.name = "Zilog/Hauppauge i2c IR",
},
.probe = ir_probe,
.remove = ir_remove,
.id_table = ir_transceiver_id,
};
static const struct file_operations lirc_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = read,
.write = write,
.poll = poll,
.unlocked_ioctl = ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ioctl,
#endif
.open = open,
.release = close
};
static struct lirc_driver lirc_template = {
.name = "lirc_zilog",
.minor = -1,
.code_length = 13,
.buffer_size = BUFLEN / 2,
.sample_rate = 0, /* tell lirc_dev to not start its own kthread */
.chunk_size = 2,
.set_use_inc = set_use_inc,
.set_use_dec = set_use_dec,
.fops = &lirc_fops,
.owner = THIS_MODULE,
};
static int ir_remove(struct i2c_client *client)
{
if (strncmp("ir_tx_z8", client->name, 8) == 0) {
struct IR_tx *tx = i2c_get_clientdata(client);
if (tx != NULL) {
mutex_lock(&tx->client_lock);
tx->c = NULL;
mutex_unlock(&tx->client_lock);
put_ir_tx(tx, false);
}
} else if (strncmp("ir_rx_z8", client->name, 8) == 0) {
struct IR_rx *rx = i2c_get_clientdata(client);
if (rx != NULL) {
mutex_lock(&rx->client_lock);
rx->c = NULL;
mutex_unlock(&rx->client_lock);
put_ir_rx(rx, false);
}
}
return 0;
}
/* ir_devices_lock must be held */
static struct IR *get_ir_device_by_adapter(struct i2c_adapter *adapter)
{
struct IR *ir;
if (list_empty(&ir_devices_list))
return NULL;
list_for_each_entry(ir, &ir_devices_list, list)
if (ir->adapter == adapter) {
get_ir_device(ir, true);
return ir;
}
return NULL;
}
static int ir_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct IR *ir;
struct IR_tx *tx;
struct IR_rx *rx;
struct i2c_adapter *adap = client->adapter;
int ret;
bool tx_probe = false;
dev_dbg(&client->dev, "%s: %s on i2c-%d (%s), client addr=0x%02x\n",
__func__, id->name, adap->nr, adap->name, client->addr);
/*
* The IR receiver is at i2c address 0x71.
* The IR transmitter is at i2c address 0x70.
*/
if (id->driver_data & ID_FLAG_TX)
tx_probe = true;
else if (tx_only) /* module option */
return -ENXIO;
pr_info("probing IR %s on %s (i2c-%d)\n",
tx_probe ? "Tx" : "Rx", adap->name, adap->nr);
mutex_lock(&ir_devices_lock);
/* Use a single struct IR instance for both the Rx and Tx functions */
ir = get_ir_device_by_adapter(adap);
if (ir == NULL) {
ir = kzalloc(sizeof(struct IR), GFP_KERNEL);
if (ir == NULL) {
ret = -ENOMEM;
goto out_no_ir;
}
kref_init(&ir->ref);
/* store for use in ir_probe() again, and open() later on */
INIT_LIST_HEAD(&ir->list);
list_add_tail(&ir->list, &ir_devices_list);
ir->adapter = adap;
mutex_init(&ir->ir_lock);
atomic_set(&ir->open_count, 0);
spin_lock_init(&ir->tx_ref_lock);
spin_lock_init(&ir->rx_ref_lock);
/* set lirc_dev stuff */
memcpy(&ir->l, &lirc_template, sizeof(struct lirc_driver));
/*
* FIXME this is a pointer reference to us, but no refcount.
*
* This OK for now, since lirc_dev currently won't touch this
* buffer as we provide our own lirc_fops.
*
* Currently our own lirc_fops rely on this ir->l.rbuf pointer
*/
ir->l.rbuf = &ir->rbuf;
ir->l.dev = &adap->dev;
ret = lirc_buffer_init(ir->l.rbuf,
ir->l.chunk_size, ir->l.buffer_size);
if (ret)
goto out_put_ir;
}
if (tx_probe) {
/* Get the IR_rx instance for later, if already allocated */
rx = get_ir_rx(ir);
/* Set up a struct IR_tx instance */
tx = kzalloc(sizeof(struct IR_tx), GFP_KERNEL);
if (tx == NULL) {
ret = -ENOMEM;
goto out_put_xx;
}
kref_init(&tx->ref);
ir->tx = tx;
ir->l.features |= LIRC_CAN_SEND_PULSE;
mutex_init(&tx->client_lock);
tx->c = client;
tx->need_boot = 1;
tx->post_tx_ready_poll =
(id->driver_data & ID_FLAG_HDPVR) ? false : true;
/* An ir ref goes to the struct IR_tx instance */
tx->ir = get_ir_device(ir, true);
/* A tx ref goes to the i2c_client */
i2c_set_clientdata(client, get_ir_tx(ir));
/*
* Load the 'firmware'. We do this before registering with
* lirc_dev, so the first firmware load attempt does not happen
* after a open() or write() call on the device.
*
* Failure here is not deemed catastrophic, so the receiver will
* still be usable. Firmware load will be retried in write(),
* if it is needed.
*/
fw_load(tx);
/* Proceed only if the Rx client is also ready or not needed */
if (rx == NULL && !tx_only) {
dev_info(tx->ir->l.dev,
"probe of IR Tx on %s (i2c-%d) done. Waiting on IR Rx.\n",
adap->name, adap->nr);
goto out_ok;
}
} else {
/* Get the IR_tx instance for later, if already allocated */
tx = get_ir_tx(ir);
/* Set up a struct IR_rx instance */
rx = kzalloc(sizeof(struct IR_rx), GFP_KERNEL);
if (rx == NULL) {
ret = -ENOMEM;
goto out_put_xx;
}
kref_init(&rx->ref);
ir->rx = rx;
ir->l.features |= LIRC_CAN_REC_LIRCCODE;
mutex_init(&rx->client_lock);
rx->c = client;
rx->hdpvr_data_fmt =
(id->driver_data & ID_FLAG_HDPVR) ? true : false;
/* An ir ref goes to the struct IR_rx instance */
rx->ir = get_ir_device(ir, true);
/* An rx ref goes to the i2c_client */
i2c_set_clientdata(client, get_ir_rx(ir));
/*
* Start the polling thread.
* It will only perform an empty loop around schedule_timeout()
* until we register with lirc_dev and the first user open()
*/
/* An ir ref goes to the new rx polling kthread */
rx->task = kthread_run(lirc_thread, get_ir_device(ir, true),
"zilog-rx-i2c-%d", adap->nr);
if (IS_ERR(rx->task)) {
ret = PTR_ERR(rx->task);
dev_err(tx->ir->l.dev,
"%s: could not start IR Rx polling thread\n",
__func__);
/* Failed kthread, so put back the ir ref */
put_ir_device(ir, true);
/* Failure exit, so put back rx ref from i2c_client */
i2c_set_clientdata(client, NULL);
put_ir_rx(rx, true);
ir->l.features &= ~LIRC_CAN_REC_LIRCCODE;
goto out_put_xx;
}
/* Proceed only if the Tx client is also ready */
if (tx == NULL) {
pr_info("probe of IR Rx on %s (i2c-%d) done. Waiting on IR Tx.\n",
adap->name, adap->nr);
goto out_ok;
}
}
/* register with lirc */
ir->l.minor = minor; /* module option: user requested minor number */
ir->l.minor = lirc_register_driver(&ir->l);
if (ir->l.minor < 0 || ir->l.minor >= MAX_IRCTL_DEVICES) {
dev_err(tx->ir->l.dev,
"%s: \"minor\" must be between 0 and %d (%d)!\n",
__func__, MAX_IRCTL_DEVICES-1, ir->l.minor);
ret = -EBADRQC;
goto out_put_xx;
}
dev_info(ir->l.dev,
"IR unit on %s (i2c-%d) registered as lirc%d and ready\n",
adap->name, adap->nr, ir->l.minor);
out_ok:
if (rx != NULL)
put_ir_rx(rx, true);
if (tx != NULL)
put_ir_tx(tx, true);
put_ir_device(ir, true);
dev_info(ir->l.dev,
"probe of IR %s on %s (i2c-%d) done\n",
tx_probe ? "Tx" : "Rx", adap->name, adap->nr);
mutex_unlock(&ir_devices_lock);
return 0;
out_put_xx:
if (rx != NULL)
put_ir_rx(rx, true);
if (tx != NULL)
put_ir_tx(tx, true);
out_put_ir:
put_ir_device(ir, true);
out_no_ir:
dev_err(&client->dev,
"%s: probing IR %s on %s (i2c-%d) failed with %d\n",
__func__, tx_probe ? "Tx" : "Rx", adap->name, adap->nr, ret);
mutex_unlock(&ir_devices_lock);
return ret;
}
static int __init zilog_init(void)
{
int ret;
pr_notice("Zilog/Hauppauge IR driver initializing\n");
mutex_init(&tx_data_lock);
request_module("firmware_class");
ret = i2c_add_driver(&driver);
if (ret)
pr_err("initialization failed\n");
else
pr_notice("initialization complete\n");
return ret;
}
static void __exit zilog_exit(void)
{
i2c_del_driver(&driver);
/* if loaded */
fw_unload();
pr_notice("Zilog/Hauppauge IR driver unloaded\n");
}
module_init(zilog_init);
module_exit(zilog_exit);
MODULE_DESCRIPTION("Zilog/Hauppauge infrared transmitter driver (i2c stack)");
MODULE_AUTHOR("Gerd Knorr, Michal Kochanowicz, Christoph Bartelmus, Ulrich Mueller, Stefan Jahn, Jerome Brock, Mark Weaver, Andy Walls");
MODULE_LICENSE("GPL");
/* for compat with old name, which isn't all that accurate anymore */
MODULE_ALIAS("lirc_pvr150");
module_param(minor, int, 0444);
MODULE_PARM_DESC(minor, "Preferred minor device number");
module_param(debug, bool, 0644);
MODULE_PARM_DESC(debug, "Enable debugging messages");
module_param(tx_only, bool, 0644);
MODULE_PARM_DESC(tx_only, "Only handle the IR transmit function");
| gpl-2.0 |
Ken-Liu/OpenScrKernel_For_XC210 | drivers/gpu/drm/i915/intel_dp.c | 470 | 42023 | /*
* Copyright © 2008 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Keith Packard <keithp@keithp.com>
*
*/
#include <linux/i2c.h>
#include <linux/slab.h>
#include "drmP.h"
#include "drm.h"
#include "drm_crtc.h"
#include "drm_crtc_helper.h"
#include "intel_drv.h"
#include "i915_drm.h"
#include "i915_drv.h"
#include "drm_dp_helper.h"
#define DP_LINK_STATUS_SIZE 6
#define DP_LINK_CHECK_TIMEOUT (10 * 1000)
#define DP_LINK_CONFIGURATION_SIZE 9
#define IS_eDP(i) ((i)->type == INTEL_OUTPUT_EDP)
struct intel_dp_priv {
uint32_t output_reg;
uint32_t DP;
uint8_t link_configuration[DP_LINK_CONFIGURATION_SIZE];
bool has_audio;
int dpms_mode;
uint8_t link_bw;
uint8_t lane_count;
uint8_t dpcd[4];
struct intel_encoder *intel_encoder;
struct i2c_adapter adapter;
struct i2c_algo_dp_aux_data algo;
};
static void
intel_dp_link_train(struct intel_encoder *intel_encoder, uint32_t DP,
uint8_t link_configuration[DP_LINK_CONFIGURATION_SIZE]);
static void
intel_dp_link_down(struct intel_encoder *intel_encoder, uint32_t DP);
void
intel_edp_link_config (struct intel_encoder *intel_encoder,
int *lane_num, int *link_bw)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
*lane_num = dp_priv->lane_count;
if (dp_priv->link_bw == DP_LINK_BW_1_62)
*link_bw = 162000;
else if (dp_priv->link_bw == DP_LINK_BW_2_7)
*link_bw = 270000;
}
static int
intel_dp_max_lane_count(struct intel_encoder *intel_encoder)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
int max_lane_count = 4;
if (dp_priv->dpcd[0] >= 0x11) {
max_lane_count = dp_priv->dpcd[2] & 0x1f;
switch (max_lane_count) {
case 1: case 2: case 4:
break;
default:
max_lane_count = 4;
}
}
return max_lane_count;
}
static int
intel_dp_max_link_bw(struct intel_encoder *intel_encoder)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
int max_link_bw = dp_priv->dpcd[1];
switch (max_link_bw) {
case DP_LINK_BW_1_62:
case DP_LINK_BW_2_7:
break;
default:
max_link_bw = DP_LINK_BW_1_62;
break;
}
return max_link_bw;
}
static int
intel_dp_link_clock(uint8_t link_bw)
{
if (link_bw == DP_LINK_BW_2_7)
return 270000;
else
return 162000;
}
/* I think this is a fiction */
static int
intel_dp_link_required(struct drm_device *dev,
struct intel_encoder *intel_encoder, int pixel_clock)
{
struct drm_i915_private *dev_priv = dev->dev_private;
if (IS_eDP(intel_encoder))
return (pixel_clock * dev_priv->edp_bpp) / 8;
else
return pixel_clock * 3;
}
static int
intel_dp_max_data_rate(int max_link_clock, int max_lanes)
{
return (max_link_clock * max_lanes * 8) / 10;
}
static int
intel_dp_mode_valid(struct drm_connector *connector,
struct drm_display_mode *mode)
{
struct drm_encoder *encoder = intel_attached_encoder(connector);
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
int max_link_clock = intel_dp_link_clock(intel_dp_max_link_bw(intel_encoder));
int max_lanes = intel_dp_max_lane_count(intel_encoder);
/* only refuse the mode on non eDP since we have seen some wierd eDP panels
which are outside spec tolerances but somehow work by magic */
if (!IS_eDP(intel_encoder) &&
(intel_dp_link_required(connector->dev, intel_encoder, mode->clock)
> intel_dp_max_data_rate(max_link_clock, max_lanes)))
return MODE_CLOCK_HIGH;
if (mode->clock < 10000)
return MODE_CLOCK_LOW;
return MODE_OK;
}
static uint32_t
pack_aux(uint8_t *src, int src_bytes)
{
int i;
uint32_t v = 0;
if (src_bytes > 4)
src_bytes = 4;
for (i = 0; i < src_bytes; i++)
v |= ((uint32_t) src[i]) << ((3-i) * 8);
return v;
}
static void
unpack_aux(uint32_t src, uint8_t *dst, int dst_bytes)
{
int i;
if (dst_bytes > 4)
dst_bytes = 4;
for (i = 0; i < dst_bytes; i++)
dst[i] = src >> ((3-i) * 8);
}
/* hrawclock is 1/4 the FSB frequency */
static int
intel_hrawclk(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t clkcfg;
clkcfg = I915_READ(CLKCFG);
switch (clkcfg & CLKCFG_FSB_MASK) {
case CLKCFG_FSB_400:
return 100;
case CLKCFG_FSB_533:
return 133;
case CLKCFG_FSB_667:
return 166;
case CLKCFG_FSB_800:
return 200;
case CLKCFG_FSB_1067:
return 266;
case CLKCFG_FSB_1333:
return 333;
/* these two are just a guess; one of them might be right */
case CLKCFG_FSB_1600:
case CLKCFG_FSB_1600_ALT:
return 400;
default:
return 133;
}
}
static int
intel_dp_aux_ch(struct intel_encoder *intel_encoder,
uint8_t *send, int send_bytes,
uint8_t *recv, int recv_size)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
uint32_t output_reg = dp_priv->output_reg;
struct drm_device *dev = intel_encoder->enc.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t ch_ctl = output_reg + 0x10;
uint32_t ch_data = ch_ctl + 4;
int i;
int recv_bytes;
uint32_t status;
uint32_t aux_clock_divider;
int try, precharge;
/* The clock divider is based off the hrawclk,
* and would like to run at 2MHz. So, take the
* hrawclk value and divide by 2 and use that
*/
if (IS_eDP(intel_encoder)) {
if (IS_GEN6(dev))
aux_clock_divider = 200; /* SNB eDP input clock at 400Mhz */
else
aux_clock_divider = 225; /* eDP input clock at 450Mhz */
} else if (HAS_PCH_SPLIT(dev))
aux_clock_divider = 62; /* IRL input clock fixed at 125Mhz */
else
aux_clock_divider = intel_hrawclk(dev) / 2;
if (IS_GEN6(dev))
precharge = 3;
else
precharge = 5;
if (I915_READ(ch_ctl) & DP_AUX_CH_CTL_SEND_BUSY) {
DRM_ERROR("dp_aux_ch not started status 0x%08x\n",
I915_READ(ch_ctl));
return -EBUSY;
}
/* Must try at least 3 times according to DP spec */
for (try = 0; try < 5; try++) {
/* Load the send data into the aux channel data registers */
for (i = 0; i < send_bytes; i += 4)
I915_WRITE(ch_data + i,
pack_aux(send + i, send_bytes - i));
/* Send the command and wait for it to complete */
I915_WRITE(ch_ctl,
DP_AUX_CH_CTL_SEND_BUSY |
DP_AUX_CH_CTL_TIME_OUT_400us |
(send_bytes << DP_AUX_CH_CTL_MESSAGE_SIZE_SHIFT) |
(precharge << DP_AUX_CH_CTL_PRECHARGE_2US_SHIFT) |
(aux_clock_divider << DP_AUX_CH_CTL_BIT_CLOCK_2X_SHIFT) |
DP_AUX_CH_CTL_DONE |
DP_AUX_CH_CTL_TIME_OUT_ERROR |
DP_AUX_CH_CTL_RECEIVE_ERROR);
for (;;) {
status = I915_READ(ch_ctl);
if ((status & DP_AUX_CH_CTL_SEND_BUSY) == 0)
break;
udelay(100);
}
/* Clear done status and any errors */
I915_WRITE(ch_ctl,
status |
DP_AUX_CH_CTL_DONE |
DP_AUX_CH_CTL_TIME_OUT_ERROR |
DP_AUX_CH_CTL_RECEIVE_ERROR);
if (status & DP_AUX_CH_CTL_DONE)
break;
}
if ((status & DP_AUX_CH_CTL_DONE) == 0) {
DRM_ERROR("dp_aux_ch not done status 0x%08x\n", status);
return -EBUSY;
}
/* Check for timeout or receive error.
* Timeouts occur when the sink is not connected
*/
if (status & DP_AUX_CH_CTL_RECEIVE_ERROR) {
DRM_ERROR("dp_aux_ch receive error status 0x%08x\n", status);
return -EIO;
}
/* Timeouts occur when the device isn't connected, so they're
* "normal" -- don't fill the kernel log with these */
if (status & DP_AUX_CH_CTL_TIME_OUT_ERROR) {
DRM_DEBUG_KMS("dp_aux_ch timeout status 0x%08x\n", status);
return -ETIMEDOUT;
}
/* Unload any bytes sent back from the other side */
recv_bytes = ((status & DP_AUX_CH_CTL_MESSAGE_SIZE_MASK) >>
DP_AUX_CH_CTL_MESSAGE_SIZE_SHIFT);
if (recv_bytes > recv_size)
recv_bytes = recv_size;
for (i = 0; i < recv_bytes; i += 4)
unpack_aux(I915_READ(ch_data + i),
recv + i, recv_bytes - i);
return recv_bytes;
}
/* Write data to the aux channel in native mode */
static int
intel_dp_aux_native_write(struct intel_encoder *intel_encoder,
uint16_t address, uint8_t *send, int send_bytes)
{
int ret;
uint8_t msg[20];
int msg_bytes;
uint8_t ack;
if (send_bytes > 16)
return -1;
msg[0] = AUX_NATIVE_WRITE << 4;
msg[1] = address >> 8;
msg[2] = address & 0xff;
msg[3] = send_bytes - 1;
memcpy(&msg[4], send, send_bytes);
msg_bytes = send_bytes + 4;
for (;;) {
ret = intel_dp_aux_ch(intel_encoder, msg, msg_bytes, &ack, 1);
if (ret < 0)
return ret;
if ((ack & AUX_NATIVE_REPLY_MASK) == AUX_NATIVE_REPLY_ACK)
break;
else if ((ack & AUX_NATIVE_REPLY_MASK) == AUX_NATIVE_REPLY_DEFER)
udelay(100);
else
return -EIO;
}
return send_bytes;
}
/* Write a single byte to the aux channel in native mode */
static int
intel_dp_aux_native_write_1(struct intel_encoder *intel_encoder,
uint16_t address, uint8_t byte)
{
return intel_dp_aux_native_write(intel_encoder, address, &byte, 1);
}
/* read bytes from a native aux channel */
static int
intel_dp_aux_native_read(struct intel_encoder *intel_encoder,
uint16_t address, uint8_t *recv, int recv_bytes)
{
uint8_t msg[4];
int msg_bytes;
uint8_t reply[20];
int reply_bytes;
uint8_t ack;
int ret;
msg[0] = AUX_NATIVE_READ << 4;
msg[1] = address >> 8;
msg[2] = address & 0xff;
msg[3] = recv_bytes - 1;
msg_bytes = 4;
reply_bytes = recv_bytes + 1;
for (;;) {
ret = intel_dp_aux_ch(intel_encoder, msg, msg_bytes,
reply, reply_bytes);
if (ret == 0)
return -EPROTO;
if (ret < 0)
return ret;
ack = reply[0];
if ((ack & AUX_NATIVE_REPLY_MASK) == AUX_NATIVE_REPLY_ACK) {
memcpy(recv, reply + 1, ret - 1);
return ret - 1;
}
else if ((ack & AUX_NATIVE_REPLY_MASK) == AUX_NATIVE_REPLY_DEFER)
udelay(100);
else
return -EIO;
}
}
static int
intel_dp_i2c_aux_ch(struct i2c_adapter *adapter, int mode,
uint8_t write_byte, uint8_t *read_byte)
{
struct i2c_algo_dp_aux_data *algo_data = adapter->algo_data;
struct intel_dp_priv *dp_priv = container_of(adapter,
struct intel_dp_priv,
adapter);
struct intel_encoder *intel_encoder = dp_priv->intel_encoder;
uint16_t address = algo_data->address;
uint8_t msg[5];
uint8_t reply[2];
int msg_bytes;
int reply_bytes;
int ret;
/* Set up the command byte */
if (mode & MODE_I2C_READ)
msg[0] = AUX_I2C_READ << 4;
else
msg[0] = AUX_I2C_WRITE << 4;
if (!(mode & MODE_I2C_STOP))
msg[0] |= AUX_I2C_MOT << 4;
msg[1] = address >> 8;
msg[2] = address;
switch (mode) {
case MODE_I2C_WRITE:
msg[3] = 0;
msg[4] = write_byte;
msg_bytes = 5;
reply_bytes = 1;
break;
case MODE_I2C_READ:
msg[3] = 0;
msg_bytes = 4;
reply_bytes = 2;
break;
default:
msg_bytes = 3;
reply_bytes = 1;
break;
}
for (;;) {
ret = intel_dp_aux_ch(intel_encoder,
msg, msg_bytes,
reply, reply_bytes);
if (ret < 0) {
DRM_DEBUG_KMS("aux_ch failed %d\n", ret);
return ret;
}
switch (reply[0] & AUX_I2C_REPLY_MASK) {
case AUX_I2C_REPLY_ACK:
if (mode == MODE_I2C_READ) {
*read_byte = reply[1];
}
return reply_bytes - 1;
case AUX_I2C_REPLY_NACK:
DRM_DEBUG_KMS("aux_ch nack\n");
return -EREMOTEIO;
case AUX_I2C_REPLY_DEFER:
DRM_DEBUG_KMS("aux_ch defer\n");
udelay(100);
break;
default:
DRM_ERROR("aux_ch invalid reply 0x%02x\n", reply[0]);
return -EREMOTEIO;
}
}
}
static int
intel_dp_i2c_init(struct intel_encoder *intel_encoder,
struct intel_connector *intel_connector, const char *name)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
DRM_DEBUG_KMS("i2c_init %s\n", name);
dp_priv->algo.running = false;
dp_priv->algo.address = 0;
dp_priv->algo.aux_ch = intel_dp_i2c_aux_ch;
memset(&dp_priv->adapter, '\0', sizeof (dp_priv->adapter));
dp_priv->adapter.owner = THIS_MODULE;
dp_priv->adapter.class = I2C_CLASS_DDC;
strncpy (dp_priv->adapter.name, name, sizeof(dp_priv->adapter.name) - 1);
dp_priv->adapter.name[sizeof(dp_priv->adapter.name) - 1] = '\0';
dp_priv->adapter.algo_data = &dp_priv->algo;
dp_priv->adapter.dev.parent = &intel_connector->base.kdev;
return i2c_dp_aux_add_bus(&dp_priv->adapter);
}
static bool
intel_dp_mode_fixup(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
int lane_count, clock;
int max_lane_count = intel_dp_max_lane_count(intel_encoder);
int max_clock = intel_dp_max_link_bw(intel_encoder) == DP_LINK_BW_2_7 ? 1 : 0;
static int bws[2] = { DP_LINK_BW_1_62, DP_LINK_BW_2_7 };
for (lane_count = 1; lane_count <= max_lane_count; lane_count <<= 1) {
for (clock = 0; clock <= max_clock; clock++) {
int link_avail = intel_dp_max_data_rate(intel_dp_link_clock(bws[clock]), lane_count);
if (intel_dp_link_required(encoder->dev, intel_encoder, mode->clock)
<= link_avail) {
dp_priv->link_bw = bws[clock];
dp_priv->lane_count = lane_count;
adjusted_mode->clock = intel_dp_link_clock(dp_priv->link_bw);
DRM_DEBUG_KMS("Display port link bw %02x lane "
"count %d clock %d\n",
dp_priv->link_bw, dp_priv->lane_count,
adjusted_mode->clock);
return true;
}
}
}
if (IS_eDP(intel_encoder)) {
/* okay we failed just pick the highest */
dp_priv->lane_count = max_lane_count;
dp_priv->link_bw = bws[max_clock];
adjusted_mode->clock = intel_dp_link_clock(dp_priv->link_bw);
DRM_DEBUG_KMS("Force picking display port link bw %02x lane "
"count %d clock %d\n",
dp_priv->link_bw, dp_priv->lane_count,
adjusted_mode->clock);
return true;
}
return false;
}
struct intel_dp_m_n {
uint32_t tu;
uint32_t gmch_m;
uint32_t gmch_n;
uint32_t link_m;
uint32_t link_n;
};
static void
intel_reduce_ratio(uint32_t *num, uint32_t *den)
{
while (*num > 0xffffff || *den > 0xffffff) {
*num >>= 1;
*den >>= 1;
}
}
static void
intel_dp_compute_m_n(int bytes_per_pixel,
int nlanes,
int pixel_clock,
int link_clock,
struct intel_dp_m_n *m_n)
{
m_n->tu = 64;
m_n->gmch_m = pixel_clock * bytes_per_pixel;
m_n->gmch_n = link_clock * nlanes;
intel_reduce_ratio(&m_n->gmch_m, &m_n->gmch_n);
m_n->link_m = pixel_clock;
m_n->link_n = link_clock;
intel_reduce_ratio(&m_n->link_m, &m_n->link_n);
}
void
intel_dp_set_m_n(struct drm_crtc *crtc, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = crtc->dev;
struct drm_mode_config *mode_config = &dev->mode_config;
struct drm_encoder *encoder;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
int lane_count = 4;
struct intel_dp_m_n m_n;
/*
* Find the lane count in the intel_encoder private
*/
list_for_each_entry(encoder, &mode_config->encoder_list, head) {
struct intel_encoder *intel_encoder;
struct intel_dp_priv *dp_priv;
if (encoder->crtc != crtc)
continue;
intel_encoder = enc_to_intel_encoder(encoder);
dp_priv = intel_encoder->dev_priv;
if (intel_encoder->type == INTEL_OUTPUT_DISPLAYPORT) {
lane_count = dp_priv->lane_count;
break;
}
}
/*
* Compute the GMCH and Link ratios. The '3' here is
* the number of bytes_per_pixel post-LUT, which we always
* set up for 8-bits of R/G/B, or 3 bytes total.
*/
intel_dp_compute_m_n(3, lane_count,
mode->clock, adjusted_mode->clock, &m_n);
if (HAS_PCH_SPLIT(dev)) {
if (intel_crtc->pipe == 0) {
I915_WRITE(TRANSA_DATA_M1,
((m_n.tu - 1) << PIPE_GMCH_DATA_M_TU_SIZE_SHIFT) |
m_n.gmch_m);
I915_WRITE(TRANSA_DATA_N1, m_n.gmch_n);
I915_WRITE(TRANSA_DP_LINK_M1, m_n.link_m);
I915_WRITE(TRANSA_DP_LINK_N1, m_n.link_n);
} else {
I915_WRITE(TRANSB_DATA_M1,
((m_n.tu - 1) << PIPE_GMCH_DATA_M_TU_SIZE_SHIFT) |
m_n.gmch_m);
I915_WRITE(TRANSB_DATA_N1, m_n.gmch_n);
I915_WRITE(TRANSB_DP_LINK_M1, m_n.link_m);
I915_WRITE(TRANSB_DP_LINK_N1, m_n.link_n);
}
} else {
if (intel_crtc->pipe == 0) {
I915_WRITE(PIPEA_GMCH_DATA_M,
((m_n.tu - 1) << PIPE_GMCH_DATA_M_TU_SIZE_SHIFT) |
m_n.gmch_m);
I915_WRITE(PIPEA_GMCH_DATA_N,
m_n.gmch_n);
I915_WRITE(PIPEA_DP_LINK_M, m_n.link_m);
I915_WRITE(PIPEA_DP_LINK_N, m_n.link_n);
} else {
I915_WRITE(PIPEB_GMCH_DATA_M,
((m_n.tu - 1) << PIPE_GMCH_DATA_M_TU_SIZE_SHIFT) |
m_n.gmch_m);
I915_WRITE(PIPEB_GMCH_DATA_N,
m_n.gmch_n);
I915_WRITE(PIPEB_DP_LINK_M, m_n.link_m);
I915_WRITE(PIPEB_DP_LINK_N, m_n.link_n);
}
}
}
static void
intel_dp_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
struct drm_crtc *crtc = intel_encoder->enc.crtc;
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
dp_priv->DP = (DP_VOLTAGE_0_4 |
DP_PRE_EMPHASIS_0);
if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
dp_priv->DP |= DP_SYNC_HS_HIGH;
if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
dp_priv->DP |= DP_SYNC_VS_HIGH;
if (HAS_PCH_CPT(dev) && !IS_eDP(intel_encoder))
dp_priv->DP |= DP_LINK_TRAIN_OFF_CPT;
else
dp_priv->DP |= DP_LINK_TRAIN_OFF;
switch (dp_priv->lane_count) {
case 1:
dp_priv->DP |= DP_PORT_WIDTH_1;
break;
case 2:
dp_priv->DP |= DP_PORT_WIDTH_2;
break;
case 4:
dp_priv->DP |= DP_PORT_WIDTH_4;
break;
}
if (dp_priv->has_audio)
dp_priv->DP |= DP_AUDIO_OUTPUT_ENABLE;
memset(dp_priv->link_configuration, 0, DP_LINK_CONFIGURATION_SIZE);
dp_priv->link_configuration[0] = dp_priv->link_bw;
dp_priv->link_configuration[1] = dp_priv->lane_count;
/*
* Check for DPCD version > 1.1 and enhanced framing support
*/
if (dp_priv->dpcd[0] >= 0x11 && (dp_priv->dpcd[2] & DP_ENHANCED_FRAME_CAP)) {
dp_priv->link_configuration[1] |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
dp_priv->DP |= DP_ENHANCED_FRAMING;
}
/* CPT DP's pipe select is decided in TRANS_DP_CTL */
if (intel_crtc->pipe == 1 && !HAS_PCH_CPT(dev))
dp_priv->DP |= DP_PIPEB_SELECT;
if (IS_eDP(intel_encoder)) {
/* don't miss out required setting for eDP */
dp_priv->DP |= DP_PLL_ENABLE;
if (adjusted_mode->clock < 200000)
dp_priv->DP |= DP_PLL_FREQ_160MHZ;
else
dp_priv->DP |= DP_PLL_FREQ_270MHZ;
}
}
static void ironlake_edp_panel_on (struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
unsigned long timeout = jiffies + msecs_to_jiffies(5000);
u32 pp, pp_status;
pp_status = I915_READ(PCH_PP_STATUS);
if (pp_status & PP_ON)
return;
pp = I915_READ(PCH_PP_CONTROL);
pp |= PANEL_UNLOCK_REGS | POWER_TARGET_ON;
I915_WRITE(PCH_PP_CONTROL, pp);
do {
pp_status = I915_READ(PCH_PP_STATUS);
} while (((pp_status & PP_ON) == 0) && !time_after(jiffies, timeout));
if (time_after(jiffies, timeout))
DRM_DEBUG_KMS("panel on wait timed out: 0x%08x\n", pp_status);
pp &= ~(PANEL_UNLOCK_REGS | EDP_FORCE_VDD);
I915_WRITE(PCH_PP_CONTROL, pp);
}
static void ironlake_edp_panel_off (struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
unsigned long timeout = jiffies + msecs_to_jiffies(5000);
u32 pp, pp_status;
pp = I915_READ(PCH_PP_CONTROL);
pp &= ~POWER_TARGET_ON;
I915_WRITE(PCH_PP_CONTROL, pp);
do {
pp_status = I915_READ(PCH_PP_STATUS);
} while ((pp_status & PP_ON) && !time_after(jiffies, timeout));
if (time_after(jiffies, timeout))
DRM_DEBUG_KMS("panel off wait timed out\n");
/* Make sure VDD is enabled so DP AUX will work */
pp |= EDP_FORCE_VDD;
I915_WRITE(PCH_PP_CONTROL, pp);
}
static void ironlake_edp_backlight_on (struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
u32 pp;
DRM_DEBUG_KMS("\n");
pp = I915_READ(PCH_PP_CONTROL);
pp |= EDP_BLC_ENABLE;
I915_WRITE(PCH_PP_CONTROL, pp);
}
static void ironlake_edp_backlight_off (struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
u32 pp;
DRM_DEBUG_KMS("\n");
pp = I915_READ(PCH_PP_CONTROL);
pp &= ~EDP_BLC_ENABLE;
I915_WRITE(PCH_PP_CONTROL, pp);
}
static void
intel_dp_dpms(struct drm_encoder *encoder, int mode)
{
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t dp_reg = I915_READ(dp_priv->output_reg);
if (mode != DRM_MODE_DPMS_ON) {
if (dp_reg & DP_PORT_EN) {
intel_dp_link_down(intel_encoder, dp_priv->DP);
if (IS_eDP(intel_encoder)) {
ironlake_edp_backlight_off(dev);
ironlake_edp_panel_off(dev);
}
}
} else {
if (!(dp_reg & DP_PORT_EN)) {
intel_dp_link_train(intel_encoder, dp_priv->DP, dp_priv->link_configuration);
if (IS_eDP(intel_encoder)) {
ironlake_edp_panel_on(dev);
ironlake_edp_backlight_on(dev);
}
}
}
dp_priv->dpms_mode = mode;
}
/*
* Fetch AUX CH registers 0x202 - 0x207 which contain
* link status information
*/
static bool
intel_dp_get_link_status(struct intel_encoder *intel_encoder,
uint8_t link_status[DP_LINK_STATUS_SIZE])
{
int ret;
ret = intel_dp_aux_native_read(intel_encoder,
DP_LANE0_1_STATUS,
link_status, DP_LINK_STATUS_SIZE);
if (ret != DP_LINK_STATUS_SIZE)
return false;
return true;
}
static uint8_t
intel_dp_link_status(uint8_t link_status[DP_LINK_STATUS_SIZE],
int r)
{
return link_status[r - DP_LANE0_1_STATUS];
}
static uint8_t
intel_get_adjust_request_voltage(uint8_t link_status[DP_LINK_STATUS_SIZE],
int lane)
{
int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
int s = ((lane & 1) ?
DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
uint8_t l = intel_dp_link_status(link_status, i);
return ((l >> s) & 3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
}
static uint8_t
intel_get_adjust_request_pre_emphasis(uint8_t link_status[DP_LINK_STATUS_SIZE],
int lane)
{
int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
int s = ((lane & 1) ?
DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
uint8_t l = intel_dp_link_status(link_status, i);
return ((l >> s) & 3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
}
#if 0
static char *voltage_names[] = {
"0.4V", "0.6V", "0.8V", "1.2V"
};
static char *pre_emph_names[] = {
"0dB", "3.5dB", "6dB", "9.5dB"
};
static char *link_train_names[] = {
"pattern 1", "pattern 2", "idle", "off"
};
#endif
/*
* These are source-specific values; current Intel hardware supports
* a maximum voltage of 800mV and a maximum pre-emphasis of 6dB
*/
#define I830_DP_VOLTAGE_MAX DP_TRAIN_VOLTAGE_SWING_800
static uint8_t
intel_dp_pre_emphasis_max(uint8_t voltage_swing)
{
switch (voltage_swing & DP_TRAIN_VOLTAGE_SWING_MASK) {
case DP_TRAIN_VOLTAGE_SWING_400:
return DP_TRAIN_PRE_EMPHASIS_6;
case DP_TRAIN_VOLTAGE_SWING_600:
return DP_TRAIN_PRE_EMPHASIS_6;
case DP_TRAIN_VOLTAGE_SWING_800:
return DP_TRAIN_PRE_EMPHASIS_3_5;
case DP_TRAIN_VOLTAGE_SWING_1200:
default:
return DP_TRAIN_PRE_EMPHASIS_0;
}
}
static void
intel_get_adjust_train(struct intel_encoder *intel_encoder,
uint8_t link_status[DP_LINK_STATUS_SIZE],
int lane_count,
uint8_t train_set[4])
{
uint8_t v = 0;
uint8_t p = 0;
int lane;
for (lane = 0; lane < lane_count; lane++) {
uint8_t this_v = intel_get_adjust_request_voltage(link_status, lane);
uint8_t this_p = intel_get_adjust_request_pre_emphasis(link_status, lane);
if (this_v > v)
v = this_v;
if (this_p > p)
p = this_p;
}
if (v >= I830_DP_VOLTAGE_MAX)
v = I830_DP_VOLTAGE_MAX | DP_TRAIN_MAX_SWING_REACHED;
if (p >= intel_dp_pre_emphasis_max(v))
p = intel_dp_pre_emphasis_max(v) | DP_TRAIN_MAX_PRE_EMPHASIS_REACHED;
for (lane = 0; lane < 4; lane++)
train_set[lane] = v | p;
}
static uint32_t
intel_dp_signal_levels(uint8_t train_set, int lane_count)
{
uint32_t signal_levels = 0;
switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
case DP_TRAIN_VOLTAGE_SWING_400:
default:
signal_levels |= DP_VOLTAGE_0_4;
break;
case DP_TRAIN_VOLTAGE_SWING_600:
signal_levels |= DP_VOLTAGE_0_6;
break;
case DP_TRAIN_VOLTAGE_SWING_800:
signal_levels |= DP_VOLTAGE_0_8;
break;
case DP_TRAIN_VOLTAGE_SWING_1200:
signal_levels |= DP_VOLTAGE_1_2;
break;
}
switch (train_set & DP_TRAIN_PRE_EMPHASIS_MASK) {
case DP_TRAIN_PRE_EMPHASIS_0:
default:
signal_levels |= DP_PRE_EMPHASIS_0;
break;
case DP_TRAIN_PRE_EMPHASIS_3_5:
signal_levels |= DP_PRE_EMPHASIS_3_5;
break;
case DP_TRAIN_PRE_EMPHASIS_6:
signal_levels |= DP_PRE_EMPHASIS_6;
break;
case DP_TRAIN_PRE_EMPHASIS_9_5:
signal_levels |= DP_PRE_EMPHASIS_9_5;
break;
}
return signal_levels;
}
/* Gen6's DP voltage swing and pre-emphasis control */
static uint32_t
intel_gen6_edp_signal_levels(uint8_t train_set)
{
switch (train_set & (DP_TRAIN_VOLTAGE_SWING_MASK|DP_TRAIN_PRE_EMPHASIS_MASK)) {
case DP_TRAIN_VOLTAGE_SWING_400 | DP_TRAIN_PRE_EMPHASIS_0:
return EDP_LINK_TRAIN_400MV_0DB_SNB_B;
case DP_TRAIN_VOLTAGE_SWING_400 | DP_TRAIN_PRE_EMPHASIS_6:
return EDP_LINK_TRAIN_400MV_6DB_SNB_B;
case DP_TRAIN_VOLTAGE_SWING_600 | DP_TRAIN_PRE_EMPHASIS_3_5:
return EDP_LINK_TRAIN_600MV_3_5DB_SNB_B;
case DP_TRAIN_VOLTAGE_SWING_800 | DP_TRAIN_PRE_EMPHASIS_0:
return EDP_LINK_TRAIN_800MV_0DB_SNB_B;
default:
DRM_DEBUG_KMS("Unsupported voltage swing/pre-emphasis level\n");
return EDP_LINK_TRAIN_400MV_0DB_SNB_B;
}
}
static uint8_t
intel_get_lane_status(uint8_t link_status[DP_LINK_STATUS_SIZE],
int lane)
{
int i = DP_LANE0_1_STATUS + (lane >> 1);
int s = (lane & 1) * 4;
uint8_t l = intel_dp_link_status(link_status, i);
return (l >> s) & 0xf;
}
/* Check for clock recovery is done on all channels */
static bool
intel_clock_recovery_ok(uint8_t link_status[DP_LINK_STATUS_SIZE], int lane_count)
{
int lane;
uint8_t lane_status;
for (lane = 0; lane < lane_count; lane++) {
lane_status = intel_get_lane_status(link_status, lane);
if ((lane_status & DP_LANE_CR_DONE) == 0)
return false;
}
return true;
}
/* Check to see if channel eq is done on all channels */
#define CHANNEL_EQ_BITS (DP_LANE_CR_DONE|\
DP_LANE_CHANNEL_EQ_DONE|\
DP_LANE_SYMBOL_LOCKED)
static bool
intel_channel_eq_ok(uint8_t link_status[DP_LINK_STATUS_SIZE], int lane_count)
{
uint8_t lane_align;
uint8_t lane_status;
int lane;
lane_align = intel_dp_link_status(link_status,
DP_LANE_ALIGN_STATUS_UPDATED);
if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
return false;
for (lane = 0; lane < lane_count; lane++) {
lane_status = intel_get_lane_status(link_status, lane);
if ((lane_status & CHANNEL_EQ_BITS) != CHANNEL_EQ_BITS)
return false;
}
return true;
}
static bool
intel_dp_set_link_train(struct intel_encoder *intel_encoder,
uint32_t dp_reg_value,
uint8_t dp_train_pat,
uint8_t train_set[4],
bool first)
{
struct drm_device *dev = intel_encoder->enc.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
int ret;
I915_WRITE(dp_priv->output_reg, dp_reg_value);
POSTING_READ(dp_priv->output_reg);
if (first)
intel_wait_for_vblank(dev);
intel_dp_aux_native_write_1(intel_encoder,
DP_TRAINING_PATTERN_SET,
dp_train_pat);
ret = intel_dp_aux_native_write(intel_encoder,
DP_TRAINING_LANE0_SET, train_set, 4);
if (ret != 4)
return false;
return true;
}
static void
intel_dp_link_train(struct intel_encoder *intel_encoder, uint32_t DP,
uint8_t link_configuration[DP_LINK_CONFIGURATION_SIZE])
{
struct drm_device *dev = intel_encoder->enc.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
uint8_t train_set[4];
uint8_t link_status[DP_LINK_STATUS_SIZE];
int i;
uint8_t voltage;
bool clock_recovery = false;
bool channel_eq = false;
bool first = true;
int tries;
u32 reg;
/* Write the link configuration data */
intel_dp_aux_native_write(intel_encoder, DP_LINK_BW_SET,
link_configuration, DP_LINK_CONFIGURATION_SIZE);
DP |= DP_PORT_EN;
if (HAS_PCH_CPT(dev) && !IS_eDP(intel_encoder))
DP &= ~DP_LINK_TRAIN_MASK_CPT;
else
DP &= ~DP_LINK_TRAIN_MASK;
memset(train_set, 0, 4);
voltage = 0xff;
tries = 0;
clock_recovery = false;
for (;;) {
/* Use train_set[0] to set the voltage and pre emphasis values */
uint32_t signal_levels;
if (IS_GEN6(dev) && IS_eDP(intel_encoder)) {
signal_levels = intel_gen6_edp_signal_levels(train_set[0]);
DP = (DP & ~EDP_LINK_TRAIN_VOL_EMP_MASK_SNB) | signal_levels;
} else {
signal_levels = intel_dp_signal_levels(train_set[0], dp_priv->lane_count);
DP = (DP & ~(DP_VOLTAGE_MASK|DP_PRE_EMPHASIS_MASK)) | signal_levels;
}
if (HAS_PCH_CPT(dev) && !IS_eDP(intel_encoder))
reg = DP | DP_LINK_TRAIN_PAT_1_CPT;
else
reg = DP | DP_LINK_TRAIN_PAT_1;
if (!intel_dp_set_link_train(intel_encoder, reg,
DP_TRAINING_PATTERN_1, train_set, first))
break;
first = false;
/* Set training pattern 1 */
udelay(100);
if (!intel_dp_get_link_status(intel_encoder, link_status))
break;
if (intel_clock_recovery_ok(link_status, dp_priv->lane_count)) {
clock_recovery = true;
break;
}
/* Check to see if we've tried the max voltage */
for (i = 0; i < dp_priv->lane_count; i++)
if ((train_set[i] & DP_TRAIN_MAX_SWING_REACHED) == 0)
break;
if (i == dp_priv->lane_count)
break;
/* Check to see if we've tried the same voltage 5 times */
if ((train_set[0] & DP_TRAIN_VOLTAGE_SWING_MASK) == voltage) {
++tries;
if (tries == 5)
break;
} else
tries = 0;
voltage = train_set[0] & DP_TRAIN_VOLTAGE_SWING_MASK;
/* Compute new train_set as requested by target */
intel_get_adjust_train(intel_encoder, link_status, dp_priv->lane_count, train_set);
}
/* channel equalization */
tries = 0;
channel_eq = false;
for (;;) {
/* Use train_set[0] to set the voltage and pre emphasis values */
uint32_t signal_levels;
if (IS_GEN6(dev) && IS_eDP(intel_encoder)) {
signal_levels = intel_gen6_edp_signal_levels(train_set[0]);
DP = (DP & ~EDP_LINK_TRAIN_VOL_EMP_MASK_SNB) | signal_levels;
} else {
signal_levels = intel_dp_signal_levels(train_set[0], dp_priv->lane_count);
DP = (DP & ~(DP_VOLTAGE_MASK|DP_PRE_EMPHASIS_MASK)) | signal_levels;
}
if (HAS_PCH_CPT(dev) && !IS_eDP(intel_encoder))
reg = DP | DP_LINK_TRAIN_PAT_2_CPT;
else
reg = DP | DP_LINK_TRAIN_PAT_2;
/* channel eq pattern */
if (!intel_dp_set_link_train(intel_encoder, reg,
DP_TRAINING_PATTERN_2, train_set,
false))
break;
udelay(400);
if (!intel_dp_get_link_status(intel_encoder, link_status))
break;
if (intel_channel_eq_ok(link_status, dp_priv->lane_count)) {
channel_eq = true;
break;
}
/* Try 5 times */
if (tries > 5)
break;
/* Compute new train_set as requested by target */
intel_get_adjust_train(intel_encoder, link_status, dp_priv->lane_count, train_set);
++tries;
}
if (HAS_PCH_CPT(dev) && !IS_eDP(intel_encoder))
reg = DP | DP_LINK_TRAIN_OFF_CPT;
else
reg = DP | DP_LINK_TRAIN_OFF;
I915_WRITE(dp_priv->output_reg, reg);
POSTING_READ(dp_priv->output_reg);
intel_dp_aux_native_write_1(intel_encoder,
DP_TRAINING_PATTERN_SET, DP_TRAINING_PATTERN_DISABLE);
}
static void
intel_dp_link_down(struct intel_encoder *intel_encoder, uint32_t DP)
{
struct drm_device *dev = intel_encoder->enc.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
DRM_DEBUG_KMS("\n");
if (IS_eDP(intel_encoder)) {
DP &= ~DP_PLL_ENABLE;
I915_WRITE(dp_priv->output_reg, DP);
POSTING_READ(dp_priv->output_reg);
udelay(100);
}
if (HAS_PCH_CPT(dev) && !IS_eDP(intel_encoder)) {
DP &= ~DP_LINK_TRAIN_MASK_CPT;
I915_WRITE(dp_priv->output_reg, DP | DP_LINK_TRAIN_PAT_IDLE_CPT);
POSTING_READ(dp_priv->output_reg);
} else {
DP &= ~DP_LINK_TRAIN_MASK;
I915_WRITE(dp_priv->output_reg, DP | DP_LINK_TRAIN_PAT_IDLE);
POSTING_READ(dp_priv->output_reg);
}
udelay(17000);
if (IS_eDP(intel_encoder))
DP |= DP_LINK_TRAIN_OFF;
I915_WRITE(dp_priv->output_reg, DP & ~DP_PORT_EN);
POSTING_READ(dp_priv->output_reg);
}
/*
* According to DP spec
* 5.1.2:
* 1. Read DPCD
* 2. Configure link according to Receiver Capabilities
* 3. Use Link Training from 2.5.3.3 and 3.5.1.3
* 4. Check link status on receipt of hot-plug interrupt
*/
static void
intel_dp_check_link_status(struct intel_encoder *intel_encoder)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
uint8_t link_status[DP_LINK_STATUS_SIZE];
if (!intel_encoder->enc.crtc)
return;
if (!intel_dp_get_link_status(intel_encoder, link_status)) {
intel_dp_link_down(intel_encoder, dp_priv->DP);
return;
}
if (!intel_channel_eq_ok(link_status, dp_priv->lane_count))
intel_dp_link_train(intel_encoder, dp_priv->DP, dp_priv->link_configuration);
}
static enum drm_connector_status
ironlake_dp_detect(struct drm_connector *connector)
{
struct drm_encoder *encoder = intel_attached_encoder(connector);
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
enum drm_connector_status status;
status = connector_status_disconnected;
if (intel_dp_aux_native_read(intel_encoder,
0x000, dp_priv->dpcd,
sizeof (dp_priv->dpcd)) == sizeof (dp_priv->dpcd))
{
if (dp_priv->dpcd[0] != 0)
status = connector_status_connected;
}
DRM_DEBUG_KMS("DPCD: %hx%hx%hx%hx\n", dp_priv->dpcd[0],
dp_priv->dpcd[1], dp_priv->dpcd[2], dp_priv->dpcd[3]);
return status;
}
/**
* Uses CRT_HOTPLUG_EN and CRT_HOTPLUG_STAT to detect DP connection.
*
* \return true if DP port is connected.
* \return false if DP port is disconnected.
*/
static enum drm_connector_status
intel_dp_detect(struct drm_connector *connector)
{
struct drm_encoder *encoder = intel_attached_encoder(connector);
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct drm_device *dev = intel_encoder->enc.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
uint32_t temp, bit;
enum drm_connector_status status;
dp_priv->has_audio = false;
if (HAS_PCH_SPLIT(dev))
return ironlake_dp_detect(connector);
switch (dp_priv->output_reg) {
case DP_B:
bit = DPB_HOTPLUG_INT_STATUS;
break;
case DP_C:
bit = DPC_HOTPLUG_INT_STATUS;
break;
case DP_D:
bit = DPD_HOTPLUG_INT_STATUS;
break;
default:
return connector_status_unknown;
}
temp = I915_READ(PORT_HOTPLUG_STAT);
if ((temp & bit) == 0)
return connector_status_disconnected;
status = connector_status_disconnected;
if (intel_dp_aux_native_read(intel_encoder,
0x000, dp_priv->dpcd,
sizeof (dp_priv->dpcd)) == sizeof (dp_priv->dpcd))
{
if (dp_priv->dpcd[0] != 0)
status = connector_status_connected;
}
return status;
}
static int intel_dp_get_modes(struct drm_connector *connector)
{
struct drm_encoder *encoder = intel_attached_encoder(connector);
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct drm_device *dev = intel_encoder->enc.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
int ret;
/* We should parse the EDID data and find out if it has an audio sink
*/
ret = intel_ddc_get_modes(connector, intel_encoder->ddc_bus);
if (ret)
return ret;
/* if eDP has no EDID, try to use fixed panel mode from VBT */
if (IS_eDP(intel_encoder)) {
if (dev_priv->panel_fixed_mode != NULL) {
struct drm_display_mode *mode;
mode = drm_mode_duplicate(dev, dev_priv->panel_fixed_mode);
drm_mode_probed_add(connector, mode);
return 1;
}
}
return 0;
}
static void
intel_dp_destroy (struct drm_connector *connector)
{
drm_sysfs_connector_remove(connector);
drm_connector_cleanup(connector);
kfree(connector);
}
static const struct drm_encoder_helper_funcs intel_dp_helper_funcs = {
.dpms = intel_dp_dpms,
.mode_fixup = intel_dp_mode_fixup,
.prepare = intel_encoder_prepare,
.mode_set = intel_dp_mode_set,
.commit = intel_encoder_commit,
};
static const struct drm_connector_funcs intel_dp_connector_funcs = {
.dpms = drm_helper_connector_dpms,
.detect = intel_dp_detect,
.fill_modes = drm_helper_probe_single_connector_modes,
.destroy = intel_dp_destroy,
};
static const struct drm_connector_helper_funcs intel_dp_connector_helper_funcs = {
.get_modes = intel_dp_get_modes,
.mode_valid = intel_dp_mode_valid,
.best_encoder = intel_attached_encoder,
};
static void intel_dp_enc_destroy(struct drm_encoder *encoder)
{
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
if (intel_encoder->i2c_bus)
intel_i2c_destroy(intel_encoder->i2c_bus);
drm_encoder_cleanup(encoder);
kfree(intel_encoder);
}
static const struct drm_encoder_funcs intel_dp_enc_funcs = {
.destroy = intel_dp_enc_destroy,
};
void
intel_dp_hot_plug(struct intel_encoder *intel_encoder)
{
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
if (dp_priv->dpms_mode == DRM_MODE_DPMS_ON)
intel_dp_check_link_status(intel_encoder);
}
/* Return which DP Port should be selected for Transcoder DP control */
int
intel_trans_dp_port_sel (struct drm_crtc *crtc)
{
struct drm_device *dev = crtc->dev;
struct drm_mode_config *mode_config = &dev->mode_config;
struct drm_encoder *encoder;
struct intel_encoder *intel_encoder = NULL;
list_for_each_entry(encoder, &mode_config->encoder_list, head) {
if (encoder->crtc != crtc)
continue;
intel_encoder = enc_to_intel_encoder(encoder);
if (intel_encoder->type == INTEL_OUTPUT_DISPLAYPORT) {
struct intel_dp_priv *dp_priv = intel_encoder->dev_priv;
return dp_priv->output_reg;
}
}
return -1;
}
void
intel_dp_init(struct drm_device *dev, int output_reg)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_connector *connector;
struct intel_encoder *intel_encoder;
struct intel_connector *intel_connector;
struct intel_dp_priv *dp_priv;
const char *name = NULL;
intel_encoder = kcalloc(sizeof(struct intel_encoder) +
sizeof(struct intel_dp_priv), 1, GFP_KERNEL);
if (!intel_encoder)
return;
intel_connector = kzalloc(sizeof(struct intel_connector), GFP_KERNEL);
if (!intel_connector) {
kfree(intel_encoder);
return;
}
dp_priv = (struct intel_dp_priv *)(intel_encoder + 1);
connector = &intel_connector->base;
drm_connector_init(dev, connector, &intel_dp_connector_funcs,
DRM_MODE_CONNECTOR_DisplayPort);
drm_connector_helper_add(connector, &intel_dp_connector_helper_funcs);
connector->polled = DRM_CONNECTOR_POLL_HPD;
if (output_reg == DP_A)
intel_encoder->type = INTEL_OUTPUT_EDP;
else
intel_encoder->type = INTEL_OUTPUT_DISPLAYPORT;
if (output_reg == DP_B || output_reg == PCH_DP_B)
intel_encoder->clone_mask = (1 << INTEL_DP_B_CLONE_BIT);
else if (output_reg == DP_C || output_reg == PCH_DP_C)
intel_encoder->clone_mask = (1 << INTEL_DP_C_CLONE_BIT);
else if (output_reg == DP_D || output_reg == PCH_DP_D)
intel_encoder->clone_mask = (1 << INTEL_DP_D_CLONE_BIT);
if (IS_eDP(intel_encoder))
intel_encoder->clone_mask = (1 << INTEL_EDP_CLONE_BIT);
intel_encoder->crtc_mask = (1 << 0) | (1 << 1);
connector->interlace_allowed = true;
connector->doublescan_allowed = 0;
dp_priv->intel_encoder = intel_encoder;
dp_priv->output_reg = output_reg;
dp_priv->has_audio = false;
dp_priv->dpms_mode = DRM_MODE_DPMS_ON;
intel_encoder->dev_priv = dp_priv;
drm_encoder_init(dev, &intel_encoder->enc, &intel_dp_enc_funcs,
DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(&intel_encoder->enc, &intel_dp_helper_funcs);
drm_mode_connector_attach_encoder(&intel_connector->base,
&intel_encoder->enc);
drm_sysfs_connector_add(connector);
/* Set up the DDC bus. */
switch (output_reg) {
case DP_A:
name = "DPDDC-A";
break;
case DP_B:
case PCH_DP_B:
dev_priv->hotplug_supported_mask |=
HDMIB_HOTPLUG_INT_STATUS;
name = "DPDDC-B";
break;
case DP_C:
case PCH_DP_C:
dev_priv->hotplug_supported_mask |=
HDMIC_HOTPLUG_INT_STATUS;
name = "DPDDC-C";
break;
case DP_D:
case PCH_DP_D:
dev_priv->hotplug_supported_mask |=
HDMID_HOTPLUG_INT_STATUS;
name = "DPDDC-D";
break;
}
intel_dp_i2c_init(intel_encoder, intel_connector, name);
intel_encoder->ddc_bus = &dp_priv->adapter;
intel_encoder->hot_plug = intel_dp_hot_plug;
if (output_reg == DP_A) {
/* initialize panel mode from VBT if available for eDP */
if (dev_priv->lfp_lvds_vbt_mode) {
dev_priv->panel_fixed_mode =
drm_mode_duplicate(dev, dev_priv->lfp_lvds_vbt_mode);
if (dev_priv->panel_fixed_mode) {
dev_priv->panel_fixed_mode->type |=
DRM_MODE_TYPE_PREFERRED;
}
}
}
/* For G4X desktop chip, PEG_BAND_GAP_DATA 3:0 must first be written
* 0xd. Failure to do so will result in spurious interrupts being
* generated on the port when a cable is not attached.
*/
if (IS_G4X(dev) && !IS_GM45(dev)) {
u32 temp = I915_READ(PEG_BAND_GAP_DATA);
I915_WRITE(PEG_BAND_GAP_DATA, (temp & ~0xf) | 0xd);
}
}
| gpl-2.0 |
TDR/Epic4GTouch-Kernel | arch/powerpc/kernel/pci-common.c | 726 | 50287 | /*
* Contains common pci routines for ALL ppc platform
* (based on pci_32.c and pci_64.c)
*
* Port for PPC64 David Engebretsen, IBM Corp.
* Contains common pci routines for ppc64 platform, pSeries and iSeries brands.
*
* Copyright (C) 2003 Anton Blanchard <anton@au.ibm.com>, IBM
* Rework, based on alpha PCI code.
*
* Common pmac/prep/chrp pci routines. -- Cort
*
* 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/pci.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <linux/syscalls.h>
#include <linux/irq.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include <asm/byteorder.h>
#include <asm/machdep.h>
#include <asm/ppc-pci.h>
#include <asm/firmware.h>
#include <asm/eeh.h>
static DEFINE_SPINLOCK(hose_spinlock);
LIST_HEAD(hose_list);
/* XXX kill that some day ... */
static int global_phb_number; /* Global phb counter */
/* ISA Memory physical address */
resource_size_t isa_mem_base;
/* Default PCI flags is 0 on ppc32, modified at boot on ppc64 */
unsigned int ppc_pci_flags = 0;
static struct dma_map_ops *pci_dma_ops = &dma_direct_ops;
void set_pci_dma_ops(struct dma_map_ops *dma_ops)
{
pci_dma_ops = dma_ops;
}
struct dma_map_ops *get_pci_dma_ops(void)
{
return pci_dma_ops;
}
EXPORT_SYMBOL(get_pci_dma_ops);
struct pci_controller *pcibios_alloc_controller(struct device_node *dev)
{
struct pci_controller *phb;
phb = zalloc_maybe_bootmem(sizeof(struct pci_controller), GFP_KERNEL);
if (phb == NULL)
return NULL;
spin_lock(&hose_spinlock);
phb->global_number = global_phb_number++;
list_add_tail(&phb->list_node, &hose_list);
spin_unlock(&hose_spinlock);
phb->dn = dev;
phb->is_dynamic = mem_init_done;
#ifdef CONFIG_PPC64
if (dev) {
int nid = of_node_to_nid(dev);
if (nid < 0 || !node_online(nid))
nid = -1;
PHB_SET_NODE(phb, nid);
}
#endif
return phb;
}
void pcibios_free_controller(struct pci_controller *phb)
{
spin_lock(&hose_spinlock);
list_del(&phb->list_node);
spin_unlock(&hose_spinlock);
if (phb->is_dynamic)
kfree(phb);
}
static resource_size_t pcibios_io_size(const struct pci_controller *hose)
{
#ifdef CONFIG_PPC64
return hose->pci_io_size;
#else
return hose->io_resource.end - hose->io_resource.start + 1;
#endif
}
int pcibios_vaddr_is_ioport(void __iomem *address)
{
int ret = 0;
struct pci_controller *hose;
resource_size_t size;
spin_lock(&hose_spinlock);
list_for_each_entry(hose, &hose_list, list_node) {
size = pcibios_io_size(hose);
if (address >= hose->io_base_virt &&
address < (hose->io_base_virt + size)) {
ret = 1;
break;
}
}
spin_unlock(&hose_spinlock);
return ret;
}
unsigned long pci_address_to_pio(phys_addr_t address)
{
struct pci_controller *hose;
resource_size_t size;
unsigned long ret = ~0;
spin_lock(&hose_spinlock);
list_for_each_entry(hose, &hose_list, list_node) {
size = pcibios_io_size(hose);
if (address >= hose->io_base_phys &&
address < (hose->io_base_phys + size)) {
unsigned long base =
(unsigned long)hose->io_base_virt - _IO_BASE;
ret = base + (address - hose->io_base_phys);
break;
}
}
spin_unlock(&hose_spinlock);
return ret;
}
EXPORT_SYMBOL_GPL(pci_address_to_pio);
/*
* Return the domain number for this bus.
*/
int pci_domain_nr(struct pci_bus *bus)
{
struct pci_controller *hose = pci_bus_to_host(bus);
return hose->global_number;
}
EXPORT_SYMBOL(pci_domain_nr);
/* This routine is meant to be used early during boot, when the
* PCI bus numbers have not yet been assigned, and you need to
* issue PCI config cycles to an OF device.
* It could also be used to "fix" RTAS config cycles if you want
* to set pci_assign_all_buses to 1 and still use RTAS for PCI
* config cycles.
*/
struct pci_controller* pci_find_hose_for_OF_device(struct device_node* node)
{
while(node) {
struct pci_controller *hose, *tmp;
list_for_each_entry_safe(hose, tmp, &hose_list, list_node)
if (hose->dn == node)
return hose;
node = node->parent;
}
return NULL;
}
static ssize_t pci_show_devspec(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pci_dev *pdev;
struct device_node *np;
pdev = to_pci_dev (dev);
np = pci_device_to_OF_node(pdev);
if (np == NULL || np->full_name == NULL)
return 0;
return sprintf(buf, "%s", np->full_name);
}
static DEVICE_ATTR(devspec, S_IRUGO, pci_show_devspec, NULL);
/* Add sysfs properties */
int pcibios_add_platform_entries(struct pci_dev *pdev)
{
return device_create_file(&pdev->dev, &dev_attr_devspec);
}
char __devinit *pcibios_setup(char *str)
{
return str;
}
/*
* Reads the interrupt pin to determine if interrupt is use by card.
* If the interrupt is used, then gets the interrupt line from the
* openfirmware and sets it in the pci_dev and pci_config line.
*/
int pci_read_irq_line(struct pci_dev *pci_dev)
{
struct of_irq oirq;
unsigned int virq;
/* The current device-tree that iSeries generates from the HV
* PCI informations doesn't contain proper interrupt routing,
* and all the fallback would do is print out crap, so we
* don't attempt to resolve the interrupts here at all, some
* iSeries specific fixup does it.
*
* In the long run, we will hopefully fix the generated device-tree
* instead.
*/
#ifdef CONFIG_PPC_ISERIES
if (firmware_has_feature(FW_FEATURE_ISERIES))
return -1;
#endif
pr_debug("PCI: Try to map irq for %s...\n", pci_name(pci_dev));
#ifdef DEBUG
memset(&oirq, 0xff, sizeof(oirq));
#endif
/* Try to get a mapping from the device-tree */
if (of_irq_map_pci(pci_dev, &oirq)) {
u8 line, pin;
/* If that fails, lets fallback to what is in the config
* space and map that through the default controller. We
* also set the type to level low since that's what PCI
* interrupts are. If your platform does differently, then
* either provide a proper interrupt tree or don't use this
* function.
*/
if (pci_read_config_byte(pci_dev, PCI_INTERRUPT_PIN, &pin))
return -1;
if (pin == 0)
return -1;
if (pci_read_config_byte(pci_dev, PCI_INTERRUPT_LINE, &line) ||
line == 0xff || line == 0) {
return -1;
}
pr_debug(" No map ! Using line %d (pin %d) from PCI config\n",
line, pin);
virq = irq_create_mapping(NULL, line);
if (virq != NO_IRQ)
set_irq_type(virq, IRQ_TYPE_LEVEL_LOW);
} else {
pr_debug(" Got one, spec %d cells (0x%08x 0x%08x...) on %s\n",
oirq.size, oirq.specifier[0], oirq.specifier[1],
oirq.controller ? oirq.controller->full_name :
"<default>");
virq = irq_create_of_mapping(oirq.controller, oirq.specifier,
oirq.size);
}
if(virq == NO_IRQ) {
pr_debug(" Failed to map !\n");
return -1;
}
pr_debug(" Mapped to linux irq %d\n", virq);
pci_dev->irq = virq;
return 0;
}
EXPORT_SYMBOL(pci_read_irq_line);
/*
* Platform support for /proc/bus/pci/X/Y mmap()s,
* modelled on the sparc64 implementation by Dave Miller.
* -- paulus.
*/
/*
* Adjust vm_pgoff of VMA such that it is the physical page offset
* corresponding to the 32-bit pci bus offset for DEV requested by the user.
*
* Basically, the user finds the base address for his device which he wishes
* to mmap. They read the 32-bit value from the config space base register,
* add whatever PAGE_SIZE multiple offset they wish, and feed this into the
* offset parameter of mmap on /proc/bus/pci/XXX for that device.
*
* Returns negative error code on failure, zero on success.
*/
static struct resource *__pci_mmap_make_offset(struct pci_dev *dev,
resource_size_t *offset,
enum pci_mmap_state mmap_state)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
unsigned long io_offset = 0;
int i, res_bit;
if (hose == 0)
return NULL; /* should never happen */
/* If memory, add on the PCI bridge address offset */
if (mmap_state == pci_mmap_mem) {
#if 0 /* See comment in pci_resource_to_user() for why this is disabled */
*offset += hose->pci_mem_offset;
#endif
res_bit = IORESOURCE_MEM;
} else {
io_offset = (unsigned long)hose->io_base_virt - _IO_BASE;
*offset += io_offset;
res_bit = IORESOURCE_IO;
}
/*
* Check that the offset requested corresponds to one of the
* resources of the device.
*/
for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
struct resource *rp = &dev->resource[i];
int flags = rp->flags;
/* treat ROM as memory (should be already) */
if (i == PCI_ROM_RESOURCE)
flags |= IORESOURCE_MEM;
/* Active and same type? */
if ((flags & res_bit) == 0)
continue;
/* In the range of this resource? */
if (*offset < (rp->start & PAGE_MASK) || *offset > rp->end)
continue;
/* found it! construct the final physical address */
if (mmap_state == pci_mmap_io)
*offset += hose->io_base_phys - io_offset;
return rp;
}
return NULL;
}
/*
* Set vm_page_prot of VMA, as appropriate for this architecture, for a pci
* device mapping.
*/
static pgprot_t __pci_mmap_set_pgprot(struct pci_dev *dev, struct resource *rp,
pgprot_t protection,
enum pci_mmap_state mmap_state,
int write_combine)
{
unsigned long prot = pgprot_val(protection);
/* Write combine is always 0 on non-memory space mappings. On
* memory space, if the user didn't pass 1, we check for a
* "prefetchable" resource. This is a bit hackish, but we use
* this to workaround the inability of /sysfs to provide a write
* combine bit
*/
if (mmap_state != pci_mmap_mem)
write_combine = 0;
else if (write_combine == 0) {
if (rp->flags & IORESOURCE_PREFETCH)
write_combine = 1;
}
/* XXX would be nice to have a way to ask for write-through */
if (write_combine)
return pgprot_noncached_wc(prot);
else
return pgprot_noncached(prot);
}
/*
* This one is used by /dev/mem and fbdev who have no clue about the
* PCI device, it tries to find the PCI device first and calls the
* above routine
*/
pgprot_t pci_phys_mem_access_prot(struct file *file,
unsigned long pfn,
unsigned long size,
pgprot_t prot)
{
struct pci_dev *pdev = NULL;
struct resource *found = NULL;
resource_size_t offset = ((resource_size_t)pfn) << PAGE_SHIFT;
int i;
if (page_is_ram(pfn))
return prot;
prot = pgprot_noncached(prot);
for_each_pci_dev(pdev) {
for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
struct resource *rp = &pdev->resource[i];
int flags = rp->flags;
/* Active and same type? */
if ((flags & IORESOURCE_MEM) == 0)
continue;
/* In the range of this resource? */
if (offset < (rp->start & PAGE_MASK) ||
offset > rp->end)
continue;
found = rp;
break;
}
if (found)
break;
}
if (found) {
if (found->flags & IORESOURCE_PREFETCH)
prot = pgprot_noncached_wc(prot);
pci_dev_put(pdev);
}
pr_debug("PCI: Non-PCI map for %llx, prot: %lx\n",
(unsigned long long)offset, pgprot_val(prot));
return prot;
}
/*
* Perform the actual remap of the pages for a PCI device mapping, as
* appropriate for this architecture. The region in the process to map
* is described by vm_start and vm_end members of VMA, the base physical
* address is found in vm_pgoff.
* The pci device structure is provided so that architectures may make mapping
* decisions on a per-device or per-bus basis.
*
* Returns a negative error code on failure, zero on success.
*/
int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
enum pci_mmap_state mmap_state, int write_combine)
{
resource_size_t offset =
((resource_size_t)vma->vm_pgoff) << PAGE_SHIFT;
struct resource *rp;
int ret;
rp = __pci_mmap_make_offset(dev, &offset, mmap_state);
if (rp == NULL)
return -EINVAL;
vma->vm_pgoff = offset >> PAGE_SHIFT;
vma->vm_page_prot = __pci_mmap_set_pgprot(dev, rp,
vma->vm_page_prot,
mmap_state, write_combine);
ret = remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start, vma->vm_page_prot);
return ret;
}
/* This provides legacy IO read access on a bus */
int pci_legacy_read(struct pci_bus *bus, loff_t port, u32 *val, size_t size)
{
unsigned long offset;
struct pci_controller *hose = pci_bus_to_host(bus);
struct resource *rp = &hose->io_resource;
void __iomem *addr;
/* Check if port can be supported by that bus. We only check
* the ranges of the PHB though, not the bus itself as the rules
* for forwarding legacy cycles down bridges are not our problem
* here. So if the host bridge supports it, we do it.
*/
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
offset += port;
if (!(rp->flags & IORESOURCE_IO))
return -ENXIO;
if (offset < rp->start || (offset + size) > rp->end)
return -ENXIO;
addr = hose->io_base_virt + port;
switch(size) {
case 1:
*((u8 *)val) = in_8(addr);
return 1;
case 2:
if (port & 1)
return -EINVAL;
*((u16 *)val) = in_le16(addr);
return 2;
case 4:
if (port & 3)
return -EINVAL;
*((u32 *)val) = in_le32(addr);
return 4;
}
return -EINVAL;
}
/* This provides legacy IO write access on a bus */
int pci_legacy_write(struct pci_bus *bus, loff_t port, u32 val, size_t size)
{
unsigned long offset;
struct pci_controller *hose = pci_bus_to_host(bus);
struct resource *rp = &hose->io_resource;
void __iomem *addr;
/* Check if port can be supported by that bus. We only check
* the ranges of the PHB though, not the bus itself as the rules
* for forwarding legacy cycles down bridges are not our problem
* here. So if the host bridge supports it, we do it.
*/
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
offset += port;
if (!(rp->flags & IORESOURCE_IO))
return -ENXIO;
if (offset < rp->start || (offset + size) > rp->end)
return -ENXIO;
addr = hose->io_base_virt + port;
/* WARNING: The generic code is idiotic. It gets passed a pointer
* to what can be a 1, 2 or 4 byte quantity and always reads that
* as a u32, which means that we have to correct the location of
* the data read within those 32 bits for size 1 and 2
*/
switch(size) {
case 1:
out_8(addr, val >> 24);
return 1;
case 2:
if (port & 1)
return -EINVAL;
out_le16(addr, val >> 16);
return 2;
case 4:
if (port & 3)
return -EINVAL;
out_le32(addr, val);
return 4;
}
return -EINVAL;
}
/* This provides legacy IO or memory mmap access on a bus */
int pci_mmap_legacy_page_range(struct pci_bus *bus,
struct vm_area_struct *vma,
enum pci_mmap_state mmap_state)
{
struct pci_controller *hose = pci_bus_to_host(bus);
resource_size_t offset =
((resource_size_t)vma->vm_pgoff) << PAGE_SHIFT;
resource_size_t size = vma->vm_end - vma->vm_start;
struct resource *rp;
pr_debug("pci_mmap_legacy_page_range(%04x:%02x, %s @%llx..%llx)\n",
pci_domain_nr(bus), bus->number,
mmap_state == pci_mmap_mem ? "MEM" : "IO",
(unsigned long long)offset,
(unsigned long long)(offset + size - 1));
if (mmap_state == pci_mmap_mem) {
/* Hack alert !
*
* Because X is lame and can fail starting if it gets an error trying
* to mmap legacy_mem (instead of just moving on without legacy memory
* access) we fake it here by giving it anonymous memory, effectively
* behaving just like /dev/zero
*/
if ((offset + size) > hose->isa_mem_size) {
printk(KERN_DEBUG
"Process %s (pid:%d) mapped non-existing PCI legacy memory for 0%04x:%02x\n",
current->comm, current->pid, pci_domain_nr(bus), bus->number);
if (vma->vm_flags & VM_SHARED)
return shmem_zero_setup(vma);
return 0;
}
offset += hose->isa_mem_phys;
} else {
unsigned long io_offset = (unsigned long)hose->io_base_virt - _IO_BASE;
unsigned long roffset = offset + io_offset;
rp = &hose->io_resource;
if (!(rp->flags & IORESOURCE_IO))
return -ENXIO;
if (roffset < rp->start || (roffset + size) > rp->end)
return -ENXIO;
offset += hose->io_base_phys;
}
pr_debug(" -> mapping phys %llx\n", (unsigned long long)offset);
vma->vm_pgoff = offset >> PAGE_SHIFT;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
void pci_resource_to_user(const struct pci_dev *dev, int bar,
const struct resource *rsrc,
resource_size_t *start, resource_size_t *end)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
resource_size_t offset = 0;
if (hose == NULL)
return;
if (rsrc->flags & IORESOURCE_IO)
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
/* We pass a fully fixed up address to userland for MMIO instead of
* a BAR value because X is lame and expects to be able to use that
* to pass to /dev/mem !
*
* That means that we'll have potentially 64 bits values where some
* userland apps only expect 32 (like X itself since it thinks only
* Sparc has 64 bits MMIO) but if we don't do that, we break it on
* 32 bits CHRPs :-(
*
* Hopefully, the sysfs insterface is immune to that gunk. Once X
* has been fixed (and the fix spread enough), we can re-enable the
* 2 lines below and pass down a BAR value to userland. In that case
* we'll also have to re-enable the matching code in
* __pci_mmap_make_offset().
*
* BenH.
*/
#if 0
else if (rsrc->flags & IORESOURCE_MEM)
offset = hose->pci_mem_offset;
#endif
*start = rsrc->start - offset;
*end = rsrc->end - offset;
}
/**
* pci_process_bridge_OF_ranges - Parse PCI bridge resources from device tree
* @hose: newly allocated pci_controller to be setup
* @dev: device node of the host bridge
* @primary: set if primary bus (32 bits only, soon to be deprecated)
*
* This function will parse the "ranges" property of a PCI host bridge device
* node and setup the resource mapping of a pci controller based on its
* content.
*
* Life would be boring if it wasn't for a few issues that we have to deal
* with here:
*
* - We can only cope with one IO space range and up to 3 Memory space
* ranges. However, some machines (thanks Apple !) tend to split their
* space into lots of small contiguous ranges. So we have to coalesce.
*
* - We can only cope with all memory ranges having the same offset
* between CPU addresses and PCI addresses. Unfortunately, some bridges
* are setup for a large 1:1 mapping along with a small "window" which
* maps PCI address 0 to some arbitrary high address of the CPU space in
* order to give access to the ISA memory hole.
* The way out of here that I've chosen for now is to always set the
* offset based on the first resource found, then override it if we
* have a different offset and the previous was set by an ISA hole.
*
* - Some busses have IO space not starting at 0, which causes trouble with
* the way we do our IO resource renumbering. The code somewhat deals with
* it for 64 bits but I would expect problems on 32 bits.
*
* - Some 32 bits platforms such as 4xx can have physical space larger than
* 32 bits so we need to use 64 bits values for the parsing
*/
void __devinit pci_process_bridge_OF_ranges(struct pci_controller *hose,
struct device_node *dev,
int primary)
{
const u32 *ranges;
int rlen;
int pna = of_n_addr_cells(dev);
int np = pna + 5;
int memno = 0, isa_hole = -1;
u32 pci_space;
unsigned long long pci_addr, cpu_addr, pci_next, cpu_next, size;
unsigned long long isa_mb = 0;
struct resource *res;
printk(KERN_INFO "PCI host bridge %s %s ranges:\n",
dev->full_name, primary ? "(primary)" : "");
/* Get ranges property */
ranges = of_get_property(dev, "ranges", &rlen);
if (ranges == NULL)
return;
/* Parse it */
while ((rlen -= np * 4) >= 0) {
/* Read next ranges element */
pci_space = ranges[0];
pci_addr = of_read_number(ranges + 1, 2);
cpu_addr = of_translate_address(dev, ranges + 3);
size = of_read_number(ranges + pna + 3, 2);
ranges += np;
/* If we failed translation or got a zero-sized region
* (some FW try to feed us with non sensical zero sized regions
* such as power3 which look like some kind of attempt at exposing
* the VGA memory hole)
*/
if (cpu_addr == OF_BAD_ADDR || size == 0)
continue;
/* Now consume following elements while they are contiguous */
for (; rlen >= np * sizeof(u32);
ranges += np, rlen -= np * 4) {
if (ranges[0] != pci_space)
break;
pci_next = of_read_number(ranges + 1, 2);
cpu_next = of_translate_address(dev, ranges + 3);
if (pci_next != pci_addr + size ||
cpu_next != cpu_addr + size)
break;
size += of_read_number(ranges + pna + 3, 2);
}
/* Act based on address space type */
res = NULL;
switch ((pci_space >> 24) & 0x3) {
case 1: /* PCI IO space */
printk(KERN_INFO
" IO 0x%016llx..0x%016llx -> 0x%016llx\n",
cpu_addr, cpu_addr + size - 1, pci_addr);
/* We support only one IO range */
if (hose->pci_io_size) {
printk(KERN_INFO
" \\--> Skipped (too many) !\n");
continue;
}
#ifdef CONFIG_PPC32
/* On 32 bits, limit I/O space to 16MB */
if (size > 0x01000000)
size = 0x01000000;
/* 32 bits needs to map IOs here */
hose->io_base_virt = ioremap(cpu_addr, size);
/* Expect trouble if pci_addr is not 0 */
if (primary)
isa_io_base =
(unsigned long)hose->io_base_virt;
#endif /* CONFIG_PPC32 */
/* pci_io_size and io_base_phys always represent IO
* space starting at 0 so we factor in pci_addr
*/
hose->pci_io_size = pci_addr + size;
hose->io_base_phys = cpu_addr - pci_addr;
/* Build resource */
res = &hose->io_resource;
res->flags = IORESOURCE_IO;
res->start = pci_addr;
break;
case 2: /* PCI Memory space */
case 3: /* PCI 64 bits Memory space */
printk(KERN_INFO
" MEM 0x%016llx..0x%016llx -> 0x%016llx %s\n",
cpu_addr, cpu_addr + size - 1, pci_addr,
(pci_space & 0x40000000) ? "Prefetch" : "");
/* We support only 3 memory ranges */
if (memno >= 3) {
printk(KERN_INFO
" \\--> Skipped (too many) !\n");
continue;
}
/* Handles ISA memory hole space here */
if (pci_addr == 0) {
isa_mb = cpu_addr;
isa_hole = memno;
if (primary || isa_mem_base == 0)
isa_mem_base = cpu_addr;
hose->isa_mem_phys = cpu_addr;
hose->isa_mem_size = size;
}
/* We get the PCI/Mem offset from the first range or
* the, current one if the offset came from an ISA
* hole. If they don't match, bugger.
*/
if (memno == 0 ||
(isa_hole >= 0 && pci_addr != 0 &&
hose->pci_mem_offset == isa_mb))
hose->pci_mem_offset = cpu_addr - pci_addr;
else if (pci_addr != 0 &&
hose->pci_mem_offset != cpu_addr - pci_addr) {
printk(KERN_INFO
" \\--> Skipped (offset mismatch) !\n");
continue;
}
/* Build resource */
res = &hose->mem_resources[memno++];
res->flags = IORESOURCE_MEM;
if (pci_space & 0x40000000)
res->flags |= IORESOURCE_PREFETCH;
res->start = cpu_addr;
break;
}
if (res != NULL) {
res->name = dev->full_name;
res->end = res->start + size - 1;
res->parent = NULL;
res->sibling = NULL;
res->child = NULL;
}
}
/* If there's an ISA hole and the pci_mem_offset is -not- matching
* the ISA hole offset, then we need to remove the ISA hole from
* the resource list for that brige
*/
if (isa_hole >= 0 && hose->pci_mem_offset != isa_mb) {
unsigned int next = isa_hole + 1;
printk(KERN_INFO " Removing ISA hole at 0x%016llx\n", isa_mb);
if (next < memno)
memmove(&hose->mem_resources[isa_hole],
&hose->mem_resources[next],
sizeof(struct resource) * (memno - next));
hose->mem_resources[--memno].flags = 0;
}
}
/* Decide whether to display the domain number in /proc */
int pci_proc_domain(struct pci_bus *bus)
{
struct pci_controller *hose = pci_bus_to_host(bus);
if (!(ppc_pci_flags & PPC_PCI_ENABLE_PROC_DOMAINS))
return 0;
if (ppc_pci_flags & PPC_PCI_COMPAT_DOMAIN_0)
return hose->global_number != 0;
return 1;
}
void pcibios_resource_to_bus(struct pci_dev *dev, struct pci_bus_region *region,
struct resource *res)
{
resource_size_t offset = 0, mask = (resource_size_t)-1;
struct pci_controller *hose = pci_bus_to_host(dev->bus);
if (!hose)
return;
if (res->flags & IORESOURCE_IO) {
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
mask = 0xffffffffu;
} else if (res->flags & IORESOURCE_MEM)
offset = hose->pci_mem_offset;
region->start = (res->start - offset) & mask;
region->end = (res->end - offset) & mask;
}
EXPORT_SYMBOL(pcibios_resource_to_bus);
void pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
struct pci_bus_region *region)
{
resource_size_t offset = 0, mask = (resource_size_t)-1;
struct pci_controller *hose = pci_bus_to_host(dev->bus);
if (!hose)
return;
if (res->flags & IORESOURCE_IO) {
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
mask = 0xffffffffu;
} else if (res->flags & IORESOURCE_MEM)
offset = hose->pci_mem_offset;
res->start = (region->start + offset) & mask;
res->end = (region->end + offset) & mask;
}
EXPORT_SYMBOL(pcibios_bus_to_resource);
/* Fixup a bus resource into a linux resource */
static void __devinit fixup_resource(struct resource *res, struct pci_dev *dev)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
resource_size_t offset = 0, mask = (resource_size_t)-1;
if (res->flags & IORESOURCE_IO) {
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
mask = 0xffffffffu;
} else if (res->flags & IORESOURCE_MEM)
offset = hose->pci_mem_offset;
res->start = (res->start + offset) & mask;
res->end = (res->end + offset) & mask;
}
/* This header fixup will do the resource fixup for all devices as they are
* probed, but not for bridge ranges
*/
static void __devinit pcibios_fixup_resources(struct pci_dev *dev)
{
struct pci_controller *hose = pci_bus_to_host(dev->bus);
int i;
if (!hose) {
printk(KERN_ERR "No host bridge for PCI dev %s !\n",
pci_name(dev));
return;
}
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
struct resource *res = dev->resource + i;
if (!res->flags)
continue;
/* On platforms that have PPC_PCI_PROBE_ONLY set, we don't
* consider 0 as an unassigned BAR value. It's technically
* a valid value, but linux doesn't like it... so when we can
* re-assign things, we do so, but if we can't, we keep it
* around and hope for the best...
*/
if (res->start == 0 && !(ppc_pci_flags & PPC_PCI_PROBE_ONLY)) {
pr_debug("PCI:%s Resource %d %016llx-%016llx [%x] is unassigned\n",
pci_name(dev), i,
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned int)res->flags);
res->end -= res->start;
res->start = 0;
res->flags |= IORESOURCE_UNSET;
continue;
}
pr_debug("PCI:%s Resource %d %016llx-%016llx [%x] fixup...\n",
pci_name(dev), i,
(unsigned long long)res->start,\
(unsigned long long)res->end,
(unsigned int)res->flags);
fixup_resource(res, dev);
pr_debug("PCI:%s %016llx-%016llx\n",
pci_name(dev),
(unsigned long long)res->start,
(unsigned long long)res->end);
}
/* Call machine specific resource fixup */
if (ppc_md.pcibios_fixup_resources)
ppc_md.pcibios_fixup_resources(dev);
}
DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, pcibios_fixup_resources);
/* This function tries to figure out if a bridge resource has been initialized
* by the firmware or not. It doesn't have to be absolutely bullet proof, but
* things go more smoothly when it gets it right. It should covers cases such
* as Apple "closed" bridge resources and bare-metal pSeries unassigned bridges
*/
static int __devinit pcibios_uninitialized_bridge_resource(struct pci_bus *bus,
struct resource *res)
{
struct pci_controller *hose = pci_bus_to_host(bus);
struct pci_dev *dev = bus->self;
resource_size_t offset;
u16 command;
int i;
/* We don't do anything if PCI_PROBE_ONLY is set */
if (ppc_pci_flags & PPC_PCI_PROBE_ONLY)
return 0;
/* Job is a bit different between memory and IO */
if (res->flags & IORESOURCE_MEM) {
/* If the BAR is non-0 (res != pci_mem_offset) then it's probably been
* initialized by somebody
*/
if (res->start != hose->pci_mem_offset)
return 0;
/* The BAR is 0, let's check if memory decoding is enabled on
* the bridge. If not, we consider it unassigned
*/
pci_read_config_word(dev, PCI_COMMAND, &command);
if ((command & PCI_COMMAND_MEMORY) == 0)
return 1;
/* Memory decoding is enabled and the BAR is 0. If any of the bridge
* resources covers that starting address (0 then it's good enough for
* us for memory
*/
for (i = 0; i < 3; i++) {
if ((hose->mem_resources[i].flags & IORESOURCE_MEM) &&
hose->mem_resources[i].start == hose->pci_mem_offset)
return 0;
}
/* Well, it starts at 0 and we know it will collide so we may as
* well consider it as unassigned. That covers the Apple case.
*/
return 1;
} else {
/* If the BAR is non-0, then we consider it assigned */
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
if (((res->start - offset) & 0xfffffffful) != 0)
return 0;
/* Here, we are a bit different than memory as typically IO space
* starting at low addresses -is- valid. What we do instead if that
* we consider as unassigned anything that doesn't have IO enabled
* in the PCI command register, and that's it.
*/
pci_read_config_word(dev, PCI_COMMAND, &command);
if (command & PCI_COMMAND_IO)
return 0;
/* It's starting at 0 and IO is disabled in the bridge, consider
* it unassigned
*/
return 1;
}
}
/* Fixup resources of a PCI<->PCI bridge */
static void __devinit pcibios_fixup_bridge(struct pci_bus *bus)
{
struct resource *res;
int i;
struct pci_dev *dev = bus->self;
pci_bus_for_each_resource(bus, res, i) {
if (!res || !res->flags)
continue;
if (i >= 3 && bus->self->transparent)
continue;
pr_debug("PCI:%s Bus rsrc %d %016llx-%016llx [%x] fixup...\n",
pci_name(dev), i,
(unsigned long long)res->start,\
(unsigned long long)res->end,
(unsigned int)res->flags);
/* Perform fixup */
fixup_resource(res, dev);
/* Try to detect uninitialized P2P bridge resources,
* and clear them out so they get re-assigned later
*/
if (pcibios_uninitialized_bridge_resource(bus, res)) {
res->flags = 0;
pr_debug("PCI:%s (unassigned)\n", pci_name(dev));
} else {
pr_debug("PCI:%s %016llx-%016llx\n",
pci_name(dev),
(unsigned long long)res->start,
(unsigned long long)res->end);
}
}
}
void __devinit pcibios_setup_bus_self(struct pci_bus *bus)
{
/* Fix up the bus resources for P2P bridges */
if (bus->self != NULL)
pcibios_fixup_bridge(bus);
/* Platform specific bus fixups. This is currently only used
* by fsl_pci and I'm hoping to get rid of it at some point
*/
if (ppc_md.pcibios_fixup_bus)
ppc_md.pcibios_fixup_bus(bus);
/* Setup bus DMA mappings */
if (ppc_md.pci_dma_bus_setup)
ppc_md.pci_dma_bus_setup(bus);
}
void __devinit pcibios_setup_bus_devices(struct pci_bus *bus)
{
struct pci_dev *dev;
pr_debug("PCI: Fixup bus devices %d (%s)\n",
bus->number, bus->self ? pci_name(bus->self) : "PHB");
list_for_each_entry(dev, &bus->devices, bus_list) {
struct dev_archdata *sd = &dev->dev.archdata;
/* Cardbus can call us to add new devices to a bus, so ignore
* those who are already fully discovered
*/
if (dev->is_added)
continue;
/* Setup OF node pointer in the device */
dev->dev.of_node = pci_device_to_OF_node(dev);
/* Fixup NUMA node as it may not be setup yet by the generic
* code and is needed by the DMA init
*/
set_dev_node(&dev->dev, pcibus_to_node(dev->bus));
/* Hook up default DMA ops */
sd->dma_ops = pci_dma_ops;
set_dma_offset(&dev->dev, PCI_DRAM_OFFSET);
/* Additional platform DMA/iommu setup */
if (ppc_md.pci_dma_dev_setup)
ppc_md.pci_dma_dev_setup(dev);
/* Read default IRQs and fixup if necessary */
pci_read_irq_line(dev);
if (ppc_md.pci_irq_fixup)
ppc_md.pci_irq_fixup(dev);
}
}
void __devinit pcibios_fixup_bus(struct pci_bus *bus)
{
/* When called from the generic PCI probe, read PCI<->PCI bridge
* bases. This is -not- called when generating the PCI tree from
* the OF device-tree.
*/
if (bus->self != NULL)
pci_read_bridge_bases(bus);
/* Now fixup the bus bus */
pcibios_setup_bus_self(bus);
/* Now fixup devices on that bus */
pcibios_setup_bus_devices(bus);
}
EXPORT_SYMBOL(pcibios_fixup_bus);
void __devinit pci_fixup_cardbus(struct pci_bus *bus)
{
/* Now fixup devices on that bus */
pcibios_setup_bus_devices(bus);
}
static int skip_isa_ioresource_align(struct pci_dev *dev)
{
if ((ppc_pci_flags & PPC_PCI_CAN_SKIP_ISA_ALIGN) &&
!(dev->bus->bridge_ctl & PCI_BRIDGE_CTL_ISA))
return 1;
return 0;
}
/*
* We need to avoid collisions with `mirrored' VGA ports
* and other strange ISA hardware, so we always want the
* addresses to be allocated in the 0x000-0x0ff region
* modulo 0x400.
*
* Why? Because some silly external IO cards only decode
* the low 10 bits of the IO address. The 0x00-0xff region
* is reserved for motherboard devices that decode all 16
* bits, so it's ok to allocate at, say, 0x2800-0x28ff,
* but we want to try to avoid allocating at 0x2900-0x2bff
* which might have be mirrored at 0x0100-0x03ff..
*/
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
struct pci_dev *dev = data;
resource_size_t start = res->start;
if (res->flags & IORESOURCE_IO) {
if (skip_isa_ioresource_align(dev))
return start;
if (start & 0x300)
start = (start + 0x3ff) & ~0x3ff;
}
return start;
}
EXPORT_SYMBOL(pcibios_align_resource);
/*
* Reparent resource children of pr that conflict with res
* under res, and make res replace those children.
*/
static int reparent_resources(struct resource *parent,
struct resource *res)
{
struct resource *p, **pp;
struct resource **firstpp = NULL;
for (pp = &parent->child; (p = *pp) != NULL; pp = &p->sibling) {
if (p->end < res->start)
continue;
if (res->end < p->start)
break;
if (p->start < res->start || p->end > res->end)
return -1; /* not completely contained */
if (firstpp == NULL)
firstpp = pp;
}
if (firstpp == NULL)
return -1; /* didn't find any conflicting entries? */
res->parent = parent;
res->child = *firstpp;
res->sibling = *pp;
*firstpp = res;
*pp = NULL;
for (p = res->child; p != NULL; p = p->sibling) {
p->parent = res;
pr_debug("PCI: Reparented %s [%llx..%llx] under %s\n",
p->name,
(unsigned long long)p->start,
(unsigned long long)p->end, res->name);
}
return 0;
}
/*
* Handle resources of PCI devices. If the world were perfect, we could
* just allocate all the resource regions and do nothing more. It isn't.
* On the other hand, we cannot just re-allocate all devices, as it would
* require us to know lots of host bridge internals. So we attempt to
* keep as much of the original configuration as possible, but tweak it
* when it's found to be wrong.
*
* Known BIOS problems we have to work around:
* - I/O or memory regions not configured
* - regions configured, but not enabled in the command register
* - bogus I/O addresses above 64K used
* - expansion ROMs left enabled (this may sound harmless, but given
* the fact the PCI specs explicitly allow address decoders to be
* shared between expansion ROMs and other resource regions, it's
* at least dangerous)
*
* Our solution:
* (1) Allocate resources for all buses behind PCI-to-PCI bridges.
* This gives us fixed barriers on where we can allocate.
* (2) Allocate resources for all enabled devices. If there is
* a collision, just mark the resource as unallocated. Also
* disable expansion ROMs during this step.
* (3) Try to allocate resources for disabled devices. If the
* resources were assigned correctly, everything goes well,
* if they weren't, they won't disturb allocation of other
* resources.
* (4) Assign new addresses to resources which were either
* not configured at all or misconfigured. If explicitly
* requested by the user, configure expansion ROM address
* as well.
*/
void pcibios_allocate_bus_resources(struct pci_bus *bus)
{
struct pci_bus *b;
int i;
struct resource *res, *pr;
pr_debug("PCI: Allocating bus resources for %04x:%02x...\n",
pci_domain_nr(bus), bus->number);
pci_bus_for_each_resource(bus, res, i) {
if (!res || !res->flags || res->start > res->end || res->parent)
continue;
if (bus->parent == NULL)
pr = (res->flags & IORESOURCE_IO) ?
&ioport_resource : &iomem_resource;
else {
/* Don't bother with non-root busses when
* re-assigning all resources. We clear the
* resource flags as if they were colliding
* and as such ensure proper re-allocation
* later.
*/
if (ppc_pci_flags & PPC_PCI_REASSIGN_ALL_RSRC)
goto clear_resource;
pr = pci_find_parent_resource(bus->self, res);
if (pr == res) {
/* this happens when the generic PCI
* code (wrongly) decides that this
* bridge is transparent -- paulus
*/
continue;
}
}
pr_debug("PCI: %s (bus %d) bridge rsrc %d: %016llx-%016llx "
"[0x%x], parent %p (%s)\n",
bus->self ? pci_name(bus->self) : "PHB",
bus->number, i,
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned int)res->flags,
pr, (pr && pr->name) ? pr->name : "nil");
if (pr && !(pr->flags & IORESOURCE_UNSET)) {
if (request_resource(pr, res) == 0)
continue;
/*
* Must be a conflict with an existing entry.
* Move that entry (or entries) under the
* bridge resource and try again.
*/
if (reparent_resources(pr, res) == 0)
continue;
}
printk(KERN_WARNING "PCI: Cannot allocate resource region "
"%d of PCI bridge %d, will remap\n", i, bus->number);
clear_resource:
res->start = res->end = 0;
res->flags = 0;
}
list_for_each_entry(b, &bus->children, node)
pcibios_allocate_bus_resources(b);
}
static inline void __devinit alloc_resource(struct pci_dev *dev, int idx)
{
struct resource *pr, *r = &dev->resource[idx];
pr_debug("PCI: Allocating %s: Resource %d: %016llx..%016llx [%x]\n",
pci_name(dev), idx,
(unsigned long long)r->start,
(unsigned long long)r->end,
(unsigned int)r->flags);
pr = pci_find_parent_resource(dev, r);
if (!pr || (pr->flags & IORESOURCE_UNSET) ||
request_resource(pr, r) < 0) {
printk(KERN_WARNING "PCI: Cannot allocate resource region %d"
" of device %s, will remap\n", idx, pci_name(dev));
if (pr)
pr_debug("PCI: parent is %p: %016llx-%016llx [%x]\n",
pr,
(unsigned long long)pr->start,
(unsigned long long)pr->end,
(unsigned int)pr->flags);
/* We'll assign a new address later */
r->flags |= IORESOURCE_UNSET;
r->end -= r->start;
r->start = 0;
}
}
static void __init pcibios_allocate_resources(int pass)
{
struct pci_dev *dev = NULL;
int idx, disabled;
u16 command;
struct resource *r;
for_each_pci_dev(dev) {
pci_read_config_word(dev, PCI_COMMAND, &command);
for (idx = 0; idx <= PCI_ROM_RESOURCE; idx++) {
r = &dev->resource[idx];
if (r->parent) /* Already allocated */
continue;
if (!r->flags || (r->flags & IORESOURCE_UNSET))
continue; /* Not assigned at all */
/* We only allocate ROMs on pass 1 just in case they
* have been screwed up by firmware
*/
if (idx == PCI_ROM_RESOURCE )
disabled = 1;
if (r->flags & IORESOURCE_IO)
disabled = !(command & PCI_COMMAND_IO);
else
disabled = !(command & PCI_COMMAND_MEMORY);
if (pass == disabled)
alloc_resource(dev, idx);
}
if (pass)
continue;
r = &dev->resource[PCI_ROM_RESOURCE];
if (r->flags) {
/* Turn the ROM off, leave the resource region,
* but keep it unregistered.
*/
u32 reg;
pci_read_config_dword(dev, dev->rom_base_reg, ®);
if (reg & PCI_ROM_ADDRESS_ENABLE) {
pr_debug("PCI: Switching off ROM of %s\n",
pci_name(dev));
r->flags &= ~IORESOURCE_ROM_ENABLE;
pci_write_config_dword(dev, dev->rom_base_reg,
reg & ~PCI_ROM_ADDRESS_ENABLE);
}
}
}
}
static void __init pcibios_reserve_legacy_regions(struct pci_bus *bus)
{
struct pci_controller *hose = pci_bus_to_host(bus);
resource_size_t offset;
struct resource *res, *pres;
int i;
pr_debug("Reserving legacy ranges for domain %04x\n", pci_domain_nr(bus));
/* Check for IO */
if (!(hose->io_resource.flags & IORESOURCE_IO))
goto no_io;
offset = (unsigned long)hose->io_base_virt - _IO_BASE;
res = kzalloc(sizeof(struct resource), GFP_KERNEL);
BUG_ON(res == NULL);
res->name = "Legacy IO";
res->flags = IORESOURCE_IO;
res->start = offset;
res->end = (offset + 0xfff) & 0xfffffffful;
pr_debug("Candidate legacy IO: %pR\n", res);
if (request_resource(&hose->io_resource, res)) {
printk(KERN_DEBUG
"PCI %04x:%02x Cannot reserve Legacy IO %pR\n",
pci_domain_nr(bus), bus->number, res);
kfree(res);
}
no_io:
/* Check for memory */
offset = hose->pci_mem_offset;
pr_debug("hose mem offset: %016llx\n", (unsigned long long)offset);
for (i = 0; i < 3; i++) {
pres = &hose->mem_resources[i];
if (!(pres->flags & IORESOURCE_MEM))
continue;
pr_debug("hose mem res: %pR\n", pres);
if ((pres->start - offset) <= 0xa0000 &&
(pres->end - offset) >= 0xbffff)
break;
}
if (i >= 3)
return;
res = kzalloc(sizeof(struct resource), GFP_KERNEL);
BUG_ON(res == NULL);
res->name = "Legacy VGA memory";
res->flags = IORESOURCE_MEM;
res->start = 0xa0000 + offset;
res->end = 0xbffff + offset;
pr_debug("Candidate VGA memory: %pR\n", res);
if (request_resource(pres, res)) {
printk(KERN_DEBUG
"PCI %04x:%02x Cannot reserve VGA memory %pR\n",
pci_domain_nr(bus), bus->number, res);
kfree(res);
}
}
void __init pcibios_resource_survey(void)
{
struct pci_bus *b;
/* Allocate and assign resources. If we re-assign everything, then
* we skip the allocate phase
*/
list_for_each_entry(b, &pci_root_buses, node)
pcibios_allocate_bus_resources(b);
if (!(ppc_pci_flags & PPC_PCI_REASSIGN_ALL_RSRC)) {
pcibios_allocate_resources(0);
pcibios_allocate_resources(1);
}
/* Before we start assigning unassigned resource, we try to reserve
* the low IO area and the VGA memory area if they intersect the
* bus available resources to avoid allocating things on top of them
*/
if (!(ppc_pci_flags & PPC_PCI_PROBE_ONLY)) {
list_for_each_entry(b, &pci_root_buses, node)
pcibios_reserve_legacy_regions(b);
}
/* Now, if the platform didn't decide to blindly trust the firmware,
* we proceed to assigning things that were left unassigned
*/
if (!(ppc_pci_flags & PPC_PCI_PROBE_ONLY)) {
pr_debug("PCI: Assigning unassigned resources...\n");
pci_assign_unassigned_resources();
}
/* Call machine dependent fixup */
if (ppc_md.pcibios_fixup)
ppc_md.pcibios_fixup();
}
#ifdef CONFIG_HOTPLUG
/* This is used by the PCI hotplug driver to allocate resource
* of newly plugged busses. We can try to consolidate with the
* rest of the code later, for now, keep it as-is as our main
* resource allocation function doesn't deal with sub-trees yet.
*/
void pcibios_claim_one_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
struct pci_bus *child_bus;
list_for_each_entry(dev, &bus->devices, bus_list) {
int i;
for (i = 0; i < PCI_NUM_RESOURCES; i++) {
struct resource *r = &dev->resource[i];
if (r->parent || !r->start || !r->flags)
continue;
pr_debug("PCI: Claiming %s: "
"Resource %d: %016llx..%016llx [%x]\n",
pci_name(dev), i,
(unsigned long long)r->start,
(unsigned long long)r->end,
(unsigned int)r->flags);
pci_claim_resource(dev, i);
}
}
list_for_each_entry(child_bus, &bus->children, node)
pcibios_claim_one_bus(child_bus);
}
/* pcibios_finish_adding_to_bus
*
* This is to be called by the hotplug code after devices have been
* added to a bus, this include calling it for a PHB that is just
* being added
*/
void pcibios_finish_adding_to_bus(struct pci_bus *bus)
{
pr_debug("PCI: Finishing adding to hotplug bus %04x:%02x\n",
pci_domain_nr(bus), bus->number);
/* Allocate bus and devices resources */
pcibios_allocate_bus_resources(bus);
pcibios_claim_one_bus(bus);
/* Add new devices to global lists. Register in proc, sysfs. */
pci_bus_add_devices(bus);
/* Fixup EEH */
eeh_add_device_tree_late(bus);
}
EXPORT_SYMBOL_GPL(pcibios_finish_adding_to_bus);
#endif /* CONFIG_HOTPLUG */
int pcibios_enable_device(struct pci_dev *dev, int mask)
{
if (ppc_md.pcibios_enable_device_hook)
if (ppc_md.pcibios_enable_device_hook(dev))
return -EINVAL;
return pci_enable_resources(dev, mask);
}
void __devinit pcibios_setup_phb_resources(struct pci_controller *hose)
{
struct pci_bus *bus = hose->bus;
struct resource *res;
int i;
/* Hookup PHB IO resource */
bus->resource[0] = res = &hose->io_resource;
if (!res->flags) {
printk(KERN_WARNING "PCI: I/O resource not set for host"
" bridge %s (domain %d)\n",
hose->dn->full_name, hose->global_number);
#ifdef CONFIG_PPC32
/* Workaround for lack of IO resource only on 32-bit */
res->start = (unsigned long)hose->io_base_virt - isa_io_base;
res->end = res->start + IO_SPACE_LIMIT;
res->flags = IORESOURCE_IO;
#endif /* CONFIG_PPC32 */
}
pr_debug("PCI: PHB IO resource = %016llx-%016llx [%lx]\n",
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned long)res->flags);
/* Hookup PHB Memory resources */
for (i = 0; i < 3; ++i) {
res = &hose->mem_resources[i];
if (!res->flags) {
if (i > 0)
continue;
printk(KERN_ERR "PCI: Memory resource 0 not set for "
"host bridge %s (domain %d)\n",
hose->dn->full_name, hose->global_number);
#ifdef CONFIG_PPC32
/* Workaround for lack of MEM resource only on 32-bit */
res->start = hose->pci_mem_offset;
res->end = (resource_size_t)-1LL;
res->flags = IORESOURCE_MEM;
#endif /* CONFIG_PPC32 */
}
bus->resource[i+1] = res;
pr_debug("PCI: PHB MEM resource %d = %016llx-%016llx [%lx]\n", i,
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned long)res->flags);
}
pr_debug("PCI: PHB MEM offset = %016llx\n",
(unsigned long long)hose->pci_mem_offset);
pr_debug("PCI: PHB IO offset = %08lx\n",
(unsigned long)hose->io_base_virt - _IO_BASE);
}
/*
* Null PCI config access functions, for the case when we can't
* find a hose.
*/
#define NULL_PCI_OP(rw, size, type) \
static int \
null_##rw##_config_##size(struct pci_dev *dev, int offset, type val) \
{ \
return PCIBIOS_DEVICE_NOT_FOUND; \
}
static int
null_read_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 *val)
{
return PCIBIOS_DEVICE_NOT_FOUND;
}
static int
null_write_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 val)
{
return PCIBIOS_DEVICE_NOT_FOUND;
}
static struct pci_ops null_pci_ops =
{
.read = null_read_config,
.write = null_write_config,
};
/*
* These functions are used early on before PCI scanning is done
* and all of the pci_dev and pci_bus structures have been created.
*/
static struct pci_bus *
fake_pci_bus(struct pci_controller *hose, int busnr)
{
static struct pci_bus bus;
if (hose == 0) {
printk(KERN_ERR "Can't find hose for PCI bus %d!\n", busnr);
}
bus.number = busnr;
bus.sysdata = hose;
bus.ops = hose? hose->ops: &null_pci_ops;
return &bus;
}
#define EARLY_PCI_OP(rw, size, type) \
int early_##rw##_config_##size(struct pci_controller *hose, int bus, \
int devfn, int offset, type value) \
{ \
return pci_bus_##rw##_config_##size(fake_pci_bus(hose, bus), \
devfn, offset, value); \
}
EARLY_PCI_OP(read, byte, u8 *)
EARLY_PCI_OP(read, word, u16 *)
EARLY_PCI_OP(read, dword, u32 *)
EARLY_PCI_OP(write, byte, u8)
EARLY_PCI_OP(write, word, u16)
EARLY_PCI_OP(write, dword, u32)
extern int pci_bus_find_capability (struct pci_bus *bus, unsigned int devfn, int cap);
int early_find_capability(struct pci_controller *hose, int bus, int devfn,
int cap)
{
return pci_bus_find_capability(fake_pci_bus(hose, bus), devfn, cap);
}
/**
* pci_scan_phb - Given a pci_controller, setup and scan the PCI bus
* @hose: Pointer to the PCI host controller instance structure
* @sysdata: value to use for sysdata pointer. ppc32 and ppc64 differ here
*
* Note: the 'data' pointer is a temporary measure. As 32 and 64 bit
* pci code gets merged, this parameter should become unnecessary because
* both will use the same value.
*/
void __devinit pcibios_scan_phb(struct pci_controller *hose, void *sysdata)
{
struct pci_bus *bus;
struct device_node *node = hose->dn;
int mode;
pr_debug("PCI: Scanning PHB %s\n",
node ? node->full_name : "<NO NAME>");
/* Create an empty bus for the toplevel */
bus = pci_create_bus(hose->parent, hose->first_busno, hose->ops,
sysdata);
if (bus == NULL) {
pr_err("Failed to create bus for PCI domain %04x\n",
hose->global_number);
return;
}
bus->secondary = hose->first_busno;
hose->bus = bus;
/* Get some IO space for the new PHB */
pcibios_setup_phb_io_space(hose);
/* Wire up PHB bus resources */
pcibios_setup_phb_resources(hose);
/* Get probe mode and perform scan */
mode = PCI_PROBE_NORMAL;
if (node && ppc_md.pci_probe_mode)
mode = ppc_md.pci_probe_mode(bus);
pr_debug(" probe mode: %d\n", mode);
if (mode == PCI_PROBE_DEVTREE) {
bus->subordinate = hose->last_busno;
of_scan_bus(node, bus);
}
if (mode == PCI_PROBE_NORMAL)
hose->last_busno = bus->subordinate = pci_scan_child_bus(bus);
}
| gpl-2.0 |
nik124seleznev/ZC500TG | net/9p/trans_rdma.c | 726 | 19221 | /*
* linux/fs/9p/trans_rdma.c
*
* RDMA transport layer based on the trans_fd.c implementation.
*
* Copyright (C) 2008 by Tom Tucker <tom@opengridcomputing.com>
* Copyright (C) 2006 by Russ Cox <rsc@swtch.com>
* Copyright (C) 2004-2005 by Latchesar Ionkov <lucho@ionkov.net>
* Copyright (C) 2004-2008 by Eric Van Hensbergen <ericvh@gmail.com>
* Copyright (C) 1997-2002 by Ron Minnich <rminnich@sarnoff.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:
* Free Software Foundation
* 51 Franklin Street, Fifth Floor
* Boston, MA 02111-1301 USA
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/in.h>
#include <linux/module.h>
#include <linux/net.h>
#include <linux/ipv6.h>
#include <linux/kthread.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/un.h>
#include <linux/uaccess.h>
#include <linux/inet.h>
#include <linux/idr.h>
#include <linux/file.h>
#include <linux/parser.h>
#include <linux/semaphore.h>
#include <linux/slab.h>
#include <net/9p/9p.h>
#include <net/9p/client.h>
#include <net/9p/transport.h>
#include <rdma/ib_verbs.h>
#include <rdma/rdma_cm.h>
#define P9_PORT 5640
#define P9_RDMA_SQ_DEPTH 32
#define P9_RDMA_RQ_DEPTH 32
#define P9_RDMA_SEND_SGE 4
#define P9_RDMA_RECV_SGE 4
#define P9_RDMA_IRD 0
#define P9_RDMA_ORD 0
#define P9_RDMA_TIMEOUT 30000 /* 30 seconds */
#define P9_RDMA_MAXSIZE (1024*1024) /* 1MB */
/**
* struct p9_trans_rdma - RDMA transport instance
*
* @state: tracks the transport state machine for connection setup and tear down
* @cm_id: The RDMA CM ID
* @pd: Protection Domain pointer
* @qp: Queue Pair pointer
* @cq: Completion Queue pointer
* @dm_mr: DMA Memory Region pointer
* @lkey: The local access only memory region key
* @timeout: Number of uSecs to wait for connection management events
* @sq_depth: The depth of the Send Queue
* @sq_sem: Semaphore for the SQ
* @rq_depth: The depth of the Receive Queue.
* @rq_sem: Semaphore for the RQ
* @excess_rc : Amount of posted Receive Contexts without a pending request.
* See rdma_request()
* @addr: The remote peer's address
* @req_lock: Protects the active request list
* @cm_done: Completion event for connection management tracking
*/
struct p9_trans_rdma {
enum {
P9_RDMA_INIT,
P9_RDMA_ADDR_RESOLVED,
P9_RDMA_ROUTE_RESOLVED,
P9_RDMA_CONNECTED,
P9_RDMA_FLUSHING,
P9_RDMA_CLOSING,
P9_RDMA_CLOSED,
} state;
struct rdma_cm_id *cm_id;
struct ib_pd *pd;
struct ib_qp *qp;
struct ib_cq *cq;
struct ib_mr *dma_mr;
u32 lkey;
long timeout;
int sq_depth;
struct semaphore sq_sem;
int rq_depth;
struct semaphore rq_sem;
atomic_t excess_rc;
struct sockaddr_in addr;
spinlock_t req_lock;
struct completion cm_done;
};
/**
* p9_rdma_context - Keeps track of in-process WR
*
* @wc_op: The original WR op for when the CQE completes in error.
* @busa: Bus address to unmap when the WR completes
* @req: Keeps track of requests (send)
* @rc: Keepts track of replies (receive)
*/
struct p9_rdma_req;
struct p9_rdma_context {
enum ib_wc_opcode wc_op;
dma_addr_t busa;
union {
struct p9_req_t *req;
struct p9_fcall *rc;
};
};
/**
* p9_rdma_opts - Collection of mount options
* @port: port of connection
* @sq_depth: The requested depth of the SQ. This really doesn't need
* to be any deeper than the number of threads used in the client
* @rq_depth: The depth of the RQ. Should be greater than or equal to SQ depth
* @timeout: Time to wait in msecs for CM events
*/
struct p9_rdma_opts {
short port;
int sq_depth;
int rq_depth;
long timeout;
};
/*
* Option Parsing (code inspired by NFS code)
*/
enum {
/* Options that take integer arguments */
Opt_port, Opt_rq_depth, Opt_sq_depth, Opt_timeout, Opt_err,
};
static match_table_t tokens = {
{Opt_port, "port=%u"},
{Opt_sq_depth, "sq=%u"},
{Opt_rq_depth, "rq=%u"},
{Opt_timeout, "timeout=%u"},
{Opt_err, NULL},
};
/**
* parse_opts - parse mount options into rdma options structure
* @params: options string passed from mount
* @opts: rdma transport-specific structure to parse options into
*
* Returns 0 upon success, -ERRNO upon failure
*/
static int parse_opts(char *params, struct p9_rdma_opts *opts)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int option;
char *options, *tmp_options;
opts->port = P9_PORT;
opts->sq_depth = P9_RDMA_SQ_DEPTH;
opts->rq_depth = P9_RDMA_RQ_DEPTH;
opts->timeout = P9_RDMA_TIMEOUT;
if (!params)
return 0;
tmp_options = kstrdup(params, GFP_KERNEL);
if (!tmp_options) {
p9_debug(P9_DEBUG_ERROR,
"failed to allocate copy of option string\n");
return -ENOMEM;
}
options = tmp_options;
while ((p = strsep(&options, ",")) != NULL) {
int token;
int r;
if (!*p)
continue;
token = match_token(p, tokens, args);
if (token == Opt_err)
continue;
r = match_int(&args[0], &option);
if (r < 0) {
p9_debug(P9_DEBUG_ERROR,
"integer field, but no integer?\n");
continue;
}
switch (token) {
case Opt_port:
opts->port = option;
break;
case Opt_sq_depth:
opts->sq_depth = option;
break;
case Opt_rq_depth:
opts->rq_depth = option;
break;
case Opt_timeout:
opts->timeout = option;
break;
default:
continue;
}
}
/* RQ must be at least as large as the SQ */
opts->rq_depth = max(opts->rq_depth, opts->sq_depth);
kfree(tmp_options);
return 0;
}
static int
p9_cm_event_handler(struct rdma_cm_id *id, struct rdma_cm_event *event)
{
struct p9_client *c = id->context;
struct p9_trans_rdma *rdma = c->trans;
switch (event->event) {
case RDMA_CM_EVENT_ADDR_RESOLVED:
BUG_ON(rdma->state != P9_RDMA_INIT);
rdma->state = P9_RDMA_ADDR_RESOLVED;
break;
case RDMA_CM_EVENT_ROUTE_RESOLVED:
BUG_ON(rdma->state != P9_RDMA_ADDR_RESOLVED);
rdma->state = P9_RDMA_ROUTE_RESOLVED;
break;
case RDMA_CM_EVENT_ESTABLISHED:
BUG_ON(rdma->state != P9_RDMA_ROUTE_RESOLVED);
rdma->state = P9_RDMA_CONNECTED;
break;
case RDMA_CM_EVENT_DISCONNECTED:
if (rdma)
rdma->state = P9_RDMA_CLOSED;
if (c)
c->status = Disconnected;
break;
case RDMA_CM_EVENT_TIMEWAIT_EXIT:
break;
case RDMA_CM_EVENT_ADDR_CHANGE:
case RDMA_CM_EVENT_ROUTE_ERROR:
case RDMA_CM_EVENT_DEVICE_REMOVAL:
case RDMA_CM_EVENT_MULTICAST_JOIN:
case RDMA_CM_EVENT_MULTICAST_ERROR:
case RDMA_CM_EVENT_REJECTED:
case RDMA_CM_EVENT_CONNECT_REQUEST:
case RDMA_CM_EVENT_CONNECT_RESPONSE:
case RDMA_CM_EVENT_CONNECT_ERROR:
case RDMA_CM_EVENT_ADDR_ERROR:
case RDMA_CM_EVENT_UNREACHABLE:
c->status = Disconnected;
rdma_disconnect(rdma->cm_id);
break;
default:
BUG();
}
complete(&rdma->cm_done);
return 0;
}
static void
handle_recv(struct p9_client *client, struct p9_trans_rdma *rdma,
struct p9_rdma_context *c, enum ib_wc_status status, u32 byte_len)
{
struct p9_req_t *req;
int err = 0;
int16_t tag;
req = NULL;
ib_dma_unmap_single(rdma->cm_id->device, c->busa, client->msize,
DMA_FROM_DEVICE);
if (status != IB_WC_SUCCESS)
goto err_out;
err = p9_parse_header(c->rc, NULL, NULL, &tag, 1);
if (err)
goto err_out;
req = p9_tag_lookup(client, tag);
if (!req)
goto err_out;
/* Check that we have not yet received a reply for this request.
*/
if (unlikely(req->rc)) {
pr_err("Duplicate reply for request %d", tag);
goto err_out;
}
req->rc = c->rc;
p9_client_cb(client, req, REQ_STATUS_RCVD);
return;
err_out:
p9_debug(P9_DEBUG_ERROR, "req %p err %d status %d\n", req, err, status);
rdma->state = P9_RDMA_FLUSHING;
client->status = Disconnected;
}
static void
handle_send(struct p9_client *client, struct p9_trans_rdma *rdma,
struct p9_rdma_context *c, enum ib_wc_status status, u32 byte_len)
{
ib_dma_unmap_single(rdma->cm_id->device,
c->busa, c->req->tc->size,
DMA_TO_DEVICE);
}
static void qp_event_handler(struct ib_event *event, void *context)
{
p9_debug(P9_DEBUG_ERROR, "QP event %d context %p\n",
event->event, context);
}
static void cq_comp_handler(struct ib_cq *cq, void *cq_context)
{
struct p9_client *client = cq_context;
struct p9_trans_rdma *rdma = client->trans;
int ret;
struct ib_wc wc;
ib_req_notify_cq(rdma->cq, IB_CQ_NEXT_COMP);
while ((ret = ib_poll_cq(cq, 1, &wc)) > 0) {
struct p9_rdma_context *c = (void *) (unsigned long) wc.wr_id;
switch (c->wc_op) {
case IB_WC_RECV:
handle_recv(client, rdma, c, wc.status, wc.byte_len);
up(&rdma->rq_sem);
break;
case IB_WC_SEND:
handle_send(client, rdma, c, wc.status, wc.byte_len);
up(&rdma->sq_sem);
break;
default:
pr_err("unexpected completion type, c->wc_op=%d, wc.opcode=%d, status=%d\n",
c->wc_op, wc.opcode, wc.status);
break;
}
kfree(c);
}
}
static void cq_event_handler(struct ib_event *e, void *v)
{
p9_debug(P9_DEBUG_ERROR, "CQ event %d context %p\n", e->event, v);
}
static void rdma_destroy_trans(struct p9_trans_rdma *rdma)
{
if (!rdma)
return;
if (rdma->dma_mr && !IS_ERR(rdma->dma_mr))
ib_dereg_mr(rdma->dma_mr);
if (rdma->qp && !IS_ERR(rdma->qp))
ib_destroy_qp(rdma->qp);
if (rdma->pd && !IS_ERR(rdma->pd))
ib_dealloc_pd(rdma->pd);
if (rdma->cq && !IS_ERR(rdma->cq))
ib_destroy_cq(rdma->cq);
if (rdma->cm_id && !IS_ERR(rdma->cm_id))
rdma_destroy_id(rdma->cm_id);
kfree(rdma);
}
static int
post_recv(struct p9_client *client, struct p9_rdma_context *c)
{
struct p9_trans_rdma *rdma = client->trans;
struct ib_recv_wr wr, *bad_wr;
struct ib_sge sge;
c->busa = ib_dma_map_single(rdma->cm_id->device,
c->rc->sdata, client->msize,
DMA_FROM_DEVICE);
if (ib_dma_mapping_error(rdma->cm_id->device, c->busa))
goto error;
sge.addr = c->busa;
sge.length = client->msize;
sge.lkey = rdma->lkey;
wr.next = NULL;
c->wc_op = IB_WC_RECV;
wr.wr_id = (unsigned long) c;
wr.sg_list = &sge;
wr.num_sge = 1;
return ib_post_recv(rdma->qp, &wr, &bad_wr);
error:
p9_debug(P9_DEBUG_ERROR, "EIO\n");
return -EIO;
}
static int rdma_request(struct p9_client *client, struct p9_req_t *req)
{
struct p9_trans_rdma *rdma = client->trans;
struct ib_send_wr wr, *bad_wr;
struct ib_sge sge;
int err = 0;
unsigned long flags;
struct p9_rdma_context *c = NULL;
struct p9_rdma_context *rpl_context = NULL;
/* When an error occurs between posting the recv and the send,
* there will be a receive context posted without a pending request.
* Since there is no way to "un-post" it, we remember it and skip
* post_recv() for the next request.
* So here,
* see if we are this `next request' and need to absorb an excess rc.
* If yes, then drop and free our own, and do not recv_post().
**/
if (unlikely(atomic_read(&rdma->excess_rc) > 0)) {
if ((atomic_sub_return(1, &rdma->excess_rc) >= 0)) {
/* Got one ! */
kfree(req->rc);
req->rc = NULL;
goto dont_need_post_recv;
} else {
/* We raced and lost. */
atomic_inc(&rdma->excess_rc);
}
}
/* Allocate an fcall for the reply */
rpl_context = kmalloc(sizeof *rpl_context, GFP_NOFS);
if (!rpl_context) {
err = -ENOMEM;
goto recv_error;
}
rpl_context->rc = req->rc;
/*
* Post a receive buffer for this request. We need to ensure
* there is a reply buffer available for every outstanding
* request. A flushed request can result in no reply for an
* outstanding request, so we must keep a count to avoid
* overflowing the RQ.
*/
if (down_interruptible(&rdma->rq_sem)) {
err = -EINTR;
goto recv_error;
}
err = post_recv(client, rpl_context);
if (err) {
p9_debug(P9_DEBUG_FCALL, "POST RECV failed\n");
goto recv_error;
}
/* remove posted receive buffer from request structure */
req->rc = NULL;
dont_need_post_recv:
/* Post the request */
c = kmalloc(sizeof *c, GFP_NOFS);
if (!c) {
err = -ENOMEM;
goto send_error;
}
c->req = req;
c->busa = ib_dma_map_single(rdma->cm_id->device,
c->req->tc->sdata, c->req->tc->size,
DMA_TO_DEVICE);
if (ib_dma_mapping_error(rdma->cm_id->device, c->busa)) {
err = -EIO;
goto send_error;
}
sge.addr = c->busa;
sge.length = c->req->tc->size;
sge.lkey = rdma->lkey;
wr.next = NULL;
c->wc_op = IB_WC_SEND;
wr.wr_id = (unsigned long) c;
wr.opcode = IB_WR_SEND;
wr.send_flags = IB_SEND_SIGNALED;
wr.sg_list = &sge;
wr.num_sge = 1;
if (down_interruptible(&rdma->sq_sem)) {
err = -EINTR;
goto send_error;
}
/* Mark request as `sent' *before* we actually send it,
* because doing if after could erase the REQ_STATUS_RCVD
* status in case of a very fast reply.
*/
req->status = REQ_STATUS_SENT;
err = ib_post_send(rdma->qp, &wr, &bad_wr);
if (err)
goto send_error;
/* Success */
return 0;
/* Handle errors that happened during or while preparing the send: */
send_error:
req->status = REQ_STATUS_ERROR;
kfree(c);
p9_debug(P9_DEBUG_ERROR, "Error %d in rdma_request()\n", err);
/* Ach.
* We did recv_post(), but not send. We have one recv_post in excess.
*/
atomic_inc(&rdma->excess_rc);
return err;
/* Handle errors that happened during or while preparing post_recv(): */
recv_error:
kfree(rpl_context);
spin_lock_irqsave(&rdma->req_lock, flags);
if (rdma->state < P9_RDMA_CLOSING) {
rdma->state = P9_RDMA_CLOSING;
spin_unlock_irqrestore(&rdma->req_lock, flags);
rdma_disconnect(rdma->cm_id);
} else
spin_unlock_irqrestore(&rdma->req_lock, flags);
return err;
}
static void rdma_close(struct p9_client *client)
{
struct p9_trans_rdma *rdma;
if (!client)
return;
rdma = client->trans;
if (!rdma)
return;
client->status = Disconnected;
rdma_disconnect(rdma->cm_id);
rdma_destroy_trans(rdma);
}
/**
* alloc_rdma - Allocate and initialize the rdma transport structure
* @opts: Mount options structure
*/
static struct p9_trans_rdma *alloc_rdma(struct p9_rdma_opts *opts)
{
struct p9_trans_rdma *rdma;
rdma = kzalloc(sizeof(struct p9_trans_rdma), GFP_KERNEL);
if (!rdma)
return NULL;
rdma->sq_depth = opts->sq_depth;
rdma->rq_depth = opts->rq_depth;
rdma->timeout = opts->timeout;
spin_lock_init(&rdma->req_lock);
init_completion(&rdma->cm_done);
sema_init(&rdma->sq_sem, rdma->sq_depth);
sema_init(&rdma->rq_sem, rdma->rq_depth);
atomic_set(&rdma->excess_rc, 0);
return rdma;
}
static int rdma_cancel(struct p9_client *client, struct p9_req_t *req)
{
/* Nothing to do here.
* We will take care of it (if we have to) in rdma_cancelled()
*/
return 1;
}
/* A request has been fully flushed without a reply.
* That means we have posted one buffer in excess.
*/
static int rdma_cancelled(struct p9_client *client, struct p9_req_t *req)
{
struct p9_trans_rdma *rdma = client->trans;
atomic_inc(&rdma->excess_rc);
return 0;
}
/**
* trans_create_rdma - Transport method for creating atransport instance
* @client: client instance
* @addr: IP address string
* @args: Mount options string
*/
static int
rdma_create_trans(struct p9_client *client, const char *addr, char *args)
{
int err;
struct p9_rdma_opts opts;
struct p9_trans_rdma *rdma;
struct rdma_conn_param conn_param;
struct ib_qp_init_attr qp_attr;
struct ib_device_attr devattr;
/* Parse the transport specific mount options */
err = parse_opts(args, &opts);
if (err < 0)
return err;
/* Create and initialize the RDMA transport structure */
rdma = alloc_rdma(&opts);
if (!rdma)
return -ENOMEM;
/* Create the RDMA CM ID */
rdma->cm_id = rdma_create_id(p9_cm_event_handler, client, RDMA_PS_TCP,
IB_QPT_RC);
if (IS_ERR(rdma->cm_id))
goto error;
/* Associate the client with the transport */
client->trans = rdma;
/* Resolve the server's address */
rdma->addr.sin_family = AF_INET;
rdma->addr.sin_addr.s_addr = in_aton(addr);
rdma->addr.sin_port = htons(opts.port);
err = rdma_resolve_addr(rdma->cm_id, NULL,
(struct sockaddr *)&rdma->addr,
rdma->timeout);
if (err)
goto error;
err = wait_for_completion_interruptible(&rdma->cm_done);
if (err || (rdma->state != P9_RDMA_ADDR_RESOLVED))
goto error;
/* Resolve the route to the server */
err = rdma_resolve_route(rdma->cm_id, rdma->timeout);
if (err)
goto error;
err = wait_for_completion_interruptible(&rdma->cm_done);
if (err || (rdma->state != P9_RDMA_ROUTE_RESOLVED))
goto error;
/* Query the device attributes */
err = ib_query_device(rdma->cm_id->device, &devattr);
if (err)
goto error;
/* Create the Completion Queue */
rdma->cq = ib_create_cq(rdma->cm_id->device, cq_comp_handler,
cq_event_handler, client,
opts.sq_depth + opts.rq_depth + 1, 0);
if (IS_ERR(rdma->cq))
goto error;
ib_req_notify_cq(rdma->cq, IB_CQ_NEXT_COMP);
/* Create the Protection Domain */
rdma->pd = ib_alloc_pd(rdma->cm_id->device);
if (IS_ERR(rdma->pd))
goto error;
/* Cache the DMA lkey in the transport */
rdma->dma_mr = NULL;
if (devattr.device_cap_flags & IB_DEVICE_LOCAL_DMA_LKEY)
rdma->lkey = rdma->cm_id->device->local_dma_lkey;
else {
rdma->dma_mr = ib_get_dma_mr(rdma->pd, IB_ACCESS_LOCAL_WRITE);
if (IS_ERR(rdma->dma_mr))
goto error;
rdma->lkey = rdma->dma_mr->lkey;
}
/* Create the Queue Pair */
memset(&qp_attr, 0, sizeof qp_attr);
qp_attr.event_handler = qp_event_handler;
qp_attr.qp_context = client;
qp_attr.cap.max_send_wr = opts.sq_depth;
qp_attr.cap.max_recv_wr = opts.rq_depth;
qp_attr.cap.max_send_sge = P9_RDMA_SEND_SGE;
qp_attr.cap.max_recv_sge = P9_RDMA_RECV_SGE;
qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
qp_attr.qp_type = IB_QPT_RC;
qp_attr.send_cq = rdma->cq;
qp_attr.recv_cq = rdma->cq;
err = rdma_create_qp(rdma->cm_id, rdma->pd, &qp_attr);
if (err)
goto error;
rdma->qp = rdma->cm_id->qp;
/* Request a connection */
memset(&conn_param, 0, sizeof(conn_param));
conn_param.private_data = NULL;
conn_param.private_data_len = 0;
conn_param.responder_resources = P9_RDMA_IRD;
conn_param.initiator_depth = P9_RDMA_ORD;
err = rdma_connect(rdma->cm_id, &conn_param);
if (err)
goto error;
err = wait_for_completion_interruptible(&rdma->cm_done);
if (err || (rdma->state != P9_RDMA_CONNECTED))
goto error;
client->status = Connected;
return 0;
error:
rdma_destroy_trans(rdma);
return -ENOTCONN;
}
static struct p9_trans_module p9_rdma_trans = {
.name = "rdma",
.maxsize = P9_RDMA_MAXSIZE,
.def = 0,
.owner = THIS_MODULE,
.create = rdma_create_trans,
.close = rdma_close,
.request = rdma_request,
.cancel = rdma_cancel,
.cancelled = rdma_cancelled,
};
/**
* p9_trans_rdma_init - Register the 9P RDMA transport driver
*/
static int __init p9_trans_rdma_init(void)
{
v9fs_register_trans(&p9_rdma_trans);
return 0;
}
static void __exit p9_trans_rdma_exit(void)
{
v9fs_unregister_trans(&p9_rdma_trans);
}
module_init(p9_trans_rdma_init);
module_exit(p9_trans_rdma_exit);
MODULE_AUTHOR("Tom Tucker <tom@opengridcomputing.com>");
MODULE_DESCRIPTION("RDMA Transport for 9P");
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
identisoft-rashid/ec3_kernel | arch/sh/kernel/cpu/sh2a/setup-mxg.c | 1750 | 5346 | /*
* Renesas MX-G (R8A03022BG) Setup
*
* Copyright (C) 2008, 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
enum {
UNUSED = 0,
/* interrupt sources */
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7,
IRQ8, IRQ9, IRQ10, IRQ11, IRQ12, IRQ13, IRQ14, IRQ15,
PINT0, PINT1, PINT2, PINT3, PINT4, PINT5, PINT6, PINT7,
SINT8, SINT7, SINT6, SINT5, SINT4, SINT3, SINT2, SINT1,
SCIF0, SCIF1,
MTU2_GROUP1, MTU2_GROUP2, MTU2_GROUP3, MTU2_GROUP4, MTU2_GROUP5,
MTU2_TGI3B, MTU2_TGI3C,
/* interrupt groups */
PINT,
};
static struct intc_vect vectors[] __initdata = {
INTC_IRQ(IRQ0, 64), INTC_IRQ(IRQ1, 65),
INTC_IRQ(IRQ2, 66), INTC_IRQ(IRQ3, 67),
INTC_IRQ(IRQ4, 68), INTC_IRQ(IRQ5, 69),
INTC_IRQ(IRQ6, 70), INTC_IRQ(IRQ7, 71),
INTC_IRQ(IRQ8, 72), INTC_IRQ(IRQ9, 73),
INTC_IRQ(IRQ10, 74), INTC_IRQ(IRQ11, 75),
INTC_IRQ(IRQ12, 76), INTC_IRQ(IRQ13, 77),
INTC_IRQ(IRQ14, 78), INTC_IRQ(IRQ15, 79),
INTC_IRQ(PINT0, 80), INTC_IRQ(PINT1, 81),
INTC_IRQ(PINT2, 82), INTC_IRQ(PINT3, 83),
INTC_IRQ(PINT4, 84), INTC_IRQ(PINT5, 85),
INTC_IRQ(PINT6, 86), INTC_IRQ(PINT7, 87),
INTC_IRQ(SINT8, 94), INTC_IRQ(SINT7, 95),
INTC_IRQ(SINT6, 96), INTC_IRQ(SINT5, 97),
INTC_IRQ(SINT4, 98), INTC_IRQ(SINT3, 99),
INTC_IRQ(SINT2, 100), INTC_IRQ(SINT1, 101),
INTC_IRQ(SCIF0, 220), INTC_IRQ(SCIF0, 221),
INTC_IRQ(SCIF0, 222), INTC_IRQ(SCIF0, 223),
INTC_IRQ(SCIF1, 224), INTC_IRQ(SCIF1, 225),
INTC_IRQ(SCIF1, 226), INTC_IRQ(SCIF1, 227),
INTC_IRQ(MTU2_GROUP1, 228), INTC_IRQ(MTU2_GROUP1, 229),
INTC_IRQ(MTU2_GROUP1, 230), INTC_IRQ(MTU2_GROUP1, 231),
INTC_IRQ(MTU2_GROUP1, 232), INTC_IRQ(MTU2_GROUP1, 233),
INTC_IRQ(MTU2_GROUP2, 234), INTC_IRQ(MTU2_GROUP2, 235),
INTC_IRQ(MTU2_GROUP2, 236), INTC_IRQ(MTU2_GROUP2, 237),
INTC_IRQ(MTU2_GROUP2, 238), INTC_IRQ(MTU2_GROUP2, 239),
INTC_IRQ(MTU2_GROUP3, 240), INTC_IRQ(MTU2_GROUP3, 241),
INTC_IRQ(MTU2_GROUP3, 242), INTC_IRQ(MTU2_GROUP3, 243),
INTC_IRQ(MTU2_TGI3B, 244),
INTC_IRQ(MTU2_TGI3C, 245),
INTC_IRQ(MTU2_GROUP4, 246), INTC_IRQ(MTU2_GROUP4, 247),
INTC_IRQ(MTU2_GROUP4, 248), INTC_IRQ(MTU2_GROUP4, 249),
INTC_IRQ(MTU2_GROUP4, 250), INTC_IRQ(MTU2_GROUP4, 251),
INTC_IRQ(MTU2_GROUP5, 252), INTC_IRQ(MTU2_GROUP5, 253),
INTC_IRQ(MTU2_GROUP5, 254), INTC_IRQ(MTU2_GROUP5, 255),
};
static struct intc_group groups[] __initdata = {
INTC_GROUP(PINT, PINT0, PINT1, PINT2, PINT3,
PINT4, PINT5, PINT6, PINT7),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xfffd9418, 0, 16, 4, /* IPR01 */ { IRQ0, IRQ1, IRQ2, IRQ3 } },
{ 0xfffd941a, 0, 16, 4, /* IPR02 */ { IRQ4, IRQ5, IRQ6, IRQ7 } },
{ 0xfffd941c, 0, 16, 4, /* IPR03 */ { IRQ8, IRQ9, IRQ10, IRQ11 } },
{ 0xfffd941e, 0, 16, 4, /* IPR04 */ { IRQ12, IRQ13, IRQ14, IRQ15 } },
{ 0xfffd9420, 0, 16, 4, /* IPR05 */ { PINT, 0, 0, 0 } },
{ 0xfffd9800, 0, 16, 4, /* IPR06 */ { } },
{ 0xfffd9802, 0, 16, 4, /* IPR07 */ { } },
{ 0xfffd9804, 0, 16, 4, /* IPR08 */ { } },
{ 0xfffd9806, 0, 16, 4, /* IPR09 */ { } },
{ 0xfffd9808, 0, 16, 4, /* IPR10 */ { } },
{ 0xfffd980a, 0, 16, 4, /* IPR11 */ { } },
{ 0xfffd980c, 0, 16, 4, /* IPR12 */ { } },
{ 0xfffd980e, 0, 16, 4, /* IPR13 */ { } },
{ 0xfffd9810, 0, 16, 4, /* IPR14 */ { 0, 0, 0, SCIF0 } },
{ 0xfffd9812, 0, 16, 4, /* IPR15 */
{ SCIF1, MTU2_GROUP1, MTU2_GROUP2, MTU2_GROUP3 } },
{ 0xfffd9814, 0, 16, 4, /* IPR16 */
{ MTU2_TGI3B, MTU2_TGI3C, MTU2_GROUP4, MTU2_GROUP5 } },
};
static struct intc_mask_reg mask_registers[] __initdata = {
{ 0xfffd9408, 0, 16, /* PINTER */
{ 0, 0, 0, 0, 0, 0, 0, 0,
PINT7, PINT6, PINT5, PINT4, PINT3, PINT2, PINT1, PINT0 } },
};
static DECLARE_INTC_DESC(intc_desc, "mxg", vectors, groups,
mask_registers, prio_registers, NULL);
static struct resource mtu2_resources[] = {
DEFINE_RES_MEM(0xff801000, 0x400),
DEFINE_RES_IRQ_NAMED(228, "tgi0a"),
DEFINE_RES_IRQ_NAMED(234, "tgi1a"),
DEFINE_RES_IRQ_NAMED(240, "tgi2a"),
};
static struct platform_device mtu2_device = {
.name = "sh-mtu2",
.id = -1,
.resource = mtu2_resources,
.num_resources = ARRAY_SIZE(mtu2_resources),
};
static struct plat_sci_port scif0_platform_data = {
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE,
.type = PORT_SCIF,
};
static struct resource scif0_resources[] = {
DEFINE_RES_MEM(0xff804000, 0x100),
DEFINE_RES_IRQ(220),
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.resource = scif0_resources,
.num_resources = ARRAY_SIZE(scif0_resources),
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct platform_device *mxg_devices[] __initdata = {
&scif0_device,
&mtu2_device,
};
static int __init mxg_devices_setup(void)
{
return platform_add_devices(mxg_devices,
ARRAY_SIZE(mxg_devices));
}
arch_initcall(mxg_devices_setup);
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
}
static struct platform_device *mxg_early_devices[] __initdata = {
&scif0_device,
&mtu2_device,
};
void __init plat_early_device_setup(void)
{
early_platform_add_devices(mxg_early_devices,
ARRAY_SIZE(mxg_early_devices));
}
| gpl-2.0 |
rektide/linux | arch/sh/kernel/traps_32.c | 1750 | 18859 | /*
* 'traps.c' handles hardware traps and faults after we have saved some
* state in 'entry.S'.
*
* SuperH version: Copyright (C) 1999 Niibe Yutaka
* Copyright (C) 2000 Philipp Rumpf
* Copyright (C) 2000 David Howells
* Copyright (C) 2002 - 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/kernel.h>
#include <linux/ptrace.h>
#include <linux/hardirq.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/kallsyms.h>
#include <linux/io.h>
#include <linux/bug.h>
#include <linux/debug_locks.h>
#include <linux/kdebug.h>
#include <linux/limits.h>
#include <linux/sysfs.h>
#include <linux/uaccess.h>
#include <linux/perf_event.h>
#include <asm/alignment.h>
#include <asm/fpu.h>
#include <asm/kprobes.h>
#include <asm/traps.h>
#include <asm/bl_bit.h>
#ifdef CONFIG_CPU_SH2
# define TRAP_RESERVED_INST 4
# define TRAP_ILLEGAL_SLOT_INST 6
# define TRAP_ADDRESS_ERROR 9
# ifdef CONFIG_CPU_SH2A
# define TRAP_UBC 12
# define TRAP_FPU_ERROR 13
# define TRAP_DIVZERO_ERROR 17
# define TRAP_DIVOVF_ERROR 18
# endif
#else
#define TRAP_RESERVED_INST 12
#define TRAP_ILLEGAL_SLOT_INST 13
#endif
static inline void sign_extend(unsigned int count, unsigned char *dst)
{
#ifdef __LITTLE_ENDIAN__
if ((count == 1) && dst[0] & 0x80) {
dst[1] = 0xff;
dst[2] = 0xff;
dst[3] = 0xff;
}
if ((count == 2) && dst[1] & 0x80) {
dst[2] = 0xff;
dst[3] = 0xff;
}
#else
if ((count == 1) && dst[3] & 0x80) {
dst[2] = 0xff;
dst[1] = 0xff;
dst[0] = 0xff;
}
if ((count == 2) && dst[2] & 0x80) {
dst[1] = 0xff;
dst[0] = 0xff;
}
#endif
}
static struct mem_access user_mem_access = {
copy_from_user,
copy_to_user,
};
/*
* handle an instruction that does an unaligned memory access by emulating the
* desired behaviour
* - note that PC _may not_ point to the faulting instruction
* (if that instruction is in a branch delay slot)
* - return 0 if emulation okay, -EFAULT on existential error
*/
static int handle_unaligned_ins(insn_size_t instruction, struct pt_regs *regs,
struct mem_access *ma)
{
int ret, index, count;
unsigned long *rm, *rn;
unsigned char *src, *dst;
unsigned char __user *srcu, *dstu;
index = (instruction>>8)&15; /* 0x0F00 */
rn = ®s->regs[index];
index = (instruction>>4)&15; /* 0x00F0 */
rm = ®s->regs[index];
count = 1<<(instruction&3);
switch (count) {
case 1: inc_unaligned_byte_access(); break;
case 2: inc_unaligned_word_access(); break;
case 4: inc_unaligned_dword_access(); break;
case 8: inc_unaligned_multi_access(); break;
}
ret = -EFAULT;
switch (instruction>>12) {
case 0: /* mov.[bwl] to/from memory via r0+rn */
if (instruction & 8) {
/* from memory */
srcu = (unsigned char __user *)*rm;
srcu += regs->regs[0];
dst = (unsigned char *)rn;
*(unsigned long *)dst = 0;
#if !defined(__LITTLE_ENDIAN__)
dst += 4-count;
#endif
if (ma->from(dst, srcu, count))
goto fetch_fault;
sign_extend(count, dst);
} else {
/* to memory */
src = (unsigned char *)rm;
#if !defined(__LITTLE_ENDIAN__)
src += 4-count;
#endif
dstu = (unsigned char __user *)*rn;
dstu += regs->regs[0];
if (ma->to(dstu, src, count))
goto fetch_fault;
}
ret = 0;
break;
case 1: /* mov.l Rm,@(disp,Rn) */
src = (unsigned char*) rm;
dstu = (unsigned char __user *)*rn;
dstu += (instruction&0x000F)<<2;
if (ma->to(dstu, src, 4))
goto fetch_fault;
ret = 0;
break;
case 2: /* mov.[bwl] to memory, possibly with pre-decrement */
if (instruction & 4)
*rn -= count;
src = (unsigned char*) rm;
dstu = (unsigned char __user *)*rn;
#if !defined(__LITTLE_ENDIAN__)
src += 4-count;
#endif
if (ma->to(dstu, src, count))
goto fetch_fault;
ret = 0;
break;
case 5: /* mov.l @(disp,Rm),Rn */
srcu = (unsigned char __user *)*rm;
srcu += (instruction & 0x000F) << 2;
dst = (unsigned char *)rn;
*(unsigned long *)dst = 0;
if (ma->from(dst, srcu, 4))
goto fetch_fault;
ret = 0;
break;
case 6: /* mov.[bwl] from memory, possibly with post-increment */
srcu = (unsigned char __user *)*rm;
if (instruction & 4)
*rm += count;
dst = (unsigned char*) rn;
*(unsigned long*)dst = 0;
#if !defined(__LITTLE_ENDIAN__)
dst += 4-count;
#endif
if (ma->from(dst, srcu, count))
goto fetch_fault;
sign_extend(count, dst);
ret = 0;
break;
case 8:
switch ((instruction&0xFF00)>>8) {
case 0x81: /* mov.w R0,@(disp,Rn) */
src = (unsigned char *) ®s->regs[0];
#if !defined(__LITTLE_ENDIAN__)
src += 2;
#endif
dstu = (unsigned char __user *)*rm; /* called Rn in the spec */
dstu += (instruction & 0x000F) << 1;
if (ma->to(dstu, src, 2))
goto fetch_fault;
ret = 0;
break;
case 0x85: /* mov.w @(disp,Rm),R0 */
srcu = (unsigned char __user *)*rm;
srcu += (instruction & 0x000F) << 1;
dst = (unsigned char *) ®s->regs[0];
*(unsigned long *)dst = 0;
#if !defined(__LITTLE_ENDIAN__)
dst += 2;
#endif
if (ma->from(dst, srcu, 2))
goto fetch_fault;
sign_extend(2, dst);
ret = 0;
break;
}
break;
case 9: /* mov.w @(disp,PC),Rn */
srcu = (unsigned char __user *)regs->pc;
srcu += 4;
srcu += (instruction & 0x00FF) << 1;
dst = (unsigned char *)rn;
*(unsigned long *)dst = 0;
#if !defined(__LITTLE_ENDIAN__)
dst += 2;
#endif
if (ma->from(dst, srcu, 2))
goto fetch_fault;
sign_extend(2, dst);
ret = 0;
break;
case 0xd: /* mov.l @(disp,PC),Rn */
srcu = (unsigned char __user *)(regs->pc & ~0x3);
srcu += 4;
srcu += (instruction & 0x00FF) << 2;
dst = (unsigned char *)rn;
*(unsigned long *)dst = 0;
if (ma->from(dst, srcu, 4))
goto fetch_fault;
ret = 0;
break;
}
return ret;
fetch_fault:
/* Argh. Address not only misaligned but also non-existent.
* Raise an EFAULT and see if it's trapped
*/
die_if_no_fixup("Fault in unaligned fixup", regs, 0);
return -EFAULT;
}
/*
* emulate the instruction in the delay slot
* - fetches the instruction from PC+2
*/
static inline int handle_delayslot(struct pt_regs *regs,
insn_size_t old_instruction,
struct mem_access *ma)
{
insn_size_t instruction;
void __user *addr = (void __user *)(regs->pc +
instruction_size(old_instruction));
if (copy_from_user(&instruction, addr, sizeof(instruction))) {
/* the instruction-fetch faulted */
if (user_mode(regs))
return -EFAULT;
/* kernel */
die("delay-slot-insn faulting in handle_unaligned_delayslot",
regs, 0);
}
return handle_unaligned_ins(instruction, regs, ma);
}
/*
* handle an instruction that does an unaligned memory access
* - have to be careful of branch delay-slot instructions that fault
* SH3:
* - if the branch would be taken PC points to the branch
* - if the branch would not be taken, PC points to delay-slot
* SH4:
* - PC always points to delayed branch
* - return 0 if handled, -EFAULT if failed (may not return if in kernel)
*/
/* Macros to determine offset from current PC for branch instructions */
/* Explicit type coercion is used to force sign extension where needed */
#define SH_PC_8BIT_OFFSET(instr) ((((signed char)(instr))*2) + 4)
#define SH_PC_12BIT_OFFSET(instr) ((((signed short)(instr<<4))>>3) + 4)
int handle_unaligned_access(insn_size_t instruction, struct pt_regs *regs,
struct mem_access *ma, int expected,
unsigned long address)
{
u_int rm;
int ret, index;
/*
* XXX: We can't handle mixed 16/32-bit instructions yet
*/
if (instruction_size(instruction) != 2)
return -EINVAL;
index = (instruction>>8)&15; /* 0x0F00 */
rm = regs->regs[index];
/*
* Log the unexpected fixups, and then pass them on to perf.
*
* We intentionally don't report the expected cases to perf as
* otherwise the trapped I/O case will skew the results too much
* to be useful.
*/
if (!expected) {
unaligned_fixups_notify(current, instruction, regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1,
regs, address);
}
ret = -EFAULT;
switch (instruction&0xF000) {
case 0x0000:
if (instruction==0x000B) {
/* rts */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc = regs->pr;
}
else if ((instruction&0x00FF)==0x0023) {
/* braf @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc += rm + 4;
}
else if ((instruction&0x00FF)==0x0003) {
/* bsrf @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc += rm + 4;
}
}
else {
/* mov.[bwl] to/from memory via r0+rn */
goto simple;
}
break;
case 0x1000: /* mov.l Rm,@(disp,Rn) */
goto simple;
case 0x2000: /* mov.[bwl] to memory, possibly with pre-decrement */
goto simple;
case 0x4000:
if ((instruction&0x00FF)==0x002B) {
/* jmp @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc = rm;
}
else if ((instruction&0x00FF)==0x000B) {
/* jsr @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc = rm;
}
}
else {
/* mov.[bwl] to/from memory via r0+rn */
goto simple;
}
break;
case 0x5000: /* mov.l @(disp,Rm),Rn */
goto simple;
case 0x6000: /* mov.[bwl] from memory, possibly with post-increment */
goto simple;
case 0x8000: /* bf lab, bf/s lab, bt lab, bt/s lab */
switch (instruction&0x0F00) {
case 0x0100: /* mov.w R0,@(disp,Rm) */
goto simple;
case 0x0500: /* mov.w @(disp,Rm),R0 */
goto simple;
case 0x0B00: /* bf lab - no delayslot*/
ret = 0;
break;
case 0x0F00: /* bf/s lab */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB)
if ((regs->sr & 0x00000001) != 0)
regs->pc += 4; /* next after slot */
else
#endif
regs->pc += SH_PC_8BIT_OFFSET(instruction);
}
break;
case 0x0900: /* bt lab - no delayslot */
ret = 0;
break;
case 0x0D00: /* bt/s lab */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB)
if ((regs->sr & 0x00000001) == 0)
regs->pc += 4; /* next after slot */
else
#endif
regs->pc += SH_PC_8BIT_OFFSET(instruction);
}
break;
}
break;
case 0x9000: /* mov.w @(disp,Rm),Rn */
goto simple;
case 0xA000: /* bra label */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc += SH_PC_12BIT_OFFSET(instruction);
break;
case 0xB000: /* bsr label */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc += SH_PC_12BIT_OFFSET(instruction);
}
break;
case 0xD000: /* mov.l @(disp,Rm),Rn */
goto simple;
}
return ret;
/* handle non-delay-slot instruction */
simple:
ret = handle_unaligned_ins(instruction, regs, ma);
if (ret==0)
regs->pc += instruction_size(instruction);
return ret;
}
/*
* Handle various address error exceptions:
* - instruction address error:
* misaligned PC
* PC >= 0x80000000 in user mode
* - data address error (read and write)
* misaligned data access
* access to >= 0x80000000 is user mode
* Unfortuntaly we can't distinguish between instruction address error
* and data address errors caused by read accesses.
*/
asmlinkage void do_address_error(struct pt_regs *regs,
unsigned long writeaccess,
unsigned long address)
{
unsigned long error_code = 0;
mm_segment_t oldfs;
siginfo_t info;
insn_size_t instruction;
int tmp;
/* Intentional ifdef */
#ifdef CONFIG_CPU_HAS_SR_RB
error_code = lookup_exception_vector();
#endif
oldfs = get_fs();
if (user_mode(regs)) {
int si_code = BUS_ADRERR;
unsigned int user_action;
local_irq_enable();
inc_unaligned_user_access();
set_fs(USER_DS);
if (copy_from_user(&instruction, (insn_size_t *)(regs->pc & ~1),
sizeof(instruction))) {
set_fs(oldfs);
goto uspace_segv;
}
set_fs(oldfs);
/* shout about userspace fixups */
unaligned_fixups_notify(current, instruction, regs);
user_action = unaligned_user_action();
if (user_action & UM_FIXUP)
goto fixup;
if (user_action & UM_SIGNAL)
goto uspace_segv;
else {
/* ignore */
regs->pc += instruction_size(instruction);
return;
}
fixup:
/* bad PC is not something we can fix */
if (regs->pc & 1) {
si_code = BUS_ADRALN;
goto uspace_segv;
}
set_fs(USER_DS);
tmp = handle_unaligned_access(instruction, regs,
&user_mem_access, 0,
address);
set_fs(oldfs);
if (tmp == 0)
return; /* sorted */
uspace_segv:
printk(KERN_NOTICE "Sending SIGBUS to \"%s\" due to unaligned "
"access (PC %lx PR %lx)\n", current->comm, regs->pc,
regs->pr);
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = si_code;
info.si_addr = (void __user *)address;
force_sig_info(SIGBUS, &info, current);
} else {
inc_unaligned_kernel_access();
if (regs->pc & 1)
die("unaligned program counter", regs, error_code);
set_fs(KERNEL_DS);
if (copy_from_user(&instruction, (void __user *)(regs->pc),
sizeof(instruction))) {
/* Argh. Fault on the instruction itself.
This should never happen non-SMP
*/
set_fs(oldfs);
die("insn faulting in do_address_error", regs, 0);
}
unaligned_fixups_notify(current, instruction, regs);
handle_unaligned_access(instruction, regs, &user_mem_access,
0, address);
set_fs(oldfs);
}
}
#ifdef CONFIG_SH_DSP
/*
* SH-DSP support gerg@snapgear.com.
*/
int is_dsp_inst(struct pt_regs *regs)
{
unsigned short inst = 0;
/*
* Safe guard if DSP mode is already enabled or we're lacking
* the DSP altogether.
*/
if (!(current_cpu_data.flags & CPU_HAS_DSP) || (regs->sr & SR_DSP))
return 0;
get_user(inst, ((unsigned short *) regs->pc));
inst &= 0xf000;
/* Check for any type of DSP or support instruction */
if ((inst == 0xf000) || (inst == 0x4000))
return 1;
return 0;
}
#else
#define is_dsp_inst(regs) (0)
#endif /* CONFIG_SH_DSP */
#ifdef CONFIG_CPU_SH2A
asmlinkage void do_divide_error(unsigned long r4)
{
siginfo_t info;
switch (r4) {
case TRAP_DIVZERO_ERROR:
info.si_code = FPE_INTDIV;
break;
case TRAP_DIVOVF_ERROR:
info.si_code = FPE_INTOVF;
break;
}
force_sig_info(SIGFPE, &info, current);
}
#endif
asmlinkage void do_reserved_inst(void)
{
struct pt_regs *regs = current_pt_regs();
unsigned long error_code;
struct task_struct *tsk = current;
#ifdef CONFIG_SH_FPU_EMU
unsigned short inst = 0;
int err;
get_user(inst, (unsigned short*)regs->pc);
err = do_fpu_inst(inst, regs);
if (!err) {
regs->pc += instruction_size(inst);
return;
}
/* not a FPU inst. */
#endif
#ifdef CONFIG_SH_DSP
/* Check if it's a DSP instruction */
if (is_dsp_inst(regs)) {
/* Enable DSP mode, and restart instruction. */
regs->sr |= SR_DSP;
/* Save DSP mode */
tsk->thread.dsp_status.status |= SR_DSP;
return;
}
#endif
error_code = lookup_exception_vector();
local_irq_enable();
force_sig(SIGILL, tsk);
die_if_no_fixup("reserved instruction", regs, error_code);
}
#ifdef CONFIG_SH_FPU_EMU
static int emulate_branch(unsigned short inst, struct pt_regs *regs)
{
/*
* bfs: 8fxx: PC+=d*2+4;
* bts: 8dxx: PC+=d*2+4;
* bra: axxx: PC+=D*2+4;
* bsr: bxxx: PC+=D*2+4 after PR=PC+4;
* braf:0x23: PC+=Rn*2+4;
* bsrf:0x03: PC+=Rn*2+4 after PR=PC+4;
* jmp: 4x2b: PC=Rn;
* jsr: 4x0b: PC=Rn after PR=PC+4;
* rts: 000b: PC=PR;
*/
if (((inst & 0xf000) == 0xb000) || /* bsr */
((inst & 0xf0ff) == 0x0003) || /* bsrf */
((inst & 0xf0ff) == 0x400b)) /* jsr */
regs->pr = regs->pc + 4;
if ((inst & 0xfd00) == 0x8d00) { /* bfs, bts */
regs->pc += SH_PC_8BIT_OFFSET(inst);
return 0;
}
if ((inst & 0xe000) == 0xa000) { /* bra, bsr */
regs->pc += SH_PC_12BIT_OFFSET(inst);
return 0;
}
if ((inst & 0xf0df) == 0x0003) { /* braf, bsrf */
regs->pc += regs->regs[(inst & 0x0f00) >> 8] + 4;
return 0;
}
if ((inst & 0xf0df) == 0x400b) { /* jmp, jsr */
regs->pc = regs->regs[(inst & 0x0f00) >> 8];
return 0;
}
if ((inst & 0xffff) == 0x000b) { /* rts */
regs->pc = regs->pr;
return 0;
}
return 1;
}
#endif
asmlinkage void do_illegal_slot_inst(void)
{
struct pt_regs *regs = current_pt_regs();
unsigned long inst;
struct task_struct *tsk = current;
if (kprobe_handle_illslot(regs->pc) == 0)
return;
#ifdef CONFIG_SH_FPU_EMU
get_user(inst, (unsigned short *)regs->pc + 1);
if (!do_fpu_inst(inst, regs)) {
get_user(inst, (unsigned short *)regs->pc);
if (!emulate_branch(inst, regs))
return;
/* fault in branch.*/
}
/* not a FPU inst. */
#endif
inst = lookup_exception_vector();
local_irq_enable();
force_sig(SIGILL, tsk);
die_if_no_fixup("illegal slot instruction", regs, inst);
}
asmlinkage void do_exception_error(void)
{
long ex;
ex = lookup_exception_vector();
die_if_kernel("exception", current_pt_regs(), ex);
}
void per_cpu_trap_init(void)
{
extern void *vbr_base;
/* NOTE: The VBR value should be at P1
(or P2, virtural "fixed" address space).
It's definitely should not in physical address. */
asm volatile("ldc %0, vbr"
: /* no output */
: "r" (&vbr_base)
: "memory");
/* disable exception blocking now when the vbr has been setup */
clear_bl_bit();
}
void *set_exception_table_vec(unsigned int vec, void *handler)
{
extern void *exception_handling_table[];
void *old_handler;
old_handler = exception_handling_table[vec];
exception_handling_table[vec] = handler;
return old_handler;
}
void __init trap_init(void)
{
set_exception_table_vec(TRAP_RESERVED_INST, do_reserved_inst);
set_exception_table_vec(TRAP_ILLEGAL_SLOT_INST, do_illegal_slot_inst);
#if defined(CONFIG_CPU_SH4) && !defined(CONFIG_SH_FPU) || \
defined(CONFIG_SH_FPU_EMU)
/*
* For SH-4 lacking an FPU, treat floating point instructions as
* reserved. They'll be handled in the math-emu case, or faulted on
* otherwise.
*/
set_exception_table_evt(0x800, do_reserved_inst);
set_exception_table_evt(0x820, do_illegal_slot_inst);
#elif defined(CONFIG_SH_FPU)
set_exception_table_evt(0x800, fpu_state_restore_trap_handler);
set_exception_table_evt(0x820, fpu_state_restore_trap_handler);
#endif
#ifdef CONFIG_CPU_SH2
set_exception_table_vec(TRAP_ADDRESS_ERROR, address_error_trap_handler);
#endif
#ifdef CONFIG_CPU_SH2A
set_exception_table_vec(TRAP_DIVZERO_ERROR, do_divide_error);
set_exception_table_vec(TRAP_DIVOVF_ERROR, do_divide_error);
#ifdef CONFIG_SH_FPU
set_exception_table_vec(TRAP_FPU_ERROR, fpu_error_trap_handler);
#endif
#endif
#ifdef TRAP_UBC
set_exception_table_vec(TRAP_UBC, breakpoint_trap_handler);
#endif
}
| gpl-2.0 |
Pafcholini/emotion_beta_511_no_updates | net/ipv6/ip6_checksum.c | 2518 | 2325 | #include <net/ip.h>
#include <net/udp.h>
#include <net/udplite.h>
#include <asm/checksum.h>
#ifndef _HAVE_ARCH_IPV6_CSUM
__sum16 csum_ipv6_magic(const struct in6_addr *saddr,
const struct in6_addr *daddr,
__u32 len, unsigned short proto,
__wsum csum)
{
int carry;
__u32 ulen;
__u32 uproto;
__u32 sum = (__force u32)csum;
sum += (__force u32)saddr->s6_addr32[0];
carry = (sum < (__force u32)saddr->s6_addr32[0]);
sum += carry;
sum += (__force u32)saddr->s6_addr32[1];
carry = (sum < (__force u32)saddr->s6_addr32[1]);
sum += carry;
sum += (__force u32)saddr->s6_addr32[2];
carry = (sum < (__force u32)saddr->s6_addr32[2]);
sum += carry;
sum += (__force u32)saddr->s6_addr32[3];
carry = (sum < (__force u32)saddr->s6_addr32[3]);
sum += carry;
sum += (__force u32)daddr->s6_addr32[0];
carry = (sum < (__force u32)daddr->s6_addr32[0]);
sum += carry;
sum += (__force u32)daddr->s6_addr32[1];
carry = (sum < (__force u32)daddr->s6_addr32[1]);
sum += carry;
sum += (__force u32)daddr->s6_addr32[2];
carry = (sum < (__force u32)daddr->s6_addr32[2]);
sum += carry;
sum += (__force u32)daddr->s6_addr32[3];
carry = (sum < (__force u32)daddr->s6_addr32[3]);
sum += carry;
ulen = (__force u32)htonl((__u32) len);
sum += ulen;
carry = (sum < ulen);
sum += carry;
uproto = (__force u32)htonl(proto);
sum += uproto;
carry = (sum < uproto);
sum += carry;
return csum_fold((__force __wsum)sum);
}
EXPORT_SYMBOL(csum_ipv6_magic);
#endif
int udp6_csum_init(struct sk_buff *skb, struct udphdr *uh, int proto)
{
int err;
UDP_SKB_CB(skb)->partial_cov = 0;
UDP_SKB_CB(skb)->cscov = skb->len;
if (proto == IPPROTO_UDPLITE) {
err = udplite_checksum_init(skb, uh);
if (err)
return err;
}
if (uh->check == 0) {
/* RFC 2460 section 8.1 says that we SHOULD log
this error. Well, it is reasonable.
*/
LIMIT_NETDEBUG(KERN_INFO "IPv6: udp checksum is 0\n");
return 1;
}
if (skb->ip_summed == CHECKSUM_COMPLETE &&
!csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr,
skb->len, proto, skb->csum))
skb->ip_summed = CHECKSUM_UNNECESSARY;
if (!skb_csum_unnecessary(skb))
skb->csum = ~csum_unfold(csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len, proto, 0));
return 0;
}
EXPORT_SYMBOL(udp6_csum_init);
| gpl-2.0 |
CandyDevices/kernel_samsung_espresso10 | drivers/media/dvb/dvb-usb/ce6230.c | 2774 | 8222 | /*
* DVB USB Linux driver for Intel CE6230 DVB-T USB2.0 receiver
*
* Copyright (C) 2009 Antti Palosaari <crope@iki.fi>
*
* 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 "ce6230.h"
#include "zl10353.h"
#include "mxl5005s.h"
/* debug */
static int dvb_usb_ce6230_debug;
module_param_named(debug, dvb_usb_ce6230_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level" DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static struct zl10353_config ce6230_zl10353_config;
static int ce6230_rw_udev(struct usb_device *udev, struct req_t *req)
{
int ret;
unsigned int pipe;
u8 request;
u8 requesttype;
u16 value;
u16 index;
u8 *buf;
request = req->cmd;
value = req->value;
index = req->index;
switch (req->cmd) {
case I2C_READ:
case DEMOD_READ:
case REG_READ:
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
break;
case I2C_WRITE:
case DEMOD_WRITE:
case REG_WRITE:
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
break;
default:
err("unknown command:%02x", req->cmd);
ret = -EPERM;
goto error;
}
buf = kmalloc(req->data_len, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto error;
}
if (requesttype == (USB_TYPE_VENDOR | USB_DIR_OUT)) {
/* write */
memcpy(buf, req->data, req->data_len);
pipe = usb_sndctrlpipe(udev, 0);
} else {
/* read */
pipe = usb_rcvctrlpipe(udev, 0);
}
msleep(1); /* avoid I2C errors */
ret = usb_control_msg(udev, pipe, request, requesttype, value, index,
buf, req->data_len, CE6230_USB_TIMEOUT);
ce6230_debug_dump(request, requesttype, value, index, buf,
req->data_len, deb_xfer);
if (ret < 0)
deb_info("%s: usb_control_msg failed:%d\n", __func__, ret);
else
ret = 0;
/* read request, copy returned data to return buf */
if (!ret && requesttype == (USB_TYPE_VENDOR | USB_DIR_IN))
memcpy(req->data, buf, req->data_len);
kfree(buf);
error:
return ret;
}
static int ce6230_ctrl_msg(struct dvb_usb_device *d, struct req_t *req)
{
return ce6230_rw_udev(d->udev, req);
}
/* I2C */
static int ce6230_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i = 0;
struct req_t req;
int ret = 0;
memset(&req, 0, sizeof(req));
if (num > 2)
return -EINVAL;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
while (i < num) {
if (num > i + 1 && (msg[i+1].flags & I2C_M_RD)) {
if (msg[i].addr ==
ce6230_zl10353_config.demod_address) {
req.cmd = DEMOD_READ;
req.value = msg[i].addr >> 1;
req.index = msg[i].buf[0];
req.data_len = msg[i+1].len;
req.data = &msg[i+1].buf[0];
ret = ce6230_ctrl_msg(d, &req);
} else {
err("i2c read not implemented");
ret = -EPERM;
}
i += 2;
} else {
if (msg[i].addr ==
ce6230_zl10353_config.demod_address) {
req.cmd = DEMOD_WRITE;
req.value = msg[i].addr >> 1;
req.index = msg[i].buf[0];
req.data_len = msg[i].len-1;
req.data = &msg[i].buf[1];
ret = ce6230_ctrl_msg(d, &req);
} else {
req.cmd = I2C_WRITE;
req.value = 0x2000 + (msg[i].addr >> 1);
req.index = 0x0000;
req.data_len = msg[i].len;
req.data = &msg[i].buf[0];
ret = ce6230_ctrl_msg(d, &req);
}
i += 1;
}
if (ret)
break;
}
mutex_unlock(&d->i2c_mutex);
return ret ? ret : i;
}
static u32 ce6230_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm ce6230_i2c_algo = {
.master_xfer = ce6230_i2c_xfer,
.functionality = ce6230_i2c_func,
};
/* Callbacks for DVB USB */
static struct zl10353_config ce6230_zl10353_config = {
.demod_address = 0x1e,
.adc_clock = 450000,
.if2 = 45700,
.no_tuner = 1,
.parallel_ts = 1,
.clock_ctl_1 = 0x34,
.pll_0 = 0x0e,
};
static int ce6230_zl10353_frontend_attach(struct dvb_usb_adapter *adap)
{
deb_info("%s:\n", __func__);
adap->fe = dvb_attach(zl10353_attach, &ce6230_zl10353_config,
&adap->dev->i2c_adap);
if (adap->fe == NULL)
return -ENODEV;
return 0;
}
static struct mxl5005s_config ce6230_mxl5003s_config = {
.i2c_address = 0xc6,
.if_freq = IF_FREQ_4570000HZ,
.xtal_freq = CRYSTAL_FREQ_16000000HZ,
.agc_mode = MXL_SINGLE_AGC,
.tracking_filter = MXL_TF_DEFAULT,
.rssi_enable = MXL_RSSI_ENABLE,
.cap_select = MXL_CAP_SEL_ENABLE,
.div_out = MXL_DIV_OUT_4,
.clock_out = MXL_CLOCK_OUT_DISABLE,
.output_load = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
.top = MXL5005S_TOP_25P2,
.mod_mode = MXL_DIGITAL_MODE,
.if_mode = MXL_ZERO_IF,
.AgcMasterByte = 0x00,
};
static int ce6230_mxl5003s_tuner_attach(struct dvb_usb_adapter *adap)
{
int ret;
deb_info("%s:\n", __func__);
ret = dvb_attach(mxl5005s_attach, adap->fe, &adap->dev->i2c_adap,
&ce6230_mxl5003s_config) == NULL ? -ENODEV : 0;
return ret;
}
static int ce6230_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
deb_info("%s: onoff:%d\n", __func__, onoff);
/* InterfaceNumber 1 / AlternateSetting 0 idle
InterfaceNumber 1 / AlternateSetting 1 streaming */
ret = usb_set_interface(d->udev, 1, onoff);
if (ret)
err("usb_set_interface failed with error:%d", ret);
return ret;
}
/* DVB USB Driver stuff */
static struct dvb_usb_device_properties ce6230_properties;
static int ce6230_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int ret = 0;
struct dvb_usb_device *d = NULL;
deb_info("%s: interface:%d\n", __func__,
intf->cur_altsetting->desc.bInterfaceNumber);
if (intf->cur_altsetting->desc.bInterfaceNumber == 1) {
ret = dvb_usb_device_init(intf, &ce6230_properties, THIS_MODULE,
&d, adapter_nr);
if (ret)
err("init failed with error:%d\n", ret);
}
return ret;
}
static struct usb_device_id ce6230_table[] = {
{ USB_DEVICE(USB_VID_INTEL, USB_PID_INTEL_CE9500) },
{ USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A310) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, ce6230_table);
static struct dvb_usb_device_properties ce6230_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.no_reconnect = 1,
.size_of_priv = 0,
.num_adapters = 1,
.adapter = {
{
.frontend_attach = ce6230_zl10353_frontend_attach,
.tuner_attach = ce6230_mxl5003s_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 6,
.endpoint = 0x82,
.u = {
.bulk = {
.buffersize = (16*512),
}
}
},
}
},
.power_ctrl = ce6230_power_ctrl,
.i2c_algo = &ce6230_i2c_algo,
.num_device_descs = 2,
.devices = {
{
.name = "Intel CE9500 reference design",
.cold_ids = {NULL},
.warm_ids = {&ce6230_table[0], NULL},
},
{
.name = "AVerMedia A310 USB 2.0 DVB-T tuner",
.cold_ids = {NULL},
.warm_ids = {&ce6230_table[1], NULL},
},
}
};
static struct usb_driver ce6230_driver = {
.name = "dvb_usb_ce6230",
.probe = ce6230_probe,
.disconnect = dvb_usb_device_exit,
.id_table = ce6230_table,
};
/* module stuff */
static int __init ce6230_module_init(void)
{
int ret;
deb_info("%s:\n", __func__);
ret = usb_register(&ce6230_driver);
if (ret)
err("usb_register failed with error:%d", ret);
return ret;
}
static void __exit ce6230_module_exit(void)
{
deb_info("%s:\n", __func__);
/* deregister this driver from the USB subsystem */
usb_deregister(&ce6230_driver);
}
module_init(ce6230_module_init);
module_exit(ce6230_module_exit);
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_DESCRIPTION("Driver for Intel CE6230 DVB-T USB2.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
icebluechao/stuttgart_kernel | drivers/platform/x86/toshiba_acpi.c | 2774 | 26562 | /*
* toshiba_acpi.c - Toshiba Laptop ACPI Extras
*
*
* Copyright (C) 2002-2004 John Belmonte
* Copyright (C) 2008 Philip Langdale
* Copyright (C) 2010 Pierre Ducroquet
*
* 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
*
*
* The devolpment page for this driver is located at
* http://memebeam.org/toys/ToshibaAcpiDriver.
*
* Credits:
* Jonathan A. Buzzard - Toshiba HCI info, and critical tips on reverse
* engineering the Windows drivers
* Yasushi Nagato - changes for linux kernel 2.4 -> 2.5
* Rob Miller - TV out and hotkeys help
*
*
* TODO
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define TOSHIBA_ACPI_VERSION "0.19"
#define PROC_INTERFACE_VERSION 1
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/backlight.h>
#include <linux/platform_device.h>
#include <linux/rfkill.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/leds.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <acpi/acpi_drivers.h>
MODULE_AUTHOR("John Belmonte");
MODULE_DESCRIPTION("Toshiba Laptop ACPI Extras Driver");
MODULE_LICENSE("GPL");
/* Toshiba ACPI method paths */
#define METHOD_LCD_BRIGHTNESS "\\_SB_.PCI0.VGA_.LCD_._BCM"
#define TOSH_INTERFACE_1 "\\_SB_.VALD"
#define TOSH_INTERFACE_2 "\\_SB_.VALZ"
#define METHOD_VIDEO_OUT "\\_SB_.VALX.DSSX"
#define GHCI_METHOD ".GHCI"
/* Toshiba HCI interface definitions
*
* HCI is Toshiba's "Hardware Control Interface" which is supposed to
* be uniform across all their models. Ideally we would just call
* dedicated ACPI methods instead of using this primitive interface.
* However the ACPI methods seem to be incomplete in some areas (for
* example they allow setting, but not reading, the LCD brightness value),
* so this is still useful.
*/
#define HCI_WORDS 6
/* operations */
#define HCI_SET 0xff00
#define HCI_GET 0xfe00
/* return codes */
#define HCI_SUCCESS 0x0000
#define HCI_FAILURE 0x1000
#define HCI_NOT_SUPPORTED 0x8000
#define HCI_EMPTY 0x8c00
/* registers */
#define HCI_FAN 0x0004
#define HCI_SYSTEM_EVENT 0x0016
#define HCI_VIDEO_OUT 0x001c
#define HCI_HOTKEY_EVENT 0x001e
#define HCI_LCD_BRIGHTNESS 0x002a
#define HCI_WIRELESS 0x0056
/* field definitions */
#define HCI_LCD_BRIGHTNESS_BITS 3
#define HCI_LCD_BRIGHTNESS_SHIFT (16-HCI_LCD_BRIGHTNESS_BITS)
#define HCI_LCD_BRIGHTNESS_LEVELS (1 << HCI_LCD_BRIGHTNESS_BITS)
#define HCI_VIDEO_OUT_LCD 0x1
#define HCI_VIDEO_OUT_CRT 0x2
#define HCI_VIDEO_OUT_TV 0x4
#define HCI_WIRELESS_KILL_SWITCH 0x01
#define HCI_WIRELESS_BT_PRESENT 0x0f
#define HCI_WIRELESS_BT_ATTACH 0x40
#define HCI_WIRELESS_BT_POWER 0x80
static const struct acpi_device_id toshiba_device_ids[] = {
{"TOS6200", 0},
{"TOS6208", 0},
{"TOS1900", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, toshiba_device_ids);
static const struct key_entry toshiba_acpi_keymap[] __initconst = {
{ KE_KEY, 0x101, { KEY_MUTE } },
{ KE_KEY, 0x102, { KEY_ZOOMOUT } },
{ KE_KEY, 0x103, { KEY_ZOOMIN } },
{ KE_KEY, 0x13b, { KEY_COFFEE } },
{ KE_KEY, 0x13c, { KEY_BATTERY } },
{ KE_KEY, 0x13d, { KEY_SLEEP } },
{ KE_KEY, 0x13e, { KEY_SUSPEND } },
{ KE_KEY, 0x13f, { KEY_SWITCHVIDEOMODE } },
{ KE_KEY, 0x140, { KEY_BRIGHTNESSDOWN } },
{ KE_KEY, 0x141, { KEY_BRIGHTNESSUP } },
{ KE_KEY, 0x142, { KEY_WLAN } },
{ KE_KEY, 0x143, { KEY_PROG1 } },
{ KE_KEY, 0x17f, { KEY_FN } },
{ KE_KEY, 0xb05, { KEY_PROG2 } },
{ KE_KEY, 0xb06, { KEY_WWW } },
{ KE_KEY, 0xb07, { KEY_MAIL } },
{ KE_KEY, 0xb30, { KEY_STOP } },
{ KE_KEY, 0xb31, { KEY_PREVIOUSSONG } },
{ KE_KEY, 0xb32, { KEY_NEXTSONG } },
{ KE_KEY, 0xb33, { KEY_PLAYPAUSE } },
{ KE_KEY, 0xb5a, { KEY_MEDIA } },
{ KE_END, 0 },
};
/* utility
*/
static __inline__ void _set_bit(u32 * word, u32 mask, int value)
{
*word = (*word & ~mask) | (mask * value);
}
/* acpi interface wrappers
*/
static int is_valid_acpi_path(const char *methodName)
{
acpi_handle handle;
acpi_status status;
status = acpi_get_handle(NULL, (char *)methodName, &handle);
return !ACPI_FAILURE(status);
}
static int write_acpi_int(const char *methodName, int val)
{
struct acpi_object_list params;
union acpi_object in_objs[1];
acpi_status status;
params.count = ARRAY_SIZE(in_objs);
params.pointer = in_objs;
in_objs[0].type = ACPI_TYPE_INTEGER;
in_objs[0].integer.value = val;
status = acpi_evaluate_object(NULL, (char *)methodName, ¶ms, NULL);
return (status == AE_OK);
}
#if 0
static int read_acpi_int(const char *methodName, int *pVal)
{
struct acpi_buffer results;
union acpi_object out_objs[1];
acpi_status status;
results.length = sizeof(out_objs);
results.pointer = out_objs;
status = acpi_evaluate_object(0, (char *)methodName, 0, &results);
*pVal = out_objs[0].integer.value;
return (status == AE_OK) && (out_objs[0].type == ACPI_TYPE_INTEGER);
}
#endif
static const char *method_hci /*= 0*/ ;
/* Perform a raw HCI call. Here we don't care about input or output buffer
* format.
*/
static acpi_status hci_raw(const u32 in[HCI_WORDS], u32 out[HCI_WORDS])
{
struct acpi_object_list params;
union acpi_object in_objs[HCI_WORDS];
struct acpi_buffer results;
union acpi_object out_objs[HCI_WORDS + 1];
acpi_status status;
int i;
params.count = HCI_WORDS;
params.pointer = in_objs;
for (i = 0; i < HCI_WORDS; ++i) {
in_objs[i].type = ACPI_TYPE_INTEGER;
in_objs[i].integer.value = in[i];
}
results.length = sizeof(out_objs);
results.pointer = out_objs;
status = acpi_evaluate_object(NULL, (char *)method_hci, ¶ms,
&results);
if ((status == AE_OK) && (out_objs->package.count <= HCI_WORDS)) {
for (i = 0; i < out_objs->package.count; ++i) {
out[i] = out_objs->package.elements[i].integer.value;
}
}
return status;
}
/* common hci tasks (get or set one or two value)
*
* In addition to the ACPI status, the HCI system returns a result which
* may be useful (such as "not supported").
*/
static acpi_status hci_write1(u32 reg, u32 in1, u32 * result)
{
u32 in[HCI_WORDS] = { HCI_SET, reg, in1, 0, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status = hci_raw(in, out);
*result = (status == AE_OK) ? out[0] : HCI_FAILURE;
return status;
}
static acpi_status hci_read1(u32 reg, u32 * out1, u32 * result)
{
u32 in[HCI_WORDS] = { HCI_GET, reg, 0, 0, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status = hci_raw(in, out);
*out1 = out[2];
*result = (status == AE_OK) ? out[0] : HCI_FAILURE;
return status;
}
static acpi_status hci_write2(u32 reg, u32 in1, u32 in2, u32 *result)
{
u32 in[HCI_WORDS] = { HCI_SET, reg, in1, in2, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status = hci_raw(in, out);
*result = (status == AE_OK) ? out[0] : HCI_FAILURE;
return status;
}
static acpi_status hci_read2(u32 reg, u32 *out1, u32 *out2, u32 *result)
{
u32 in[HCI_WORDS] = { HCI_GET, reg, *out1, *out2, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status = hci_raw(in, out);
*out1 = out[2];
*out2 = out[3];
*result = (status == AE_OK) ? out[0] : HCI_FAILURE;
return status;
}
struct toshiba_acpi_dev {
struct platform_device *p_dev;
struct rfkill *bt_rfk;
struct input_dev *hotkey_dev;
int illumination_installed;
acpi_handle handle;
const char *bt_name;
struct mutex mutex;
};
/* Illumination support */
static int toshiba_illumination_available(void)
{
u32 in[HCI_WORDS] = { 0, 0, 0, 0, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status;
in[0] = 0xf100;
status = hci_raw(in, out);
if (ACPI_FAILURE(status)) {
pr_info("Illumination device not available\n");
return 0;
}
in[0] = 0xf400;
status = hci_raw(in, out);
return 1;
}
static void toshiba_illumination_set(struct led_classdev *cdev,
enum led_brightness brightness)
{
u32 in[HCI_WORDS] = { 0, 0, 0, 0, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status;
/* First request : initialize communication. */
in[0] = 0xf100;
status = hci_raw(in, out);
if (ACPI_FAILURE(status)) {
pr_info("Illumination device not available\n");
return;
}
if (brightness) {
/* Switch the illumination on */
in[0] = 0xf400;
in[1] = 0x14e;
in[2] = 1;
status = hci_raw(in, out);
if (ACPI_FAILURE(status)) {
pr_info("ACPI call for illumination failed\n");
return;
}
} else {
/* Switch the illumination off */
in[0] = 0xf400;
in[1] = 0x14e;
in[2] = 0;
status = hci_raw(in, out);
if (ACPI_FAILURE(status)) {
pr_info("ACPI call for illumination failed.\n");
return;
}
}
/* Last request : close communication. */
in[0] = 0xf200;
in[1] = 0;
in[2] = 0;
hci_raw(in, out);
}
static enum led_brightness toshiba_illumination_get(struct led_classdev *cdev)
{
u32 in[HCI_WORDS] = { 0, 0, 0, 0, 0, 0 };
u32 out[HCI_WORDS];
acpi_status status;
enum led_brightness result;
/* First request : initialize communication. */
in[0] = 0xf100;
status = hci_raw(in, out);
if (ACPI_FAILURE(status)) {
pr_info("Illumination device not available\n");
return LED_OFF;
}
/* Check the illumination */
in[0] = 0xf300;
in[1] = 0x14e;
status = hci_raw(in, out);
if (ACPI_FAILURE(status)) {
pr_info("ACPI call for illumination failed.\n");
return LED_OFF;
}
result = out[2] ? LED_FULL : LED_OFF;
/* Last request : close communication. */
in[0] = 0xf200;
in[1] = 0;
in[2] = 0;
hci_raw(in, out);
return result;
}
static struct led_classdev toshiba_led = {
.name = "toshiba::illumination",
.max_brightness = 1,
.brightness_set = toshiba_illumination_set,
.brightness_get = toshiba_illumination_get,
};
static struct toshiba_acpi_dev toshiba_acpi = {
.bt_name = "Toshiba Bluetooth",
};
/* Bluetooth rfkill handlers */
static u32 hci_get_bt_present(bool *present)
{
u32 hci_result;
u32 value, value2;
value = 0;
value2 = 0;
hci_read2(HCI_WIRELESS, &value, &value2, &hci_result);
if (hci_result == HCI_SUCCESS)
*present = (value & HCI_WIRELESS_BT_PRESENT) ? true : false;
return hci_result;
}
static u32 hci_get_radio_state(bool *radio_state)
{
u32 hci_result;
u32 value, value2;
value = 0;
value2 = 0x0001;
hci_read2(HCI_WIRELESS, &value, &value2, &hci_result);
*radio_state = value & HCI_WIRELESS_KILL_SWITCH;
return hci_result;
}
static int bt_rfkill_set_block(void *data, bool blocked)
{
struct toshiba_acpi_dev *dev = data;
u32 result1, result2;
u32 value;
int err;
bool radio_state;
value = (blocked == false);
mutex_lock(&dev->mutex);
if (hci_get_radio_state(&radio_state) != HCI_SUCCESS) {
err = -EBUSY;
goto out;
}
if (!radio_state) {
err = 0;
goto out;
}
hci_write2(HCI_WIRELESS, value, HCI_WIRELESS_BT_POWER, &result1);
hci_write2(HCI_WIRELESS, value, HCI_WIRELESS_BT_ATTACH, &result2);
if (result1 != HCI_SUCCESS || result2 != HCI_SUCCESS)
err = -EBUSY;
else
err = 0;
out:
mutex_unlock(&dev->mutex);
return err;
}
static void bt_rfkill_poll(struct rfkill *rfkill, void *data)
{
bool new_rfk_state;
bool value;
u32 hci_result;
struct toshiba_acpi_dev *dev = data;
mutex_lock(&dev->mutex);
hci_result = hci_get_radio_state(&value);
if (hci_result != HCI_SUCCESS) {
/* Can't do anything useful */
mutex_unlock(&dev->mutex);
return;
}
new_rfk_state = value;
mutex_unlock(&dev->mutex);
if (rfkill_set_hw_state(rfkill, !new_rfk_state))
bt_rfkill_set_block(data, true);
}
static const struct rfkill_ops toshiba_rfk_ops = {
.set_block = bt_rfkill_set_block,
.poll = bt_rfkill_poll,
};
static struct proc_dir_entry *toshiba_proc_dir /*= 0*/ ;
static struct backlight_device *toshiba_backlight_device;
static int force_fan;
static int last_key_event;
static int key_event_valid;
static int get_lcd(struct backlight_device *bd)
{
u32 hci_result;
u32 value;
hci_read1(HCI_LCD_BRIGHTNESS, &value, &hci_result);
if (hci_result == HCI_SUCCESS) {
return (value >> HCI_LCD_BRIGHTNESS_SHIFT);
} else
return -EFAULT;
}
static int lcd_proc_show(struct seq_file *m, void *v)
{
int value = get_lcd(NULL);
if (value >= 0) {
seq_printf(m, "brightness: %d\n", value);
seq_printf(m, "brightness_levels: %d\n",
HCI_LCD_BRIGHTNESS_LEVELS);
} else {
pr_err("Error reading LCD brightness\n");
}
return 0;
}
static int lcd_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, lcd_proc_show, NULL);
}
static int set_lcd(int value)
{
u32 hci_result;
value = value << HCI_LCD_BRIGHTNESS_SHIFT;
hci_write1(HCI_LCD_BRIGHTNESS, value, &hci_result);
if (hci_result != HCI_SUCCESS)
return -EFAULT;
return 0;
}
static int set_lcd_status(struct backlight_device *bd)
{
return set_lcd(bd->props.brightness);
}
static ssize_t lcd_proc_write(struct file *file, const char __user *buf,
size_t count, loff_t *pos)
{
char cmd[42];
size_t len;
int value;
int ret;
len = min(count, sizeof(cmd) - 1);
if (copy_from_user(cmd, buf, len))
return -EFAULT;
cmd[len] = '\0';
if (sscanf(cmd, " brightness : %i", &value) == 1 &&
value >= 0 && value < HCI_LCD_BRIGHTNESS_LEVELS) {
ret = set_lcd(value);
if (ret == 0)
ret = count;
} else {
ret = -EINVAL;
}
return ret;
}
static const struct file_operations lcd_proc_fops = {
.owner = THIS_MODULE,
.open = lcd_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = lcd_proc_write,
};
static int video_proc_show(struct seq_file *m, void *v)
{
u32 hci_result;
u32 value;
hci_read1(HCI_VIDEO_OUT, &value, &hci_result);
if (hci_result == HCI_SUCCESS) {
int is_lcd = (value & HCI_VIDEO_OUT_LCD) ? 1 : 0;
int is_crt = (value & HCI_VIDEO_OUT_CRT) ? 1 : 0;
int is_tv = (value & HCI_VIDEO_OUT_TV) ? 1 : 0;
seq_printf(m, "lcd_out: %d\n", is_lcd);
seq_printf(m, "crt_out: %d\n", is_crt);
seq_printf(m, "tv_out: %d\n", is_tv);
} else {
pr_err("Error reading video out status\n");
}
return 0;
}
static int video_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, video_proc_show, NULL);
}
static ssize_t video_proc_write(struct file *file, const char __user *buf,
size_t count, loff_t *pos)
{
char *cmd, *buffer;
int value;
int remain = count;
int lcd_out = -1;
int crt_out = -1;
int tv_out = -1;
u32 hci_result;
u32 video_out;
cmd = kmalloc(count + 1, GFP_KERNEL);
if (!cmd)
return -ENOMEM;
if (copy_from_user(cmd, buf, count)) {
kfree(cmd);
return -EFAULT;
}
cmd[count] = '\0';
buffer = cmd;
/* scan expression. Multiple expressions may be delimited with ;
*
* NOTE: to keep scanning simple, invalid fields are ignored
*/
while (remain) {
if (sscanf(buffer, " lcd_out : %i", &value) == 1)
lcd_out = value & 1;
else if (sscanf(buffer, " crt_out : %i", &value) == 1)
crt_out = value & 1;
else if (sscanf(buffer, " tv_out : %i", &value) == 1)
tv_out = value & 1;
/* advance to one character past the next ; */
do {
++buffer;
--remain;
}
while (remain && *(buffer - 1) != ';');
}
kfree(cmd);
hci_read1(HCI_VIDEO_OUT, &video_out, &hci_result);
if (hci_result == HCI_SUCCESS) {
unsigned int new_video_out = video_out;
if (lcd_out != -1)
_set_bit(&new_video_out, HCI_VIDEO_OUT_LCD, lcd_out);
if (crt_out != -1)
_set_bit(&new_video_out, HCI_VIDEO_OUT_CRT, crt_out);
if (tv_out != -1)
_set_bit(&new_video_out, HCI_VIDEO_OUT_TV, tv_out);
/* To avoid unnecessary video disruption, only write the new
* video setting if something changed. */
if (new_video_out != video_out)
write_acpi_int(METHOD_VIDEO_OUT, new_video_out);
} else {
return -EFAULT;
}
return count;
}
static const struct file_operations video_proc_fops = {
.owner = THIS_MODULE,
.open = video_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = video_proc_write,
};
static int fan_proc_show(struct seq_file *m, void *v)
{
u32 hci_result;
u32 value;
hci_read1(HCI_FAN, &value, &hci_result);
if (hci_result == HCI_SUCCESS) {
seq_printf(m, "running: %d\n", (value > 0));
seq_printf(m, "force_on: %d\n", force_fan);
} else {
pr_err("Error reading fan status\n");
}
return 0;
}
static int fan_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, fan_proc_show, NULL);
}
static ssize_t fan_proc_write(struct file *file, const char __user *buf,
size_t count, loff_t *pos)
{
char cmd[42];
size_t len;
int value;
u32 hci_result;
len = min(count, sizeof(cmd) - 1);
if (copy_from_user(cmd, buf, len))
return -EFAULT;
cmd[len] = '\0';
if (sscanf(cmd, " force_on : %i", &value) == 1 &&
value >= 0 && value <= 1) {
hci_write1(HCI_FAN, value, &hci_result);
if (hci_result != HCI_SUCCESS)
return -EFAULT;
else
force_fan = value;
} else {
return -EINVAL;
}
return count;
}
static const struct file_operations fan_proc_fops = {
.owner = THIS_MODULE,
.open = fan_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = fan_proc_write,
};
static int keys_proc_show(struct seq_file *m, void *v)
{
u32 hci_result;
u32 value;
if (!key_event_valid) {
hci_read1(HCI_SYSTEM_EVENT, &value, &hci_result);
if (hci_result == HCI_SUCCESS) {
key_event_valid = 1;
last_key_event = value;
} else if (hci_result == HCI_EMPTY) {
/* better luck next time */
} else if (hci_result == HCI_NOT_SUPPORTED) {
/* This is a workaround for an unresolved issue on
* some machines where system events sporadically
* become disabled. */
hci_write1(HCI_SYSTEM_EVENT, 1, &hci_result);
pr_notice("Re-enabled hotkeys\n");
} else {
pr_err("Error reading hotkey status\n");
goto end;
}
}
seq_printf(m, "hotkey_ready: %d\n", key_event_valid);
seq_printf(m, "hotkey: 0x%04x\n", last_key_event);
end:
return 0;
}
static int keys_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, keys_proc_show, NULL);
}
static ssize_t keys_proc_write(struct file *file, const char __user *buf,
size_t count, loff_t *pos)
{
char cmd[42];
size_t len;
int value;
len = min(count, sizeof(cmd) - 1);
if (copy_from_user(cmd, buf, len))
return -EFAULT;
cmd[len] = '\0';
if (sscanf(cmd, " hotkey_ready : %i", &value) == 1 && value == 0) {
key_event_valid = 0;
} else {
return -EINVAL;
}
return count;
}
static const struct file_operations keys_proc_fops = {
.owner = THIS_MODULE,
.open = keys_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = keys_proc_write,
};
static int version_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "driver: %s\n", TOSHIBA_ACPI_VERSION);
seq_printf(m, "proc_interface: %d\n", PROC_INTERFACE_VERSION);
return 0;
}
static int version_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, version_proc_show, PDE(inode)->data);
}
static const struct file_operations version_proc_fops = {
.owner = THIS_MODULE,
.open = version_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/* proc and module init
*/
#define PROC_TOSHIBA "toshiba"
static void __init create_toshiba_proc_entries(void)
{
proc_create("lcd", S_IRUGO | S_IWUSR, toshiba_proc_dir, &lcd_proc_fops);
proc_create("video", S_IRUGO | S_IWUSR, toshiba_proc_dir, &video_proc_fops);
proc_create("fan", S_IRUGO | S_IWUSR, toshiba_proc_dir, &fan_proc_fops);
proc_create("keys", S_IRUGO | S_IWUSR, toshiba_proc_dir, &keys_proc_fops);
proc_create("version", S_IRUGO, toshiba_proc_dir, &version_proc_fops);
}
static void remove_toshiba_proc_entries(void)
{
remove_proc_entry("lcd", toshiba_proc_dir);
remove_proc_entry("video", toshiba_proc_dir);
remove_proc_entry("fan", toshiba_proc_dir);
remove_proc_entry("keys", toshiba_proc_dir);
remove_proc_entry("version", toshiba_proc_dir);
}
static const struct backlight_ops toshiba_backlight_data = {
.get_brightness = get_lcd,
.update_status = set_lcd_status,
};
static void toshiba_acpi_notify(acpi_handle handle, u32 event, void *context)
{
u32 hci_result, value;
if (event != 0x80)
return;
do {
hci_read1(HCI_SYSTEM_EVENT, &value, &hci_result);
if (hci_result == HCI_SUCCESS) {
if (value == 0x100)
continue;
/* act on key press; ignore key release */
if (value & 0x80)
continue;
if (!sparse_keymap_report_event(toshiba_acpi.hotkey_dev,
value, 1, true)) {
pr_info("Unknown key %x\n",
value);
}
} else if (hci_result == HCI_NOT_SUPPORTED) {
/* This is a workaround for an unresolved issue on
* some machines where system events sporadically
* become disabled. */
hci_write1(HCI_SYSTEM_EVENT, 1, &hci_result);
pr_notice("Re-enabled hotkeys\n");
}
} while (hci_result != HCI_EMPTY);
}
static int __init toshiba_acpi_setup_keyboard(char *device)
{
acpi_status status;
int error;
status = acpi_get_handle(NULL, device, &toshiba_acpi.handle);
if (ACPI_FAILURE(status)) {
pr_info("Unable to get notification device\n");
return -ENODEV;
}
toshiba_acpi.hotkey_dev = input_allocate_device();
if (!toshiba_acpi.hotkey_dev) {
pr_info("Unable to register input device\n");
return -ENOMEM;
}
toshiba_acpi.hotkey_dev->name = "Toshiba input device";
toshiba_acpi.hotkey_dev->phys = device;
toshiba_acpi.hotkey_dev->id.bustype = BUS_HOST;
error = sparse_keymap_setup(toshiba_acpi.hotkey_dev,
toshiba_acpi_keymap, NULL);
if (error)
goto err_free_dev;
status = acpi_install_notify_handler(toshiba_acpi.handle,
ACPI_DEVICE_NOTIFY, toshiba_acpi_notify, NULL);
if (ACPI_FAILURE(status)) {
pr_info("Unable to install hotkey notification\n");
error = -ENODEV;
goto err_free_keymap;
}
status = acpi_evaluate_object(toshiba_acpi.handle, "ENAB", NULL, NULL);
if (ACPI_FAILURE(status)) {
pr_info("Unable to enable hotkeys\n");
error = -ENODEV;
goto err_remove_notify;
}
error = input_register_device(toshiba_acpi.hotkey_dev);
if (error) {
pr_info("Unable to register input device\n");
goto err_remove_notify;
}
return 0;
err_remove_notify:
acpi_remove_notify_handler(toshiba_acpi.handle,
ACPI_DEVICE_NOTIFY, toshiba_acpi_notify);
err_free_keymap:
sparse_keymap_free(toshiba_acpi.hotkey_dev);
err_free_dev:
input_free_device(toshiba_acpi.hotkey_dev);
toshiba_acpi.hotkey_dev = NULL;
return error;
}
static void toshiba_acpi_exit(void)
{
if (toshiba_acpi.hotkey_dev) {
acpi_remove_notify_handler(toshiba_acpi.handle,
ACPI_DEVICE_NOTIFY, toshiba_acpi_notify);
sparse_keymap_free(toshiba_acpi.hotkey_dev);
input_unregister_device(toshiba_acpi.hotkey_dev);
}
if (toshiba_acpi.bt_rfk) {
rfkill_unregister(toshiba_acpi.bt_rfk);
rfkill_destroy(toshiba_acpi.bt_rfk);
}
if (toshiba_backlight_device)
backlight_device_unregister(toshiba_backlight_device);
remove_toshiba_proc_entries();
if (toshiba_proc_dir)
remove_proc_entry(PROC_TOSHIBA, acpi_root_dir);
if (toshiba_acpi.illumination_installed)
led_classdev_unregister(&toshiba_led);
platform_device_unregister(toshiba_acpi.p_dev);
return;
}
static int __init toshiba_acpi_init(void)
{
u32 hci_result;
bool bt_present;
int ret = 0;
struct backlight_properties props;
if (acpi_disabled)
return -ENODEV;
/* simple device detection: look for HCI method */
if (is_valid_acpi_path(TOSH_INTERFACE_1 GHCI_METHOD)) {
method_hci = TOSH_INTERFACE_1 GHCI_METHOD;
if (toshiba_acpi_setup_keyboard(TOSH_INTERFACE_1))
pr_info("Unable to activate hotkeys\n");
} else if (is_valid_acpi_path(TOSH_INTERFACE_2 GHCI_METHOD)) {
method_hci = TOSH_INTERFACE_2 GHCI_METHOD;
if (toshiba_acpi_setup_keyboard(TOSH_INTERFACE_2))
pr_info("Unable to activate hotkeys\n");
} else
return -ENODEV;
pr_info("Toshiba Laptop ACPI Extras version %s\n",
TOSHIBA_ACPI_VERSION);
pr_info(" HCI method: %s\n", method_hci);
mutex_init(&toshiba_acpi.mutex);
toshiba_acpi.p_dev = platform_device_register_simple("toshiba_acpi",
-1, NULL, 0);
if (IS_ERR(toshiba_acpi.p_dev)) {
ret = PTR_ERR(toshiba_acpi.p_dev);
pr_err("unable to register platform device\n");
toshiba_acpi.p_dev = NULL;
toshiba_acpi_exit();
return ret;
}
force_fan = 0;
key_event_valid = 0;
/* enable event fifo */
hci_write1(HCI_SYSTEM_EVENT, 1, &hci_result);
toshiba_proc_dir = proc_mkdir(PROC_TOSHIBA, acpi_root_dir);
if (!toshiba_proc_dir) {
toshiba_acpi_exit();
return -ENODEV;
} else {
create_toshiba_proc_entries();
}
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = HCI_LCD_BRIGHTNESS_LEVELS - 1;
toshiba_backlight_device = backlight_device_register("toshiba",
&toshiba_acpi.p_dev->dev,
NULL,
&toshiba_backlight_data,
&props);
if (IS_ERR(toshiba_backlight_device)) {
ret = PTR_ERR(toshiba_backlight_device);
pr_err("Could not register toshiba backlight device\n");
toshiba_backlight_device = NULL;
toshiba_acpi_exit();
return ret;
}
/* Register rfkill switch for Bluetooth */
if (hci_get_bt_present(&bt_present) == HCI_SUCCESS && bt_present) {
toshiba_acpi.bt_rfk = rfkill_alloc(toshiba_acpi.bt_name,
&toshiba_acpi.p_dev->dev,
RFKILL_TYPE_BLUETOOTH,
&toshiba_rfk_ops,
&toshiba_acpi);
if (!toshiba_acpi.bt_rfk) {
pr_err("unable to allocate rfkill device\n");
toshiba_acpi_exit();
return -ENOMEM;
}
ret = rfkill_register(toshiba_acpi.bt_rfk);
if (ret) {
pr_err("unable to register rfkill device\n");
rfkill_destroy(toshiba_acpi.bt_rfk);
toshiba_acpi_exit();
return ret;
}
}
toshiba_acpi.illumination_installed = 0;
if (toshiba_illumination_available()) {
if (!led_classdev_register(&(toshiba_acpi.p_dev->dev),
&toshiba_led))
toshiba_acpi.illumination_installed = 1;
}
return 0;
}
module_init(toshiba_acpi_init);
module_exit(toshiba_acpi_exit);
| gpl-2.0 |
NookieDevs/android_kernel_bn_encore | drivers/media/dvb/dvb-usb/m920x.c | 2774 | 26644 | /* DVB USB compliant linux driver for MSI Mega Sky 580 DVB-T USB2.0 receiver
*
* Copyright (C) 2006 Aapo Tahkola (aet@rasterburn.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, version 2.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "m920x.h"
#include "mt352.h"
#include "mt352_priv.h"
#include "qt1010.h"
#include "tda1004x.h"
#include "tda827x.h"
#include <media/tuner.h>
#include "tuner-simple.h"
#include <asm/unaligned.h>
/* debug */
static int dvb_usb_m920x_debug;
module_param_named(debug,dvb_usb_m920x_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=rc (or-able))." DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static int m920x_set_filter(struct dvb_usb_device *d, int type, int idx, int pid);
static inline int m920x_read(struct usb_device *udev, u8 request, u16 value,
u16 index, void *data, int size)
{
int ret;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
request, USB_TYPE_VENDOR | USB_DIR_IN,
value, index, data, size, 2000);
if (ret < 0) {
printk(KERN_INFO "m920x_read = error: %d\n", ret);
return ret;
}
if (ret != size) {
deb("m920x_read = no data\n");
return -EIO;
}
return 0;
}
static inline int m920x_write(struct usb_device *udev, u8 request,
u16 value, u16 index)
{
int ret;
ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
request, USB_TYPE_VENDOR | USB_DIR_OUT,
value, index, NULL, 0, 2000);
return ret;
}
static int m920x_init(struct dvb_usb_device *d, struct m920x_inits *rc_seq)
{
int ret = 0, i, epi, flags = 0;
int adap_enabled[M9206_MAX_ADAPTERS] = { 0 };
/* Remote controller init. */
if (d->props.rc.legacy.rc_query) {
deb("Initialising remote control\n");
while (rc_seq->address) {
if ((ret = m920x_write(d->udev, M9206_CORE,
rc_seq->data,
rc_seq->address)) != 0) {
deb("Initialising remote control failed\n");
return ret;
}
rc_seq++;
}
deb("Initialising remote control success\n");
}
for (i = 0; i < d->props.num_adapters; i++)
flags |= d->adapter[i].props.caps;
/* Some devices(Dposh) might crash if we attempt touch at all. */
if (flags & DVB_USB_ADAP_HAS_PID_FILTER) {
for (i = 0; i < d->props.num_adapters; i++) {
epi = d->adapter[i].props.stream.endpoint - 0x81;
if (epi < 0 || epi >= M9206_MAX_ADAPTERS) {
printk(KERN_INFO "m920x: Unexpected adapter endpoint!\n");
return -EINVAL;
}
adap_enabled[epi] = 1;
}
for (i = 0; i < M9206_MAX_ADAPTERS; i++) {
if (adap_enabled[i])
continue;
if ((ret = m920x_set_filter(d, 0x81 + i, 0, 0x0)) != 0)
return ret;
if ((ret = m920x_set_filter(d, 0x81 + i, 0, 0x02f5)) != 0)
return ret;
}
}
return ret;
}
static int m920x_init_ep(struct usb_interface *intf)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_host_interface *alt;
if ((alt = usb_altnum_to_altsetting(intf, 1)) == NULL) {
deb("No alt found!\n");
return -ENODEV;
}
return usb_set_interface(udev, alt->desc.bInterfaceNumber,
alt->desc.bAlternateSetting);
}
static int m920x_rc_query(struct dvb_usb_device *d, u32 *event, int *state)
{
struct m920x_state *m = d->priv;
int i, ret = 0;
u8 *rc_state;
rc_state = kmalloc(2, GFP_KERNEL);
if (!rc_state)
return -ENOMEM;
if ((ret = m920x_read(d->udev, M9206_CORE, 0x0, M9206_RC_STATE, rc_state, 1)) != 0)
goto out;
if ((ret = m920x_read(d->udev, M9206_CORE, 0x0, M9206_RC_KEY, rc_state + 1, 1)) != 0)
goto out;
for (i = 0; i < d->props.rc.legacy.rc_map_size; i++)
if (rc5_data(&d->props.rc.legacy.rc_map_table[i]) == rc_state[1]) {
*event = d->props.rc.legacy.rc_map_table[i].keycode;
switch(rc_state[0]) {
case 0x80:
*state = REMOTE_NO_KEY_PRESSED;
goto out;
case 0x88: /* framing error or "invalid code" */
case 0x99:
case 0xc0:
case 0xd8:
*state = REMOTE_NO_KEY_PRESSED;
m->rep_count = 0;
goto out;
case 0x93:
case 0x92:
case 0x83: /* pinnacle PCTV310e */
case 0x82:
m->rep_count = 0;
*state = REMOTE_KEY_PRESSED;
goto out;
case 0x91:
case 0x81: /* pinnacle PCTV310e */
/* prevent immediate auto-repeat */
if (++m->rep_count > 2)
*state = REMOTE_KEY_REPEAT;
else
*state = REMOTE_NO_KEY_PRESSED;
goto out;
default:
deb("Unexpected rc state %02x\n", rc_state[0]);
*state = REMOTE_NO_KEY_PRESSED;
goto out;
}
}
if (rc_state[1] != 0)
deb("Unknown rc key %02x\n", rc_state[1]);
*state = REMOTE_NO_KEY_PRESSED;
out:
kfree(rc_state);
return ret;
}
/* I2C */
static int m920x_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i, j;
int ret = 0;
if (!num)
return -EINVAL;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
if (msg[i].flags & (I2C_M_NO_RD_ACK | I2C_M_IGNORE_NAK | I2C_M_TEN) || msg[i].len == 0) {
/* For a 0 byte message, I think sending the address
* to index 0x80|0x40 would be the correct thing to
* do. However, zero byte messages are only used for
* probing, and since we don't know how to get the
* slave's ack, we can't probe. */
ret = -ENOTSUPP;
goto unlock;
}
/* Send START & address/RW bit */
if (!(msg[i].flags & I2C_M_NOSTART)) {
if ((ret = m920x_write(d->udev, M9206_I2C,
(msg[i].addr << 1) |
(msg[i].flags & I2C_M_RD ? 0x01 : 0), 0x80)) != 0)
goto unlock;
/* Should check for ack here, if we knew how. */
}
if (msg[i].flags & I2C_M_RD) {
for (j = 0; j < msg[i].len; j++) {
/* Last byte of transaction?
* Send STOP, otherwise send ACK. */
int stop = (i+1 == num && j+1 == msg[i].len) ? 0x40 : 0x01;
if ((ret = m920x_read(d->udev, M9206_I2C, 0x0,
0x20 | stop,
&msg[i].buf[j], 1)) != 0)
goto unlock;
}
} else {
for (j = 0; j < msg[i].len; j++) {
/* Last byte of transaction? Then send STOP. */
int stop = (i+1 == num && j+1 == msg[i].len) ? 0x40 : 0x00;
if ((ret = m920x_write(d->udev, M9206_I2C, msg[i].buf[j], stop)) != 0)
goto unlock;
/* Should check for ack here too. */
}
}
}
ret = num;
unlock:
mutex_unlock(&d->i2c_mutex);
return ret;
}
static u32 m920x_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm m920x_i2c_algo = {
.master_xfer = m920x_i2c_xfer,
.functionality = m920x_i2c_func,
};
/* pid filter */
static int m920x_set_filter(struct dvb_usb_device *d, int type, int idx, int pid)
{
int ret = 0;
if (pid >= 0x8000)
return -EINVAL;
pid |= 0x8000;
if ((ret = m920x_write(d->udev, M9206_FILTER, pid, (type << 8) | (idx * 4) )) != 0)
return ret;
if ((ret = m920x_write(d->udev, M9206_FILTER, 0, (type << 8) | (idx * 4) )) != 0)
return ret;
return ret;
}
static int m920x_update_filters(struct dvb_usb_adapter *adap)
{
struct m920x_state *m = adap->dev->priv;
int enabled = m->filtering_enabled[adap->id];
int i, ret = 0, filter = 0;
int ep = adap->props.stream.endpoint;
for (i = 0; i < M9206_MAX_FILTERS; i++)
if (m->filters[adap->id][i] == 8192)
enabled = 0;
/* Disable all filters */
if ((ret = m920x_set_filter(adap->dev, ep, 1, enabled)) != 0)
return ret;
for (i = 0; i < M9206_MAX_FILTERS; i++)
if ((ret = m920x_set_filter(adap->dev, ep, i + 2, 0)) != 0)
return ret;
/* Set */
if (enabled) {
for (i = 0; i < M9206_MAX_FILTERS; i++) {
if (m->filters[adap->id][i] == 0)
continue;
if ((ret = m920x_set_filter(adap->dev, ep, filter + 2, m->filters[adap->id][i])) != 0)
return ret;
filter++;
}
}
return ret;
}
static int m920x_pid_filter_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
struct m920x_state *m = adap->dev->priv;
m->filtering_enabled[adap->id] = onoff ? 1 : 0;
return m920x_update_filters(adap);
}
static int m920x_pid_filter(struct dvb_usb_adapter *adap, int index, u16 pid, int onoff)
{
struct m920x_state *m = adap->dev->priv;
m->filters[adap->id][index] = onoff ? pid : 0;
return m920x_update_filters(adap);
}
static int m920x_firmware_download(struct usb_device *udev, const struct firmware *fw)
{
u16 value, index, size;
u8 *read, *buff;
int i, pass, ret = 0;
buff = kmalloc(65536, GFP_KERNEL);
if (buff == NULL)
return -ENOMEM;
read = kmalloc(4, GFP_KERNEL);
if (!read) {
kfree(buff);
return -ENOMEM;
}
if ((ret = m920x_read(udev, M9206_FILTER, 0x0, 0x8000, read, 4)) != 0)
goto done;
deb("%x %x %x %x\n", read[0], read[1], read[2], read[3]);
if ((ret = m920x_read(udev, M9206_FW, 0x0, 0x0, read, 1)) != 0)
goto done;
deb("%x\n", read[0]);
for (pass = 0; pass < 2; pass++) {
for (i = 0; i + (sizeof(u16) * 3) < fw->size;) {
value = get_unaligned_le16(fw->data + i);
i += sizeof(u16);
index = get_unaligned_le16(fw->data + i);
i += sizeof(u16);
size = get_unaligned_le16(fw->data + i);
i += sizeof(u16);
if (pass == 1) {
/* Will stall if using fw->data ... */
memcpy(buff, fw->data + i, size);
ret = usb_control_msg(udev, usb_sndctrlpipe(udev,0),
M9206_FW,
USB_TYPE_VENDOR | USB_DIR_OUT,
value, index, buff, size, 20);
if (ret != size) {
deb("error while uploading fw!\n");
ret = -EIO;
goto done;
}
msleep(3);
}
i += size;
}
if (i != fw->size) {
deb("bad firmware file!\n");
ret = -EINVAL;
goto done;
}
}
msleep(36);
/* m920x will disconnect itself from the bus after this. */
(void) m920x_write(udev, M9206_CORE, 0x01, M9206_FW_GO);
deb("firmware uploaded!\n");
done:
kfree(read);
kfree(buff);
return ret;
}
/* Callbacks for DVB USB */
static int m920x_identify_state(struct usb_device *udev,
struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc,
int *cold)
{
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(usb_ifnum_to_if(udev, 0), 1);
*cold = (alt == NULL) ? 1 : 0;
return 0;
}
/* demod configurations */
static int m920x_mt352_demod_init(struct dvb_frontend *fe)
{
int ret;
u8 config[] = { CONFIG, 0x3d };
u8 clock[] = { CLOCK_CTL, 0x30 };
u8 reset[] = { RESET, 0x80 };
u8 adc_ctl[] = { ADC_CTL_1, 0x40 };
u8 agc[] = { AGC_TARGET, 0x1c, 0x20 };
u8 sec_agc[] = { 0x69, 0x00, 0xff, 0xff, 0x40, 0xff, 0x00, 0x40, 0x40 };
u8 unk1[] = { 0x93, 0x1a };
u8 unk2[] = { 0xb5, 0x7a };
deb("Demod init!\n");
if ((ret = mt352_write(fe, config, ARRAY_SIZE(config))) != 0)
return ret;
if ((ret = mt352_write(fe, clock, ARRAY_SIZE(clock))) != 0)
return ret;
if ((ret = mt352_write(fe, reset, ARRAY_SIZE(reset))) != 0)
return ret;
if ((ret = mt352_write(fe, adc_ctl, ARRAY_SIZE(adc_ctl))) != 0)
return ret;
if ((ret = mt352_write(fe, agc, ARRAY_SIZE(agc))) != 0)
return ret;
if ((ret = mt352_write(fe, sec_agc, ARRAY_SIZE(sec_agc))) != 0)
return ret;
if ((ret = mt352_write(fe, unk1, ARRAY_SIZE(unk1))) != 0)
return ret;
if ((ret = mt352_write(fe, unk2, ARRAY_SIZE(unk2))) != 0)
return ret;
return 0;
}
static struct mt352_config m920x_mt352_config = {
.demod_address = 0x0f,
.no_tuner = 1,
.demod_init = m920x_mt352_demod_init,
};
static struct tda1004x_config m920x_tda10046_08_config = {
.demod_address = 0x08,
.invert = 0,
.invert_oclk = 0,
.ts_mode = TDA10046_TS_SERIAL,
.xtal_freq = TDA10046_XTAL_16M,
.if_freq = TDA10046_FREQ_045,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GPTRI,
.request_firmware = NULL,
};
static struct tda1004x_config m920x_tda10046_0b_config = {
.demod_address = 0x0b,
.invert = 0,
.invert_oclk = 0,
.ts_mode = TDA10046_TS_SERIAL,
.xtal_freq = TDA10046_XTAL_16M,
.if_freq = TDA10046_FREQ_045,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GPTRI,
.request_firmware = NULL, /* uses firmware EEPROM */
};
/* tuner configurations */
static struct qt1010_config m920x_qt1010_config = {
.i2c_address = 0x62
};
/* Callbacks for DVB USB */
static int m920x_mt352_frontend_attach(struct dvb_usb_adapter *adap)
{
deb("%s\n",__func__);
if ((adap->fe = dvb_attach(mt352_attach,
&m920x_mt352_config,
&adap->dev->i2c_adap)) == NULL)
return -EIO;
return 0;
}
static int m920x_tda10046_08_frontend_attach(struct dvb_usb_adapter *adap)
{
deb("%s\n",__func__);
if ((adap->fe = dvb_attach(tda10046_attach,
&m920x_tda10046_08_config,
&adap->dev->i2c_adap)) == NULL)
return -EIO;
return 0;
}
static int m920x_tda10046_0b_frontend_attach(struct dvb_usb_adapter *adap)
{
deb("%s\n",__func__);
if ((adap->fe = dvb_attach(tda10046_attach,
&m920x_tda10046_0b_config,
&adap->dev->i2c_adap)) == NULL)
return -EIO;
return 0;
}
static int m920x_qt1010_tuner_attach(struct dvb_usb_adapter *adap)
{
deb("%s\n",__func__);
if (dvb_attach(qt1010_attach, adap->fe, &adap->dev->i2c_adap, &m920x_qt1010_config) == NULL)
return -ENODEV;
return 0;
}
static int m920x_tda8275_60_tuner_attach(struct dvb_usb_adapter *adap)
{
deb("%s\n",__func__);
if (dvb_attach(tda827x_attach, adap->fe, 0x60, &adap->dev->i2c_adap, NULL) == NULL)
return -ENODEV;
return 0;
}
static int m920x_tda8275_61_tuner_attach(struct dvb_usb_adapter *adap)
{
deb("%s\n",__func__);
if (dvb_attach(tda827x_attach, adap->fe, 0x61, &adap->dev->i2c_adap, NULL) == NULL)
return -ENODEV;
return 0;
}
static int m920x_fmd1216me_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe,
&adap->dev->i2c_adap, 0x61,
TUNER_PHILIPS_FMD1216ME_MK3);
return 0;
}
/* device-specific initialization */
static struct m920x_inits megasky_rc_init [] = {
{ M9206_RC_INIT2, 0xa8 },
{ M9206_RC_INIT1, 0x51 },
{ } /* terminating entry */
};
static struct m920x_inits tvwalkertwin_rc_init [] = {
{ M9206_RC_INIT2, 0x00 },
{ M9206_RC_INIT1, 0xef },
{ 0xff28, 0x00 },
{ 0xff23, 0x00 },
{ 0xff21, 0x30 },
{ } /* terminating entry */
};
static struct m920x_inits pinnacle310e_init[] = {
/* without these the tuner don't work */
{ 0xff20, 0x9b },
{ 0xff22, 0x70 },
/* rc settings */
{ 0xff50, 0x80 },
{ M9206_RC_INIT1, 0x00 },
{ M9206_RC_INIT2, 0xff },
{ } /* terminating entry */
};
/* ir keymaps */
static struct rc_map_table rc_map_megasky_table[] = {
{ 0x0012, KEY_POWER },
{ 0x001e, KEY_CYCLEWINDOWS }, /* min/max */
{ 0x0002, KEY_CHANNELUP },
{ 0x0005, KEY_CHANNELDOWN },
{ 0x0003, KEY_VOLUMEUP },
{ 0x0006, KEY_VOLUMEDOWN },
{ 0x0004, KEY_MUTE },
{ 0x0007, KEY_OK }, /* TS */
{ 0x0008, KEY_STOP },
{ 0x0009, KEY_MENU }, /* swap */
{ 0x000a, KEY_REWIND },
{ 0x001b, KEY_PAUSE },
{ 0x001f, KEY_FASTFORWARD },
{ 0x000c, KEY_RECORD },
{ 0x000d, KEY_CAMERA }, /* screenshot */
{ 0x000e, KEY_COFFEE }, /* "MTS" */
};
static struct rc_map_table rc_map_tvwalkertwin_table[] = {
{ 0x0001, KEY_ZOOM }, /* Full Screen */
{ 0x0002, KEY_CAMERA }, /* snapshot */
{ 0x0003, KEY_MUTE },
{ 0x0004, KEY_REWIND },
{ 0x0005, KEY_PLAYPAUSE }, /* Play/Pause */
{ 0x0006, KEY_FASTFORWARD },
{ 0x0007, KEY_RECORD },
{ 0x0008, KEY_STOP },
{ 0x0009, KEY_TIME }, /* Timeshift */
{ 0x000c, KEY_COFFEE }, /* Recall */
{ 0x000e, KEY_CHANNELUP },
{ 0x0012, KEY_POWER },
{ 0x0015, KEY_MENU }, /* source */
{ 0x0018, KEY_CYCLEWINDOWS }, /* TWIN PIP */
{ 0x001a, KEY_CHANNELDOWN },
{ 0x001b, KEY_VOLUMEDOWN },
{ 0x001e, KEY_VOLUMEUP },
};
static struct rc_map_table rc_map_pinnacle310e_table[] = {
{ 0x16, KEY_POWER },
{ 0x17, KEY_FAVORITES },
{ 0x0f, KEY_TEXT },
{ 0x48, KEY_PROGRAM }, /* preview */
{ 0x1c, KEY_EPG },
{ 0x04, KEY_LIST }, /* record list */
{ 0x03, KEY_1 },
{ 0x01, KEY_2 },
{ 0x06, KEY_3 },
{ 0x09, KEY_4 },
{ 0x1d, KEY_5 },
{ 0x1f, KEY_6 },
{ 0x0d, KEY_7 },
{ 0x19, KEY_8 },
{ 0x1b, KEY_9 },
{ 0x15, KEY_0 },
{ 0x0c, KEY_CANCEL },
{ 0x4a, KEY_CLEAR },
{ 0x13, KEY_BACK },
{ 0x00, KEY_TAB },
{ 0x4b, KEY_UP },
{ 0x4e, KEY_LEFT },
{ 0x52, KEY_RIGHT },
{ 0x51, KEY_DOWN },
{ 0x4f, KEY_ENTER }, /* could also be KEY_OK */
{ 0x1e, KEY_VOLUMEUP },
{ 0x0a, KEY_VOLUMEDOWN },
{ 0x05, KEY_CHANNELUP },
{ 0x02, KEY_CHANNELDOWN },
{ 0x11, KEY_RECORD },
{ 0x14, KEY_PLAY },
{ 0x4c, KEY_PAUSE },
{ 0x1a, KEY_STOP },
{ 0x40, KEY_REWIND },
{ 0x12, KEY_FASTFORWARD },
{ 0x41, KEY_PREVIOUSSONG }, /* Replay */
{ 0x42, KEY_NEXTSONG }, /* Skip */
{ 0x54, KEY_CAMERA }, /* Capture */
/* { 0x50, KEY_SAP }, */ /* Sap */
{ 0x47, KEY_CYCLEWINDOWS }, /* Pip */
{ 0x4d, KEY_SCREEN }, /* FullScreen */
{ 0x08, KEY_SUBTITLE },
{ 0x0e, KEY_MUTE },
/* { 0x49, KEY_LR }, */ /* L/R */
{ 0x07, KEY_SLEEP }, /* Hibernate */
{ 0x08, KEY_VIDEO }, /* A/V */
{ 0x0e, KEY_MENU }, /* Recall */
{ 0x45, KEY_ZOOMIN },
{ 0x46, KEY_ZOOMOUT },
{ 0x18, KEY_RED }, /* Red */
{ 0x53, KEY_GREEN }, /* Green */
{ 0x5e, KEY_YELLOW }, /* Yellow */
{ 0x5f, KEY_BLUE }, /* Blue */
};
/* DVB USB Driver stuff */
static struct dvb_usb_device_properties megasky_properties;
static struct dvb_usb_device_properties digivox_mini_ii_properties;
static struct dvb_usb_device_properties tvwalkertwin_properties;
static struct dvb_usb_device_properties dposh_properties;
static struct dvb_usb_device_properties pinnacle_pctv310e_properties;
static int m920x_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct dvb_usb_device *d = NULL;
int ret;
struct m920x_inits *rc_init_seq = NULL;
int bInterfaceNumber = intf->cur_altsetting->desc.bInterfaceNumber;
deb("Probing for m920x device at interface %d\n", bInterfaceNumber);
if (bInterfaceNumber == 0) {
/* Single-tuner device, or first interface on
* multi-tuner device
*/
ret = dvb_usb_device_init(intf, &megasky_properties,
THIS_MODULE, &d, adapter_nr);
if (ret == 0) {
rc_init_seq = megasky_rc_init;
goto found;
}
ret = dvb_usb_device_init(intf, &digivox_mini_ii_properties,
THIS_MODULE, &d, adapter_nr);
if (ret == 0) {
/* No remote control, so no rc_init_seq */
goto found;
}
/* This configures both tuners on the TV Walker Twin */
ret = dvb_usb_device_init(intf, &tvwalkertwin_properties,
THIS_MODULE, &d, adapter_nr);
if (ret == 0) {
rc_init_seq = tvwalkertwin_rc_init;
goto found;
}
ret = dvb_usb_device_init(intf, &dposh_properties,
THIS_MODULE, &d, adapter_nr);
if (ret == 0) {
/* Remote controller not supported yet. */
goto found;
}
ret = dvb_usb_device_init(intf, &pinnacle_pctv310e_properties,
THIS_MODULE, &d, adapter_nr);
if (ret == 0) {
rc_init_seq = pinnacle310e_init;
goto found;
}
return ret;
} else {
/* Another interface on a multi-tuner device */
/* The LifeView TV Walker Twin gets here, but struct
* tvwalkertwin_properties already configured both
* tuners, so there is nothing for us to do here
*/
}
found:
if ((ret = m920x_init_ep(intf)) < 0)
return ret;
if (d && (ret = m920x_init(d, rc_init_seq)) != 0)
return ret;
return ret;
}
static struct usb_device_id m920x_table [] = {
{ USB_DEVICE(USB_VID_MSI, USB_PID_MSI_MEGASKY580) },
{ USB_DEVICE(USB_VID_ANUBIS_ELECTRONIC,
USB_PID_MSI_DIGI_VOX_MINI_II) },
{ USB_DEVICE(USB_VID_ANUBIS_ELECTRONIC,
USB_PID_LIFEVIEW_TV_WALKER_TWIN_COLD) },
{ USB_DEVICE(USB_VID_ANUBIS_ELECTRONIC,
USB_PID_LIFEVIEW_TV_WALKER_TWIN_WARM) },
{ USB_DEVICE(USB_VID_DPOSH, USB_PID_DPOSH_M9206_COLD) },
{ USB_DEVICE(USB_VID_DPOSH, USB_PID_DPOSH_M9206_WARM) },
{ USB_DEVICE(USB_VID_VISIONPLUS, USB_PID_PINNACLE_PCTV310E) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, m920x_table);
static struct dvb_usb_device_properties megasky_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-megasky-02.fw",
.download_firmware = m920x_firmware_download,
.rc.legacy = {
.rc_interval = 100,
.rc_map_table = rc_map_megasky_table,
.rc_map_size = ARRAY_SIZE(rc_map_megasky_table),
.rc_query = m920x_rc_query,
},
.size_of_priv = sizeof(struct m920x_state),
.identify_state = m920x_identify_state,
.num_adapters = 1,
.adapter = {{
.caps = DVB_USB_ADAP_HAS_PID_FILTER |
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 8,
.pid_filter = m920x_pid_filter,
.pid_filter_ctrl = m920x_pid_filter_ctrl,
.frontend_attach = m920x_mt352_frontend_attach,
.tuner_attach = m920x_qt1010_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 8,
.endpoint = 0x81,
.u = {
.bulk = {
.buffersize = 512,
}
}
},
}},
.i2c_algo = &m920x_i2c_algo,
.num_device_descs = 1,
.devices = {
{ "MSI Mega Sky 580 DVB-T USB2.0",
{ &m920x_table[0], NULL },
{ NULL },
}
}
};
static struct dvb_usb_device_properties digivox_mini_ii_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-digivox-02.fw",
.download_firmware = m920x_firmware_download,
.size_of_priv = sizeof(struct m920x_state),
.identify_state = m920x_identify_state,
.num_adapters = 1,
.adapter = {{
.caps = DVB_USB_ADAP_HAS_PID_FILTER |
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 8,
.pid_filter = m920x_pid_filter,
.pid_filter_ctrl = m920x_pid_filter_ctrl,
.frontend_attach = m920x_tda10046_08_frontend_attach,
.tuner_attach = m920x_tda8275_60_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 8,
.endpoint = 0x81,
.u = {
.bulk = {
.buffersize = 0x4000,
}
}
},
}},
.i2c_algo = &m920x_i2c_algo,
.num_device_descs = 1,
.devices = {
{ "MSI DIGI VOX mini II DVB-T USB2.0",
{ &m920x_table[1], NULL },
{ NULL },
},
}
};
/* LifeView TV Walker Twin support by Nick Andrew <nick@nick-andrew.net>
*
* LifeView TV Walker Twin has 1 x M9206, 2 x TDA10046, 2 x TDA8275A
* TDA10046 #0 is located at i2c address 0x08
* TDA10046 #1 is located at i2c address 0x0b
* TDA8275A #0 is located at i2c address 0x60
* TDA8275A #1 is located at i2c address 0x61
*/
static struct dvb_usb_device_properties tvwalkertwin_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-tvwalkert.fw",
.download_firmware = m920x_firmware_download,
.rc.legacy = {
.rc_interval = 100,
.rc_map_table = rc_map_tvwalkertwin_table,
.rc_map_size = ARRAY_SIZE(rc_map_tvwalkertwin_table),
.rc_query = m920x_rc_query,
},
.size_of_priv = sizeof(struct m920x_state),
.identify_state = m920x_identify_state,
.num_adapters = 2,
.adapter = {{
.caps = DVB_USB_ADAP_HAS_PID_FILTER |
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 8,
.pid_filter = m920x_pid_filter,
.pid_filter_ctrl = m920x_pid_filter_ctrl,
.frontend_attach = m920x_tda10046_08_frontend_attach,
.tuner_attach = m920x_tda8275_60_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 8,
.endpoint = 0x81,
.u = {
.bulk = {
.buffersize = 512,
}
}
}},{
.caps = DVB_USB_ADAP_HAS_PID_FILTER |
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 8,
.pid_filter = m920x_pid_filter,
.pid_filter_ctrl = m920x_pid_filter_ctrl,
.frontend_attach = m920x_tda10046_0b_frontend_attach,
.tuner_attach = m920x_tda8275_61_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 8,
.endpoint = 0x82,
.u = {
.bulk = {
.buffersize = 512,
}
}
},
}},
.i2c_algo = &m920x_i2c_algo,
.num_device_descs = 1,
.devices = {
{ .name = "LifeView TV Walker Twin DVB-T USB2.0",
.cold_ids = { &m920x_table[2], NULL },
.warm_ids = { &m920x_table[3], NULL },
},
}
};
static struct dvb_usb_device_properties dposh_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-dposh-01.fw",
.download_firmware = m920x_firmware_download,
.size_of_priv = sizeof(struct m920x_state),
.identify_state = m920x_identify_state,
.num_adapters = 1,
.adapter = {{
/* Hardware pid filters don't work with this device/firmware */
.frontend_attach = m920x_mt352_frontend_attach,
.tuner_attach = m920x_qt1010_tuner_attach,
.stream = {
.type = USB_BULK,
.count = 8,
.endpoint = 0x81,
.u = {
.bulk = {
.buffersize = 512,
}
}
},
}},
.i2c_algo = &m920x_i2c_algo,
.num_device_descs = 1,
.devices = {
{ .name = "Dposh DVB-T USB2.0",
.cold_ids = { &m920x_table[4], NULL },
.warm_ids = { &m920x_table[5], NULL },
},
}
};
static struct dvb_usb_device_properties pinnacle_pctv310e_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.download_firmware = NULL,
.rc.legacy = {
.rc_interval = 100,
.rc_map_table = rc_map_pinnacle310e_table,
.rc_map_size = ARRAY_SIZE(rc_map_pinnacle310e_table),
.rc_query = m920x_rc_query,
},
.size_of_priv = sizeof(struct m920x_state),
.identify_state = m920x_identify_state,
.num_adapters = 1,
.adapter = {{
.caps = DVB_USB_ADAP_HAS_PID_FILTER |
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 8,
.pid_filter = m920x_pid_filter,
.pid_filter_ctrl = m920x_pid_filter_ctrl,
.frontend_attach = m920x_mt352_frontend_attach,
.tuner_attach = m920x_fmd1216me_tuner_attach,
.stream = {
.type = USB_ISOC,
.count = 5,
.endpoint = 0x84,
.u = {
.isoc = {
.framesperurb = 128,
.framesize = 564,
.interval = 1,
}
}
},
} },
.i2c_algo = &m920x_i2c_algo,
.num_device_descs = 1,
.devices = {
{ "Pinnacle PCTV 310e",
{ &m920x_table[6], NULL },
{ NULL },
}
}
};
static struct usb_driver m920x_driver = {
.name = "dvb_usb_m920x",
.probe = m920x_probe,
.disconnect = dvb_usb_device_exit,
.id_table = m920x_table,
};
/* module stuff */
static int __init m920x_module_init(void)
{
int ret;
if ((ret = usb_register(&m920x_driver))) {
err("usb_register failed. Error number %d", ret);
return ret;
}
return 0;
}
static void __exit m920x_module_exit(void)
{
/* deregister this driver from the USB subsystem */
usb_deregister(&m920x_driver);
}
module_init (m920x_module_init);
module_exit (m920x_module_exit);
MODULE_AUTHOR("Aapo Tahkola <aet@rasterburn.org>");
MODULE_DESCRIPTION("DVB Driver for ULI M920x");
MODULE_VERSION("0.1");
MODULE_LICENSE("GPL");
/*
* Local variables:
* c-basic-offset: 8
*/
| gpl-2.0 |
AscendP6U06/android_kernel_huawei_hwp6_u06 | arch/mips/dec/kn02xa-berr.c | 4566 | 3969 | /*
* Bus error event handling code for 5000-series systems equipped
* with parity error detection logic, i.e. DECstation/DECsystem
* 5000/120, /125, /133 (KN02-BA), 5000/150 (KN04-BA) and Personal
* DECstation/DECsystem 5000/20, /25, /33 (KN02-CA), 5000/50
* (KN04-CA) systems.
*
* Copyright (c) 2005 Maciej W. Rozycki
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <asm/addrspace.h>
#include <asm/irq_regs.h>
#include <asm/ptrace.h>
#include <asm/system.h>
#include <asm/traps.h>
#include <asm/dec/kn02ca.h>
#include <asm/dec/kn02xa.h>
#include <asm/dec/kn05.h>
static inline void dec_kn02xa_be_ack(void)
{
volatile u32 *mer = (void *)CKSEG1ADDR(KN02XA_MER);
volatile u32 *mem_intr = (void *)CKSEG1ADDR(KN02XA_MEM_INTR);
*mer = KN02CA_MER_INTR; /* Clear errors; keep the ARC IRQ. */
*mem_intr = 0; /* Any write clears the bus IRQ. */
iob();
}
static int dec_kn02xa_be_backend(struct pt_regs *regs, int is_fixup,
int invoker)
{
volatile u32 *kn02xa_mer = (void *)CKSEG1ADDR(KN02XA_MER);
volatile u32 *kn02xa_ear = (void *)CKSEG1ADDR(KN02XA_EAR);
static const char excstr[] = "exception";
static const char intstr[] = "interrupt";
static const char cpustr[] = "CPU";
static const char mreadstr[] = "memory read";
static const char readstr[] = "read";
static const char writestr[] = "write";
static const char timestr[] = "timeout";
static const char paritystr[] = "parity error";
static const char lanestat[][4] = { " OK", "BAD" };
const char *kind, *agent, *cycle, *event;
unsigned long address;
u32 mer = *kn02xa_mer;
u32 ear = *kn02xa_ear;
int action = MIPS_BE_FATAL;
/* Ack ASAP, so that any subsequent errors get caught. */
dec_kn02xa_be_ack();
kind = invoker ? intstr : excstr;
/* No DMA errors? */
agent = cpustr;
address = ear & KN02XA_EAR_ADDRESS;
/* Low 256MB is decoded as memory, high -- as TC. */
if (address < 0x10000000) {
cycle = mreadstr;
event = paritystr;
} else {
cycle = invoker ? writestr : readstr;
event = timestr;
}
if (is_fixup)
action = MIPS_BE_FIXUP;
if (action != MIPS_BE_FIXUP)
printk(KERN_ALERT "Bus error %s: %s %s %s at %#010lx\n",
kind, agent, cycle, event, address);
if (action != MIPS_BE_FIXUP && address < 0x10000000)
printk(KERN_ALERT " Byte lane status %#3x -- "
"#3: %s, #2: %s, #1: %s, #0: %s\n",
(mer & KN02XA_MER_BYTERR) >> 8,
lanestat[(mer & KN02XA_MER_BYTERR_3) != 0],
lanestat[(mer & KN02XA_MER_BYTERR_2) != 0],
lanestat[(mer & KN02XA_MER_BYTERR_1) != 0],
lanestat[(mer & KN02XA_MER_BYTERR_0) != 0]);
return action;
}
int dec_kn02xa_be_handler(struct pt_regs *regs, int is_fixup)
{
return dec_kn02xa_be_backend(regs, is_fixup, 0);
}
irqreturn_t dec_kn02xa_be_interrupt(int irq, void *dev_id)
{
struct pt_regs *regs = get_irq_regs();
int action = dec_kn02xa_be_backend(regs, 0, 1);
if (action == MIPS_BE_DISCARD)
return IRQ_HANDLED;
/*
* FIXME: Find the affected processes and kill them, otherwise
* we must die.
*
* The interrupt is asynchronously delivered thus EPC and RA
* may be irrelevant, but are printed for a reference.
*/
printk(KERN_ALERT "Fatal bus interrupt, epc == %08lx, ra == %08lx\n",
regs->cp0_epc, regs->regs[31]);
die("Unrecoverable bus error", regs);
}
void __init dec_kn02xa_be_init(void)
{
volatile u32 *mbcs = (void *)CKSEG1ADDR(KN4K_SLOT_BASE + KN4K_MB_CSR);
/* For KN04 we need to make sure EE (?) is enabled in the MB. */
if (current_cpu_type() == CPU_R4000SC)
*mbcs |= KN4K_MB_CSR_EE;
fast_iob();
/* Clear any leftover errors from the firmware. */
dec_kn02xa_be_ack();
}
| gpl-2.0 |
LeEco-MSM8996-Development/android_kernel_leeco_msm8996 | drivers/isdn/gigaset/interface.c | 4566 | 13971 | /*
* interface to user space for the gigaset driver
*
* Copyright (c) 2004 by Hansjoerg Lipp <hjlipp@web.de>
*
* =====================================================================
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
* =====================================================================
*/
#include "gigaset.h"
#include <linux/gigaset_dev.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
/*** our ioctls ***/
static int if_lock(struct cardstate *cs, int *arg)
{
int cmd = *arg;
gig_dbg(DEBUG_IF, "%u: if_lock (%d)", cs->minor_index, cmd);
if (cmd > 1)
return -EINVAL;
if (cmd < 0) {
*arg = cs->mstate == MS_LOCKED;
return 0;
}
if (!cmd && cs->mstate == MS_LOCKED && cs->connected) {
cs->ops->set_modem_ctrl(cs, 0, TIOCM_DTR | TIOCM_RTS);
cs->ops->baud_rate(cs, B115200);
cs->ops->set_line_ctrl(cs, CS8);
cs->control_state = TIOCM_DTR | TIOCM_RTS;
}
cs->waiting = 1;
if (!gigaset_add_event(cs, &cs->at_state, EV_IF_LOCK,
NULL, cmd, NULL)) {
cs->waiting = 0;
return -ENOMEM;
}
gigaset_schedule_event(cs);
wait_event(cs->waitqueue, !cs->waiting);
if (cs->cmd_result >= 0) {
*arg = cs->cmd_result;
return 0;
}
return cs->cmd_result;
}
static int if_version(struct cardstate *cs, unsigned arg[4])
{
static const unsigned version[4] = GIG_VERSION;
static const unsigned compat[4] = GIG_COMPAT;
unsigned cmd = arg[0];
gig_dbg(DEBUG_IF, "%u: if_version (%d)", cs->minor_index, cmd);
switch (cmd) {
case GIGVER_DRIVER:
memcpy(arg, version, sizeof version);
return 0;
case GIGVER_COMPAT:
memcpy(arg, compat, sizeof compat);
return 0;
case GIGVER_FWBASE:
cs->waiting = 1;
if (!gigaset_add_event(cs, &cs->at_state, EV_IF_VER,
NULL, 0, arg)) {
cs->waiting = 0;
return -ENOMEM;
}
gigaset_schedule_event(cs);
wait_event(cs->waitqueue, !cs->waiting);
if (cs->cmd_result >= 0)
return 0;
return cs->cmd_result;
default:
return -EINVAL;
}
}
static int if_config(struct cardstate *cs, int *arg)
{
gig_dbg(DEBUG_IF, "%u: if_config (%d)", cs->minor_index, *arg);
if (*arg != 1)
return -EINVAL;
if (cs->mstate != MS_LOCKED)
return -EBUSY;
if (!cs->connected) {
pr_err("%s: not connected\n", __func__);
return -ENODEV;
}
*arg = 0;
return gigaset_enterconfigmode(cs);
}
/*** the terminal driver ***/
static int if_open(struct tty_struct *tty, struct file *filp)
{
struct cardstate *cs;
gig_dbg(DEBUG_IF, "%d+%d: %s()",
tty->driver->minor_start, tty->index, __func__);
cs = gigaset_get_cs_by_tty(tty);
if (!cs || !try_module_get(cs->driver->owner))
return -ENODEV;
if (mutex_lock_interruptible(&cs->mutex)) {
module_put(cs->driver->owner);
return -ERESTARTSYS;
}
tty->driver_data = cs;
++cs->port.count;
if (cs->port.count == 1) {
tty_port_tty_set(&cs->port, tty);
cs->port.low_latency = 1;
}
mutex_unlock(&cs->mutex);
return 0;
}
static void if_close(struct tty_struct *tty, struct file *filp)
{
struct cardstate *cs = tty->driver_data;
if (!cs) { /* happens if we didn't find cs in open */
gig_dbg(DEBUG_IF, "%s: no cardstate", __func__);
return;
}
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
mutex_lock(&cs->mutex);
if (!cs->connected)
gig_dbg(DEBUG_IF, "not connected"); /* nothing to do */
else if (!cs->port.count)
dev_warn(cs->dev, "%s: device not opened\n", __func__);
else if (!--cs->port.count)
tty_port_tty_set(&cs->port, NULL);
mutex_unlock(&cs->mutex);
module_put(cs->driver->owner);
}
static int if_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct cardstate *cs = tty->driver_data;
int retval = -ENODEV;
int int_arg;
unsigned char buf[6];
unsigned version[4];
gig_dbg(DEBUG_IF, "%u: %s(0x%x)", cs->minor_index, __func__, cmd);
if (mutex_lock_interruptible(&cs->mutex))
return -ERESTARTSYS;
if (!cs->connected) {
gig_dbg(DEBUG_IF, "not connected");
retval = -ENODEV;
} else {
retval = 0;
switch (cmd) {
case GIGASET_REDIR:
retval = get_user(int_arg, (int __user *) arg);
if (retval >= 0)
retval = if_lock(cs, &int_arg);
if (retval >= 0)
retval = put_user(int_arg, (int __user *) arg);
break;
case GIGASET_CONFIG:
retval = get_user(int_arg, (int __user *) arg);
if (retval >= 0)
retval = if_config(cs, &int_arg);
if (retval >= 0)
retval = put_user(int_arg, (int __user *) arg);
break;
case GIGASET_BRKCHARS:
retval = copy_from_user(&buf,
(const unsigned char __user *) arg, 6)
? -EFAULT : 0;
if (retval >= 0) {
gigaset_dbg_buffer(DEBUG_IF, "GIGASET_BRKCHARS",
6, (const unsigned char *) arg);
retval = cs->ops->brkchars(cs, buf);
}
break;
case GIGASET_VERSION:
retval = copy_from_user(version,
(unsigned __user *) arg, sizeof version)
? -EFAULT : 0;
if (retval >= 0)
retval = if_version(cs, version);
if (retval >= 0)
retval = copy_to_user((unsigned __user *) arg,
version, sizeof version)
? -EFAULT : 0;
break;
default:
gig_dbg(DEBUG_IF, "%s: arg not supported - 0x%04x",
__func__, cmd);
retval = -ENOIOCTLCMD;
}
}
mutex_unlock(&cs->mutex);
return retval;
}
static int if_tiocmget(struct tty_struct *tty)
{
struct cardstate *cs = tty->driver_data;
int retval;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
if (mutex_lock_interruptible(&cs->mutex))
return -ERESTARTSYS;
retval = cs->control_state & (TIOCM_RTS | TIOCM_DTR);
mutex_unlock(&cs->mutex);
return retval;
}
static int if_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct cardstate *cs = tty->driver_data;
int retval;
unsigned mc;
gig_dbg(DEBUG_IF, "%u: %s(0x%x, 0x%x)",
cs->minor_index, __func__, set, clear);
if (mutex_lock_interruptible(&cs->mutex))
return -ERESTARTSYS;
if (!cs->connected) {
gig_dbg(DEBUG_IF, "not connected");
retval = -ENODEV;
} else {
mc = (cs->control_state | set) & ~clear & (TIOCM_RTS | TIOCM_DTR);
retval = cs->ops->set_modem_ctrl(cs, cs->control_state, mc);
cs->control_state = mc;
}
mutex_unlock(&cs->mutex);
return retval;
}
static int if_write(struct tty_struct *tty, const unsigned char *buf, int count)
{
struct cardstate *cs = tty->driver_data;
struct cmdbuf_t *cb;
int retval;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
if (mutex_lock_interruptible(&cs->mutex))
return -ERESTARTSYS;
if (!cs->connected) {
gig_dbg(DEBUG_IF, "not connected");
retval = -ENODEV;
goto done;
}
if (cs->mstate != MS_LOCKED) {
dev_warn(cs->dev, "can't write to unlocked device\n");
retval = -EBUSY;
goto done;
}
if (count <= 0) {
/* nothing to do */
retval = 0;
goto done;
}
cb = kmalloc(sizeof(struct cmdbuf_t) + count, GFP_KERNEL);
if (!cb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
retval = -ENOMEM;
goto done;
}
memcpy(cb->buf, buf, count);
cb->len = count;
cb->offset = 0;
cb->next = NULL;
cb->wake_tasklet = &cs->if_wake_tasklet;
retval = cs->ops->write_cmd(cs, cb);
done:
mutex_unlock(&cs->mutex);
return retval;
}
static int if_write_room(struct tty_struct *tty)
{
struct cardstate *cs = tty->driver_data;
int retval;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
if (mutex_lock_interruptible(&cs->mutex))
return -ERESTARTSYS;
if (!cs->connected) {
gig_dbg(DEBUG_IF, "not connected");
retval = -ENODEV;
} else if (cs->mstate != MS_LOCKED) {
dev_warn(cs->dev, "can't write to unlocked device\n");
retval = -EBUSY;
} else
retval = cs->ops->write_room(cs);
mutex_unlock(&cs->mutex);
return retval;
}
static int if_chars_in_buffer(struct tty_struct *tty)
{
struct cardstate *cs = tty->driver_data;
int retval = 0;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
mutex_lock(&cs->mutex);
if (!cs->connected)
gig_dbg(DEBUG_IF, "not connected");
else if (cs->mstate != MS_LOCKED)
dev_warn(cs->dev, "can't write to unlocked device\n");
else
retval = cs->ops->chars_in_buffer(cs);
mutex_unlock(&cs->mutex);
return retval;
}
static void if_throttle(struct tty_struct *tty)
{
struct cardstate *cs = tty->driver_data;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
mutex_lock(&cs->mutex);
if (!cs->connected)
gig_dbg(DEBUG_IF, "not connected"); /* nothing to do */
else
gig_dbg(DEBUG_IF, "%s: not implemented\n", __func__);
mutex_unlock(&cs->mutex);
}
static void if_unthrottle(struct tty_struct *tty)
{
struct cardstate *cs = tty->driver_data;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
mutex_lock(&cs->mutex);
if (!cs->connected)
gig_dbg(DEBUG_IF, "not connected"); /* nothing to do */
else
gig_dbg(DEBUG_IF, "%s: not implemented\n", __func__);
mutex_unlock(&cs->mutex);
}
static void if_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct cardstate *cs = tty->driver_data;
unsigned int iflag;
unsigned int cflag;
unsigned int old_cflag;
unsigned int control_state, new_state;
gig_dbg(DEBUG_IF, "%u: %s()", cs->minor_index, __func__);
mutex_lock(&cs->mutex);
if (!cs->connected) {
gig_dbg(DEBUG_IF, "not connected");
goto out;
}
iflag = tty->termios.c_iflag;
cflag = tty->termios.c_cflag;
old_cflag = old ? old->c_cflag : cflag;
gig_dbg(DEBUG_IF, "%u: iflag %x cflag %x old %x",
cs->minor_index, iflag, cflag, old_cflag);
/* get a local copy of the current port settings */
control_state = cs->control_state;
/*
* Update baud rate.
* Do not attempt to cache old rates and skip settings,
* disconnects screw such tricks up completely.
* Premature optimization is the root of all evil.
*/
/* reassert DTR and (maybe) RTS on transition from B0 */
if ((old_cflag & CBAUD) == B0) {
new_state = control_state | TIOCM_DTR;
/* don't set RTS if using hardware flow control */
if (!(old_cflag & CRTSCTS))
new_state |= TIOCM_RTS;
gig_dbg(DEBUG_IF, "%u: from B0 - set DTR%s",
cs->minor_index,
(new_state & TIOCM_RTS) ? " only" : "/RTS");
cs->ops->set_modem_ctrl(cs, control_state, new_state);
control_state = new_state;
}
cs->ops->baud_rate(cs, cflag & CBAUD);
if ((cflag & CBAUD) == B0) {
/* Drop RTS and DTR */
gig_dbg(DEBUG_IF, "%u: to B0 - drop DTR/RTS", cs->minor_index);
new_state = control_state & ~(TIOCM_DTR | TIOCM_RTS);
cs->ops->set_modem_ctrl(cs, control_state, new_state);
control_state = new_state;
}
/*
* Update line control register (LCR)
*/
cs->ops->set_line_ctrl(cs, cflag);
/* save off the modified port settings */
cs->control_state = control_state;
out:
mutex_unlock(&cs->mutex);
}
static const struct tty_operations if_ops = {
.open = if_open,
.close = if_close,
.ioctl = if_ioctl,
.write = if_write,
.write_room = if_write_room,
.chars_in_buffer = if_chars_in_buffer,
.set_termios = if_set_termios,
.throttle = if_throttle,
.unthrottle = if_unthrottle,
.tiocmget = if_tiocmget,
.tiocmset = if_tiocmset,
};
/* wakeup tasklet for the write operation */
static void if_wake(unsigned long data)
{
struct cardstate *cs = (struct cardstate *)data;
tty_port_tty_wakeup(&cs->port);
}
/*** interface to common ***/
void gigaset_if_init(struct cardstate *cs)
{
struct gigaset_driver *drv;
drv = cs->driver;
if (!drv->have_tty)
return;
tasklet_init(&cs->if_wake_tasklet, if_wake, (unsigned long) cs);
mutex_lock(&cs->mutex);
cs->tty_dev = tty_port_register_device(&cs->port, drv->tty,
cs->minor_index, NULL);
if (!IS_ERR(cs->tty_dev))
dev_set_drvdata(cs->tty_dev, cs);
else {
pr_warning("could not register device to the tty subsystem\n");
cs->tty_dev = NULL;
}
mutex_unlock(&cs->mutex);
}
void gigaset_if_free(struct cardstate *cs)
{
struct gigaset_driver *drv;
drv = cs->driver;
if (!drv->have_tty)
return;
tasklet_disable(&cs->if_wake_tasklet);
tasklet_kill(&cs->if_wake_tasklet);
cs->tty_dev = NULL;
tty_unregister_device(drv->tty, cs->minor_index);
}
/**
* gigaset_if_receive() - pass a received block of data to the tty device
* @cs: device descriptor structure.
* @buffer: received data.
* @len: number of bytes received.
*
* Called by asyncdata/isocdata if a block of data received from the
* device must be sent to userspace through the ttyG* device.
*/
void gigaset_if_receive(struct cardstate *cs,
unsigned char *buffer, size_t len)
{
tty_insert_flip_string(&cs->port, buffer, len);
tty_flip_buffer_push(&cs->port);
}
EXPORT_SYMBOL_GPL(gigaset_if_receive);
/* gigaset_if_initdriver
* Initialize tty interface.
* parameters:
* drv Driver
* procname Name of the driver (e.g. for /proc/tty/drivers)
* devname Name of the device files (prefix without minor number)
*/
void gigaset_if_initdriver(struct gigaset_driver *drv, const char *procname,
const char *devname)
{
int ret;
struct tty_driver *tty;
drv->have_tty = 0;
drv->tty = tty = alloc_tty_driver(drv->minors);
if (tty == NULL)
goto enomem;
tty->type = TTY_DRIVER_TYPE_SERIAL;
tty->subtype = SERIAL_TYPE_NORMAL;
tty->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
tty->driver_name = procname;
tty->name = devname;
tty->minor_start = drv->minor;
tty->init_termios = tty_std_termios;
tty->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
tty_set_operations(tty, &if_ops);
ret = tty_register_driver(tty);
if (ret < 0) {
pr_err("error %d registering tty driver\n", ret);
goto error;
}
gig_dbg(DEBUG_IF, "tty driver initialized");
drv->have_tty = 1;
return;
enomem:
pr_err("out of memory\n");
error:
if (drv->tty)
put_tty_driver(drv->tty);
}
void gigaset_if_freedriver(struct gigaset_driver *drv)
{
if (!drv->have_tty)
return;
drv->have_tty = 0;
tty_unregister_driver(drv->tty);
put_tty_driver(drv->tty);
}
| gpl-2.0 |
djmax81/android_kernel_samsung_exynos5420 | drivers/media/dvb/dvb-usb/az6027.c | 5078 | 27717 | /* DVB USB compliant Linux driver for the AZUREWAVE DVB-S/S2 USB2.0 (AZ6027)
* receiver.
*
* Copyright (C) 2009 Adams.Xu <adams.xu@azwave.com.cn>
*
* 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.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "az6027.h"
#include "stb0899_drv.h"
#include "stb0899_reg.h"
#include "stb0899_cfg.h"
#include "stb6100.h"
#include "stb6100_cfg.h"
#include "dvb_ca_en50221.h"
int dvb_usb_az6027_debug;
module_param_named(debug, dvb_usb_az6027_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info,xfer=2,rc=4 (or-able))." DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct az6027_device_state {
struct dvb_ca_en50221 ca;
struct mutex ca_mutex;
u8 power_state;
};
static const struct stb0899_s1_reg az6027_stb0899_s1_init_1[] = {
/* 0x0000000b, SYSREG */
{ STB0899_DEV_ID , 0x30 },
{ STB0899_DISCNTRL1 , 0x32 },
{ STB0899_DISCNTRL2 , 0x80 },
{ STB0899_DISRX_ST0 , 0x04 },
{ STB0899_DISRX_ST1 , 0x00 },
{ STB0899_DISPARITY , 0x00 },
{ STB0899_DISSTATUS , 0x20 },
{ STB0899_DISF22 , 0x99 },
{ STB0899_DISF22RX , 0xa8 },
/* SYSREG ? */
{ STB0899_ACRPRESC , 0x11 },
{ STB0899_ACRDIV1 , 0x0a },
{ STB0899_ACRDIV2 , 0x05 },
{ STB0899_DACR1 , 0x00 },
{ STB0899_DACR2 , 0x00 },
{ STB0899_OUTCFG , 0x00 },
{ STB0899_MODECFG , 0x00 },
{ STB0899_IRQSTATUS_3 , 0xfe },
{ STB0899_IRQSTATUS_2 , 0x03 },
{ STB0899_IRQSTATUS_1 , 0x7c },
{ STB0899_IRQSTATUS_0 , 0xf4 },
{ STB0899_IRQMSK_3 , 0xf3 },
{ STB0899_IRQMSK_2 , 0xfc },
{ STB0899_IRQMSK_1 , 0xff },
{ STB0899_IRQMSK_0 , 0xff },
{ STB0899_IRQCFG , 0x00 },
{ STB0899_I2CCFG , 0x88 },
{ STB0899_I2CRPT , 0x58 },
{ STB0899_IOPVALUE5 , 0x00 },
{ STB0899_IOPVALUE4 , 0x33 },
{ STB0899_IOPVALUE3 , 0x6d },
{ STB0899_IOPVALUE2 , 0x90 },
{ STB0899_IOPVALUE1 , 0x60 },
{ STB0899_IOPVALUE0 , 0x00 },
{ STB0899_GPIO00CFG , 0x82 },
{ STB0899_GPIO01CFG , 0x82 },
{ STB0899_GPIO02CFG , 0x82 },
{ STB0899_GPIO03CFG , 0x82 },
{ STB0899_GPIO04CFG , 0x82 },
{ STB0899_GPIO05CFG , 0x82 },
{ STB0899_GPIO06CFG , 0x82 },
{ STB0899_GPIO07CFG , 0x82 },
{ STB0899_GPIO08CFG , 0x82 },
{ STB0899_GPIO09CFG , 0x82 },
{ STB0899_GPIO10CFG , 0x82 },
{ STB0899_GPIO11CFG , 0x82 },
{ STB0899_GPIO12CFG , 0x82 },
{ STB0899_GPIO13CFG , 0x82 },
{ STB0899_GPIO14CFG , 0x82 },
{ STB0899_GPIO15CFG , 0x82 },
{ STB0899_GPIO16CFG , 0x82 },
{ STB0899_GPIO17CFG , 0x82 },
{ STB0899_GPIO18CFG , 0x82 },
{ STB0899_GPIO19CFG , 0x82 },
{ STB0899_GPIO20CFG , 0x82 },
{ STB0899_SDATCFG , 0xb8 },
{ STB0899_SCLTCFG , 0xba },
{ STB0899_AGCRFCFG , 0x1c }, /* 0x11 */
{ STB0899_GPIO22 , 0x82 }, /* AGCBB2CFG */
{ STB0899_GPIO21 , 0x91 }, /* AGCBB1CFG */
{ STB0899_DIRCLKCFG , 0x82 },
{ STB0899_CLKOUT27CFG , 0x7e },
{ STB0899_STDBYCFG , 0x82 },
{ STB0899_CS0CFG , 0x82 },
{ STB0899_CS1CFG , 0x82 },
{ STB0899_DISEQCOCFG , 0x20 },
{ STB0899_GPIO32CFG , 0x82 },
{ STB0899_GPIO33CFG , 0x82 },
{ STB0899_GPIO34CFG , 0x82 },
{ STB0899_GPIO35CFG , 0x82 },
{ STB0899_GPIO36CFG , 0x82 },
{ STB0899_GPIO37CFG , 0x82 },
{ STB0899_GPIO38CFG , 0x82 },
{ STB0899_GPIO39CFG , 0x82 },
{ STB0899_NCOARSE , 0x17 }, /* 0x15 = 27 Mhz Clock, F/3 = 198MHz, F/6 = 99MHz */
{ STB0899_SYNTCTRL , 0x02 }, /* 0x00 = CLK from CLKI, 0x02 = CLK from XTALI */
{ STB0899_FILTCTRL , 0x00 },
{ STB0899_SYSCTRL , 0x01 },
{ STB0899_STOPCLK1 , 0x20 },
{ STB0899_STOPCLK2 , 0x00 },
{ STB0899_INTBUFSTATUS , 0x00 },
{ STB0899_INTBUFCTRL , 0x0a },
{ 0xffff , 0xff },
};
static const struct stb0899_s1_reg az6027_stb0899_s1_init_3[] = {
{ STB0899_DEMOD , 0x00 },
{ STB0899_RCOMPC , 0xc9 },
{ STB0899_AGC1CN , 0x01 },
{ STB0899_AGC1REF , 0x10 },
{ STB0899_RTC , 0x23 },
{ STB0899_TMGCFG , 0x4e },
{ STB0899_AGC2REF , 0x34 },
{ STB0899_TLSR , 0x84 },
{ STB0899_CFD , 0xf7 },
{ STB0899_ACLC , 0x87 },
{ STB0899_BCLC , 0x94 },
{ STB0899_EQON , 0x41 },
{ STB0899_LDT , 0xf1 },
{ STB0899_LDT2 , 0xe3 },
{ STB0899_EQUALREF , 0xb4 },
{ STB0899_TMGRAMP , 0x10 },
{ STB0899_TMGTHD , 0x30 },
{ STB0899_IDCCOMP , 0xfd },
{ STB0899_QDCCOMP , 0xff },
{ STB0899_POWERI , 0x0c },
{ STB0899_POWERQ , 0x0f },
{ STB0899_RCOMP , 0x6c },
{ STB0899_AGCIQIN , 0x80 },
{ STB0899_AGC2I1 , 0x06 },
{ STB0899_AGC2I2 , 0x00 },
{ STB0899_TLIR , 0x30 },
{ STB0899_RTF , 0x7f },
{ STB0899_DSTATUS , 0x00 },
{ STB0899_LDI , 0xbc },
{ STB0899_CFRM , 0xea },
{ STB0899_CFRL , 0x31 },
{ STB0899_NIRM , 0x2b },
{ STB0899_NIRL , 0x80 },
{ STB0899_ISYMB , 0x1d },
{ STB0899_QSYMB , 0xa6 },
{ STB0899_SFRH , 0x2f },
{ STB0899_SFRM , 0x68 },
{ STB0899_SFRL , 0x40 },
{ STB0899_SFRUPH , 0x2f },
{ STB0899_SFRUPM , 0x68 },
{ STB0899_SFRUPL , 0x40 },
{ STB0899_EQUAI1 , 0x02 },
{ STB0899_EQUAQ1 , 0xff },
{ STB0899_EQUAI2 , 0x04 },
{ STB0899_EQUAQ2 , 0x05 },
{ STB0899_EQUAI3 , 0x02 },
{ STB0899_EQUAQ3 , 0xfd },
{ STB0899_EQUAI4 , 0x03 },
{ STB0899_EQUAQ4 , 0x07 },
{ STB0899_EQUAI5 , 0x08 },
{ STB0899_EQUAQ5 , 0xf5 },
{ STB0899_DSTATUS2 , 0x00 },
{ STB0899_VSTATUS , 0x00 },
{ STB0899_VERROR , 0x86 },
{ STB0899_IQSWAP , 0x2a },
{ STB0899_ECNT1M , 0x00 },
{ STB0899_ECNT1L , 0x00 },
{ STB0899_ECNT2M , 0x00 },
{ STB0899_ECNT2L , 0x00 },
{ STB0899_ECNT3M , 0x0a },
{ STB0899_ECNT3L , 0xad },
{ STB0899_FECAUTO1 , 0x06 },
{ STB0899_FECM , 0x01 },
{ STB0899_VTH12 , 0xb0 },
{ STB0899_VTH23 , 0x7a },
{ STB0899_VTH34 , 0x58 },
{ STB0899_VTH56 , 0x38 },
{ STB0899_VTH67 , 0x34 },
{ STB0899_VTH78 , 0x24 },
{ STB0899_PRVIT , 0xff },
{ STB0899_VITSYNC , 0x19 },
{ STB0899_RSULC , 0xb1 }, /* DVB = 0xb1, DSS = 0xa1 */
{ STB0899_TSULC , 0x42 },
{ STB0899_RSLLC , 0x41 },
{ STB0899_TSLPL , 0x12 },
{ STB0899_TSCFGH , 0x0c },
{ STB0899_TSCFGM , 0x00 },
{ STB0899_TSCFGL , 0x00 },
{ STB0899_TSOUT , 0x69 }, /* 0x0d for CAM */
{ STB0899_RSSYNCDEL , 0x00 },
{ STB0899_TSINHDELH , 0x02 },
{ STB0899_TSINHDELM , 0x00 },
{ STB0899_TSINHDELL , 0x00 },
{ STB0899_TSLLSTKM , 0x1b },
{ STB0899_TSLLSTKL , 0xb3 },
{ STB0899_TSULSTKM , 0x00 },
{ STB0899_TSULSTKL , 0x00 },
{ STB0899_PCKLENUL , 0xbc },
{ STB0899_PCKLENLL , 0xcc },
{ STB0899_RSPCKLEN , 0xbd },
{ STB0899_TSSTATUS , 0x90 },
{ STB0899_ERRCTRL1 , 0xb6 },
{ STB0899_ERRCTRL2 , 0x95 },
{ STB0899_ERRCTRL3 , 0x8d },
{ STB0899_DMONMSK1 , 0x27 },
{ STB0899_DMONMSK0 , 0x03 },
{ STB0899_DEMAPVIT , 0x5c },
{ STB0899_PLPARM , 0x19 },
{ STB0899_PDELCTRL , 0x48 },
{ STB0899_PDELCTRL2 , 0x00 },
{ STB0899_BBHCTRL1 , 0x00 },
{ STB0899_BBHCTRL2 , 0x00 },
{ STB0899_HYSTTHRESH , 0x77 },
{ STB0899_MATCSTM , 0x00 },
{ STB0899_MATCSTL , 0x00 },
{ STB0899_UPLCSTM , 0x00 },
{ STB0899_UPLCSTL , 0x00 },
{ STB0899_DFLCSTM , 0x00 },
{ STB0899_DFLCSTL , 0x00 },
{ STB0899_SYNCCST , 0x00 },
{ STB0899_SYNCDCSTM , 0x00 },
{ STB0899_SYNCDCSTL , 0x00 },
{ STB0899_ISI_ENTRY , 0x00 },
{ STB0899_ISI_BIT_EN , 0x00 },
{ STB0899_MATSTRM , 0xf0 },
{ STB0899_MATSTRL , 0x02 },
{ STB0899_UPLSTRM , 0x45 },
{ STB0899_UPLSTRL , 0x60 },
{ STB0899_DFLSTRM , 0xe3 },
{ STB0899_DFLSTRL , 0x00 },
{ STB0899_SYNCSTR , 0x47 },
{ STB0899_SYNCDSTRM , 0x05 },
{ STB0899_SYNCDSTRL , 0x18 },
{ STB0899_CFGPDELSTATUS1 , 0x19 },
{ STB0899_CFGPDELSTATUS2 , 0x2b },
{ STB0899_BBFERRORM , 0x00 },
{ STB0899_BBFERRORL , 0x01 },
{ STB0899_UPKTERRORM , 0x00 },
{ STB0899_UPKTERRORL , 0x00 },
{ 0xffff , 0xff },
};
struct stb0899_config az6027_stb0899_config = {
.init_dev = az6027_stb0899_s1_init_1,
.init_s2_demod = stb0899_s2_init_2,
.init_s1_demod = az6027_stb0899_s1_init_3,
.init_s2_fec = stb0899_s2_init_4,
.init_tst = stb0899_s1_init_5,
.demod_address = 0xd0, /* 0x68, 0xd0 >> 1 */
.xtal_freq = 27000000,
.inversion = IQ_SWAP_ON, /* 1 */
.lo_clk = 76500000,
.hi_clk = 99000000,
.esno_ave = STB0899_DVBS2_ESNO_AVE,
.esno_quant = STB0899_DVBS2_ESNO_QUANT,
.avframes_coarse = STB0899_DVBS2_AVFRAMES_COARSE,
.avframes_fine = STB0899_DVBS2_AVFRAMES_FINE,
.miss_threshold = STB0899_DVBS2_MISS_THRESHOLD,
.uwp_threshold_acq = STB0899_DVBS2_UWP_THRESHOLD_ACQ,
.uwp_threshold_track = STB0899_DVBS2_UWP_THRESHOLD_TRACK,
.uwp_threshold_sof = STB0899_DVBS2_UWP_THRESHOLD_SOF,
.sof_search_timeout = STB0899_DVBS2_SOF_SEARCH_TIMEOUT,
.btr_nco_bits = STB0899_DVBS2_BTR_NCO_BITS,
.btr_gain_shift_offset = STB0899_DVBS2_BTR_GAIN_SHIFT_OFFSET,
.crl_nco_bits = STB0899_DVBS2_CRL_NCO_BITS,
.ldpc_max_iter = STB0899_DVBS2_LDPC_MAX_ITER,
.tuner_get_frequency = stb6100_get_frequency,
.tuner_set_frequency = stb6100_set_frequency,
.tuner_set_bandwidth = stb6100_set_bandwidth,
.tuner_get_bandwidth = stb6100_get_bandwidth,
.tuner_set_rfsiggain = NULL,
};
struct stb6100_config az6027_stb6100_config = {
.tuner_address = 0xc0,
.refclock = 27000000,
};
/* check for mutex FIXME */
int az6027_usb_in_op(struct dvb_usb_device *d, u8 req, u16 value, u16 index, u8 *b, int blen)
{
int ret = -1;
if (mutex_lock_interruptible(&d->usb_mutex))
return -EAGAIN;
ret = usb_control_msg(d->udev,
usb_rcvctrlpipe(d->udev, 0),
req,
USB_TYPE_VENDOR | USB_DIR_IN,
value,
index,
b,
blen,
2000);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EIO;
} else
ret = 0;
deb_xfer("in: req. %02x, val: %04x, ind: %04x, buffer: ", req, value, index);
debug_dump(b, blen, deb_xfer);
mutex_unlock(&d->usb_mutex);
return ret;
}
static int az6027_usb_out_op(struct dvb_usb_device *d,
u8 req,
u16 value,
u16 index,
u8 *b,
int blen)
{
int ret;
deb_xfer("out: req. %02x, val: %04x, ind: %04x, buffer: ", req, value, index);
debug_dump(b, blen, deb_xfer);
if (mutex_lock_interruptible(&d->usb_mutex))
return -EAGAIN;
ret = usb_control_msg(d->udev,
usb_sndctrlpipe(d->udev, 0),
req,
USB_TYPE_VENDOR | USB_DIR_OUT,
value,
index,
b,
blen,
2000);
if (ret != blen) {
warn("usb out operation failed. (%d)", ret);
mutex_unlock(&d->usb_mutex);
return -EIO;
} else{
mutex_unlock(&d->usb_mutex);
return 0;
}
}
static int az6027_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
deb_info("%s %d", __func__, onoff);
req = 0xBC;
value = onoff;
index = 0;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
warn("usb out operation failed. (%d)", ret);
return ret;
}
/* keys for the enclosed remote control */
static struct rc_map_table rc_map_az6027_table[] = {
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
};
/* remote control stuff (does not work with my box) */
static int az6027_rc_query(struct dvb_usb_device *d, u32 *event, int *state)
{
return 0;
}
/*
int az6027_power_ctrl(struct dvb_usb_device *d, int onoff)
{
u8 v = onoff;
return az6027_usb_out_op(d,0xBC,v,3,NULL,1);
}
*/
static int az6027_ci_read_attribute_mem(struct dvb_ca_en50221 *ca,
int slot,
int address)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
if (slot != 0)
return -EINVAL;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
mutex_lock(&state->ca_mutex);
req = 0xC1;
value = address;
index = 0;
blen = 1;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EINVAL;
} else {
ret = b[0];
}
mutex_unlock(&state->ca_mutex);
kfree(b);
return ret;
}
static int az6027_ci_write_attribute_mem(struct dvb_ca_en50221 *ca,
int slot,
int address,
u8 value)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value1;
u16 index;
int blen;
deb_info("%s %d", __func__, slot);
if (slot != 0)
return -EINVAL;
mutex_lock(&state->ca_mutex);
req = 0xC2;
value1 = address;
index = value;
blen = 0;
ret = az6027_usb_out_op(d, req, value1, index, NULL, blen);
if (ret != 0)
warn("usb out operation failed. (%d)", ret);
mutex_unlock(&state->ca_mutex);
return ret;
}
static int az6027_ci_read_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
if (slot != 0)
return -EINVAL;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
mutex_lock(&state->ca_mutex);
req = 0xC3;
value = address;
index = 0;
blen = 2;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EINVAL;
} else {
if (b[0] == 0)
warn("Read CI IO error");
ret = b[1];
deb_info("read cam data = %x from 0x%x", b[1], value);
}
mutex_unlock(&state->ca_mutex);
kfree(b);
return ret;
}
static int az6027_ci_write_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address,
u8 value)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value1;
u16 index;
int blen;
if (slot != 0)
return -EINVAL;
mutex_lock(&state->ca_mutex);
req = 0xC4;
value1 = address;
index = value;
blen = 0;
ret = az6027_usb_out_op(d, req, value1, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int CI_CamReady(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
req = 0xC8;
value = 0;
index = 0;
blen = 1;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EIO;
} else{
ret = b[0];
}
kfree(b);
return ret;
}
static int az6027_ci_slot_reset(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret, i;
u8 req;
u16 value;
u16 index;
int blen;
mutex_lock(&state->ca_mutex);
req = 0xC6;
value = 1;
index = 0;
blen = 0;
ret = az6027_usb_out_op(d, req, value, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
msleep(500);
req = 0xC6;
value = 0;
index = 0;
blen = 0;
ret = az6027_usb_out_op(d, req, value, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
for (i = 0; i < 15; i++) {
msleep(100);
if (CI_CamReady(ca, slot)) {
deb_info("CAM Ready");
break;
}
}
msleep(5000);
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int az6027_ci_slot_shutdown(struct dvb_ca_en50221 *ca, int slot)
{
return 0;
}
static int az6027_ci_slot_ts_enable(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
deb_info("%s", __func__);
mutex_lock(&state->ca_mutex);
req = 0xC7;
value = 1;
index = 0;
blen = 0;
ret = az6027_usb_out_op(d, req, value, index, NULL, blen);
if (ret != 0) {
warn("usb out operation failed. (%d)", ret);
goto failed;
}
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int az6027_ci_poll_slot_status(struct dvb_ca_en50221 *ca, int slot, int open)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
u8 req;
u16 value;
u16 index;
int blen;
u8 *b;
b = kmalloc(12, GFP_KERNEL);
if (!b)
return -ENOMEM;
mutex_lock(&state->ca_mutex);
req = 0xC5;
value = 0;
index = 0;
blen = 1;
ret = az6027_usb_in_op(d, req, value, index, b, blen);
if (ret < 0) {
warn("usb in operation failed. (%d)", ret);
ret = -EIO;
} else
ret = 0;
if (!ret && b[0] == 1) {
ret = DVB_CA_EN50221_POLL_CAM_PRESENT |
DVB_CA_EN50221_POLL_CAM_READY;
}
mutex_unlock(&state->ca_mutex);
kfree(b);
return ret;
}
static void az6027_ci_uninit(struct dvb_usb_device *d)
{
struct az6027_device_state *state;
deb_info("%s", __func__);
if (NULL == d)
return;
state = (struct az6027_device_state *)d->priv;
if (NULL == state)
return;
if (NULL == state->ca.data)
return;
dvb_ca_en50221_release(&state->ca);
memset(&state->ca, 0, sizeof(state->ca));
}
static int az6027_ci_init(struct dvb_usb_adapter *a)
{
struct dvb_usb_device *d = a->dev;
struct az6027_device_state *state = (struct az6027_device_state *)d->priv;
int ret;
deb_info("%s", __func__);
mutex_init(&state->ca_mutex);
state->ca.owner = THIS_MODULE;
state->ca.read_attribute_mem = az6027_ci_read_attribute_mem;
state->ca.write_attribute_mem = az6027_ci_write_attribute_mem;
state->ca.read_cam_control = az6027_ci_read_cam_control;
state->ca.write_cam_control = az6027_ci_write_cam_control;
state->ca.slot_reset = az6027_ci_slot_reset;
state->ca.slot_shutdown = az6027_ci_slot_shutdown;
state->ca.slot_ts_enable = az6027_ci_slot_ts_enable;
state->ca.poll_slot_status = az6027_ci_poll_slot_status;
state->ca.data = d;
ret = dvb_ca_en50221_init(&a->dvb_adap,
&state->ca,
0, /* flags */
1);/* n_slots */
if (ret != 0) {
err("Cannot initialize CI: Error %d.", ret);
memset(&state->ca, 0, sizeof(state->ca));
return ret;
}
deb_info("CI initialized.");
return 0;
}
/*
static int az6027_read_mac_addr(struct dvb_usb_device *d, u8 mac[6])
{
az6027_usb_in_op(d, 0xb7, 6, 0, &mac[0], 6);
return 0;
}
*/
static int az6027_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
u8 buf;
struct dvb_usb_adapter *adap = fe->dvb->priv;
struct i2c_msg i2c_msg = {
.addr = 0x99,
.flags = 0,
.buf = &buf,
.len = 1
};
/*
* 2 --18v
* 1 --13v
* 0 --off
*/
switch (voltage) {
case SEC_VOLTAGE_13:
buf = 1;
i2c_transfer(&adap->dev->i2c_adap, &i2c_msg, 1);
break;
case SEC_VOLTAGE_18:
buf = 2;
i2c_transfer(&adap->dev->i2c_adap, &i2c_msg, 1);
break;
case SEC_VOLTAGE_OFF:
buf = 0;
i2c_transfer(&adap->dev->i2c_adap, &i2c_msg, 1);
break;
default:
return -EINVAL;
}
return 0;
}
static int az6027_frontend_poweron(struct dvb_usb_adapter *adap)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
req = 0xBC;
value = 1; /* power on */
index = 3;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
return 0;
}
static int az6027_frontend_reset(struct dvb_usb_adapter *adap)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
/* reset demodulator */
req = 0xC0;
value = 1; /* high */
index = 3;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
req = 0xC0;
value = 0; /* low */
index = 3;
blen = 0;
msleep_interruptible(200);
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
msleep_interruptible(200);
req = 0xC0;
value = 1; /*high */
index = 3;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
msleep_interruptible(200);
return 0;
}
static int az6027_frontend_tsbypass(struct dvb_usb_adapter *adap, int onoff)
{
int ret;
u8 req;
u16 value;
u16 index;
int blen;
/* TS passthrough */
req = 0xC7;
value = onoff;
index = 0;
blen = 0;
ret = az6027_usb_out_op(adap->dev, req, value, index, NULL, blen);
if (ret != 0)
return -EIO;
return 0;
}
static int az6027_frontend_attach(struct dvb_usb_adapter *adap)
{
az6027_frontend_poweron(adap);
az6027_frontend_reset(adap);
deb_info("adap = %p, dev = %p\n", adap, adap->dev);
adap->fe_adap[0].fe = stb0899_attach(&az6027_stb0899_config, &adap->dev->i2c_adap);
if (adap->fe_adap[0].fe) {
deb_info("found STB0899 DVB-S/DVB-S2 frontend @0x%02x", az6027_stb0899_config.demod_address);
if (stb6100_attach(adap->fe_adap[0].fe, &az6027_stb6100_config, &adap->dev->i2c_adap)) {
deb_info("found STB6100 DVB-S/DVB-S2 frontend @0x%02x", az6027_stb6100_config.tuner_address);
adap->fe_adap[0].fe->ops.set_voltage = az6027_set_voltage;
az6027_ci_init(adap);
} else {
adap->fe_adap[0].fe = NULL;
}
} else
warn("no front-end attached\n");
az6027_frontend_tsbypass(adap, 0);
return 0;
}
static struct dvb_usb_device_properties az6027_properties;
static void az6027_usb_disconnect(struct usb_interface *intf)
{
struct dvb_usb_device *d = usb_get_intfdata(intf);
az6027_ci_uninit(d);
dvb_usb_device_exit(intf);
}
static int az6027_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return dvb_usb_device_init(intf,
&az6027_properties,
THIS_MODULE,
NULL,
adapter_nr);
}
/* I2C */
static int az6027_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i = 0, j = 0, len = 0;
u16 index;
u16 value;
int length;
u8 req;
u8 *data;
data = kmalloc(256, GFP_KERNEL);
if (!data)
return -ENOMEM;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0) {
kfree(data);
return -EAGAIN;
}
if (num > 2)
warn("more than 2 i2c messages at a time is not handled yet. TODO.");
for (i = 0; i < num; i++) {
if (msg[i].addr == 0x99) {
req = 0xBE;
index = 0;
value = msg[i].buf[0] & 0x00ff;
length = 1;
az6027_usb_out_op(d, req, value, index, data, length);
}
if (msg[i].addr == 0xd0) {
/* write/read request */
if (i + 1 < num && (msg[i + 1].flags & I2C_M_RD)) {
req = 0xB9;
index = (((msg[i].buf[0] << 8) & 0xff00) | (msg[i].buf[1] & 0x00ff));
value = msg[i].addr + (msg[i].len << 8);
length = msg[i + 1].len + 6;
az6027_usb_in_op(d, req, value, index, data, length);
len = msg[i + 1].len;
for (j = 0; j < len; j++)
msg[i + 1].buf[j] = data[j + 5];
i++;
} else {
/* demod 16bit addr */
req = 0xBD;
index = (((msg[i].buf[0] << 8) & 0xff00) | (msg[i].buf[1] & 0x00ff));
value = msg[i].addr + (2 << 8);
length = msg[i].len - 2;
len = msg[i].len - 2;
for (j = 0; j < len; j++)
data[j] = msg[i].buf[j + 2];
az6027_usb_out_op(d, req, value, index, data, length);
}
}
if (msg[i].addr == 0xc0) {
if (msg[i].flags & I2C_M_RD) {
req = 0xB9;
index = 0x0;
value = msg[i].addr;
length = msg[i].len + 6;
az6027_usb_in_op(d, req, value, index, data, length);
len = msg[i].len;
for (j = 0; j < len; j++)
msg[i].buf[j] = data[j + 5];
} else {
req = 0xBD;
index = msg[i].buf[0] & 0x00FF;
value = msg[i].addr + (1 << 8);
length = msg[i].len - 1;
len = msg[i].len - 1;
for (j = 0; j < len; j++)
data[j] = msg[i].buf[j + 1];
az6027_usb_out_op(d, req, value, index, data, length);
}
}
}
mutex_unlock(&d->i2c_mutex);
kfree(data);
return i;
}
static u32 az6027_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm az6027_i2c_algo = {
.master_xfer = az6027_i2c_xfer,
.functionality = az6027_i2c_func,
};
int az6027_identify_state(struct usb_device *udev,
struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc,
int *cold)
{
u8 *b;
s16 ret;
b = kmalloc(16, GFP_KERNEL);
if (!b)
return -ENOMEM;
ret = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
0xb7,
USB_TYPE_VENDOR | USB_DIR_IN,
6,
0,
b,
6,
USB_CTRL_GET_TIMEOUT);
*cold = ret <= 0;
kfree(b);
deb_info("cold: %d\n", *cold);
return 0;
}
static struct usb_device_id az6027_usb_table[] = {
{ USB_DEVICE(USB_VID_AZUREWAVE, USB_PID_AZUREWAVE_AZ6027) },
{ USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_DVBS2CI_V1) },
{ USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_DVBS2CI_V2) },
{ USB_DEVICE(USB_VID_TECHNISAT, USB_PID_TECHNISAT_USB2_HDCI_V1) },
{ USB_DEVICE(USB_VID_TECHNISAT, USB_PID_TECHNISAT_USB2_HDCI_V2) },
{ USB_DEVICE(USB_VID_ELGATO, USB_PID_ELGATO_EYETV_SAT) },
{ },
};
MODULE_DEVICE_TABLE(usb, az6027_usb_table);
static struct dvb_usb_device_properties az6027_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-az6027-03.fw",
.no_reconnect = 1,
.size_of_priv = sizeof(struct az6027_device_state),
.identify_state = az6027_identify_state,
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = az6027_streaming_ctrl,
.frontend_attach = az6027_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 10,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}},
}
},
/*
.power_ctrl = az6027_power_ctrl,
.read_mac_address = az6027_read_mac_addr,
*/
.rc.legacy = {
.rc_map_table = rc_map_az6027_table,
.rc_map_size = ARRAY_SIZE(rc_map_az6027_table),
.rc_interval = 400,
.rc_query = az6027_rc_query,
},
.i2c_algo = &az6027_i2c_algo,
.num_device_descs = 6,
.devices = {
{
.name = "AZUREWAVE DVB-S/S2 USB2.0 (AZ6027)",
.cold_ids = { &az6027_usb_table[0], NULL },
.warm_ids = { NULL },
}, {
.name = "TERRATEC S7",
.cold_ids = { &az6027_usb_table[1], NULL },
.warm_ids = { NULL },
}, {
.name = "TERRATEC S7 MKII",
.cold_ids = { &az6027_usb_table[2], NULL },
.warm_ids = { NULL },
}, {
.name = "Technisat SkyStar USB 2 HD CI",
.cold_ids = { &az6027_usb_table[3], NULL },
.warm_ids = { NULL },
}, {
.name = "Technisat SkyStar USB 2 HD CI",
.cold_ids = { &az6027_usb_table[4], NULL },
.warm_ids = { NULL },
}, {
.name = "Elgato EyeTV Sat",
.cold_ids = { &az6027_usb_table[5], NULL },
.warm_ids = { NULL },
},
{ NULL },
}
};
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver az6027_usb_driver = {
.name = "dvb_usb_az6027",
.probe = az6027_usb_probe,
.disconnect = az6027_usb_disconnect,
.id_table = az6027_usb_table,
};
module_usb_driver(az6027_usb_driver);
MODULE_AUTHOR("Adams Xu <Adams.xu@azwave.com.cn>");
MODULE_DESCRIPTION("Driver for AZUREWAVE DVB-S/S2 USB2.0 (AZ6027)");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
sicknemesis/AK-OnePone | drivers/net/ethernet/8390/3c503.c | 5078 | 22741 | /* 3c503.c: A shared-memory NS8390 ethernet driver for linux. */
/*
Written 1992-94 by Donald Becker.
Copyright 1993 United States Government as represented by the
Director, National Security Agency. This software may be used and
distributed according to the terms of the GNU General Public License,
incorporated herein by reference.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
This driver should work with the 3c503 and 3c503/16. It should be used
in shared memory mode for best performance, although it may also work
in programmed-I/O mode.
Sources:
EtherLink II Technical Reference Manual,
EtherLink II/16 Technical Reference Manual Supplement,
3Com Corporation, 5400 Bayfront Plaza, Santa Clara CA 95052-8145
The Crynwr 3c503 packet driver.
Changelog:
Paul Gortmaker : add support for the 2nd 8kB of RAM on 16 bit cards.
Paul Gortmaker : multiple card support for module users.
rjohnson@analogic.com : Fix up PIO interface for efficient operation.
Jeff Garzik : ethtool support
*/
#define DRV_NAME "3c503"
#define DRV_VERSION "1.10a"
#define DRV_RELDATE "11/17/2001"
static const char version[] =
DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " Donald Becker (becker@scyld.com)\n";
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ethtool.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include "8390.h"
#include "3c503.h"
#define WRD_COUNT 4
static int el2_pio_probe(struct net_device *dev);
static int el2_probe1(struct net_device *dev, int ioaddr);
/* A zero-terminated list of I/O addresses to be probed in PIO mode. */
static unsigned int netcard_portlist[] __initdata =
{ 0x300,0x310,0x330,0x350,0x250,0x280,0x2a0,0x2e0,0};
#define EL2_IO_EXTENT 16
static int el2_open(struct net_device *dev);
static int el2_close(struct net_device *dev);
static void el2_reset_8390(struct net_device *dev);
static void el2_init_card(struct net_device *dev);
static void el2_block_output(struct net_device *dev, int count,
const unsigned char *buf, int start_page);
static void el2_block_input(struct net_device *dev, int count, struct sk_buff *skb,
int ring_offset);
static void el2_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page);
static const struct ethtool_ops netdev_ethtool_ops;
/* This routine probes for a memory-mapped 3c503 board by looking for
the "location register" at the end of the jumpered boot PROM space.
This works even if a PROM isn't there.
If the ethercard isn't found there is an optional probe for
ethercard jumpered to programmed-I/O mode.
*/
static int __init do_el2_probe(struct net_device *dev)
{
int *addr, addrs[] = { 0xddffe, 0xd9ffe, 0xcdffe, 0xc9ffe, 0};
int base_addr = dev->base_addr;
int irq = dev->irq;
if (base_addr > 0x1ff) /* Check a single specified location. */
return el2_probe1(dev, base_addr);
else if (base_addr != 0) /* Don't probe at all. */
return -ENXIO;
for (addr = addrs; *addr; addr++) {
void __iomem *p = ioremap(*addr, 1);
unsigned base_bits;
int i;
if (!p)
continue;
base_bits = readb(p);
iounmap(p);
i = ffs(base_bits) - 1;
if (i == -1 || base_bits != (1 << i))
continue;
if (el2_probe1(dev, netcard_portlist[i]) == 0)
return 0;
dev->irq = irq;
}
#if ! defined(no_probe_nonshared_memory)
return el2_pio_probe(dev);
#else
return -ENODEV;
#endif
}
/* Try all of the locations that aren't obviously empty. This touches
a lot of locations, and is much riskier than the code above. */
static int __init
el2_pio_probe(struct net_device *dev)
{
int i;
int base_addr = dev->base_addr;
int irq = dev->irq;
if (base_addr > 0x1ff) /* Check a single specified location. */
return el2_probe1(dev, base_addr);
else if (base_addr != 0) /* Don't probe at all. */
return -ENXIO;
for (i = 0; netcard_portlist[i]; i++) {
if (el2_probe1(dev, netcard_portlist[i]) == 0)
return 0;
dev->irq = irq;
}
return -ENODEV;
}
#ifndef MODULE
struct net_device * __init el2_probe(int unit)
{
struct net_device *dev = alloc_eip_netdev();
int err;
if (!dev)
return ERR_PTR(-ENOMEM);
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
err = do_el2_probe(dev);
if (err)
goto out;
return dev;
out:
free_netdev(dev);
return ERR_PTR(err);
}
#endif
static const struct net_device_ops el2_netdev_ops = {
.ndo_open = el2_open,
.ndo_stop = el2_close,
.ndo_start_xmit = eip_start_xmit,
.ndo_tx_timeout = eip_tx_timeout,
.ndo_get_stats = eip_get_stats,
.ndo_set_rx_mode = eip_set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = eip_poll,
#endif
};
/* Probe for the Etherlink II card at I/O port base IOADDR,
returning non-zero on success. If found, set the station
address and memory parameters in DEVICE. */
static int __init
el2_probe1(struct net_device *dev, int ioaddr)
{
int i, iobase_reg, membase_reg, saved_406, wordlength, retval;
static unsigned version_printed;
unsigned long vendor_id;
if (!request_region(ioaddr, EL2_IO_EXTENT, DRV_NAME))
return -EBUSY;
if (!request_region(ioaddr + 0x400, 8, DRV_NAME)) {
retval = -EBUSY;
goto out;
}
/* Reset and/or avoid any lurking NE2000 */
if (inb(ioaddr + 0x408) == 0xff) {
mdelay(1);
retval = -ENODEV;
goto out1;
}
/* We verify that it's a 3C503 board by checking the first three octets
of its ethernet address. */
iobase_reg = inb(ioaddr+0x403);
membase_reg = inb(ioaddr+0x404);
/* ASIC location registers should be 0 or have only a single bit set. */
if ((iobase_reg & (iobase_reg - 1)) ||
(membase_reg & (membase_reg - 1))) {
retval = -ENODEV;
goto out1;
}
saved_406 = inb_p(ioaddr + 0x406);
outb_p(ECNTRL_RESET|ECNTRL_THIN, ioaddr + 0x406); /* Reset it... */
outb_p(ECNTRL_THIN, ioaddr + 0x406);
/* Map the station addr PROM into the lower I/O ports. We now check
for both the old and new 3Com prefix */
outb(ECNTRL_SAPROM|ECNTRL_THIN, ioaddr + 0x406);
vendor_id = inb(ioaddr)*0x10000 + inb(ioaddr + 1)*0x100 + inb(ioaddr + 2);
if ((vendor_id != OLD_3COM_ID) && (vendor_id != NEW_3COM_ID)) {
/* Restore the register we frobbed. */
outb(saved_406, ioaddr + 0x406);
retval = -ENODEV;
goto out1;
}
if (ei_debug && version_printed++ == 0)
pr_debug("%s", version);
dev->base_addr = ioaddr;
pr_info("%s: 3c503 at i/o base %#3x, node ", dev->name, ioaddr);
/* Retrieve and print the ethernet address. */
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb(ioaddr + i);
pr_cont("%pM", dev->dev_addr);
/* Map the 8390 back into the window. */
outb(ECNTRL_THIN, ioaddr + 0x406);
/* Check for EL2/16 as described in tech. man. */
outb_p(E8390_PAGE0, ioaddr + E8390_CMD);
outb_p(0, ioaddr + EN0_DCFG);
outb_p(E8390_PAGE2, ioaddr + E8390_CMD);
wordlength = inb_p(ioaddr + EN0_DCFG) & ENDCFG_WTS;
outb_p(E8390_PAGE0, ioaddr + E8390_CMD);
/* Probe for, turn on and clear the board's shared memory. */
if (ei_debug > 2)
pr_cont(" memory jumpers %2.2x ", membase_reg);
outb(EGACFR_NORM, ioaddr + 0x405); /* Enable RAM */
/* This should be probed for (or set via an ioctl()) at run-time.
Right now we use a sleazy hack to pass in the interface number
at boot-time via the low bits of the mem_end field. That value is
unused, and the low bits would be discarded even if it was used. */
#if defined(EI8390_THICK) || defined(EL2_AUI)
ei_status.interface_num = 1;
#else
ei_status.interface_num = dev->mem_end & 0xf;
#endif
pr_cont(", using %sternal xcvr.\n", ei_status.interface_num == 0 ? "in" : "ex");
if ((membase_reg & 0xf0) == 0) {
dev->mem_start = 0;
ei_status.name = "3c503-PIO";
ei_status.mem = NULL;
} else {
dev->mem_start = ((membase_reg & 0xc0) ? 0xD8000 : 0xC8000) +
((membase_reg & 0xA0) ? 0x4000 : 0);
#define EL2_MEMSIZE (EL2_MB1_STOP_PG - EL2_MB1_START_PG)*256
ei_status.mem = ioremap(dev->mem_start, EL2_MEMSIZE);
#ifdef EL2MEMTEST
/* This has never found an error, but someone might care.
Note that it only tests the 2nd 8kB on 16kB 3c503/16
cards between card addr. 0x2000 and 0x3fff. */
{ /* Check the card's memory. */
void __iomem *mem_base = ei_status.mem;
unsigned int test_val = 0xbbadf00d;
writel(0xba5eba5e, mem_base);
for (i = sizeof(test_val); i < EL2_MEMSIZE; i+=sizeof(test_val)) {
writel(test_val, mem_base + i);
if (readl(mem_base) != 0xba5eba5e ||
readl(mem_base + i) != test_val) {
pr_warning("3c503: memory failure or memory address conflict.\n");
dev->mem_start = 0;
ei_status.name = "3c503-PIO";
iounmap(mem_base);
ei_status.mem = NULL;
break;
}
test_val += 0x55555555;
writel(0, mem_base + i);
}
}
#endif /* EL2MEMTEST */
if (dev->mem_start)
dev->mem_end = dev->mem_start + EL2_MEMSIZE;
if (wordlength) { /* No Tx pages to skip over to get to Rx */
ei_status.priv = 0;
ei_status.name = "3c503/16";
} else {
ei_status.priv = TX_PAGES * 256;
ei_status.name = "3c503";
}
}
/*
Divide up the memory on the card. This is the same regardless of
whether shared-mem or PIO is used. For 16 bit cards (16kB RAM),
we use the entire 8k of bank1 for an Rx ring. We only use 3k
of the bank0 for 2 full size Tx packet slots. For 8 bit cards,
(8kB RAM) we use 3kB of bank1 for two Tx slots, and the remaining
5kB for an Rx ring. */
if (wordlength) {
ei_status.tx_start_page = EL2_MB0_START_PG;
ei_status.rx_start_page = EL2_MB1_START_PG;
} else {
ei_status.tx_start_page = EL2_MB1_START_PG;
ei_status.rx_start_page = EL2_MB1_START_PG + TX_PAGES;
}
/* Finish setting the board's parameters. */
ei_status.stop_page = EL2_MB1_STOP_PG;
ei_status.word16 = wordlength;
ei_status.reset_8390 = el2_reset_8390;
ei_status.get_8390_hdr = el2_get_8390_hdr;
ei_status.block_input = el2_block_input;
ei_status.block_output = el2_block_output;
if (dev->irq == 2)
dev->irq = 9;
else if (dev->irq > 5 && dev->irq != 9) {
pr_warning("3c503: configured interrupt %d invalid, will use autoIRQ.\n",
dev->irq);
dev->irq = 0;
}
ei_status.saved_irq = dev->irq;
dev->netdev_ops = &el2_netdev_ops;
dev->ethtool_ops = &netdev_ethtool_ops;
retval = register_netdev(dev);
if (retval)
goto out1;
if (dev->mem_start)
pr_info("%s: %s - %dkB RAM, 8kB shared mem window at %#6lx-%#6lx.\n",
dev->name, ei_status.name, (wordlength+1)<<3,
dev->mem_start, dev->mem_end-1);
else
{
ei_status.tx_start_page = EL2_MB1_START_PG;
ei_status.rx_start_page = EL2_MB1_START_PG + TX_PAGES;
pr_info("%s: %s, %dkB RAM, using programmed I/O (REJUMPER for SHARED MEMORY).\n",
dev->name, ei_status.name, (wordlength+1)<<3);
}
release_region(ioaddr + 0x400, 8);
return 0;
out1:
release_region(ioaddr + 0x400, 8);
out:
release_region(ioaddr, EL2_IO_EXTENT);
return retval;
}
static irqreturn_t el2_probe_interrupt(int irq, void *seen)
{
*(bool *)seen = true;
return IRQ_HANDLED;
}
static int
el2_open(struct net_device *dev)
{
int retval;
if (dev->irq < 2) {
static const int irqlist[] = {5, 9, 3, 4, 0};
const int *irqp = irqlist;
outb(EGACFR_NORM, E33G_GACFR); /* Enable RAM and interrupts. */
do {
bool seen;
retval = request_irq(*irqp, el2_probe_interrupt, 0,
dev->name, &seen);
if (retval == -EBUSY)
continue;
if (retval < 0)
goto err_disable;
/* Twinkle the interrupt, and check if it's seen. */
seen = false;
smp_wmb();
outb_p(0x04 << ((*irqp == 9) ? 2 : *irqp), E33G_IDCFR);
outb_p(0x00, E33G_IDCFR);
msleep(1);
free_irq(*irqp, &seen);
if (!seen)
continue;
retval = request_irq(dev->irq = *irqp, eip_interrupt, 0,
dev->name, dev);
if (retval == -EBUSY)
continue;
if (retval < 0)
goto err_disable;
break;
} while (*++irqp);
if (*irqp == 0) {
err_disable:
outb(EGACFR_IRQOFF, E33G_GACFR); /* disable interrupts. */
return -EAGAIN;
}
} else {
if ((retval = request_irq(dev->irq, eip_interrupt, 0, dev->name, dev))) {
return retval;
}
}
el2_init_card(dev);
eip_open(dev);
return 0;
}
static int
el2_close(struct net_device *dev)
{
free_irq(dev->irq, dev);
dev->irq = ei_status.saved_irq;
outb(EGACFR_IRQOFF, E33G_GACFR); /* disable interrupts. */
eip_close(dev);
return 0;
}
/* This is called whenever we have a unrecoverable failure:
transmit timeout
Bad ring buffer packet header
*/
static void
el2_reset_8390(struct net_device *dev)
{
if (ei_debug > 1) {
pr_debug("%s: Resetting the 3c503 board...", dev->name);
pr_cont(" %#lx=%#02x %#lx=%#02x %#lx=%#02x...", E33G_IDCFR, inb(E33G_IDCFR),
E33G_CNTRL, inb(E33G_CNTRL), E33G_GACFR, inb(E33G_GACFR));
}
outb_p(ECNTRL_RESET|ECNTRL_THIN, E33G_CNTRL);
ei_status.txing = 0;
outb_p(ei_status.interface_num==0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
el2_init_card(dev);
if (ei_debug > 1)
pr_cont("done\n");
}
/* Initialize the 3c503 GA registers after a reset. */
static void
el2_init_card(struct net_device *dev)
{
/* Unmap the station PROM and select the DIX or BNC connector. */
outb_p(ei_status.interface_num==0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
/* Set ASIC copy of rx's first and last+1 buffer pages */
/* These must be the same as in the 8390. */
outb(ei_status.rx_start_page, E33G_STARTPG);
outb(ei_status.stop_page, E33G_STOPPG);
/* Point the vector pointer registers somewhere ?harmless?. */
outb(0xff, E33G_VP2); /* Point at the ROM restart location 0xffff0 */
outb(0xff, E33G_VP1);
outb(0x00, E33G_VP0);
/* Turn off all interrupts until we're opened. */
outb_p(0x00, dev->base_addr + EN0_IMR);
/* Enable IRQs iff started. */
outb(EGACFR_NORM, E33G_GACFR);
/* Set the interrupt line. */
outb_p((0x04 << (dev->irq == 9 ? 2 : dev->irq)), E33G_IDCFR);
outb_p((WRD_COUNT << 1), E33G_DRQCNT); /* Set burst size to 8 */
outb_p(0x20, E33G_DMAAH); /* Put a valid addr in the GA DMA */
outb_p(0x00, E33G_DMAAL);
return; /* We always succeed */
}
/*
* Either use the shared memory (if enabled on the board) or put the packet
* out through the ASIC FIFO.
*/
static void
el2_block_output(struct net_device *dev, int count,
const unsigned char *buf, int start_page)
{
unsigned short int *wrd;
int boguscount; /* timeout counter */
unsigned short word; /* temporary for better machine code */
void __iomem *base = ei_status.mem;
if (ei_status.word16) /* Tx packets go into bank 0 on EL2/16 card */
outb(EGACFR_RSEL|EGACFR_TCM, E33G_GACFR);
else
outb(EGACFR_NORM, E33G_GACFR);
if (base) { /* Shared memory transfer */
memcpy_toio(base + ((start_page - ei_status.tx_start_page) << 8),
buf, count);
outb(EGACFR_NORM, E33G_GACFR); /* Back to bank1 in case on bank0 */
return;
}
/*
* No shared memory, put the packet out the other way.
* Set up then start the internal memory transfer to Tx Start Page
*/
word = (unsigned short)start_page;
outb(word&0xFF, E33G_DMAAH);
outb(word>>8, E33G_DMAAL);
outb_p((ei_status.interface_num ? ECNTRL_AUI : ECNTRL_THIN ) | ECNTRL_OUTPUT
| ECNTRL_START, E33G_CNTRL);
/*
* Here I am going to write data to the FIFO as quickly as possible.
* Note that E33G_FIFOH is defined incorrectly. It is really
* E33G_FIFOL, the lowest port address for both the byte and
* word write. Variable 'count' is NOT checked. Caller must supply a
* valid count. Note that I may write a harmless extra byte to the
* 8390 if the byte-count was not even.
*/
wrd = (unsigned short int *) buf;
count = (count + 1) >> 1;
for(;;)
{
boguscount = 0x1000;
while ((inb(E33G_STATUS) & ESTAT_DPRDY) == 0)
{
if(!boguscount--)
{
pr_notice("%s: FIFO blocked in el2_block_output.\n", dev->name);
el2_reset_8390(dev);
goto blocked;
}
}
if(count > WRD_COUNT)
{
outsw(E33G_FIFOH, wrd, WRD_COUNT);
wrd += WRD_COUNT;
count -= WRD_COUNT;
}
else
{
outsw(E33G_FIFOH, wrd, count);
break;
}
}
blocked:;
outb_p(ei_status.interface_num==0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
}
/* Read the 4 byte, page aligned 8390 specific header. */
static void
el2_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page)
{
int boguscount;
void __iomem *base = ei_status.mem;
unsigned short word;
if (base) { /* Use the shared memory. */
void __iomem *hdr_start = base + ((ring_page - EL2_MB1_START_PG)<<8);
memcpy_fromio(hdr, hdr_start, sizeof(struct e8390_pkt_hdr));
hdr->count = le16_to_cpu(hdr->count);
return;
}
/*
* No shared memory, use programmed I/O.
*/
word = (unsigned short)ring_page;
outb(word&0xFF, E33G_DMAAH);
outb(word>>8, E33G_DMAAL);
outb_p((ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI) | ECNTRL_INPUT
| ECNTRL_START, E33G_CNTRL);
boguscount = 0x1000;
while ((inb(E33G_STATUS) & ESTAT_DPRDY) == 0)
{
if(!boguscount--)
{
pr_notice("%s: FIFO blocked in el2_get_8390_hdr.\n", dev->name);
memset(hdr, 0x00, sizeof(struct e8390_pkt_hdr));
el2_reset_8390(dev);
goto blocked;
}
}
insw(E33G_FIFOH, hdr, (sizeof(struct e8390_pkt_hdr))>> 1);
blocked:;
outb_p(ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
}
static void
el2_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset)
{
int boguscount = 0;
void __iomem *base = ei_status.mem;
unsigned short int *buf;
unsigned short word;
/* Maybe enable shared memory just be to be safe... nahh.*/
if (base) { /* Use the shared memory. */
ring_offset -= (EL2_MB1_START_PG<<8);
if (ring_offset + count > EL2_MEMSIZE) {
/* We must wrap the input move. */
int semi_count = EL2_MEMSIZE - ring_offset;
memcpy_fromio(skb->data, base + ring_offset, semi_count);
count -= semi_count;
memcpy_fromio(skb->data + semi_count, base + ei_status.priv, count);
} else {
memcpy_fromio(skb->data, base + ring_offset, count);
}
return;
}
/*
* No shared memory, use programmed I/O.
*/
word = (unsigned short) ring_offset;
outb(word>>8, E33G_DMAAH);
outb(word&0xFF, E33G_DMAAL);
outb_p((ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI) | ECNTRL_INPUT
| ECNTRL_START, E33G_CNTRL);
/*
* Here I also try to get data as fast as possible. I am betting that I
* can read one extra byte without clobbering anything in the kernel because
* this would only occur on an odd byte-count and allocation of skb->data
* is word-aligned. Variable 'count' is NOT checked. Caller must check
* for a valid count.
* [This is currently quite safe.... but if one day the 3c503 explodes
* you know where to come looking ;)]
*/
buf = (unsigned short int *) skb->data;
count = (count + 1) >> 1;
for(;;)
{
boguscount = 0x1000;
while ((inb(E33G_STATUS) & ESTAT_DPRDY) == 0)
{
if(!boguscount--)
{
pr_notice("%s: FIFO blocked in el2_block_input.\n", dev->name);
el2_reset_8390(dev);
goto blocked;
}
}
if(count > WRD_COUNT)
{
insw(E33G_FIFOH, buf, WRD_COUNT);
buf += WRD_COUNT;
count -= WRD_COUNT;
}
else
{
insw(E33G_FIFOH, buf, count);
break;
}
}
blocked:;
outb_p(ei_status.interface_num == 0 ? ECNTRL_THIN : ECNTRL_AUI, E33G_CNTRL);
}
static void netdev_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
sprintf(info->bus_info, "ISA 0x%lx", dev->base_addr);
}
static const struct ethtool_ops netdev_ethtool_ops = {
.get_drvinfo = netdev_get_drvinfo,
};
#ifdef MODULE
#define MAX_EL2_CARDS 4 /* Max number of EL2 cards per module */
static struct net_device *dev_el2[MAX_EL2_CARDS];
static int io[MAX_EL2_CARDS];
static int irq[MAX_EL2_CARDS];
static int xcvr[MAX_EL2_CARDS]; /* choose int. or ext. xcvr */
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param_array(xcvr, int, NULL, 0);
MODULE_PARM_DESC(io, "I/O base address(es)");
MODULE_PARM_DESC(irq, "IRQ number(s) (assigned)");
MODULE_PARM_DESC(xcvr, "transceiver(s) (0=internal, 1=external)");
MODULE_DESCRIPTION("3Com ISA EtherLink II, II/16 (3c503, 3c503/16) driver");
MODULE_LICENSE("GPL");
/* This is set up so that only a single autoprobe takes place per call.
ISA device autoprobes on a running machine are not recommended. */
int __init
init_module(void)
{
struct net_device *dev;
int this_dev, found = 0;
for (this_dev = 0; this_dev < MAX_EL2_CARDS; this_dev++) {
if (io[this_dev] == 0) {
if (this_dev != 0) break; /* only autoprobe 1st one */
pr_notice("3c503.c: Presently autoprobing (not recommended) for a single card.\n");
}
dev = alloc_eip_netdev();
if (!dev)
break;
dev->irq = irq[this_dev];
dev->base_addr = io[this_dev];
dev->mem_end = xcvr[this_dev]; /* low 4bits = xcvr sel. */
if (do_el2_probe(dev) == 0) {
dev_el2[found++] = dev;
continue;
}
free_netdev(dev);
pr_warning("3c503.c: No 3c503 card found (i/o = 0x%x).\n", io[this_dev]);
break;
}
if (found)
return 0;
return -ENXIO;
}
static void cleanup_card(struct net_device *dev)
{
/* NB: el2_close() handles free_irq */
release_region(dev->base_addr, EL2_IO_EXTENT);
if (ei_status.mem)
iounmap(ei_status.mem);
}
void __exit
cleanup_module(void)
{
int this_dev;
for (this_dev = 0; this_dev < MAX_EL2_CARDS; this_dev++) {
struct net_device *dev = dev_el2[this_dev];
if (dev) {
unregister_netdev(dev);
cleanup_card(dev);
free_netdev(dev);
}
}
}
#endif /* MODULE */
| gpl-2.0 |
tim-yang/linux-3.8 | drivers/net/wimax/i2400m/rx.c | 5334 | 43839 | /*
* Intel Wireless WiMAX Connection 2400m
* Handle incoming traffic and deliver it to the control or data planes
*
*
* Copyright (C) 2007-2008 Intel Corporation. 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Intel Corporation <linux-wimax@intel.com>
* Yanir Lubetkin <yanirx.lubetkin@intel.com>
* - Initial implementation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
* - Use skb_clone(), break up processing in chunks
* - Split transport/device specific
* - Make buffer size dynamic to exert less memory pressure
* - RX reorder support
*
* This handles the RX path.
*
* We receive an RX message from the bus-specific driver, which
* contains one or more payloads that have potentially different
* destinataries (data or control paths).
*
* So we just take that payload from the transport specific code in
* the form of an skb, break it up in chunks (a cloned skb each in the
* case of network packets) and pass it to netdev or to the
* command/ack handler (and from there to the WiMAX stack).
*
* PROTOCOL FORMAT
*
* The format of the buffer is:
*
* HEADER (struct i2400m_msg_hdr)
* PAYLOAD DESCRIPTOR 0 (struct i2400m_pld)
* PAYLOAD DESCRIPTOR 1
* ...
* PAYLOAD DESCRIPTOR N
* PAYLOAD 0 (raw bytes)
* PAYLOAD 1
* ...
* PAYLOAD N
*
* See tx.c for a deeper description on alignment requirements and
* other fun facts of it.
*
* DATA PACKETS
*
* In firmwares <= v1.3, data packets have no header for RX, but they
* do for TX (currently unused).
*
* In firmware >= 1.4, RX packets have an extended header (16
* bytes). This header conveys information for management of host
* reordering of packets (the device offloads storage of the packets
* for reordering to the host). Read below for more information.
*
* The header is used as dummy space to emulate an ethernet header and
* thus be able to act as an ethernet device without having to reallocate.
*
* DATA RX REORDERING
*
* Starting in firmware v1.4, the device can deliver packets for
* delivery with special reordering information; this allows it to
* more effectively do packet management when some frames were lost in
* the radio traffic.
*
* Thus, for RX packets that come out of order, the device gives the
* driver enough information to queue them properly and then at some
* point, the signal to deliver the whole (or part) of the queued
* packets to the networking stack. There are 16 such queues.
*
* This only happens when a packet comes in with the "need reorder"
* flag set in the RX header. When such bit is set, the following
* operations might be indicated:
*
* - reset queue: send all queued packets to the OS
*
* - queue: queue a packet
*
* - update ws: update the queue's window start and deliver queued
* packets that meet the criteria
*
* - queue & update ws: queue a packet, update the window start and
* deliver queued packets that meet the criteria
*
* (delivery criteria: the packet's [normalized] sequence number is
* lower than the new [normalized] window start).
*
* See the i2400m_roq_*() functions for details.
*
* ROADMAP
*
* i2400m_rx
* i2400m_rx_msg_hdr_check
* i2400m_rx_pl_descr_check
* i2400m_rx_payload
* i2400m_net_rx
* i2400m_rx_edata
* i2400m_net_erx
* i2400m_roq_reset
* i2400m_net_erx
* i2400m_roq_queue
* __i2400m_roq_queue
* i2400m_roq_update_ws
* __i2400m_roq_update_ws
* i2400m_net_erx
* i2400m_roq_queue_update_ws
* __i2400m_roq_queue
* __i2400m_roq_update_ws
* i2400m_net_erx
* i2400m_rx_ctl
* i2400m_msg_size_check
* i2400m_report_hook_work [in a workqueue]
* i2400m_report_hook
* wimax_msg_to_user
* i2400m_rx_ctl_ack
* wimax_msg_to_user_alloc
* i2400m_rx_trace
* i2400m_msg_size_check
* wimax_msg
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/if_arp.h>
#include <linux/netdevice.h>
#include <linux/workqueue.h>
#include <linux/export.h>
#include <linux/moduleparam.h>
#include "i2400m.h"
#define D_SUBMODULE rx
#include "debug-levels.h"
static int i2400m_rx_reorder_disabled; /* 0 (rx reorder enabled) by default */
module_param_named(rx_reorder_disabled, i2400m_rx_reorder_disabled, int, 0644);
MODULE_PARM_DESC(rx_reorder_disabled,
"If true, RX reordering will be disabled.");
struct i2400m_report_hook_args {
struct sk_buff *skb_rx;
const struct i2400m_l3l4_hdr *l3l4_hdr;
size_t size;
struct list_head list_node;
};
/*
* Execute i2400m_report_hook in a workqueue
*
* Goes over the list of queued reports in i2400m->rx_reports and
* processes them.
*
* NOTE: refcounts on i2400m are not needed because we flush the
* workqueue this runs on (i2400m->work_queue) before destroying
* i2400m.
*/
void i2400m_report_hook_work(struct work_struct *ws)
{
struct i2400m *i2400m = container_of(ws, struct i2400m, rx_report_ws);
struct device *dev = i2400m_dev(i2400m);
struct i2400m_report_hook_args *args, *args_next;
LIST_HEAD(list);
unsigned long flags;
while (1) {
spin_lock_irqsave(&i2400m->rx_lock, flags);
list_splice_init(&i2400m->rx_reports, &list);
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
if (list_empty(&list))
break;
else
d_printf(1, dev, "processing queued reports\n");
list_for_each_entry_safe(args, args_next, &list, list_node) {
d_printf(2, dev, "processing queued report %p\n", args);
i2400m_report_hook(i2400m, args->l3l4_hdr, args->size);
kfree_skb(args->skb_rx);
list_del(&args->list_node);
kfree(args);
}
}
}
/*
* Flush the list of queued reports
*/
static
void i2400m_report_hook_flush(struct i2400m *i2400m)
{
struct device *dev = i2400m_dev(i2400m);
struct i2400m_report_hook_args *args, *args_next;
LIST_HEAD(list);
unsigned long flags;
d_printf(1, dev, "flushing queued reports\n");
spin_lock_irqsave(&i2400m->rx_lock, flags);
list_splice_init(&i2400m->rx_reports, &list);
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
list_for_each_entry_safe(args, args_next, &list, list_node) {
d_printf(2, dev, "flushing queued report %p\n", args);
kfree_skb(args->skb_rx);
list_del(&args->list_node);
kfree(args);
}
}
/*
* Queue a report for later processing
*
* @i2400m: device descriptor
* @skb_rx: skb that contains the payload (for reference counting)
* @l3l4_hdr: pointer to the control
* @size: size of the message
*/
static
void i2400m_report_hook_queue(struct i2400m *i2400m, struct sk_buff *skb_rx,
const void *l3l4_hdr, size_t size)
{
struct device *dev = i2400m_dev(i2400m);
unsigned long flags;
struct i2400m_report_hook_args *args;
args = kzalloc(sizeof(*args), GFP_NOIO);
if (args) {
args->skb_rx = skb_get(skb_rx);
args->l3l4_hdr = l3l4_hdr;
args->size = size;
spin_lock_irqsave(&i2400m->rx_lock, flags);
list_add_tail(&args->list_node, &i2400m->rx_reports);
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
d_printf(2, dev, "queued report %p\n", args);
rmb(); /* see i2400m->ready's documentation */
if (likely(i2400m->ready)) /* only send if up */
queue_work(i2400m->work_queue, &i2400m->rx_report_ws);
} else {
if (printk_ratelimit())
dev_err(dev, "%s:%u: Can't allocate %zu B\n",
__func__, __LINE__, sizeof(*args));
}
}
/*
* Process an ack to a command
*
* @i2400m: device descriptor
* @payload: pointer to message
* @size: size of the message
*
* Pass the acknodledgment (in an skb) to the thread that is waiting
* for it in i2400m->msg_completion.
*
* We need to coordinate properly with the thread waiting for the
* ack. Check if it is waiting or if it is gone. We loose the spinlock
* to avoid allocating on atomic contexts (yeah, could use GFP_ATOMIC,
* but this is not so speed critical).
*/
static
void i2400m_rx_ctl_ack(struct i2400m *i2400m,
const void *payload, size_t size)
{
struct device *dev = i2400m_dev(i2400m);
struct wimax_dev *wimax_dev = &i2400m->wimax_dev;
unsigned long flags;
struct sk_buff *ack_skb;
/* Anyone waiting for an answer? */
spin_lock_irqsave(&i2400m->rx_lock, flags);
if (i2400m->ack_skb != ERR_PTR(-EINPROGRESS)) {
dev_err(dev, "Huh? reply to command with no waiters\n");
goto error_no_waiter;
}
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
ack_skb = wimax_msg_alloc(wimax_dev, NULL, payload, size, GFP_KERNEL);
/* Check waiter didn't time out waiting for the answer... */
spin_lock_irqsave(&i2400m->rx_lock, flags);
if (i2400m->ack_skb != ERR_PTR(-EINPROGRESS)) {
d_printf(1, dev, "Huh? waiter for command reply cancelled\n");
goto error_waiter_cancelled;
}
if (IS_ERR(ack_skb))
dev_err(dev, "CMD/GET/SET ack: cannot allocate SKB\n");
i2400m->ack_skb = ack_skb;
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
complete(&i2400m->msg_completion);
return;
error_waiter_cancelled:
if (!IS_ERR(ack_skb))
kfree_skb(ack_skb);
error_no_waiter:
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
}
/*
* Receive and process a control payload
*
* @i2400m: device descriptor
* @skb_rx: skb that contains the payload (for reference counting)
* @payload: pointer to message
* @size: size of the message
*
* There are two types of control RX messages: reports (asynchronous,
* like your every day interrupts) and 'acks' (reponses to a command,
* get or set request).
*
* If it is a report, we run hooks on it (to extract information for
* things we need to do in the driver) and then pass it over to the
* WiMAX stack to send it to user space.
*
* NOTE: report processing is done in a workqueue specific to the
* generic driver, to avoid deadlocks in the system.
*
* If it is not a report, it is an ack to a previously executed
* command, set or get, so wake up whoever is waiting for it from
* i2400m_msg_to_dev(). i2400m_rx_ctl_ack() takes care of that.
*
* Note that the sizes we pass to other functions from here are the
* sizes of the _l3l4_hdr + payload, not full buffer sizes, as we have
* verified in _msg_size_check() that they are congruent.
*
* For reports: We can't clone the original skb where the data is
* because we need to send this up via netlink; netlink has to add
* headers and we can't overwrite what's preceding the payload...as
* it is another message. So we just dup them.
*/
static
void i2400m_rx_ctl(struct i2400m *i2400m, struct sk_buff *skb_rx,
const void *payload, size_t size)
{
int result;
struct device *dev = i2400m_dev(i2400m);
const struct i2400m_l3l4_hdr *l3l4_hdr = payload;
unsigned msg_type;
result = i2400m_msg_size_check(i2400m, l3l4_hdr, size);
if (result < 0) {
dev_err(dev, "HW BUG? device sent a bad message: %d\n",
result);
goto error_check;
}
msg_type = le16_to_cpu(l3l4_hdr->type);
d_printf(1, dev, "%s 0x%04x: %zu bytes\n",
msg_type & I2400M_MT_REPORT_MASK ? "REPORT" : "CMD/SET/GET",
msg_type, size);
d_dump(2, dev, l3l4_hdr, size);
if (msg_type & I2400M_MT_REPORT_MASK) {
/*
* Process each report
*
* - has to be ran serialized as well
*
* - the handling might force the execution of
* commands. That might cause reentrancy issues with
* bus-specific subdrivers and workqueues, so the we
* run it in a separate workqueue.
*
* - when the driver is not yet ready to handle them,
* they are queued and at some point the queue is
* restarted [NOTE: we can't queue SKBs directly, as
* this might be a piece of a SKB, not the whole
* thing, and this is cheaper than cloning the
* SKB].
*
* Note we don't do refcounting for the device
* structure; this is because before destroying
* 'i2400m', we make sure to flush the
* i2400m->work_queue, so there are no issues.
*/
i2400m_report_hook_queue(i2400m, skb_rx, l3l4_hdr, size);
if (unlikely(i2400m->trace_msg_from_user))
wimax_msg(&i2400m->wimax_dev, "echo",
l3l4_hdr, size, GFP_KERNEL);
result = wimax_msg(&i2400m->wimax_dev, NULL, l3l4_hdr, size,
GFP_KERNEL);
if (result < 0)
dev_err(dev, "error sending report to userspace: %d\n",
result);
} else /* an ack to a CMD, GET or SET */
i2400m_rx_ctl_ack(i2400m, payload, size);
error_check:
return;
}
/*
* Receive and send up a trace
*
* @i2400m: device descriptor
* @skb_rx: skb that contains the trace (for reference counting)
* @payload: pointer to trace message inside the skb
* @size: size of the message
*
* THe i2400m might produce trace information (diagnostics) and we
* send them through a different kernel-to-user pipe (to avoid
* clogging it).
*
* As in i2400m_rx_ctl(), we can't clone the original skb where the
* data is because we need to send this up via netlink; netlink has to
* add headers and we can't overwrite what's preceding the
* payload...as it is another message. So we just dup them.
*/
static
void i2400m_rx_trace(struct i2400m *i2400m,
const void *payload, size_t size)
{
int result;
struct device *dev = i2400m_dev(i2400m);
struct wimax_dev *wimax_dev = &i2400m->wimax_dev;
const struct i2400m_l3l4_hdr *l3l4_hdr = payload;
unsigned msg_type;
result = i2400m_msg_size_check(i2400m, l3l4_hdr, size);
if (result < 0) {
dev_err(dev, "HW BUG? device sent a bad trace message: %d\n",
result);
goto error_check;
}
msg_type = le16_to_cpu(l3l4_hdr->type);
d_printf(1, dev, "Trace %s 0x%04x: %zu bytes\n",
msg_type & I2400M_MT_REPORT_MASK ? "REPORT" : "CMD/SET/GET",
msg_type, size);
d_dump(2, dev, l3l4_hdr, size);
result = wimax_msg(wimax_dev, "trace", l3l4_hdr, size, GFP_KERNEL);
if (result < 0)
dev_err(dev, "error sending trace to userspace: %d\n",
result);
error_check:
return;
}
/*
* Reorder queue data stored on skb->cb while the skb is queued in the
* reorder queues.
*/
struct i2400m_roq_data {
unsigned sn; /* Serial number for the skb */
enum i2400m_cs cs; /* packet type for the skb */
};
/*
* ReOrder Queue
*
* @ws: Window Start; sequence number where the current window start
* is for this queue
* @queue: the skb queue itself
* @log: circular ring buffer used to log information about the
* reorder process in this queue that can be displayed in case of
* error to help diagnose it.
*
* This is the head for a list of skbs. In the skb->cb member of the
* skb when queued here contains a 'struct i2400m_roq_data' were we
* store the sequence number (sn) and the cs (packet type) coming from
* the RX payload header from the device.
*/
struct i2400m_roq
{
unsigned ws;
struct sk_buff_head queue;
struct i2400m_roq_log *log;
};
static
void __i2400m_roq_init(struct i2400m_roq *roq)
{
roq->ws = 0;
skb_queue_head_init(&roq->queue);
}
static
unsigned __i2400m_roq_index(struct i2400m *i2400m, struct i2400m_roq *roq)
{
return ((unsigned long) roq - (unsigned long) i2400m->rx_roq)
/ sizeof(*roq);
}
/*
* Normalize a sequence number based on the queue's window start
*
* nsn = (sn - ws) % 2048
*
* Note that if @sn < @roq->ws, we still need a positive number; %'s
* sign is implementation specific, so we normalize it by adding 2048
* to bring it to be positive.
*/
static
unsigned __i2400m_roq_nsn(struct i2400m_roq *roq, unsigned sn)
{
int r;
r = ((int) sn - (int) roq->ws) % 2048;
if (r < 0)
r += 2048;
return r;
}
/*
* Circular buffer to keep the last N reorder operations
*
* In case something fails, dumb then to try to come up with what
* happened.
*/
enum {
I2400M_ROQ_LOG_LENGTH = 32,
};
struct i2400m_roq_log {
struct i2400m_roq_log_entry {
enum i2400m_ro_type type;
unsigned ws, count, sn, nsn, new_ws;
} entry[I2400M_ROQ_LOG_LENGTH];
unsigned in, out;
};
/* Print a log entry */
static
void i2400m_roq_log_entry_print(struct i2400m *i2400m, unsigned index,
unsigned e_index,
struct i2400m_roq_log_entry *e)
{
struct device *dev = i2400m_dev(i2400m);
switch(e->type) {
case I2400M_RO_TYPE_RESET:
dev_err(dev, "q#%d reset ws %u cnt %u sn %u/%u"
" - new nws %u\n",
index, e->ws, e->count, e->sn, e->nsn, e->new_ws);
break;
case I2400M_RO_TYPE_PACKET:
dev_err(dev, "q#%d queue ws %u cnt %u sn %u/%u\n",
index, e->ws, e->count, e->sn, e->nsn);
break;
case I2400M_RO_TYPE_WS:
dev_err(dev, "q#%d update_ws ws %u cnt %u sn %u/%u"
" - new nws %u\n",
index, e->ws, e->count, e->sn, e->nsn, e->new_ws);
break;
case I2400M_RO_TYPE_PACKET_WS:
dev_err(dev, "q#%d queue_update_ws ws %u cnt %u sn %u/%u"
" - new nws %u\n",
index, e->ws, e->count, e->sn, e->nsn, e->new_ws);
break;
default:
dev_err(dev, "q#%d BUG? entry %u - unknown type %u\n",
index, e_index, e->type);
break;
}
}
static
void i2400m_roq_log_add(struct i2400m *i2400m,
struct i2400m_roq *roq, enum i2400m_ro_type type,
unsigned ws, unsigned count, unsigned sn,
unsigned nsn, unsigned new_ws)
{
struct i2400m_roq_log_entry *e;
unsigned cnt_idx;
int index = __i2400m_roq_index(i2400m, roq);
/* if we run out of space, we eat from the end */
if (roq->log->in - roq->log->out == I2400M_ROQ_LOG_LENGTH)
roq->log->out++;
cnt_idx = roq->log->in++ % I2400M_ROQ_LOG_LENGTH;
e = &roq->log->entry[cnt_idx];
e->type = type;
e->ws = ws;
e->count = count;
e->sn = sn;
e->nsn = nsn;
e->new_ws = new_ws;
if (d_test(1))
i2400m_roq_log_entry_print(i2400m, index, cnt_idx, e);
}
/* Dump all the entries in the FIFO and reinitialize it */
static
void i2400m_roq_log_dump(struct i2400m *i2400m, struct i2400m_roq *roq)
{
unsigned cnt, cnt_idx;
struct i2400m_roq_log_entry *e;
int index = __i2400m_roq_index(i2400m, roq);
BUG_ON(roq->log->out > roq->log->in);
for (cnt = roq->log->out; cnt < roq->log->in; cnt++) {
cnt_idx = cnt % I2400M_ROQ_LOG_LENGTH;
e = &roq->log->entry[cnt_idx];
i2400m_roq_log_entry_print(i2400m, index, cnt_idx, e);
memset(e, 0, sizeof(*e));
}
roq->log->in = roq->log->out = 0;
}
/*
* Backbone for the queuing of an skb (by normalized sequence number)
*
* @i2400m: device descriptor
* @roq: reorder queue where to add
* @skb: the skb to add
* @sn: the sequence number of the skb
* @nsn: the normalized sequence number of the skb (pre-computed by the
* caller from the @sn and @roq->ws).
*
* We try first a couple of quick cases:
*
* - the queue is empty
* - the skb would be appended to the queue
*
* These will be the most common operations.
*
* If these fail, then we have to do a sorted insertion in the queue,
* which is the slowest path.
*
* We don't have to acquire a reference count as we are going to own it.
*/
static
void __i2400m_roq_queue(struct i2400m *i2400m, struct i2400m_roq *roq,
struct sk_buff *skb, unsigned sn, unsigned nsn)
{
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *skb_itr;
struct i2400m_roq_data *roq_data_itr, *roq_data;
unsigned nsn_itr;
d_fnstart(4, dev, "(i2400m %p roq %p skb %p sn %u nsn %u)\n",
i2400m, roq, skb, sn, nsn);
roq_data = (struct i2400m_roq_data *) &skb->cb;
BUILD_BUG_ON(sizeof(*roq_data) > sizeof(skb->cb));
roq_data->sn = sn;
d_printf(3, dev, "ERX: roq %p [ws %u] nsn %d sn %u\n",
roq, roq->ws, nsn, roq_data->sn);
/* Queues will be empty on not-so-bad environments, so try
* that first */
if (skb_queue_empty(&roq->queue)) {
d_printf(2, dev, "ERX: roq %p - first one\n", roq);
__skb_queue_head(&roq->queue, skb);
goto out;
}
/* Now try append, as most of the operations will be that */
skb_itr = skb_peek_tail(&roq->queue);
roq_data_itr = (struct i2400m_roq_data *) &skb_itr->cb;
nsn_itr = __i2400m_roq_nsn(roq, roq_data_itr->sn);
/* NSN bounds assumed correct (checked when it was queued) */
if (nsn >= nsn_itr) {
d_printf(2, dev, "ERX: roq %p - appended after %p (nsn %d sn %u)\n",
roq, skb_itr, nsn_itr, roq_data_itr->sn);
__skb_queue_tail(&roq->queue, skb);
goto out;
}
/* None of the fast paths option worked. Iterate to find the
* right spot where to insert the packet; we know the queue is
* not empty, so we are not the first ones; we also know we
* are not going to be the last ones. The list is sorted, so
* we have to insert before the the first guy with an nsn_itr
* greater that our nsn. */
skb_queue_walk(&roq->queue, skb_itr) {
roq_data_itr = (struct i2400m_roq_data *) &skb_itr->cb;
nsn_itr = __i2400m_roq_nsn(roq, roq_data_itr->sn);
/* NSN bounds assumed correct (checked when it was queued) */
if (nsn_itr > nsn) {
d_printf(2, dev, "ERX: roq %p - queued before %p "
"(nsn %d sn %u)\n", roq, skb_itr, nsn_itr,
roq_data_itr->sn);
__skb_queue_before(&roq->queue, skb_itr, skb);
goto out;
}
}
/* If we get here, that is VERY bad -- print info to help
* diagnose and crash it */
dev_err(dev, "SW BUG? failed to insert packet\n");
dev_err(dev, "ERX: roq %p [ws %u] skb %p nsn %d sn %u\n",
roq, roq->ws, skb, nsn, roq_data->sn);
skb_queue_walk(&roq->queue, skb_itr) {
roq_data_itr = (struct i2400m_roq_data *) &skb_itr->cb;
nsn_itr = __i2400m_roq_nsn(roq, roq_data_itr->sn);
/* NSN bounds assumed correct (checked when it was queued) */
dev_err(dev, "ERX: roq %p skb_itr %p nsn %d sn %u\n",
roq, skb_itr, nsn_itr, roq_data_itr->sn);
}
BUG();
out:
d_fnend(4, dev, "(i2400m %p roq %p skb %p sn %u nsn %d) = void\n",
i2400m, roq, skb, sn, nsn);
}
/*
* Backbone for the update window start operation
*
* @i2400m: device descriptor
* @roq: Reorder queue
* @sn: New sequence number
*
* Updates the window start of a queue; when doing so, it must deliver
* to the networking stack all the queued skb's whose normalized
* sequence number is lower than the new normalized window start.
*/
static
unsigned __i2400m_roq_update_ws(struct i2400m *i2400m, struct i2400m_roq *roq,
unsigned sn)
{
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *skb_itr, *tmp_itr;
struct i2400m_roq_data *roq_data_itr;
unsigned new_nws, nsn_itr;
new_nws = __i2400m_roq_nsn(roq, sn);
/*
* For type 2(update_window_start) rx messages, there is no
* need to check if the normalized sequence number is greater 1023.
* Simply insert and deliver all packets to the host up to the
* window start.
*/
skb_queue_walk_safe(&roq->queue, skb_itr, tmp_itr) {
roq_data_itr = (struct i2400m_roq_data *) &skb_itr->cb;
nsn_itr = __i2400m_roq_nsn(roq, roq_data_itr->sn);
/* NSN bounds assumed correct (checked when it was queued) */
if (nsn_itr < new_nws) {
d_printf(2, dev, "ERX: roq %p - release skb %p "
"(nsn %u/%u new nws %u)\n",
roq, skb_itr, nsn_itr, roq_data_itr->sn,
new_nws);
__skb_unlink(skb_itr, &roq->queue);
i2400m_net_erx(i2400m, skb_itr, roq_data_itr->cs);
}
else
break; /* rest of packets all nsn_itr > nws */
}
roq->ws = sn;
return new_nws;
}
/*
* Reset a queue
*
* @i2400m: device descriptor
* @cin: Queue Index
*
* Deliver all the packets and reset the window-start to zero. Name is
* kind of misleading.
*/
static
void i2400m_roq_reset(struct i2400m *i2400m, struct i2400m_roq *roq)
{
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *skb_itr, *tmp_itr;
struct i2400m_roq_data *roq_data_itr;
d_fnstart(2, dev, "(i2400m %p roq %p)\n", i2400m, roq);
i2400m_roq_log_add(i2400m, roq, I2400M_RO_TYPE_RESET,
roq->ws, skb_queue_len(&roq->queue),
~0, ~0, 0);
skb_queue_walk_safe(&roq->queue, skb_itr, tmp_itr) {
roq_data_itr = (struct i2400m_roq_data *) &skb_itr->cb;
d_printf(2, dev, "ERX: roq %p - release skb %p (sn %u)\n",
roq, skb_itr, roq_data_itr->sn);
__skb_unlink(skb_itr, &roq->queue);
i2400m_net_erx(i2400m, skb_itr, roq_data_itr->cs);
}
roq->ws = 0;
d_fnend(2, dev, "(i2400m %p roq %p) = void\n", i2400m, roq);
}
/*
* Queue a packet
*
* @i2400m: device descriptor
* @cin: Queue Index
* @skb: containing the packet data
* @fbn: First block number of the packet in @skb
* @lbn: Last block number of the packet in @skb
*
* The hardware is asking the driver to queue a packet for later
* delivery to the networking stack.
*/
static
void i2400m_roq_queue(struct i2400m *i2400m, struct i2400m_roq *roq,
struct sk_buff * skb, unsigned lbn)
{
struct device *dev = i2400m_dev(i2400m);
unsigned nsn, len;
d_fnstart(2, dev, "(i2400m %p roq %p skb %p lbn %u) = void\n",
i2400m, roq, skb, lbn);
len = skb_queue_len(&roq->queue);
nsn = __i2400m_roq_nsn(roq, lbn);
if (unlikely(nsn >= 1024)) {
dev_err(dev, "SW BUG? queue nsn %d (lbn %u ws %u)\n",
nsn, lbn, roq->ws);
i2400m_roq_log_dump(i2400m, roq);
i2400m_reset(i2400m, I2400M_RT_WARM);
} else {
__i2400m_roq_queue(i2400m, roq, skb, lbn, nsn);
i2400m_roq_log_add(i2400m, roq, I2400M_RO_TYPE_PACKET,
roq->ws, len, lbn, nsn, ~0);
}
d_fnend(2, dev, "(i2400m %p roq %p skb %p lbn %u) = void\n",
i2400m, roq, skb, lbn);
}
/*
* Update the window start in a reorder queue and deliver all skbs
* with a lower window start
*
* @i2400m: device descriptor
* @roq: Reorder queue
* @sn: New sequence number
*/
static
void i2400m_roq_update_ws(struct i2400m *i2400m, struct i2400m_roq *roq,
unsigned sn)
{
struct device *dev = i2400m_dev(i2400m);
unsigned old_ws, nsn, len;
d_fnstart(2, dev, "(i2400m %p roq %p sn %u)\n", i2400m, roq, sn);
old_ws = roq->ws;
len = skb_queue_len(&roq->queue);
nsn = __i2400m_roq_update_ws(i2400m, roq, sn);
i2400m_roq_log_add(i2400m, roq, I2400M_RO_TYPE_WS,
old_ws, len, sn, nsn, roq->ws);
d_fnstart(2, dev, "(i2400m %p roq %p sn %u) = void\n", i2400m, roq, sn);
}
/*
* Queue a packet and update the window start
*
* @i2400m: device descriptor
* @cin: Queue Index
* @skb: containing the packet data
* @fbn: First block number of the packet in @skb
* @sn: Last block number of the packet in @skb
*
* Note that unlike i2400m_roq_update_ws(), which sets the new window
* start to @sn, in here we'll set it to @sn + 1.
*/
static
void i2400m_roq_queue_update_ws(struct i2400m *i2400m, struct i2400m_roq *roq,
struct sk_buff * skb, unsigned sn)
{
struct device *dev = i2400m_dev(i2400m);
unsigned nsn, old_ws, len;
d_fnstart(2, dev, "(i2400m %p roq %p skb %p sn %u)\n",
i2400m, roq, skb, sn);
len = skb_queue_len(&roq->queue);
nsn = __i2400m_roq_nsn(roq, sn);
/*
* For type 3(queue_update_window_start) rx messages, there is no
* need to check if the normalized sequence number is greater 1023.
* Simply insert and deliver all packets to the host up to the
* window start.
*/
old_ws = roq->ws;
/* If the queue is empty, don't bother as we'd queue
* it and immediately unqueue it -- just deliver it.
*/
if (len == 0) {
struct i2400m_roq_data *roq_data;
roq_data = (struct i2400m_roq_data *) &skb->cb;
i2400m_net_erx(i2400m, skb, roq_data->cs);
} else
__i2400m_roq_queue(i2400m, roq, skb, sn, nsn);
__i2400m_roq_update_ws(i2400m, roq, sn + 1);
i2400m_roq_log_add(i2400m, roq, I2400M_RO_TYPE_PACKET_WS,
old_ws, len, sn, nsn, roq->ws);
d_fnend(2, dev, "(i2400m %p roq %p skb %p sn %u) = void\n",
i2400m, roq, skb, sn);
}
/*
* This routine destroys the memory allocated for rx_roq, when no
* other thread is accessing it. Access to rx_roq is refcounted by
* rx_roq_refcount, hence memory allocated must be destroyed when
* rx_roq_refcount becomes zero. This routine gets executed when
* rx_roq_refcount becomes zero.
*/
static void i2400m_rx_roq_destroy(struct kref *ref)
{
unsigned itr;
struct i2400m *i2400m
= container_of(ref, struct i2400m, rx_roq_refcount);
for (itr = 0; itr < I2400M_RO_CIN + 1; itr++)
__skb_queue_purge(&i2400m->rx_roq[itr].queue);
kfree(i2400m->rx_roq[0].log);
kfree(i2400m->rx_roq);
i2400m->rx_roq = NULL;
}
/*
* Receive and send up an extended data packet
*
* @i2400m: device descriptor
* @skb_rx: skb that contains the extended data packet
* @single_last: 1 if the payload is the only one or the last one of
* the skb.
* @payload: pointer to the packet's data inside the skb
* @size: size of the payload
*
* Starting in v1.4 of the i2400m's firmware, the device can send data
* packets to the host in an extended format that; this incudes a 16
* byte header (struct i2400m_pl_edata_hdr). Using this header's space
* we can fake ethernet headers for ethernet device emulation without
* having to copy packets around.
*
* This function handles said path.
*
*
* Receive and send up an extended data packet that requires no reordering
*
* @i2400m: device descriptor
* @skb_rx: skb that contains the extended data packet
* @single_last: 1 if the payload is the only one or the last one of
* the skb.
* @payload: pointer to the packet's data (past the actual extended
* data payload header).
* @size: size of the payload
*
* Pass over to the networking stack a data packet that might have
* reordering requirements.
*
* This needs to the decide if the skb in which the packet is
* contained can be reused or if it needs to be cloned. Then it has to
* be trimmed in the edges so that the beginning is the space for eth
* header and then pass it to i2400m_net_erx() for the stack
*
* Assumes the caller has verified the sanity of the payload (size,
* etc) already.
*/
static
void i2400m_rx_edata(struct i2400m *i2400m, struct sk_buff *skb_rx,
unsigned single_last, const void *payload, size_t size)
{
struct device *dev = i2400m_dev(i2400m);
const struct i2400m_pl_edata_hdr *hdr = payload;
struct net_device *net_dev = i2400m->wimax_dev.net_dev;
struct sk_buff *skb;
enum i2400m_cs cs;
u32 reorder;
unsigned ro_needed, ro_type, ro_cin, ro_sn;
struct i2400m_roq *roq;
struct i2400m_roq_data *roq_data;
unsigned long flags;
BUILD_BUG_ON(ETH_HLEN > sizeof(*hdr));
d_fnstart(2, dev, "(i2400m %p skb_rx %p single %u payload %p "
"size %zu)\n", i2400m, skb_rx, single_last, payload, size);
if (size < sizeof(*hdr)) {
dev_err(dev, "ERX: HW BUG? message with short header (%zu "
"vs %zu bytes expected)\n", size, sizeof(*hdr));
goto error;
}
if (single_last) {
skb = skb_get(skb_rx);
d_printf(3, dev, "ERX: skb %p reusing\n", skb);
} else {
skb = skb_clone(skb_rx, GFP_KERNEL);
if (skb == NULL) {
dev_err(dev, "ERX: no memory to clone skb\n");
net_dev->stats.rx_dropped++;
goto error_skb_clone;
}
d_printf(3, dev, "ERX: skb %p cloned from %p\n", skb, skb_rx);
}
/* now we have to pull and trim so that the skb points to the
* beginning of the IP packet; the netdev part will add the
* ethernet header as needed - we know there is enough space
* because we checked in i2400m_rx_edata(). */
skb_pull(skb, payload + sizeof(*hdr) - (void *) skb->data);
skb_trim(skb, (void *) skb_end_pointer(skb) - payload - sizeof(*hdr));
reorder = le32_to_cpu(hdr->reorder);
ro_needed = reorder & I2400M_RO_NEEDED;
cs = hdr->cs;
if (ro_needed) {
ro_type = (reorder >> I2400M_RO_TYPE_SHIFT) & I2400M_RO_TYPE;
ro_cin = (reorder >> I2400M_RO_CIN_SHIFT) & I2400M_RO_CIN;
ro_sn = (reorder >> I2400M_RO_SN_SHIFT) & I2400M_RO_SN;
spin_lock_irqsave(&i2400m->rx_lock, flags);
if (i2400m->rx_roq == NULL) {
kfree_skb(skb); /* rx_roq is already destroyed */
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
goto error;
}
roq = &i2400m->rx_roq[ro_cin];
kref_get(&i2400m->rx_roq_refcount);
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
roq_data = (struct i2400m_roq_data *) &skb->cb;
roq_data->sn = ro_sn;
roq_data->cs = cs;
d_printf(2, dev, "ERX: reorder needed: "
"type %u cin %u [ws %u] sn %u/%u len %zuB\n",
ro_type, ro_cin, roq->ws, ro_sn,
__i2400m_roq_nsn(roq, ro_sn), size);
d_dump(2, dev, payload, size);
switch(ro_type) {
case I2400M_RO_TYPE_RESET:
i2400m_roq_reset(i2400m, roq);
kfree_skb(skb); /* no data here */
break;
case I2400M_RO_TYPE_PACKET:
i2400m_roq_queue(i2400m, roq, skb, ro_sn);
break;
case I2400M_RO_TYPE_WS:
i2400m_roq_update_ws(i2400m, roq, ro_sn);
kfree_skb(skb); /* no data here */
break;
case I2400M_RO_TYPE_PACKET_WS:
i2400m_roq_queue_update_ws(i2400m, roq, skb, ro_sn);
break;
default:
dev_err(dev, "HW BUG? unknown reorder type %u\n", ro_type);
}
spin_lock_irqsave(&i2400m->rx_lock, flags);
kref_put(&i2400m->rx_roq_refcount, i2400m_rx_roq_destroy);
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
}
else
i2400m_net_erx(i2400m, skb, cs);
error_skb_clone:
error:
d_fnend(2, dev, "(i2400m %p skb_rx %p single %u payload %p "
"size %zu) = void\n", i2400m, skb_rx, single_last, payload, size);
}
/*
* Act on a received payload
*
* @i2400m: device instance
* @skb_rx: skb where the transaction was received
* @single_last: 1 this is the only payload or the last one (so the
* skb can be reused instead of cloned).
* @pld: payload descriptor
* @payload: payload data
*
* Upon reception of a payload, look at its guts in the payload
* descriptor and decide what to do with it. If it is a single payload
* skb or if the last skb is a data packet, the skb will be referenced
* and modified (so it doesn't have to be cloned).
*/
static
void i2400m_rx_payload(struct i2400m *i2400m, struct sk_buff *skb_rx,
unsigned single_last, const struct i2400m_pld *pld,
const void *payload)
{
struct device *dev = i2400m_dev(i2400m);
size_t pl_size = i2400m_pld_size(pld);
enum i2400m_pt pl_type = i2400m_pld_type(pld);
d_printf(7, dev, "RX: received payload type %u, %zu bytes\n",
pl_type, pl_size);
d_dump(8, dev, payload, pl_size);
switch (pl_type) {
case I2400M_PT_DATA:
d_printf(3, dev, "RX: data payload %zu bytes\n", pl_size);
i2400m_net_rx(i2400m, skb_rx, single_last, payload, pl_size);
break;
case I2400M_PT_CTRL:
i2400m_rx_ctl(i2400m, skb_rx, payload, pl_size);
break;
case I2400M_PT_TRACE:
i2400m_rx_trace(i2400m, payload, pl_size);
break;
case I2400M_PT_EDATA:
d_printf(3, dev, "ERX: data payload %zu bytes\n", pl_size);
i2400m_rx_edata(i2400m, skb_rx, single_last, payload, pl_size);
break;
default: /* Anything else shouldn't come to the host */
if (printk_ratelimit())
dev_err(dev, "RX: HW BUG? unexpected payload type %u\n",
pl_type);
}
}
/*
* Check a received transaction's message header
*
* @i2400m: device descriptor
* @msg_hdr: message header
* @buf_size: size of the received buffer
*
* Check that the declarations done by a RX buffer message header are
* sane and consistent with the amount of data that was received.
*/
static
int i2400m_rx_msg_hdr_check(struct i2400m *i2400m,
const struct i2400m_msg_hdr *msg_hdr,
size_t buf_size)
{
int result = -EIO;
struct device *dev = i2400m_dev(i2400m);
if (buf_size < sizeof(*msg_hdr)) {
dev_err(dev, "RX: HW BUG? message with short header (%zu "
"vs %zu bytes expected)\n", buf_size, sizeof(*msg_hdr));
goto error;
}
if (msg_hdr->barker != cpu_to_le32(I2400M_D2H_MSG_BARKER)) {
dev_err(dev, "RX: HW BUG? message received with unknown "
"barker 0x%08x (buf_size %zu bytes)\n",
le32_to_cpu(msg_hdr->barker), buf_size);
goto error;
}
if (msg_hdr->num_pls == 0) {
dev_err(dev, "RX: HW BUG? zero payload packets in message\n");
goto error;
}
if (le16_to_cpu(msg_hdr->num_pls) > I2400M_MAX_PLS_IN_MSG) {
dev_err(dev, "RX: HW BUG? message contains more payload "
"than maximum; ignoring.\n");
goto error;
}
result = 0;
error:
return result;
}
/*
* Check a payload descriptor against the received data
*
* @i2400m: device descriptor
* @pld: payload descriptor
* @pl_itr: offset (in bytes) in the received buffer the payload is
* located
* @buf_size: size of the received buffer
*
* Given a payload descriptor (part of a RX buffer), check it is sane
* and that the data it declares fits in the buffer.
*/
static
int i2400m_rx_pl_descr_check(struct i2400m *i2400m,
const struct i2400m_pld *pld,
size_t pl_itr, size_t buf_size)
{
int result = -EIO;
struct device *dev = i2400m_dev(i2400m);
size_t pl_size = i2400m_pld_size(pld);
enum i2400m_pt pl_type = i2400m_pld_type(pld);
if (pl_size > i2400m->bus_pl_size_max) {
dev_err(dev, "RX: HW BUG? payload @%zu: size %zu is "
"bigger than maximum %zu; ignoring message\n",
pl_itr, pl_size, i2400m->bus_pl_size_max);
goto error;
}
if (pl_itr + pl_size > buf_size) { /* enough? */
dev_err(dev, "RX: HW BUG? payload @%zu: size %zu "
"goes beyond the received buffer "
"size (%zu bytes); ignoring message\n",
pl_itr, pl_size, buf_size);
goto error;
}
if (pl_type >= I2400M_PT_ILLEGAL) {
dev_err(dev, "RX: HW BUG? illegal payload type %u; "
"ignoring message\n", pl_type);
goto error;
}
result = 0;
error:
return result;
}
/**
* i2400m_rx - Receive a buffer of data from the device
*
* @i2400m: device descriptor
* @skb: skbuff where the data has been received
*
* Parse in a buffer of data that contains an RX message sent from the
* device. See the file header for the format. Run all checks on the
* buffer header, then run over each payload's descriptors, verify
* their consistency and act on each payload's contents. If
* everything is successful, update the device's statistics.
*
* Note: You need to set the skb to contain only the length of the
* received buffer; for that, use skb_trim(skb, RECEIVED_SIZE).
*
* Returns:
*
* 0 if ok, < 0 errno on error
*
* If ok, this function owns now the skb and the caller DOESN'T have
* to run kfree_skb() on it. However, on error, the caller still owns
* the skb and it is responsible for releasing it.
*/
int i2400m_rx(struct i2400m *i2400m, struct sk_buff *skb)
{
int i, result;
struct device *dev = i2400m_dev(i2400m);
const struct i2400m_msg_hdr *msg_hdr;
size_t pl_itr, pl_size;
unsigned long flags;
unsigned num_pls, single_last, skb_len;
skb_len = skb->len;
d_fnstart(4, dev, "(i2400m %p skb %p [size %u])\n",
i2400m, skb, skb_len);
result = -EIO;
msg_hdr = (void *) skb->data;
result = i2400m_rx_msg_hdr_check(i2400m, msg_hdr, skb_len);
if (result < 0)
goto error_msg_hdr_check;
result = -EIO;
num_pls = le16_to_cpu(msg_hdr->num_pls);
pl_itr = sizeof(*msg_hdr) + /* Check payload descriptor(s) */
num_pls * sizeof(msg_hdr->pld[0]);
pl_itr = ALIGN(pl_itr, I2400M_PL_ALIGN);
if (pl_itr > skb_len) { /* got all the payload descriptors? */
dev_err(dev, "RX: HW BUG? message too short (%u bytes) for "
"%u payload descriptors (%zu each, total %zu)\n",
skb_len, num_pls, sizeof(msg_hdr->pld[0]), pl_itr);
goto error_pl_descr_short;
}
/* Walk each payload payload--check we really got it */
for (i = 0; i < num_pls; i++) {
/* work around old gcc warnings */
pl_size = i2400m_pld_size(&msg_hdr->pld[i]);
result = i2400m_rx_pl_descr_check(i2400m, &msg_hdr->pld[i],
pl_itr, skb_len);
if (result < 0)
goto error_pl_descr_check;
single_last = num_pls == 1 || i == num_pls - 1;
i2400m_rx_payload(i2400m, skb, single_last, &msg_hdr->pld[i],
skb->data + pl_itr);
pl_itr += ALIGN(pl_size, I2400M_PL_ALIGN);
cond_resched(); /* Don't monopolize */
}
kfree_skb(skb);
/* Update device statistics */
spin_lock_irqsave(&i2400m->rx_lock, flags);
i2400m->rx_pl_num += i;
if (i > i2400m->rx_pl_max)
i2400m->rx_pl_max = i;
if (i < i2400m->rx_pl_min)
i2400m->rx_pl_min = i;
i2400m->rx_num++;
i2400m->rx_size_acc += skb_len;
if (skb_len < i2400m->rx_size_min)
i2400m->rx_size_min = skb_len;
if (skb_len > i2400m->rx_size_max)
i2400m->rx_size_max = skb_len;
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
error_pl_descr_check:
error_pl_descr_short:
error_msg_hdr_check:
d_fnend(4, dev, "(i2400m %p skb %p [size %u]) = %d\n",
i2400m, skb, skb_len, result);
return result;
}
EXPORT_SYMBOL_GPL(i2400m_rx);
void i2400m_unknown_barker(struct i2400m *i2400m,
const void *buf, size_t size)
{
struct device *dev = i2400m_dev(i2400m);
char prefix[64];
const __le32 *barker = buf;
dev_err(dev, "RX: HW BUG? unknown barker %08x, "
"dropping %zu bytes\n", le32_to_cpu(*barker), size);
snprintf(prefix, sizeof(prefix), "%s %s: ",
dev_driver_string(dev), dev_name(dev));
if (size > 64) {
print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET,
8, 4, buf, 64, 0);
printk(KERN_ERR "%s... (only first 64 bytes "
"dumped)\n", prefix);
} else
print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET,
8, 4, buf, size, 0);
}
EXPORT_SYMBOL(i2400m_unknown_barker);
/*
* Initialize the RX queue and infrastructure
*
* This sets up all the RX reordering infrastructures, which will not
* be used if reordering is not enabled or if the firmware does not
* support it. The device is told to do reordering in
* i2400m_dev_initialize(), where it also looks at the value of the
* i2400m->rx_reorder switch before taking a decission.
*
* Note we allocate the roq queues in one chunk and the actual logging
* support for it (logging) in another one and then we setup the
* pointers from the first to the last.
*/
int i2400m_rx_setup(struct i2400m *i2400m)
{
int result = 0;
struct device *dev = i2400m_dev(i2400m);
i2400m->rx_reorder = i2400m_rx_reorder_disabled? 0 : 1;
if (i2400m->rx_reorder) {
unsigned itr;
size_t size;
struct i2400m_roq_log *rd;
result = -ENOMEM;
size = sizeof(i2400m->rx_roq[0]) * (I2400M_RO_CIN + 1);
i2400m->rx_roq = kzalloc(size, GFP_KERNEL);
if (i2400m->rx_roq == NULL) {
dev_err(dev, "RX: cannot allocate %zu bytes for "
"reorder queues\n", size);
goto error_roq_alloc;
}
size = sizeof(*i2400m->rx_roq[0].log) * (I2400M_RO_CIN + 1);
rd = kzalloc(size, GFP_KERNEL);
if (rd == NULL) {
dev_err(dev, "RX: cannot allocate %zu bytes for "
"reorder queues log areas\n", size);
result = -ENOMEM;
goto error_roq_log_alloc;
}
for(itr = 0; itr < I2400M_RO_CIN + 1; itr++) {
__i2400m_roq_init(&i2400m->rx_roq[itr]);
i2400m->rx_roq[itr].log = &rd[itr];
}
kref_init(&i2400m->rx_roq_refcount);
}
return 0;
error_roq_log_alloc:
kfree(i2400m->rx_roq);
error_roq_alloc:
return result;
}
/* Tear down the RX queue and infrastructure */
void i2400m_rx_release(struct i2400m *i2400m)
{
unsigned long flags;
if (i2400m->rx_reorder) {
spin_lock_irqsave(&i2400m->rx_lock, flags);
kref_put(&i2400m->rx_roq_refcount, i2400m_rx_roq_destroy);
spin_unlock_irqrestore(&i2400m->rx_lock, flags);
}
/* at this point, nothing can be received... */
i2400m_report_hook_flush(i2400m);
}
| gpl-2.0 |
PureNexusProject/android_kernel_google_molly | drivers/net/wireless/iwmc3200wifi/fw.c | 5590 | 11624 | /*
* Intel Wireless Multicomm 3200 WiFi driver
*
* Copyright (C) 2009 Intel Corporation. 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Intel Corporation <ilw@linux.intel.com>
* Samuel Ortiz <samuel.ortiz@intel.com>
* Zhu Yi <yi.zhu@intel.com>
*
*/
#include <linux/kernel.h>
#include <linux/firmware.h>
#include "iwm.h"
#include "bus.h"
#include "hal.h"
#include "umac.h"
#include "debug.h"
#include "fw.h"
#include "commands.h"
static const char fw_barker[] = "*WESTOPFORNOONE*";
/*
* @op_code: Op code we're looking for.
* @index: There can be several instances of the same opcode within
* the firmware. Index specifies which one we're looking for.
*/
static int iwm_fw_op_offset(struct iwm_priv *iwm, const struct firmware *fw,
u16 op_code, u32 index)
{
int offset = -EINVAL, fw_offset;
u32 op_index = 0;
const u8 *fw_ptr;
struct iwm_fw_hdr_rec *rec;
fw_offset = 0;
fw_ptr = fw->data;
/* We first need to look for the firmware barker */
if (memcmp(fw_ptr, fw_barker, IWM_HDR_BARKER_LEN)) {
IWM_ERR(iwm, "No barker string in this FW\n");
return -EINVAL;
}
if (fw->size < IWM_HDR_LEN) {
IWM_ERR(iwm, "FW is too small (%zu)\n", fw->size);
return -EINVAL;
}
fw_offset += IWM_HDR_BARKER_LEN;
while (fw_offset < fw->size) {
rec = (struct iwm_fw_hdr_rec *)(fw_ptr + fw_offset);
IWM_DBG_FW(iwm, DBG, "FW: op_code: 0x%x, len: %d @ 0x%x\n",
rec->op_code, rec->len, fw_offset);
if (rec->op_code == IWM_HDR_REC_OP_INVALID) {
IWM_DBG_FW(iwm, DBG, "Reached INVALID op code\n");
break;
}
if (rec->op_code == op_code) {
if (op_index == index) {
fw_offset += sizeof(struct iwm_fw_hdr_rec);
offset = fw_offset;
goto out;
}
op_index++;
}
fw_offset += sizeof(struct iwm_fw_hdr_rec) + rec->len;
}
out:
return offset;
}
static int iwm_load_firmware_chunk(struct iwm_priv *iwm,
const struct firmware *fw,
struct iwm_fw_img_desc *img_desc)
{
struct iwm_udma_nonwifi_cmd target_cmd;
u32 chunk_size;
const u8 *chunk_ptr;
int ret = 0;
IWM_DBG_FW(iwm, INFO, "Loading FW chunk: %d bytes @ 0x%x\n",
img_desc->length, img_desc->address);
target_cmd.opcode = UMAC_HDI_OUT_OPCODE_WRITE;
target_cmd.handle_by_hw = 1;
target_cmd.op2 = 0;
target_cmd.resp = 0;
target_cmd.eop = 1;
chunk_size = img_desc->length;
chunk_ptr = fw->data + img_desc->offset;
while (chunk_size > 0) {
u32 tmp_chunk_size;
tmp_chunk_size = min_t(u32, chunk_size,
IWM_MAX_NONWIFI_CMD_BUFF_SIZE);
target_cmd.addr = cpu_to_le32(img_desc->address +
(chunk_ptr - fw->data - img_desc->offset));
target_cmd.op1_sz = cpu_to_le32(tmp_chunk_size);
IWM_DBG_FW(iwm, DBG, "\t%d bytes @ 0x%x\n",
tmp_chunk_size, target_cmd.addr);
ret = iwm_hal_send_target_cmd(iwm, &target_cmd, chunk_ptr);
if (ret < 0) {
IWM_ERR(iwm, "Couldn't load FW chunk\n");
break;
}
chunk_size -= tmp_chunk_size;
chunk_ptr += tmp_chunk_size;
}
return ret;
}
/*
* To load a fw image to the target, we basically go through the
* fw, looking for OP_MEM_DESC records. Once we found one, we
* pass it to iwm_load_firmware_chunk().
* The OP_MEM_DESC records contain the actuall memory chunk to be
* sent, but also the destination address.
*/
static int iwm_load_img(struct iwm_priv *iwm, const char *img_name)
{
const struct firmware *fw;
struct iwm_fw_img_desc *img_desc;
struct iwm_fw_img_ver *ver;
int ret = 0, fw_offset;
u32 opcode_idx = 0, build_date;
char *build_tag;
ret = request_firmware(&fw, img_name, iwm_to_dev(iwm));
if (ret) {
IWM_ERR(iwm, "Request firmware failed");
return ret;
}
IWM_DBG_FW(iwm, INFO, "Start to load FW %s\n", img_name);
while (1) {
fw_offset = iwm_fw_op_offset(iwm, fw,
IWM_HDR_REC_OP_MEM_DESC,
opcode_idx);
if (fw_offset < 0)
break;
img_desc = (struct iwm_fw_img_desc *)(fw->data + fw_offset);
ret = iwm_load_firmware_chunk(iwm, fw, img_desc);
if (ret < 0)
goto err_release_fw;
opcode_idx++;
}
/* Read firmware version */
fw_offset = iwm_fw_op_offset(iwm, fw, IWM_HDR_REC_OP_SW_VER, 0);
if (fw_offset < 0)
goto err_release_fw;
ver = (struct iwm_fw_img_ver *)(fw->data + fw_offset);
/* Read build tag */
fw_offset = iwm_fw_op_offset(iwm, fw, IWM_HDR_REC_OP_BUILD_TAG, 0);
if (fw_offset < 0)
goto err_release_fw;
build_tag = (char *)(fw->data + fw_offset);
/* Read build date */
fw_offset = iwm_fw_op_offset(iwm, fw, IWM_HDR_REC_OP_BUILD_DATE, 0);
if (fw_offset < 0)
goto err_release_fw;
build_date = *(u32 *)(fw->data + fw_offset);
IWM_INFO(iwm, "%s:\n", img_name);
IWM_INFO(iwm, "\tVersion: %02X.%02X\n", ver->major, ver->minor);
IWM_INFO(iwm, "\tBuild tag: %s\n", build_tag);
IWM_INFO(iwm, "\tBuild date: %x-%x-%x\n",
IWM_BUILD_YEAR(build_date), IWM_BUILD_MONTH(build_date),
IWM_BUILD_DAY(build_date));
if (!strcmp(img_name, iwm->bus_ops->umac_name))
sprintf(iwm->umac_version, "%02X.%02X",
ver->major, ver->minor);
if (!strcmp(img_name, iwm->bus_ops->lmac_name))
sprintf(iwm->lmac_version, "%02X.%02X",
ver->major, ver->minor);
err_release_fw:
release_firmware(fw);
return ret;
}
static int iwm_load_umac(struct iwm_priv *iwm)
{
struct iwm_udma_nonwifi_cmd target_cmd;
int ret;
ret = iwm_load_img(iwm, iwm->bus_ops->umac_name);
if (ret < 0)
return ret;
/* We've loaded the UMAC, we can tell the target to jump there */
target_cmd.opcode = UMAC_HDI_OUT_OPCODE_JUMP;
target_cmd.addr = cpu_to_le32(UMAC_MU_FW_INST_DATA_12_ADDR);
target_cmd.op1_sz = 0;
target_cmd.op2 = 0;
target_cmd.handle_by_hw = 0;
target_cmd.resp = 1 ;
target_cmd.eop = 1;
ret = iwm_hal_send_target_cmd(iwm, &target_cmd, NULL);
if (ret < 0)
IWM_ERR(iwm, "Couldn't send JMP command\n");
return ret;
}
static int iwm_load_lmac(struct iwm_priv *iwm, const char *img_name)
{
int ret;
ret = iwm_load_img(iwm, img_name);
if (ret < 0)
return ret;
return iwm_send_umac_reset(iwm,
cpu_to_le32(UMAC_RST_CTRL_FLG_LARC_CLK_EN), 0);
}
static int iwm_init_calib(struct iwm_priv *iwm, unsigned long cfg_bitmap,
unsigned long expected_bitmap, u8 rx_iq_cmd)
{
/* Read RX IQ calibration result from EEPROM */
if (test_bit(rx_iq_cmd, &cfg_bitmap)) {
iwm_store_rxiq_calib_result(iwm);
set_bit(PHY_CALIBRATE_RX_IQ_CMD, &iwm->calib_done_map);
}
iwm_send_prio_table(iwm);
iwm_send_init_calib_cfg(iwm, cfg_bitmap);
while (iwm->calib_done_map != expected_bitmap) {
if (iwm_notif_handle(iwm, CALIBRATION_RES_NOTIFICATION,
IWM_SRC_LMAC, WAIT_NOTIF_TIMEOUT)) {
IWM_DBG_FW(iwm, DBG, "Initial calibration timeout\n");
return -ETIMEDOUT;
}
IWM_DBG_FW(iwm, DBG, "Got calibration result. calib_done_map: "
"0x%lx, expected calibrations: 0x%lx\n",
iwm->calib_done_map, expected_bitmap);
}
return 0;
}
/*
* We currently have to load 3 FWs:
* 1) The UMAC (Upper MAC).
* 2) The calibration LMAC (Lower MAC).
* We then send the calibration init command, so that the device can
* run a first calibration round.
* 3) The operational LMAC, which replaces the calibration one when it's
* done with the first calibration round.
*
* Once those 3 FWs have been loaded, we send the periodic calibration
* command, and then the device is available for regular 802.11 operations.
*/
int iwm_load_fw(struct iwm_priv *iwm)
{
unsigned long init_calib_map, periodic_calib_map;
unsigned long expected_calib_map;
int ret;
/* We first start downloading the UMAC */
ret = iwm_load_umac(iwm);
if (ret < 0) {
IWM_ERR(iwm, "UMAC loading failed\n");
return ret;
}
/* Handle UMAC_ALIVE notification */
ret = iwm_notif_handle(iwm, UMAC_NOTIFY_OPCODE_ALIVE, IWM_SRC_UMAC,
WAIT_NOTIF_TIMEOUT);
if (ret) {
IWM_ERR(iwm, "Handle UMAC_ALIVE failed: %d\n", ret);
return ret;
}
/* UMAC is alive, we can download the calibration LMAC */
ret = iwm_load_lmac(iwm, iwm->bus_ops->calib_lmac_name);
if (ret) {
IWM_ERR(iwm, "Calibration LMAC loading failed\n");
return ret;
}
/* Handle UMAC_INIT_COMPLETE notification */
ret = iwm_notif_handle(iwm, UMAC_NOTIFY_OPCODE_INIT_COMPLETE,
IWM_SRC_UMAC, WAIT_NOTIF_TIMEOUT);
if (ret) {
IWM_ERR(iwm, "Handle INIT_COMPLETE failed for calibration "
"LMAC: %d\n", ret);
return ret;
}
/* Read EEPROM data */
ret = iwm_eeprom_init(iwm);
if (ret < 0) {
IWM_ERR(iwm, "Couldn't init eeprom array\n");
return ret;
}
init_calib_map = iwm->conf.calib_map & IWM_CALIB_MAP_INIT_MSK;
expected_calib_map = iwm->conf.expected_calib_map &
IWM_CALIB_MAP_INIT_MSK;
periodic_calib_map = IWM_CALIB_MAP_PER_LMAC(iwm->conf.calib_map);
ret = iwm_init_calib(iwm, init_calib_map, expected_calib_map,
CALIB_CFG_RX_IQ_IDX);
if (ret < 0) {
/* Let's try the old way */
ret = iwm_init_calib(iwm, expected_calib_map,
expected_calib_map,
PHY_CALIBRATE_RX_IQ_CMD);
if (ret < 0) {
IWM_ERR(iwm, "Calibration result timeout\n");
goto out;
}
}
/* Handle LMAC CALIBRATION_COMPLETE notification */
ret = iwm_notif_handle(iwm, CALIBRATION_COMPLETE_NOTIFICATION,
IWM_SRC_LMAC, WAIT_NOTIF_TIMEOUT);
if (ret) {
IWM_ERR(iwm, "Wait for CALIBRATION_COMPLETE timeout\n");
goto out;
}
IWM_INFO(iwm, "LMAC calibration done: 0x%lx\n", iwm->calib_done_map);
iwm_send_umac_reset(iwm, cpu_to_le32(UMAC_RST_CTRL_FLG_LARC_RESET), 1);
ret = iwm_notif_handle(iwm, UMAC_CMD_OPCODE_RESET, IWM_SRC_UMAC,
WAIT_NOTIF_TIMEOUT);
if (ret) {
IWM_ERR(iwm, "Wait for UMAC RESET timeout\n");
goto out;
}
/* Download the operational LMAC */
ret = iwm_load_lmac(iwm, iwm->bus_ops->lmac_name);
if (ret) {
IWM_ERR(iwm, "LMAC loading failed\n");
goto out;
}
ret = iwm_notif_handle(iwm, UMAC_NOTIFY_OPCODE_INIT_COMPLETE,
IWM_SRC_UMAC, WAIT_NOTIF_TIMEOUT);
if (ret) {
IWM_ERR(iwm, "Handle INIT_COMPLETE failed for LMAC: %d\n", ret);
goto out;
}
iwm_send_prio_table(iwm);
iwm_send_calib_results(iwm);
iwm_send_periodic_calib_cfg(iwm, periodic_calib_map);
iwm_send_ct_kill_cfg(iwm, iwm->conf.ct_kill_entry,
iwm->conf.ct_kill_exit);
return 0;
out:
iwm_eeprom_exit(iwm);
return ret;
}
| gpl-2.0 |
avoltz/linux-vybrid | arch/arm/mach-omap2/clkt34xx_dpll3m2.c | 7894 | 3209 | /*
* OMAP34xx M2 divider clock code
*
* Copyright (C) 2007-2008 Texas Instruments, Inc.
* Copyright (C) 2007-2010 Nokia Corporation
*
* Paul Walmsley
* Jouni Högander
*
* Parts of this code are based on code written by
* Richard Woodruff, Tony Lindgren, Tuukka Tikkanen, Karthik Dasu
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/clock.h>
#include <plat/sram.h>
#include <plat/sdrc.h>
#include "clock.h"
#include "clock3xxx.h"
#include "clock34xx.h"
#include "sdrc.h"
#define CYCLES_PER_MHZ 1000000
/*
* CORE DPLL (DPLL3) M2 divider rate programming functions
*
* These call into SRAM code to do the actual CM writes, since the SDRAM
* is clocked from DPLL3.
*/
/**
* omap3_core_dpll_m2_set_rate - set CORE DPLL M2 divider
* @clk: struct clk * of DPLL to set
* @rate: rounded target rate
*
* Program the DPLL M2 divider with the rounded target rate. Returns
* -EINVAL upon error, or 0 upon success.
*/
int omap3_core_dpll_m2_set_rate(struct clk *clk, unsigned long rate)
{
u32 new_div = 0;
u32 unlock_dll = 0;
u32 c;
unsigned long validrate, sdrcrate, _mpurate;
struct omap_sdrc_params *sdrc_cs0;
struct omap_sdrc_params *sdrc_cs1;
int ret;
if (!clk || !rate)
return -EINVAL;
validrate = omap2_clksel_round_rate_div(clk, rate, &new_div);
if (validrate != rate)
return -EINVAL;
sdrcrate = sdrc_ick_p->rate;
if (rate > clk->rate)
sdrcrate <<= ((rate / clk->rate) >> 1);
else
sdrcrate >>= ((clk->rate / rate) >> 1);
ret = omap2_sdrc_get_params(sdrcrate, &sdrc_cs0, &sdrc_cs1);
if (ret)
return -EINVAL;
if (sdrcrate < MIN_SDRC_DLL_LOCK_FREQ) {
pr_debug("clock: will unlock SDRC DLL\n");
unlock_dll = 1;
}
/*
* XXX This only needs to be done when the CPU frequency changes
*/
_mpurate = arm_fck_p->rate / CYCLES_PER_MHZ;
c = (_mpurate << SDRC_MPURATE_SCALE) >> SDRC_MPURATE_BASE_SHIFT;
c += 1; /* for safety */
c *= SDRC_MPURATE_LOOPS;
c >>= SDRC_MPURATE_SCALE;
if (c == 0)
c = 1;
pr_debug("clock: changing CORE DPLL rate from %lu to %lu\n", clk->rate,
validrate);
pr_debug("clock: SDRC CS0 timing params used:"
" RFR %08x CTRLA %08x CTRLB %08x MR %08x\n",
sdrc_cs0->rfr_ctrl, sdrc_cs0->actim_ctrla,
sdrc_cs0->actim_ctrlb, sdrc_cs0->mr);
if (sdrc_cs1)
pr_debug("clock: SDRC CS1 timing params used: "
" RFR %08x CTRLA %08x CTRLB %08x MR %08x\n",
sdrc_cs1->rfr_ctrl, sdrc_cs1->actim_ctrla,
sdrc_cs1->actim_ctrlb, sdrc_cs1->mr);
if (sdrc_cs1)
omap3_configure_core_dpll(
new_div, unlock_dll, c, rate > clk->rate,
sdrc_cs0->rfr_ctrl, sdrc_cs0->actim_ctrla,
sdrc_cs0->actim_ctrlb, sdrc_cs0->mr,
sdrc_cs1->rfr_ctrl, sdrc_cs1->actim_ctrla,
sdrc_cs1->actim_ctrlb, sdrc_cs1->mr);
else
omap3_configure_core_dpll(
new_div, unlock_dll, c, rate > clk->rate,
sdrc_cs0->rfr_ctrl, sdrc_cs0->actim_ctrla,
sdrc_cs0->actim_ctrlb, sdrc_cs0->mr,
0, 0, 0, 0);
clk->rate = rate;
return 0;
}
| gpl-2.0 |
vasudev-33/os | arch/cris/arch-v32/mach-a3/pinmux.c | 9686 | 9980 | /*
* Allocator for I/O pins. All pins are allocated to GPIO at bootup.
* Unassigned pins and GPIO pins can be allocated to a fixed interface
* or the I/O processor instead.
*
* Copyright (c) 2005-2007 Axis Communications AB.
*/
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <pinmux.h>
#include <hwregs/pinmux_defs.h>
#include <hwregs/clkgen_defs.h>
#undef DEBUG
#define PINS 80
#define PORT_PINS 32
#define PORTS 3
static char pins[PINS];
static DEFINE_SPINLOCK(pinmux_lock);
static void crisv32_pinmux_set(int port);
int
crisv32_pinmux_init(void)
{
static int initialized;
if (!initialized) {
initialized = 1;
REG_WR_INT(pinmux, regi_pinmux, rw_hwprot, 0);
crisv32_pinmux_alloc(PORT_A, 0, 31, pinmux_gpio);
crisv32_pinmux_alloc(PORT_B, 0, 31, pinmux_gpio);
crisv32_pinmux_alloc(PORT_C, 0, 15, pinmux_gpio);
}
return 0;
}
int
crisv32_pinmux_alloc(int port, int first_pin, int last_pin, enum pin_mode mode)
{
int i;
unsigned long flags;
crisv32_pinmux_init();
if (port >= PORTS)
return -EINVAL;
spin_lock_irqsave(&pinmux_lock, flags);
for (i = first_pin; i <= last_pin; i++) {
if ((pins[port * PORT_PINS + i] != pinmux_none) &&
(pins[port * PORT_PINS + i] != pinmux_gpio) &&
(pins[port * PORT_PINS + i] != mode)) {
spin_unlock_irqrestore(&pinmux_lock, flags);
#ifdef DEBUG
panic("Pinmux alloc failed!\n");
#endif
return -EPERM;
}
}
for (i = first_pin; i <= last_pin; i++)
pins[port * PORT_PINS + i] = mode;
crisv32_pinmux_set(port);
spin_unlock_irqrestore(&pinmux_lock, flags);
return 0;
}
int
crisv32_pinmux_alloc_fixed(enum fixed_function function)
{
int ret = -EINVAL;
char saved[sizeof pins];
unsigned long flags;
reg_pinmux_rw_hwprot hwprot;
reg_clkgen_rw_clk_ctrl clk_ctrl;
spin_lock_irqsave(&pinmux_lock, flags);
/* Save internal data for recovery */
memcpy(saved, pins, sizeof pins);
crisv32_pinmux_init(); /* must be done before we read rw_hwprot */
hwprot = REG_RD(pinmux, regi_pinmux, rw_hwprot);
clk_ctrl = REG_RD(clkgen, regi_clkgen, rw_clk_ctrl);
switch (function) {
case pinmux_eth:
clk_ctrl.eth = regk_clkgen_yes;
clk_ctrl.dma0_1_eth = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_B, 8, 23, pinmux_fixed);
ret |= crisv32_pinmux_alloc(PORT_B, 24, 25, pinmux_fixed);
hwprot.eth = hwprot.eth_mdio = regk_pinmux_yes;
break;
case pinmux_geth:
ret = crisv32_pinmux_alloc(PORT_B, 0, 7, pinmux_fixed);
hwprot.geth = regk_pinmux_yes;
break;
case pinmux_tg_cmos:
clk_ctrl.ccd_tg_100 = clk_ctrl.ccd_tg_200 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_B, 27, 29, pinmux_fixed);
hwprot.tg_clk = regk_pinmux_yes;
break;
case pinmux_tg_ccd:
clk_ctrl.ccd_tg_100 = clk_ctrl.ccd_tg_200 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_B, 27, 31, pinmux_fixed);
ret |= crisv32_pinmux_alloc(PORT_C, 0, 15, pinmux_fixed);
hwprot.tg = hwprot.tg_clk = regk_pinmux_yes;
break;
case pinmux_vout:
clk_ctrl.strdma0_2_video = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_A, 8, 18, pinmux_fixed);
hwprot.vout = hwprot.vout_sync = regk_pinmux_yes;
break;
case pinmux_ser1:
clk_ctrl.sser_ser_dma6_7 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_A, 24, 25, pinmux_fixed);
hwprot.ser1 = regk_pinmux_yes;
break;
case pinmux_ser2:
clk_ctrl.sser_ser_dma6_7 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_A, 26, 27, pinmux_fixed);
hwprot.ser2 = regk_pinmux_yes;
break;
case pinmux_ser3:
clk_ctrl.sser_ser_dma6_7 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_A, 28, 29, pinmux_fixed);
hwprot.ser3 = regk_pinmux_yes;
break;
case pinmux_ser4:
clk_ctrl.sser_ser_dma6_7 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_A, 30, 31, pinmux_fixed);
hwprot.ser4 = regk_pinmux_yes;
break;
case pinmux_sser:
clk_ctrl.sser_ser_dma6_7 = regk_clkgen_yes;
ret = crisv32_pinmux_alloc(PORT_A, 19, 23, pinmux_fixed);
hwprot.sser = regk_pinmux_yes;
break;
case pinmux_pio:
hwprot.pio = regk_pinmux_yes;
ret = 0;
break;
case pinmux_pwm0:
ret = crisv32_pinmux_alloc(PORT_A, 30, 30, pinmux_fixed);
hwprot.pwm0 = regk_pinmux_yes;
break;
case pinmux_pwm1:
ret = crisv32_pinmux_alloc(PORT_A, 31, 31, pinmux_fixed);
hwprot.pwm1 = regk_pinmux_yes;
break;
case pinmux_pwm2:
ret = crisv32_pinmux_alloc(PORT_B, 26, 26, pinmux_fixed);
hwprot.pwm2 = regk_pinmux_yes;
break;
case pinmux_i2c0:
ret = crisv32_pinmux_alloc(PORT_A, 0, 1, pinmux_fixed);
hwprot.i2c0 = regk_pinmux_yes;
break;
case pinmux_i2c1:
ret = crisv32_pinmux_alloc(PORT_A, 2, 3, pinmux_fixed);
hwprot.i2c1 = regk_pinmux_yes;
break;
case pinmux_i2c1_3wire:
ret = crisv32_pinmux_alloc(PORT_A, 2, 3, pinmux_fixed);
ret |= crisv32_pinmux_alloc(PORT_A, 7, 7, pinmux_fixed);
hwprot.i2c1 = hwprot.i2c1_sen = regk_pinmux_yes;
break;
case pinmux_i2c1_sda1:
ret = crisv32_pinmux_alloc(PORT_A, 2, 4, pinmux_fixed);
hwprot.i2c1 = hwprot.i2c1_sda1 = regk_pinmux_yes;
break;
case pinmux_i2c1_sda2:
ret = crisv32_pinmux_alloc(PORT_A, 2, 3, pinmux_fixed);
ret |= crisv32_pinmux_alloc(PORT_A, 5, 5, pinmux_fixed);
hwprot.i2c1 = hwprot.i2c1_sda2 = regk_pinmux_yes;
break;
case pinmux_i2c1_sda3:
ret = crisv32_pinmux_alloc(PORT_A, 2, 3, pinmux_fixed);
ret |= crisv32_pinmux_alloc(PORT_A, 6, 6, pinmux_fixed);
hwprot.i2c1 = hwprot.i2c1_sda3 = regk_pinmux_yes;
break;
default:
ret = -EINVAL;
break;
}
if (!ret) {
REG_WR(pinmux, regi_pinmux, rw_hwprot, hwprot);
REG_WR(clkgen, regi_clkgen, rw_clk_ctrl, clk_ctrl);
} else
memcpy(pins, saved, sizeof pins);
spin_unlock_irqrestore(&pinmux_lock, flags);
return ret;
}
void
crisv32_pinmux_set(int port)
{
int i;
int gpio_val = 0;
int iop_val = 0;
int pin = port * PORT_PINS;
for (i = 0; (i < PORT_PINS) && (pin < PINS); i++, pin++) {
if (pins[pin] == pinmux_gpio)
gpio_val |= (1 << i);
else if (pins[pin] == pinmux_iop)
iop_val |= (1 << i);
}
REG_WRITE(int, regi_pinmux + REG_RD_ADDR_pinmux_rw_gio_pa + 4 * port,
gpio_val);
REG_WRITE(int, regi_pinmux + REG_RD_ADDR_pinmux_rw_iop_pa + 4 * port,
iop_val);
#ifdef DEBUG
crisv32_pinmux_dump();
#endif
}
int
crisv32_pinmux_dealloc(int port, int first_pin, int last_pin)
{
int i;
unsigned long flags;
crisv32_pinmux_init();
if (port > PORTS || port < 0)
return -EINVAL;
spin_lock_irqsave(&pinmux_lock, flags);
for (i = first_pin; i <= last_pin; i++)
pins[port * PORT_PINS + i] = pinmux_none;
crisv32_pinmux_set(port);
spin_unlock_irqrestore(&pinmux_lock, flags);
return 0;
}
int
crisv32_pinmux_dealloc_fixed(enum fixed_function function)
{
int ret = -EINVAL;
char saved[sizeof pins];
unsigned long flags;
reg_pinmux_rw_hwprot hwprot;
spin_lock_irqsave(&pinmux_lock, flags);
/* Save internal data for recovery */
memcpy(saved, pins, sizeof pins);
crisv32_pinmux_init(); /* must be done before we read rw_hwprot */
hwprot = REG_RD(pinmux, regi_pinmux, rw_hwprot);
switch (function) {
case pinmux_eth:
ret = crisv32_pinmux_dealloc(PORT_B, 8, 23);
ret |= crisv32_pinmux_dealloc(PORT_B, 24, 25);
ret |= crisv32_pinmux_dealloc(PORT_B, 0, 7);
hwprot.eth = hwprot.eth_mdio = hwprot.geth = regk_pinmux_no;
break;
case pinmux_tg_cmos:
ret = crisv32_pinmux_dealloc(PORT_B, 27, 29);
hwprot.tg_clk = regk_pinmux_no;
break;
case pinmux_tg_ccd:
ret = crisv32_pinmux_dealloc(PORT_B, 27, 31);
ret |= crisv32_pinmux_dealloc(PORT_C, 0, 15);
hwprot.tg = hwprot.tg_clk = regk_pinmux_no;
break;
case pinmux_vout:
ret = crisv32_pinmux_dealloc(PORT_A, 8, 18);
hwprot.vout = hwprot.vout_sync = regk_pinmux_no;
break;
case pinmux_ser1:
ret = crisv32_pinmux_dealloc(PORT_A, 24, 25);
hwprot.ser1 = regk_pinmux_no;
break;
case pinmux_ser2:
ret = crisv32_pinmux_dealloc(PORT_A, 26, 27);
hwprot.ser2 = regk_pinmux_no;
break;
case pinmux_ser3:
ret = crisv32_pinmux_dealloc(PORT_A, 28, 29);
hwprot.ser3 = regk_pinmux_no;
break;
case pinmux_ser4:
ret = crisv32_pinmux_dealloc(PORT_A, 30, 31);
hwprot.ser4 = regk_pinmux_no;
break;
case pinmux_sser:
ret = crisv32_pinmux_dealloc(PORT_A, 19, 23);
hwprot.sser = regk_pinmux_no;
break;
case pinmux_pwm0:
ret = crisv32_pinmux_dealloc(PORT_A, 30, 30);
hwprot.pwm0 = regk_pinmux_no;
break;
case pinmux_pwm1:
ret = crisv32_pinmux_dealloc(PORT_A, 31, 31);
hwprot.pwm1 = regk_pinmux_no;
break;
case pinmux_pwm2:
ret = crisv32_pinmux_dealloc(PORT_B, 26, 26);
hwprot.pwm2 = regk_pinmux_no;
break;
case pinmux_i2c0:
ret = crisv32_pinmux_dealloc(PORT_A, 0, 1);
hwprot.i2c0 = regk_pinmux_no;
break;
case pinmux_i2c1:
ret = crisv32_pinmux_dealloc(PORT_A, 2, 3);
hwprot.i2c1 = regk_pinmux_no;
break;
case pinmux_i2c1_3wire:
ret = crisv32_pinmux_dealloc(PORT_A, 2, 3);
ret |= crisv32_pinmux_dealloc(PORT_A, 7, 7);
hwprot.i2c1 = hwprot.i2c1_sen = regk_pinmux_no;
break;
case pinmux_i2c1_sda1:
ret = crisv32_pinmux_dealloc(PORT_A, 2, 4);
hwprot.i2c1_sda1 = regk_pinmux_no;
break;
case pinmux_i2c1_sda2:
ret = crisv32_pinmux_dealloc(PORT_A, 2, 3);
ret |= crisv32_pinmux_dealloc(PORT_A, 5, 5);
hwprot.i2c1_sda2 = regk_pinmux_no;
break;
case pinmux_i2c1_sda3:
ret = crisv32_pinmux_dealloc(PORT_A, 2, 3);
ret |= crisv32_pinmux_dealloc(PORT_A, 6, 6);
hwprot.i2c1_sda3 = regk_pinmux_no;
break;
default:
ret = -EINVAL;
break;
}
if (!ret)
REG_WR(pinmux, regi_pinmux, rw_hwprot, hwprot);
else
memcpy(pins, saved, sizeof pins);
spin_unlock_irqrestore(&pinmux_lock, flags);
return ret;
}
void
crisv32_pinmux_dump(void)
{
int i, j;
int pin = 0;
crisv32_pinmux_init();
for (i = 0; i < PORTS; i++) {
pin++;
printk(KERN_DEBUG "Port %c\n", 'A'+i);
for (j = 0; (j < PORT_PINS) && (pin < PINS); j++, pin++)
printk(KERN_DEBUG
" Pin %d = %d\n", j, pins[i * PORT_PINS + j]);
}
}
__initcall(crisv32_pinmux_init);
| gpl-2.0 |
Red--Code/Code-Red-honami | drivers/pnp/core.c | 11734 | 4880 | /*
* core.c - contains all core device and protocol registration functions
*
* Copyright 2002 Adam Belay <ambx1@neo.rr.com>
*/
#include <linux/pnp.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/dma-mapping.h>
#include "base.h"
static LIST_HEAD(pnp_protocols);
LIST_HEAD(pnp_global);
DEFINE_SPINLOCK(pnp_lock);
/*
* ACPI or PNPBIOS should tell us about all platform devices, so we can
* skip some blind probes. ISAPNP typically enumerates only plug-in ISA
* devices, not built-in things like COM ports.
*/
int pnp_platform_devices;
EXPORT_SYMBOL(pnp_platform_devices);
void *pnp_alloc(long size)
{
void *result;
result = kzalloc(size, GFP_KERNEL);
if (!result) {
printk(KERN_ERR "pnp: Out of Memory\n");
return NULL;
}
return result;
}
/**
* pnp_protocol_register - adds a pnp protocol to the pnp layer
* @protocol: pointer to the corresponding pnp_protocol structure
*
* Ex protocols: ISAPNP, PNPBIOS, etc
*/
int pnp_register_protocol(struct pnp_protocol *protocol)
{
int nodenum;
struct list_head *pos;
INIT_LIST_HEAD(&protocol->devices);
INIT_LIST_HEAD(&protocol->cards);
nodenum = 0;
spin_lock(&pnp_lock);
/* assign the lowest unused number */
list_for_each(pos, &pnp_protocols) {
struct pnp_protocol *cur = to_pnp_protocol(pos);
if (cur->number == nodenum) {
pos = &pnp_protocols;
nodenum++;
}
}
list_add_tail(&protocol->protocol_list, &pnp_protocols);
spin_unlock(&pnp_lock);
protocol->number = nodenum;
dev_set_name(&protocol->dev, "pnp%d", nodenum);
return device_register(&protocol->dev);
}
/**
* pnp_protocol_unregister - removes a pnp protocol from the pnp layer
* @protocol: pointer to the corresponding pnp_protocol structure
*/
void pnp_unregister_protocol(struct pnp_protocol *protocol)
{
spin_lock(&pnp_lock);
list_del(&protocol->protocol_list);
spin_unlock(&pnp_lock);
device_unregister(&protocol->dev);
}
static void pnp_free_ids(struct pnp_dev *dev)
{
struct pnp_id *id;
struct pnp_id *next;
id = dev->id;
while (id) {
next = id->next;
kfree(id);
id = next;
}
}
void pnp_free_resource(struct pnp_resource *pnp_res)
{
list_del(&pnp_res->list);
kfree(pnp_res);
}
void pnp_free_resources(struct pnp_dev *dev)
{
struct pnp_resource *pnp_res, *tmp;
list_for_each_entry_safe(pnp_res, tmp, &dev->resources, list) {
pnp_free_resource(pnp_res);
}
}
static void pnp_release_device(struct device *dmdev)
{
struct pnp_dev *dev = to_pnp_dev(dmdev);
pnp_free_ids(dev);
pnp_free_resources(dev);
pnp_free_options(dev);
kfree(dev);
}
struct pnp_dev *pnp_alloc_dev(struct pnp_protocol *protocol, int id,
const char *pnpid)
{
struct pnp_dev *dev;
struct pnp_id *dev_id;
dev = kzalloc(sizeof(struct pnp_dev), GFP_KERNEL);
if (!dev)
return NULL;
INIT_LIST_HEAD(&dev->resources);
INIT_LIST_HEAD(&dev->options);
dev->protocol = protocol;
dev->number = id;
dev->dma_mask = DMA_BIT_MASK(24);
dev->dev.parent = &dev->protocol->dev;
dev->dev.bus = &pnp_bus_type;
dev->dev.dma_mask = &dev->dma_mask;
dev->dev.coherent_dma_mask = dev->dma_mask;
dev->dev.release = &pnp_release_device;
dev_set_name(&dev->dev, "%02x:%02x", dev->protocol->number, dev->number);
dev_id = pnp_add_id(dev, pnpid);
if (!dev_id) {
kfree(dev);
return NULL;
}
return dev;
}
int __pnp_add_device(struct pnp_dev *dev)
{
pnp_fixup_device(dev);
dev->status = PNP_READY;
spin_lock(&pnp_lock);
list_add_tail(&dev->global_list, &pnp_global);
list_add_tail(&dev->protocol_list, &dev->protocol->devices);
spin_unlock(&pnp_lock);
if (dev->protocol->can_wakeup)
device_set_wakeup_capable(&dev->dev,
dev->protocol->can_wakeup(dev));
return device_register(&dev->dev);
}
/*
* pnp_add_device - adds a pnp device to the pnp layer
* @dev: pointer to dev to add
*
* adds to driver model, name database, fixups, interface, etc.
*/
int pnp_add_device(struct pnp_dev *dev)
{
int ret;
char buf[128];
int len = 0;
struct pnp_id *id;
if (dev->card)
return -EINVAL;
ret = __pnp_add_device(dev);
if (ret)
return ret;
buf[0] = '\0';
for (id = dev->id; id; id = id->next)
len += scnprintf(buf + len, sizeof(buf) - len, " %s", id->id);
dev_printk(KERN_DEBUG, &dev->dev, "%s device, IDs%s (%s)\n",
dev->protocol->name, buf,
dev->active ? "active" : "disabled");
return 0;
}
void __pnp_remove_device(struct pnp_dev *dev)
{
spin_lock(&pnp_lock);
list_del(&dev->global_list);
list_del(&dev->protocol_list);
spin_unlock(&pnp_lock);
device_unregister(&dev->dev);
}
static int __init pnp_init(void)
{
return bus_register(&pnp_bus_type);
}
subsys_initcall(pnp_init);
int pnp_debug;
#if defined(CONFIG_PNP_DEBUG_MESSAGES)
module_param_named(debug, pnp_debug, int, 0644);
#endif
| gpl-2.0 |
nothingisdead/tostab03_kernel_cm10 | sound/drivers/vx/vx_cmd.c | 14806 | 5193 | /*
* Driver for Digigram VX soundcards
*
* DSP commands
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/vx_core.h>
#include "vx_cmd.h"
/*
* Array of DSP commands
*/
static struct vx_cmd_info vx_dsp_cmds[] = {
[CMD_VERSION] = { 0x010000, 2, RMH_SSIZE_FIXED, 1 },
[CMD_SUPPORTED] = { 0x020000, 1, RMH_SSIZE_FIXED, 2 },
[CMD_TEST_IT] = { 0x040000, 1, RMH_SSIZE_FIXED, 1 },
[CMD_SEND_IRQA] = { 0x070001, 1, RMH_SSIZE_FIXED, 0 },
[CMD_IBL] = { 0x080000, 1, RMH_SSIZE_FIXED, 4 },
[CMD_ASYNC] = { 0x0A0000, 1, RMH_SSIZE_ARG, 0 },
[CMD_RES_PIPE] = { 0x400000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_FREE_PIPE] = { 0x410000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_CONF_PIPE] = { 0x42A101, 2, RMH_SSIZE_FIXED, 0 },
[CMD_ABORT_CONF_PIPE] = { 0x42A100, 2, RMH_SSIZE_FIXED, 0 },
[CMD_PARAM_OUTPUT_PIPE] = { 0x43A000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_STOP_PIPE] = { 0x470004, 1, RMH_SSIZE_FIXED, 0 },
[CMD_PIPE_STATE] = { 0x480000, 1, RMH_SSIZE_FIXED, 1 },
[CMD_PIPE_SPL_COUNT] = { 0x49A000, 2, RMH_SSIZE_FIXED, 2 },
[CMD_CAN_START_PIPE] = { 0x4b0000, 1, RMH_SSIZE_FIXED, 1 },
[CMD_SIZE_HBUFFER] = { 0x4C0000, 1, RMH_SSIZE_FIXED, 1 },
[CMD_START_STREAM] = { 0x80A000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_START_ONE_STREAM] = { 0x800000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_PAUSE_STREAM] = { 0x81A000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_PAUSE_ONE_STREAM] = { 0x810000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_STREAM_OUT_LEVEL_ADJUST] = { 0x828000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_STOP_STREAM] = { 0x830000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_FORMAT_STREAM_OUT] = { 0x868000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_FORMAT_STREAM_IN] = { 0x878800, 1, RMH_SSIZE_FIXED, 0 },
[CMD_GET_STREAM_STATE] = { 0x890001, 2, RMH_SSIZE_FIXED, 1 },
[CMD_DROP_BYTES_AWAY] = { 0x8A8000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_GET_REMAINING_BYTES] = { 0x8D0800, 1, RMH_SSIZE_FIXED, 2 },
[CMD_CONNECT_AUDIO] = { 0xC10000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_AUDIO_LEVEL_ADJUST] = { 0xC2A000, 3, RMH_SSIZE_FIXED, 0 },
[CMD_AUDIO_VU_PIC_METER] = { 0xC3A003, 2, RMH_SSIZE_FIXED, 1 },
[CMD_GET_AUDIO_LEVELS] = { 0xC4A000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_GET_NOTIFY_EVENT] = { 0x4D0000, 1, RMH_SSIZE_ARG, 0 },
[CMD_INFO_NOTIFIED] = { 0x0B0000, 1, RMH_SSIZE_FIXED, 2 },
[CMD_ACCESS_IO_FCT] = { 0x098000, 1, RMH_SSIZE_ARG, 0 },
[CMD_STATUS_R_BUFFERS] = { 0x440000, 1, RMH_SSIZE_ARG, 0 },
[CMD_UPDATE_R_BUFFERS] = { 0x848000, 4, RMH_SSIZE_FIXED, 0 },
[CMD_LOAD_EFFECT_CONTEXT] = { 0x0c8000, 3, RMH_SSIZE_FIXED, 1 },
[CMD_EFFECT_ONE_PIPE] = { 0x458000, 0, RMH_SSIZE_FIXED, 0 },
[CMD_MODIFY_CLOCK] = { 0x0d0000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_STREAM1_OUT_SET_N_LEVELS] ={ 0x858000, 3, RMH_SSIZE_FIXED, 0 },
[CMD_PURGE_STREAM_DCMDS] = { 0x8b8000, 3, RMH_SSIZE_FIXED, 0 },
[CMD_NOTIFY_PIPE_TIME] = { 0x4e0000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_LOAD_EFFECT_CONTEXT_PACKET] = { 0x0c8000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_RELIC_R_BUFFER] = { 0x8e0800, 1, RMH_SSIZE_FIXED, 1 },
[CMD_RESYNC_AUDIO_INPUTS] = { 0x0e0000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_NOTIFY_STREAM_TIME] = { 0x8f0000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_STREAM_SAMPLE_COUNT] = { 0x900000, 1, RMH_SSIZE_FIXED, 2 },
[CMD_CONFIG_TIME_CODE] = { 0x050000, 2, RMH_SSIZE_FIXED, 0 },
[CMD_GET_TIME_CODE] = { 0x060000, 1, RMH_SSIZE_FIXED, 5 },
[CMD_MANAGE_SIGNAL] = { 0x0f0000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_PARAMETER_STREAM_OUT] = { 0x91A000, 3, RMH_SSIZE_FIXED, 0 },
[CMD_READ_BOARD_FREQ] = { 0x030000, 1, RMH_SSIZE_FIXED, 2 },
[CMD_GET_STREAM_LEVELS] = { 0x8c0000, 1, RMH_SSIZE_FIXED, 3 },
[CMD_PURGE_PIPE_DCMDS] = { 0x4f8000, 3, RMH_SSIZE_FIXED, 0 },
// [CMD_SET_STREAM_OUT_EFFECTS] = { 0x888000, 34, RMH_SSIZE_FIXED, 0 },
// [CMD_GET_STREAM_OUT_EFFECTS] = { 0x928000, 2, RMH_SSIZE_FIXED, 32 },
[CMD_CONNECT_MONITORING] = { 0xC00000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_STREAM2_OUT_SET_N_LEVELS] = { 0x938000, 3, RMH_SSIZE_FIXED, 0 },
[CMD_CANCEL_R_BUFFERS] = { 0x948000, 4, RMH_SSIZE_FIXED, 0 },
[CMD_NOTIFY_END_OF_BUFFER] = { 0x950000, 1, RMH_SSIZE_FIXED, 0 },
[CMD_GET_STREAM_VU_METER] = { 0x95A000, 2, RMH_SSIZE_ARG, 0 },
};
/**
* vx_init_rmh - initialize the RMH instance
* @rmh: the rmh pointer to be initialized
* @cmd: the rmh command to be set
*/
void vx_init_rmh(struct vx_rmh *rmh, unsigned int cmd)
{
if (snd_BUG_ON(cmd >= CMD_LAST_INDEX))
return;
rmh->LgCmd = vx_dsp_cmds[cmd].length;
rmh->LgStat = vx_dsp_cmds[cmd].st_length;
rmh->DspStat = vx_dsp_cmds[cmd].st_type;
rmh->Cmd[0] = vx_dsp_cmds[cmd].opcode;
}
| gpl-2.0 |
w1ndy/linux | drivers/gpu/drm/msm/hdmi/hdmi_phy_8960.c | 215 | 16135 | /*
* Copyright (C) 2013 Red Hat
* Author: Rob Clark <robdclark@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, see <http://www.gnu.org/licenses/>.
*/
#ifdef CONFIG_COMMON_CLK
#include <linux/clk.h>
#include <linux/clk-provider.h>
#endif
#include "hdmi.h"
struct hdmi_phy_8960 {
struct hdmi_phy base;
struct hdmi *hdmi;
#ifdef CONFIG_COMMON_CLK
struct clk_hw pll_hw;
struct clk *pll;
unsigned long pixclk;
#endif
};
#define to_hdmi_phy_8960(x) container_of(x, struct hdmi_phy_8960, base)
#ifdef CONFIG_COMMON_CLK
#define clk_to_phy(x) container_of(x, struct hdmi_phy_8960, pll_hw)
/*
* HDMI PLL:
*
* To get the parent clock setup properly, we need to plug in hdmi pll
* configuration into common-clock-framework.
*/
struct pll_rate {
unsigned long rate;
struct {
uint32_t val;
uint32_t reg;
} conf[32];
};
/* NOTE: keep sorted highest freq to lowest: */
static const struct pll_rate freqtbl[] = {
/* 1080p60/1080p50 case */
{ 148500000, {
{ 0x02, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x02, REG_HDMI_8960_PHY_PLL_CHRG_PUMP_CFG },
{ 0x01, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0x33, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x2c, REG_HDMI_8960_PHY_PLL_IDAC_ADJ_CFG },
{ 0x06, REG_HDMI_8960_PHY_PLL_I_VI_KVCO_CFG },
{ 0x0a, REG_HDMI_8960_PHY_PLL_PWRDN_B },
{ 0x76, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0x01, REG_HDMI_8960_PHY_PLL_SDM_CFG1 },
{ 0x4c, REG_HDMI_8960_PHY_PLL_SDM_CFG2 },
{ 0xc0, REG_HDMI_8960_PHY_PLL_SDM_CFG3 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG4 },
{ 0x9a, REG_HDMI_8960_PHY_PLL_SSC_CFG0 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG1 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG3 },
{ 0x10, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG0 },
{ 0x1a, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG1 },
{ 0x0d, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2 },
{ 0xe6, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x02, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG3 },
{ 0x86, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG4 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG5 },
{ 0x33, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG6 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG7 },
{ 0, 0 } }
},
{ 108000000, {
{ 0x08, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x21, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0xf9, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x1c, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x02, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0x86, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG4 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG5 },
{ 0x49, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0x49, REG_HDMI_8960_PHY_PLL_SDM_CFG1 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG3 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG4 },
{ 0, 0 } }
},
/* 720p60/720p50/1080i60/1080i50/1080p24/1080p30/1080p25 */
{ 74250000, {
{ 0x0a, REG_HDMI_8960_PHY_PLL_PWRDN_B },
{ 0x12, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x01, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0x33, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x76, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0xe6, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x02, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0, 0 } }
},
{ 65000000, {
{ 0x18, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x20, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0xf9, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x8a, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x02, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG3 },
{ 0x86, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG4 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG5 },
{ 0x0b, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0x4b, REG_HDMI_8960_PHY_PLL_SDM_CFG1 },
{ 0x7b, REG_HDMI_8960_PHY_PLL_SDM_CFG2 },
{ 0x09, REG_HDMI_8960_PHY_PLL_SDM_CFG3 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG4 },
{ 0, 0 } }
},
/* 480p60/480i60 */
{ 27030000, {
{ 0x0a, REG_HDMI_8960_PHY_PLL_PWRDN_B },
{ 0x38, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x02, REG_HDMI_8960_PHY_PLL_CHRG_PUMP_CFG },
{ 0x20, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0xff, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0x4e, REG_HDMI_8960_PHY_PLL_SDM_CFG1 },
{ 0xd7, REG_HDMI_8960_PHY_PLL_SDM_CFG2 },
{ 0x03, REG_HDMI_8960_PHY_PLL_SDM_CFG3 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG4 },
{ 0x2a, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x03, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG3 },
{ 0x86, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG4 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG5 },
{ 0x33, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG6 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG7 },
{ 0, 0 } }
},
/* 576p50/576i50 */
{ 27000000, {
{ 0x32, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x02, REG_HDMI_8960_PHY_PLL_CHRG_PUMP_CFG },
{ 0x01, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0x33, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x2c, REG_HDMI_8960_PHY_PLL_IDAC_ADJ_CFG },
{ 0x06, REG_HDMI_8960_PHY_PLL_I_VI_KVCO_CFG },
{ 0x0a, REG_HDMI_8960_PHY_PLL_PWRDN_B },
{ 0x7b, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0x01, REG_HDMI_8960_PHY_PLL_SDM_CFG1 },
{ 0x4c, REG_HDMI_8960_PHY_PLL_SDM_CFG2 },
{ 0xc0, REG_HDMI_8960_PHY_PLL_SDM_CFG3 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG4 },
{ 0x9a, REG_HDMI_8960_PHY_PLL_SSC_CFG0 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG1 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG3 },
{ 0x10, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG0 },
{ 0x1a, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG1 },
{ 0x0d, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2 },
{ 0x2a, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x03, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG3 },
{ 0x86, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG4 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG5 },
{ 0x33, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG6 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG7 },
{ 0, 0 } }
},
/* 640x480p60 */
{ 25200000, {
{ 0x32, REG_HDMI_8960_PHY_PLL_REFCLK_CFG },
{ 0x02, REG_HDMI_8960_PHY_PLL_CHRG_PUMP_CFG },
{ 0x01, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG0 },
{ 0x33, REG_HDMI_8960_PHY_PLL_LOOP_FLT_CFG1 },
{ 0x2c, REG_HDMI_8960_PHY_PLL_IDAC_ADJ_CFG },
{ 0x06, REG_HDMI_8960_PHY_PLL_I_VI_KVCO_CFG },
{ 0x0a, REG_HDMI_8960_PHY_PLL_PWRDN_B },
{ 0x77, REG_HDMI_8960_PHY_PLL_SDM_CFG0 },
{ 0x4c, REG_HDMI_8960_PHY_PLL_SDM_CFG1 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG2 },
{ 0xc0, REG_HDMI_8960_PHY_PLL_SDM_CFG3 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SDM_CFG4 },
{ 0x9a, REG_HDMI_8960_PHY_PLL_SSC_CFG0 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG1 },
{ 0x00, REG_HDMI_8960_PHY_PLL_SSC_CFG2 },
{ 0x20, REG_HDMI_8960_PHY_PLL_SSC_CFG3 },
{ 0x10, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG0 },
{ 0x1a, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG1 },
{ 0x0d, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2 },
{ 0xf4, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG0 },
{ 0x02, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG1 },
{ 0x3b, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG2 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG3 },
{ 0x86, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG4 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG5 },
{ 0x33, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG6 },
{ 0x00, REG_HDMI_8960_PHY_PLL_VCOCAL_CFG7 },
{ 0, 0 } }
},
};
static int hdmi_pll_enable(struct clk_hw *hw)
{
struct hdmi_phy_8960 *phy_8960 = clk_to_phy(hw);
struct hdmi *hdmi = phy_8960->hdmi;
int timeout_count, pll_lock_retry = 10;
unsigned int val;
DBG("");
/* Assert PLL S/W reset */
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2, 0x8d);
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG0, 0x10);
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG1, 0x1a);
/* Wait for a short time before de-asserting
* to allow the hardware to complete its job.
* This much of delay should be fine for hardware
* to assert and de-assert.
*/
udelay(10);
/* De-assert PLL S/W reset */
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2, 0x0d);
val = hdmi_read(hdmi, REG_HDMI_8960_PHY_REG12);
val |= HDMI_8960_PHY_REG12_SW_RESET;
/* Assert PHY S/W reset */
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG12, val);
val &= ~HDMI_8960_PHY_REG12_SW_RESET;
/* Wait for a short time before de-asserting
to allow the hardware to complete its job.
This much of delay should be fine for hardware
to assert and de-assert. */
udelay(10);
/* De-assert PHY S/W reset */
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG12, val);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG2, 0x3f);
val = hdmi_read(hdmi, REG_HDMI_8960_PHY_REG12);
val |= HDMI_8960_PHY_REG12_PWRDN_B;
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG12, val);
/* Wait 10 us for enabling global power for PHY */
mb();
udelay(10);
val = hdmi_read(hdmi, REG_HDMI_8960_PHY_PLL_PWRDN_B);
val |= HDMI_8960_PHY_PLL_PWRDN_B_PLL_PWRDN_B;
val &= ~HDMI_8960_PHY_PLL_PWRDN_B_PD_PLL;
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_PWRDN_B, val);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG2, 0x80);
timeout_count = 1000;
while (--pll_lock_retry > 0) {
/* are we there yet? */
val = hdmi_read(hdmi, REG_HDMI_8960_PHY_PLL_STATUS0);
if (val & HDMI_8960_PHY_PLL_STATUS0_PLL_LOCK)
break;
udelay(1);
if (--timeout_count > 0)
continue;
/*
* PLL has still not locked.
* Do a software reset and try again
* Assert PLL S/W reset first
*/
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2, 0x8d);
udelay(10);
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_LOCKDET_CFG2, 0x0d);
/*
* Wait for a short duration for the PLL calibration
* before checking if the PLL gets locked
*/
udelay(350);
timeout_count = 1000;
}
return 0;
}
static void hdmi_pll_disable(struct clk_hw *hw)
{
struct hdmi_phy_8960 *phy_8960 = clk_to_phy(hw);
struct hdmi *hdmi = phy_8960->hdmi;
unsigned int val;
DBG("");
val = hdmi_read(hdmi, REG_HDMI_8960_PHY_REG12);
val &= ~HDMI_8960_PHY_REG12_PWRDN_B;
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG12, val);
val = hdmi_read(hdmi, REG_HDMI_8960_PHY_PLL_PWRDN_B);
val |= HDMI_8960_PHY_REG12_SW_RESET;
val &= ~HDMI_8960_PHY_REG12_PWRDN_B;
hdmi_write(hdmi, REG_HDMI_8960_PHY_PLL_PWRDN_B, val);
/* Make sure HDMI PHY/PLL are powered down */
mb();
}
static const struct pll_rate *find_rate(unsigned long rate)
{
int i;
for (i = 1; i < ARRAY_SIZE(freqtbl); i++)
if (rate > freqtbl[i].rate)
return &freqtbl[i-1];
return &freqtbl[i-1];
}
static unsigned long hdmi_pll_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct hdmi_phy_8960 *phy_8960 = clk_to_phy(hw);
return phy_8960->pixclk;
}
static long hdmi_pll_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *parent_rate)
{
const struct pll_rate *pll_rate = find_rate(rate);
return pll_rate->rate;
}
static int hdmi_pll_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct hdmi_phy_8960 *phy_8960 = clk_to_phy(hw);
struct hdmi *hdmi = phy_8960->hdmi;
const struct pll_rate *pll_rate = find_rate(rate);
int i;
DBG("rate=%lu", rate);
for (i = 0; pll_rate->conf[i].reg; i++)
hdmi_write(hdmi, pll_rate->conf[i].reg, pll_rate->conf[i].val);
phy_8960->pixclk = rate;
return 0;
}
static const struct clk_ops hdmi_pll_ops = {
.enable = hdmi_pll_enable,
.disable = hdmi_pll_disable,
.recalc_rate = hdmi_pll_recalc_rate,
.round_rate = hdmi_pll_round_rate,
.set_rate = hdmi_pll_set_rate,
};
static const char *hdmi_pll_parents[] = {
"pxo",
};
static struct clk_init_data pll_init = {
.name = "hdmi_pll",
.ops = &hdmi_pll_ops,
.parent_names = hdmi_pll_parents,
.num_parents = ARRAY_SIZE(hdmi_pll_parents),
};
#endif
/*
* HDMI Phy:
*/
static void hdmi_phy_8960_destroy(struct hdmi_phy *phy)
{
struct hdmi_phy_8960 *phy_8960 = to_hdmi_phy_8960(phy);
kfree(phy_8960);
}
static void hdmi_phy_8960_reset(struct hdmi_phy *phy)
{
struct hdmi_phy_8960 *phy_8960 = to_hdmi_phy_8960(phy);
struct hdmi *hdmi = phy_8960->hdmi;
unsigned int val;
val = hdmi_read(hdmi, REG_HDMI_PHY_CTRL);
if (val & HDMI_PHY_CTRL_SW_RESET_LOW) {
/* pull low */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val & ~HDMI_PHY_CTRL_SW_RESET);
} else {
/* pull high */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val | HDMI_PHY_CTRL_SW_RESET);
}
if (val & HDMI_PHY_CTRL_SW_RESET_PLL_LOW) {
/* pull low */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val & ~HDMI_PHY_CTRL_SW_RESET_PLL);
} else {
/* pull high */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val | HDMI_PHY_CTRL_SW_RESET_PLL);
}
msleep(100);
if (val & HDMI_PHY_CTRL_SW_RESET_LOW) {
/* pull high */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val | HDMI_PHY_CTRL_SW_RESET);
} else {
/* pull low */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val & ~HDMI_PHY_CTRL_SW_RESET);
}
if (val & HDMI_PHY_CTRL_SW_RESET_PLL_LOW) {
/* pull high */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val | HDMI_PHY_CTRL_SW_RESET_PLL);
} else {
/* pull low */
hdmi_write(hdmi, REG_HDMI_PHY_CTRL,
val & ~HDMI_PHY_CTRL_SW_RESET_PLL);
}
}
static void hdmi_phy_8960_powerup(struct hdmi_phy *phy,
unsigned long int pixclock)
{
struct hdmi_phy_8960 *phy_8960 = to_hdmi_phy_8960(phy);
struct hdmi *hdmi = phy_8960->hdmi;
DBG("pixclock: %lu", pixclock);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG2, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG0, 0x1b);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG1, 0xf2);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG4, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG5, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG6, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG7, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG8, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG9, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG10, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG11, 0x00);
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG3, 0x20);
}
static void hdmi_phy_8960_powerdown(struct hdmi_phy *phy)
{
struct hdmi_phy_8960 *phy_8960 = to_hdmi_phy_8960(phy);
struct hdmi *hdmi = phy_8960->hdmi;
DBG("");
hdmi_write(hdmi, REG_HDMI_8960_PHY_REG2, 0x7f);
}
static const struct hdmi_phy_funcs hdmi_phy_8960_funcs = {
.destroy = hdmi_phy_8960_destroy,
.reset = hdmi_phy_8960_reset,
.powerup = hdmi_phy_8960_powerup,
.powerdown = hdmi_phy_8960_powerdown,
};
struct hdmi_phy *hdmi_phy_8960_init(struct hdmi *hdmi)
{
struct hdmi_phy_8960 *phy_8960;
struct hdmi_phy *phy = NULL;
int ret;
#ifdef CONFIG_COMMON_CLK
int i;
/* sanity check: */
for (i = 0; i < (ARRAY_SIZE(freqtbl) - 1); i++)
if (WARN_ON(freqtbl[i].rate < freqtbl[i+1].rate))
return ERR_PTR(-EINVAL);
#endif
phy_8960 = kzalloc(sizeof(*phy_8960), GFP_KERNEL);
if (!phy_8960) {
ret = -ENOMEM;
goto fail;
}
phy = &phy_8960->base;
phy->funcs = &hdmi_phy_8960_funcs;
phy_8960->hdmi = hdmi;
#ifdef CONFIG_COMMON_CLK
phy_8960->pll_hw.init = &pll_init;
phy_8960->pll = devm_clk_register(&hdmi->pdev->dev, &phy_8960->pll_hw);
if (IS_ERR(phy_8960->pll)) {
ret = PTR_ERR(phy_8960->pll);
phy_8960->pll = NULL;
goto fail;
}
#endif
return phy;
fail:
if (phy)
hdmi_phy_8960_destroy(phy);
return ERR_PTR(ret);
}
| gpl-2.0 |
raydtang/linux-rockchip | drivers/scsi/atari_scsi.c | 215 | 32732 | /*
* atari_scsi.c -- Device dependent functions for the Atari generic SCSI port
*
* Copyright 1994 Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
*
* Loosely based on the work of Robert De Vries' team and added:
* - working real DMA
* - Falcon support (untested yet!) ++bjoern fixed and now it works
* - lots of extensions and bug fixes.
*
* 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.
*
*/
/**************************************************************************/
/* */
/* Notes for Falcon SCSI: */
/* ---------------------- */
/* */
/* Since the Falcon SCSI uses the ST-DMA chip, that is shared among */
/* several device drivers, locking and unlocking the access to this */
/* chip is required. But locking is not possible from an interrupt, */
/* since it puts the process to sleep if the lock is not available. */
/* This prevents "late" locking of the DMA chip, i.e. locking it just */
/* before using it, since in case of disconnection-reconnection */
/* commands, the DMA is started from the reselection interrupt. */
/* */
/* Two possible schemes for ST-DMA-locking would be: */
/* 1) The lock is taken for each command separately and disconnecting */
/* is forbidden (i.e. can_queue = 1). */
/* 2) The DMA chip is locked when the first command comes in and */
/* released when the last command is finished and all queues are */
/* empty. */
/* The first alternative would result in bad performance, since the */
/* interleaving of commands would not be used. The second is unfair to */
/* other drivers using the ST-DMA, because the queues will seldom be */
/* totally empty if there is a lot of disk traffic. */
/* */
/* For this reasons I decided to employ a more elaborate scheme: */
/* - First, we give up the lock every time we can (for fairness), this */
/* means every time a command finishes and there are no other commands */
/* on the disconnected queue. */
/* - If there are others waiting to lock the DMA chip, we stop */
/* issuing commands, i.e. moving them onto the issue queue. */
/* Because of that, the disconnected queue will run empty in a */
/* while. Instead we go to sleep on a 'fairness_queue'. */
/* - If the lock is released, all processes waiting on the fairness */
/* queue will be woken. The first of them tries to re-lock the DMA, */
/* the others wait for the first to finish this task. After that, */
/* they can all run on and do their commands... */
/* This sounds complicated (and it is it :-(), but it seems to be a */
/* good compromise between fairness and performance: As long as no one */
/* else wants to work with the ST-DMA chip, SCSI can go along as */
/* usual. If now someone else comes, this behaviour is changed to a */
/* "fairness mode": just already initiated commands are finished and */
/* then the lock is released. The other one waiting will probably win */
/* the race for locking the DMA, since it was waiting for longer. And */
/* after it has finished, SCSI can go ahead again. Finally: I hope I */
/* have not produced any deadlock possibilities! */
/* */
/**************************************************************************/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/nvram.h>
#include <linux/bitops.h>
#include <linux/wait.h>
#include <linux/platform_device.h>
#include <asm/setup.h>
#include <asm/atarihw.h>
#include <asm/atariints.h>
#include <asm/atari_stdma.h>
#include <asm/atari_stram.h>
#include <asm/io.h>
#include <scsi/scsi_host.h>
/* Definitions for the core NCR5380 driver. */
#define REAL_DMA
#define SUPPORT_TAGS
#define MAX_TAGS 32
#define DMA_MIN_SIZE 32
#define NCR5380_implementation_fields /* none */
#define NCR5380_read(reg) atari_scsi_reg_read(reg)
#define NCR5380_write(reg, value) atari_scsi_reg_write(reg, value)
#define NCR5380_queue_command atari_scsi_queue_command
#define NCR5380_abort atari_scsi_abort
#define NCR5380_show_info atari_scsi_show_info
#define NCR5380_info atari_scsi_info
#define NCR5380_dma_read_setup(instance, data, count) \
atari_scsi_dma_setup(instance, data, count, 0)
#define NCR5380_dma_write_setup(instance, data, count) \
atari_scsi_dma_setup(instance, data, count, 1)
#define NCR5380_dma_residual(instance) \
atari_scsi_dma_residual(instance)
#define NCR5380_dma_xfer_len(instance, cmd, phase) \
atari_dma_xfer_len(cmd->SCp.this_residual, cmd, !((phase) & SR_IO))
#define NCR5380_acquire_dma_irq(instance) falcon_get_lock(instance)
#define NCR5380_release_dma_irq(instance) falcon_release_lock()
#include "NCR5380.h"
#define IS_A_TT() ATARIHW_PRESENT(TT_SCSI)
#define SCSI_DMA_WRITE_P(elt,val) \
do { \
unsigned long v = val; \
tt_scsi_dma.elt##_lo = v & 0xff; \
v >>= 8; \
tt_scsi_dma.elt##_lmd = v & 0xff; \
v >>= 8; \
tt_scsi_dma.elt##_hmd = v & 0xff; \
v >>= 8; \
tt_scsi_dma.elt##_hi = v & 0xff; \
} while(0)
#define SCSI_DMA_READ_P(elt) \
(((((((unsigned long)tt_scsi_dma.elt##_hi << 8) | \
(unsigned long)tt_scsi_dma.elt##_hmd) << 8) | \
(unsigned long)tt_scsi_dma.elt##_lmd) << 8) | \
(unsigned long)tt_scsi_dma.elt##_lo)
static inline void SCSI_DMA_SETADR(unsigned long adr)
{
st_dma.dma_lo = (unsigned char)adr;
MFPDELAY();
adr >>= 8;
st_dma.dma_md = (unsigned char)adr;
MFPDELAY();
adr >>= 8;
st_dma.dma_hi = (unsigned char)adr;
MFPDELAY();
}
static inline unsigned long SCSI_DMA_GETADR(void)
{
unsigned long adr;
adr = st_dma.dma_lo;
MFPDELAY();
adr |= (st_dma.dma_md & 0xff) << 8;
MFPDELAY();
adr |= (st_dma.dma_hi & 0xff) << 16;
MFPDELAY();
return adr;
}
#define HOSTDATA_DMALEN (((struct NCR5380_hostdata *) \
(atari_scsi_host->hostdata))->dma_len)
/* Time (in jiffies) to wait after a reset; the SCSI standard calls for 250ms,
* we usually do 0.5s to be on the safe side. But Toshiba CD-ROMs once more
* need ten times the standard value... */
#ifndef CONFIG_ATARI_SCSI_TOSHIBA_DELAY
#define AFTER_RESET_DELAY (HZ/2)
#else
#define AFTER_RESET_DELAY (5*HZ/2)
#endif
#ifdef REAL_DMA
static void atari_scsi_fetch_restbytes(void);
#endif
static struct Scsi_Host *atari_scsi_host;
static unsigned char (*atari_scsi_reg_read)(unsigned char reg);
static void (*atari_scsi_reg_write)(unsigned char reg, unsigned char value);
#ifdef REAL_DMA
static unsigned long atari_dma_residual, atari_dma_startaddr;
static short atari_dma_active;
/* pointer to the dribble buffer */
static char *atari_dma_buffer;
/* precalculated physical address of the dribble buffer */
static unsigned long atari_dma_phys_buffer;
/* != 0 tells the Falcon int handler to copy data from the dribble buffer */
static char *atari_dma_orig_addr;
/* size of the dribble buffer; 4k seems enough, since the Falcon cannot use
* scatter-gather anyway, so most transfers are 1024 byte only. In the rare
* cases where requests to physical contiguous buffers have been merged, this
* request is <= 4k (one page). So I don't think we have to split transfers
* just due to this buffer size...
*/
#define STRAM_BUFFER_SIZE (4096)
/* mask for address bits that can't be used with the ST-DMA */
static unsigned long atari_dma_stram_mask;
#define STRAM_ADDR(a) (((a) & atari_dma_stram_mask) == 0)
#endif
static int setup_can_queue = -1;
module_param(setup_can_queue, int, 0);
static int setup_cmd_per_lun = -1;
module_param(setup_cmd_per_lun, int, 0);
static int setup_sg_tablesize = -1;
module_param(setup_sg_tablesize, int, 0);
#ifdef SUPPORT_TAGS
static int setup_use_tagged_queuing = -1;
module_param(setup_use_tagged_queuing, int, 0);
#endif
static int setup_hostid = -1;
module_param(setup_hostid, int, 0);
#if defined(REAL_DMA)
static int scsi_dma_is_ignored_buserr(unsigned char dma_stat)
{
int i;
unsigned long addr = SCSI_DMA_READ_P(dma_addr), end_addr;
if (dma_stat & 0x01) {
/* A bus error happens when DMA-ing from the last page of a
* physical memory chunk (DMA prefetch!), but that doesn't hurt.
* Check for this case:
*/
for (i = 0; i < m68k_num_memory; ++i) {
end_addr = m68k_memory[i].addr + m68k_memory[i].size;
if (end_addr <= addr && addr <= end_addr + 4)
return 1;
}
}
return 0;
}
#if 0
/* Dead code... wasn't called anyway :-) and causes some trouble, because at
* end-of-DMA, both SCSI ints are triggered simultaneously, so the NCR int has
* to clear the DMA int pending bit before it allows other level 6 interrupts.
*/
static void scsi_dma_buserr(int irq, void *dummy)
{
unsigned char dma_stat = tt_scsi_dma.dma_ctrl;
/* Don't do anything if a NCR interrupt is pending. Probably it's just
* masked... */
if (atari_irq_pending(IRQ_TT_MFP_SCSI))
return;
printk("Bad SCSI DMA interrupt! dma_addr=0x%08lx dma_stat=%02x dma_cnt=%08lx\n",
SCSI_DMA_READ_P(dma_addr), dma_stat, SCSI_DMA_READ_P(dma_cnt));
if (dma_stat & 0x80) {
if (!scsi_dma_is_ignored_buserr(dma_stat))
printk("SCSI DMA bus error -- bad DMA programming!\n");
} else {
/* Under normal circumstances we never should get to this point,
* since both interrupts are triggered simultaneously and the 5380
* int has higher priority. When this irq is handled, that DMA
* interrupt is cleared. So a warning message is printed here.
*/
printk("SCSI DMA intr ?? -- this shouldn't happen!\n");
}
}
#endif
#endif
static irqreturn_t scsi_tt_intr(int irq, void *dummy)
{
#ifdef REAL_DMA
int dma_stat;
dma_stat = tt_scsi_dma.dma_ctrl;
dprintk(NDEBUG_INTR, "scsi%d: NCR5380 interrupt, DMA status = %02x\n",
atari_scsi_host->host_no, dma_stat & 0xff);
/* Look if it was the DMA that has interrupted: First possibility
* is that a bus error occurred...
*/
if (dma_stat & 0x80) {
if (!scsi_dma_is_ignored_buserr(dma_stat)) {
printk(KERN_ERR "SCSI DMA caused bus error near 0x%08lx\n",
SCSI_DMA_READ_P(dma_addr));
printk(KERN_CRIT "SCSI DMA bus error -- bad DMA programming!");
}
}
/* If the DMA is active but not finished, we have the case
* that some other 5380 interrupt occurred within the DMA transfer.
* This means we have residual bytes, if the desired end address
* is not yet reached. Maybe we have to fetch some bytes from the
* rest data register, too. The residual must be calculated from
* the address pointer, not the counter register, because only the
* addr reg counts bytes not yet written and pending in the rest
* data reg!
*/
if ((dma_stat & 0x02) && !(dma_stat & 0x40)) {
atari_dma_residual = HOSTDATA_DMALEN - (SCSI_DMA_READ_P(dma_addr) - atari_dma_startaddr);
dprintk(NDEBUG_DMA, "SCSI DMA: There are %ld residual bytes.\n",
atari_dma_residual);
if ((signed int)atari_dma_residual < 0)
atari_dma_residual = 0;
if ((dma_stat & 1) == 0) {
/*
* After read operations, we maybe have to
* transport some rest bytes
*/
atari_scsi_fetch_restbytes();
} else {
/*
* There seems to be a nasty bug in some SCSI-DMA/NCR
* combinations: If a target disconnects while a write
* operation is going on, the address register of the
* DMA may be a few bytes farer than it actually read.
* This is probably due to DMA prefetching and a delay
* between DMA and NCR. Experiments showed that the
* dma_addr is 9 bytes to high, but this could vary.
* The problem is, that the residual is thus calculated
* wrong and the next transfer will start behind where
* it should. So we round up the residual to the next
* multiple of a sector size, if it isn't already a
* multiple and the originally expected transfer size
* was. The latter condition is there to ensure that
* the correction is taken only for "real" data
* transfers and not for, e.g., the parameters of some
* other command. These shouldn't disconnect anyway.
*/
if (atari_dma_residual & 0x1ff) {
dprintk(NDEBUG_DMA, "SCSI DMA: DMA bug corrected, "
"difference %ld bytes\n",
512 - (atari_dma_residual & 0x1ff));
atari_dma_residual = (atari_dma_residual + 511) & ~0x1ff;
}
}
tt_scsi_dma.dma_ctrl = 0;
}
/* If the DMA is finished, fetch the rest bytes and turn it off */
if (dma_stat & 0x40) {
atari_dma_residual = 0;
if ((dma_stat & 1) == 0)
atari_scsi_fetch_restbytes();
tt_scsi_dma.dma_ctrl = 0;
}
#endif /* REAL_DMA */
NCR5380_intr(irq, dummy);
return IRQ_HANDLED;
}
static irqreturn_t scsi_falcon_intr(int irq, void *dummy)
{
#ifdef REAL_DMA
int dma_stat;
/* Turn off DMA and select sector counter register before
* accessing the status register (Atari recommendation!)
*/
st_dma.dma_mode_status = 0x90;
dma_stat = st_dma.dma_mode_status;
/* Bit 0 indicates some error in the DMA process... don't know
* what happened exactly (no further docu).
*/
if (!(dma_stat & 0x01)) {
/* DMA error */
printk(KERN_CRIT "SCSI DMA error near 0x%08lx!\n", SCSI_DMA_GETADR());
}
/* If the DMA was active, but now bit 1 is not clear, it is some
* other 5380 interrupt that finishes the DMA transfer. We have to
* calculate the number of residual bytes and give a warning if
* bytes are stuck in the ST-DMA fifo (there's no way to reach them!)
*/
if (atari_dma_active && (dma_stat & 0x02)) {
unsigned long transferred;
transferred = SCSI_DMA_GETADR() - atari_dma_startaddr;
/* The ST-DMA address is incremented in 2-byte steps, but the
* data are written only in 16-byte chunks. If the number of
* transferred bytes is not divisible by 16, the remainder is
* lost somewhere in outer space.
*/
if (transferred & 15)
printk(KERN_ERR "SCSI DMA error: %ld bytes lost in "
"ST-DMA fifo\n", transferred & 15);
atari_dma_residual = HOSTDATA_DMALEN - transferred;
dprintk(NDEBUG_DMA, "SCSI DMA: There are %ld residual bytes.\n",
atari_dma_residual);
} else
atari_dma_residual = 0;
atari_dma_active = 0;
if (atari_dma_orig_addr) {
/* If the dribble buffer was used on a read operation, copy the DMA-ed
* data to the original destination address.
*/
memcpy(atari_dma_orig_addr, phys_to_virt(atari_dma_startaddr),
HOSTDATA_DMALEN - atari_dma_residual);
atari_dma_orig_addr = NULL;
}
#endif /* REAL_DMA */
NCR5380_intr(irq, dummy);
return IRQ_HANDLED;
}
#ifdef REAL_DMA
static void atari_scsi_fetch_restbytes(void)
{
int nr;
char *src, *dst;
unsigned long phys_dst;
/* fetch rest bytes in the DMA register */
phys_dst = SCSI_DMA_READ_P(dma_addr);
nr = phys_dst & 3;
if (nr) {
/* there are 'nr' bytes left for the last long address
before the DMA pointer */
phys_dst ^= nr;
dprintk(NDEBUG_DMA, "SCSI DMA: there are %d rest bytes for phys addr 0x%08lx",
nr, phys_dst);
/* The content of the DMA pointer is a physical address! */
dst = phys_to_virt(phys_dst);
dprintk(NDEBUG_DMA, " = virt addr %p\n", dst);
for (src = (char *)&tt_scsi_dma.dma_restdata; nr != 0; --nr)
*dst++ = *src++;
}
}
#endif /* REAL_DMA */
/* This function releases the lock on the DMA chip if there is no
* connected command and the disconnected queue is empty.
*/
static void falcon_release_lock(void)
{
if (IS_A_TT())
return;
if (stdma_is_locked_by(scsi_falcon_intr))
stdma_release();
}
/* This function manages the locking of the ST-DMA.
* If the DMA isn't locked already for SCSI, it tries to lock it by
* calling stdma_lock(). But if the DMA is locked by the SCSI code and
* there are other drivers waiting for the chip, we do not issue the
* command immediately but tell the SCSI mid-layer to defer.
*/
static int falcon_get_lock(struct Scsi_Host *instance)
{
if (IS_A_TT())
return 1;
if (in_interrupt())
return stdma_try_lock(scsi_falcon_intr, instance);
stdma_lock(scsi_falcon_intr, instance);
return 1;
}
#ifndef MODULE
static int __init atari_scsi_setup(char *str)
{
/* Format of atascsi parameter is:
* atascsi=<can_queue>,<cmd_per_lun>,<sg_tablesize>,<hostid>,<use_tags>
* Defaults depend on TT or Falcon, determined at run time.
* Negative values mean don't change.
*/
int ints[6];
get_options(str, ARRAY_SIZE(ints), ints);
if (ints[0] < 1) {
printk("atari_scsi_setup: no arguments!\n");
return 0;
}
if (ints[0] >= 1)
setup_can_queue = ints[1];
if (ints[0] >= 2)
setup_cmd_per_lun = ints[2];
if (ints[0] >= 3)
setup_sg_tablesize = ints[3];
if (ints[0] >= 4)
setup_hostid = ints[4];
#ifdef SUPPORT_TAGS
if (ints[0] >= 5)
setup_use_tagged_queuing = ints[5];
#endif
return 1;
}
__setup("atascsi=", atari_scsi_setup);
#endif /* !MODULE */
#ifdef CONFIG_ATARI_SCSI_RESET_BOOT
static void __init atari_scsi_reset_boot(void)
{
unsigned long end;
/*
* Do a SCSI reset to clean up the bus during initialization. No messing
* with the queues, interrupts, or locks necessary here.
*/
printk("Atari SCSI: resetting the SCSI bus...");
/* get in phase */
NCR5380_write(TARGET_COMMAND_REG,
PHASE_SR_TO_TCR(NCR5380_read(STATUS_REG)));
/* assert RST */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST);
/* The min. reset hold time is 25us, so 40us should be enough */
udelay(50);
/* reset RST and interrupt */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
NCR5380_read(RESET_PARITY_INTERRUPT_REG);
end = jiffies + AFTER_RESET_DELAY;
while (time_before(jiffies, end))
barrier();
printk(" done\n");
}
#endif
#if defined(REAL_DMA)
static unsigned long atari_scsi_dma_setup(struct Scsi_Host *instance,
void *data, unsigned long count,
int dir)
{
unsigned long addr = virt_to_phys(data);
dprintk(NDEBUG_DMA, "scsi%d: setting up dma, data = %p, phys = %lx, count = %ld, "
"dir = %d\n", instance->host_no, data, addr, count, dir);
if (!IS_A_TT() && !STRAM_ADDR(addr)) {
/* If we have a non-DMAable address on a Falcon, use the dribble
* buffer; 'orig_addr' != 0 in the read case tells the interrupt
* handler to copy data from the dribble buffer to the originally
* wanted address.
*/
if (dir)
memcpy(atari_dma_buffer, data, count);
else
atari_dma_orig_addr = data;
addr = atari_dma_phys_buffer;
}
atari_dma_startaddr = addr; /* Needed for calculating residual later. */
/* Cache cleanup stuff: On writes, push any dirty cache out before sending
* it to the peripheral. (Must be done before DMA setup, since at least
* the ST-DMA begins to fill internal buffers right after setup. For
* reads, invalidate any cache, may be altered after DMA without CPU
* knowledge.
*
* ++roman: For the Medusa, there's no need at all for that cache stuff,
* because the hardware does bus snooping (fine!).
*/
dma_cache_maintenance(addr, count, dir);
if (count == 0)
printk(KERN_NOTICE "SCSI warning: DMA programmed for 0 bytes !\n");
if (IS_A_TT()) {
tt_scsi_dma.dma_ctrl = dir;
SCSI_DMA_WRITE_P(dma_addr, addr);
SCSI_DMA_WRITE_P(dma_cnt, count);
tt_scsi_dma.dma_ctrl = dir | 2;
} else { /* ! IS_A_TT */
/* set address */
SCSI_DMA_SETADR(addr);
/* toggle direction bit to clear FIFO and set DMA direction */
dir <<= 8;
st_dma.dma_mode_status = 0x90 | dir;
st_dma.dma_mode_status = 0x90 | (dir ^ 0x100);
st_dma.dma_mode_status = 0x90 | dir;
udelay(40);
/* On writes, round up the transfer length to the next multiple of 512
* (see also comment at atari_dma_xfer_len()). */
st_dma.fdc_acces_seccount = (count + (dir ? 511 : 0)) >> 9;
udelay(40);
st_dma.dma_mode_status = 0x10 | dir;
udelay(40);
/* need not restore value of dir, only boolean value is tested */
atari_dma_active = 1;
}
return count;
}
static long atari_scsi_dma_residual(struct Scsi_Host *instance)
{
return atari_dma_residual;
}
#define CMD_SURELY_BLOCK_MODE 0
#define CMD_SURELY_BYTE_MODE 1
#define CMD_MODE_UNKNOWN 2
static int falcon_classify_cmd(struct scsi_cmnd *cmd)
{
unsigned char opcode = cmd->cmnd[0];
if (opcode == READ_DEFECT_DATA || opcode == READ_LONG ||
opcode == READ_BUFFER)
return CMD_SURELY_BYTE_MODE;
else if (opcode == READ_6 || opcode == READ_10 ||
opcode == 0xa8 /* READ_12 */ || opcode == READ_REVERSE ||
opcode == RECOVER_BUFFERED_DATA) {
/* In case of a sequential-access target (tape), special care is
* needed here: The transfer is block-mode only if the 'fixed' bit is
* set! */
if (cmd->device->type == TYPE_TAPE && !(cmd->cmnd[1] & 1))
return CMD_SURELY_BYTE_MODE;
else
return CMD_SURELY_BLOCK_MODE;
} else
return CMD_MODE_UNKNOWN;
}
/* This function calculates the number of bytes that can be transferred via
* DMA. On the TT, this is arbitrary, but on the Falcon we have to use the
* ST-DMA chip. There are only multiples of 512 bytes possible and max.
* 255*512 bytes :-( This means also, that defining READ_OVERRUNS is not
* possible on the Falcon, since that would require to program the DMA for
* n*512 - atari_read_overrun bytes. But it seems that the Falcon doesn't have
* the overrun problem, so this question is academic :-)
*/
static unsigned long atari_dma_xfer_len(unsigned long wanted_len,
struct scsi_cmnd *cmd, int write_flag)
{
unsigned long possible_len, limit;
if (IS_A_TT())
/* TT SCSI DMA can transfer arbitrary #bytes */
return wanted_len;
/* ST DMA chip is stupid -- only multiples of 512 bytes! (and max.
* 255*512 bytes, but this should be enough)
*
* ++roman: Aaargl! Another Falcon-SCSI problem... There are some commands
* that return a number of bytes which cannot be known beforehand. In this
* case, the given transfer length is an "allocation length". Now it
* can happen that this allocation length is a multiple of 512 bytes and
* the DMA is used. But if not n*512 bytes really arrive, some input data
* will be lost in the ST-DMA's FIFO :-( Thus, we have to distinguish
* between commands that do block transfers and those that do byte
* transfers. But this isn't easy... there are lots of vendor specific
* commands, and the user can issue any command via the
* SCSI_IOCTL_SEND_COMMAND.
*
* The solution: We classify SCSI commands in 1) surely block-mode cmd.s,
* 2) surely byte-mode cmd.s and 3) cmd.s with unknown mode. In case 1)
* and 3), the thing to do is obvious: allow any number of blocks via DMA
* or none. In case 2), we apply some heuristic: Byte mode is assumed if
* the transfer (allocation) length is < 1024, hoping that no cmd. not
* explicitly known as byte mode have such big allocation lengths...
* BTW, all the discussion above applies only to reads. DMA writes are
* unproblematic anyways, since the targets aborts the transfer after
* receiving a sufficient number of bytes.
*
* Another point: If the transfer is from/to an non-ST-RAM address, we
* use the dribble buffer and thus can do only STRAM_BUFFER_SIZE bytes.
*/
if (write_flag) {
/* Write operation can always use the DMA, but the transfer size must
* be rounded up to the next multiple of 512 (atari_dma_setup() does
* this).
*/
possible_len = wanted_len;
} else {
/* Read operations: if the wanted transfer length is not a multiple of
* 512, we cannot use DMA, since the ST-DMA cannot split transfers
* (no interrupt on DMA finished!)
*/
if (wanted_len & 0x1ff)
possible_len = 0;
else {
/* Now classify the command (see above) and decide whether it is
* allowed to do DMA at all */
switch (falcon_classify_cmd(cmd)) {
case CMD_SURELY_BLOCK_MODE:
possible_len = wanted_len;
break;
case CMD_SURELY_BYTE_MODE:
possible_len = 0; /* DMA prohibited */
break;
case CMD_MODE_UNKNOWN:
default:
/* For unknown commands assume block transfers if the transfer
* size/allocation length is >= 1024 */
possible_len = (wanted_len < 1024) ? 0 : wanted_len;
break;
}
}
}
/* Last step: apply the hard limit on DMA transfers */
limit = (atari_dma_buffer && !STRAM_ADDR(virt_to_phys(cmd->SCp.ptr))) ?
STRAM_BUFFER_SIZE : 255*512;
if (possible_len > limit)
possible_len = limit;
if (possible_len != wanted_len)
dprintk(NDEBUG_DMA, "Sorry, must cut DMA transfer size to %ld bytes "
"instead of %ld\n", possible_len, wanted_len);
return possible_len;
}
#endif /* REAL_DMA */
/* NCR5380 register access functions
*
* There are separate functions for TT and Falcon, because the access
* methods are quite different. The calling macros NCR5380_read and
* NCR5380_write call these functions via function pointers.
*/
static unsigned char atari_scsi_tt_reg_read(unsigned char reg)
{
return tt_scsi_regp[reg * 2];
}
static void atari_scsi_tt_reg_write(unsigned char reg, unsigned char value)
{
tt_scsi_regp[reg * 2] = value;
}
static unsigned char atari_scsi_falcon_reg_read(unsigned char reg)
{
dma_wd.dma_mode_status= (u_short)(0x88 + reg);
return (u_char)dma_wd.fdc_acces_seccount;
}
static void atari_scsi_falcon_reg_write(unsigned char reg, unsigned char value)
{
dma_wd.dma_mode_status = (u_short)(0x88 + reg);
dma_wd.fdc_acces_seccount = (u_short)value;
}
#include "atari_NCR5380.c"
static int atari_scsi_bus_reset(struct scsi_cmnd *cmd)
{
int rv;
unsigned long flags;
local_irq_save(flags);
#ifdef REAL_DMA
/* Abort a maybe active DMA transfer */
if (IS_A_TT()) {
tt_scsi_dma.dma_ctrl = 0;
} else {
st_dma.dma_mode_status = 0x90;
atari_dma_active = 0;
atari_dma_orig_addr = NULL;
}
#endif
rv = NCR5380_bus_reset(cmd);
/* The 5380 raises its IRQ line while _RST is active but the ST DMA
* "lock" has been released so this interrupt may end up handled by
* floppy or IDE driver (if one of them holds the lock). The NCR5380
* interrupt flag has been cleared already.
*/
local_irq_restore(flags);
return rv;
}
#define DRV_MODULE_NAME "atari_scsi"
#define PFX DRV_MODULE_NAME ": "
static struct scsi_host_template atari_scsi_template = {
.module = THIS_MODULE,
.proc_name = DRV_MODULE_NAME,
.show_info = atari_scsi_show_info,
.name = "Atari native SCSI",
.info = atari_scsi_info,
.queuecommand = atari_scsi_queue_command,
.eh_abort_handler = atari_scsi_abort,
.eh_bus_reset_handler = atari_scsi_bus_reset,
.this_id = 7,
.use_clustering = DISABLE_CLUSTERING
};
static int __init atari_scsi_probe(struct platform_device *pdev)
{
struct Scsi_Host *instance;
int error;
struct resource *irq;
int host_flags = 0;
irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq)
return -ENODEV;
if (ATARIHW_PRESENT(TT_SCSI)) {
atari_scsi_reg_read = atari_scsi_tt_reg_read;
atari_scsi_reg_write = atari_scsi_tt_reg_write;
} else {
atari_scsi_reg_read = atari_scsi_falcon_reg_read;
atari_scsi_reg_write = atari_scsi_falcon_reg_write;
}
/* The values for CMD_PER_LUN and CAN_QUEUE are somehow arbitrary.
* Higher values should work, too; try it!
* (But cmd_per_lun costs memory!)
*
* But there seems to be a bug somewhere that requires CAN_QUEUE to be
* 2*CMD_PER_LUN. At least on a TT, no spurious timeouts seen since
* changed CMD_PER_LUN...
*
* Note: The Falcon currently uses 8/1 setting due to unsolved problems
* with cmd_per_lun != 1
*/
if (ATARIHW_PRESENT(TT_SCSI)) {
atari_scsi_template.can_queue = 16;
atari_scsi_template.cmd_per_lun = 8;
atari_scsi_template.sg_tablesize = SG_ALL;
} else {
atari_scsi_template.can_queue = 8;
atari_scsi_template.cmd_per_lun = 1;
atari_scsi_template.sg_tablesize = SG_NONE;
}
if (setup_can_queue > 0)
atari_scsi_template.can_queue = setup_can_queue;
if (setup_cmd_per_lun > 0)
atari_scsi_template.cmd_per_lun = setup_cmd_per_lun;
/* Leave sg_tablesize at 0 on a Falcon! */
if (ATARIHW_PRESENT(TT_SCSI) && setup_sg_tablesize >= 0)
atari_scsi_template.sg_tablesize = setup_sg_tablesize;
if (setup_hostid >= 0) {
atari_scsi_template.this_id = setup_hostid & 7;
} else {
/* Test if a host id is set in the NVRam */
if (ATARIHW_PRESENT(TT_CLK) && nvram_check_checksum()) {
unsigned char b = nvram_read_byte(14);
/* Arbitration enabled? (for TOS)
* If yes, use configured host ID
*/
if (b & 0x80)
atari_scsi_template.this_id = b & 7;
}
}
#ifdef REAL_DMA
/* If running on a Falcon and if there's TT-Ram (i.e., more than one
* memory block, since there's always ST-Ram in a Falcon), then
* allocate a STRAM_BUFFER_SIZE byte dribble buffer for transfers
* from/to alternative Ram.
*/
if (ATARIHW_PRESENT(ST_SCSI) && !ATARIHW_PRESENT(EXTD_DMA) &&
m68k_num_memory > 1) {
atari_dma_buffer = atari_stram_alloc(STRAM_BUFFER_SIZE, "SCSI");
if (!atari_dma_buffer) {
pr_err(PFX "can't allocate ST-RAM double buffer\n");
return -ENOMEM;
}
atari_dma_phys_buffer = atari_stram_to_phys(atari_dma_buffer);
atari_dma_orig_addr = 0;
}
#endif
instance = scsi_host_alloc(&atari_scsi_template,
sizeof(struct NCR5380_hostdata));
if (!instance) {
error = -ENOMEM;
goto fail_alloc;
}
atari_scsi_host = instance;
#ifdef CONFIG_ATARI_SCSI_RESET_BOOT
atari_scsi_reset_boot();
#endif
instance->irq = irq->start;
host_flags |= IS_A_TT() ? 0 : FLAG_LATE_DMA_SETUP;
#ifdef SUPPORT_TAGS
host_flags |= setup_use_tagged_queuing > 0 ? FLAG_TAGGED_QUEUING : 0;
#endif
NCR5380_init(instance, host_flags);
if (IS_A_TT()) {
error = request_irq(instance->irq, scsi_tt_intr, 0,
"NCR5380", instance);
if (error) {
pr_err(PFX "request irq %d failed, aborting\n",
instance->irq);
goto fail_irq;
}
tt_mfp.active_edge |= 0x80; /* SCSI int on L->H */
#ifdef REAL_DMA
tt_scsi_dma.dma_ctrl = 0;
atari_dma_residual = 0;
/* While the read overruns (described by Drew Eckhardt in
* NCR5380.c) never happened on TTs, they do in fact on the
* Medusa (This was the cause why SCSI didn't work right for
* so long there.) Since handling the overruns slows down
* a bit, I turned the #ifdef's into a runtime condition.
*
* In principle it should be sufficient to do max. 1 byte with
* PIO, but there is another problem on the Medusa with the DMA
* rest data register. So read_overruns is currently set
* to 4 to avoid having transfers that aren't a multiple of 4.
* If the rest data bug is fixed, this can be lowered to 1.
*/
if (MACH_IS_MEDUSA) {
struct NCR5380_hostdata *hostdata =
shost_priv(instance);
hostdata->read_overruns = 4;
}
#endif
} else {
/* Nothing to do for the interrupt: the ST-DMA is initialized
* already.
*/
#ifdef REAL_DMA
atari_dma_residual = 0;
atari_dma_active = 0;
atari_dma_stram_mask = (ATARIHW_PRESENT(EXTD_DMA) ? 0x00000000
: 0xff000000);
#endif
}
error = scsi_add_host(instance, NULL);
if (error)
goto fail_host;
platform_set_drvdata(pdev, instance);
scsi_scan_host(instance);
return 0;
fail_host:
if (IS_A_TT())
free_irq(instance->irq, instance);
fail_irq:
NCR5380_exit(instance);
scsi_host_put(instance);
fail_alloc:
if (atari_dma_buffer)
atari_stram_free(atari_dma_buffer);
return error;
}
static int __exit atari_scsi_remove(struct platform_device *pdev)
{
struct Scsi_Host *instance = platform_get_drvdata(pdev);
scsi_remove_host(instance);
if (IS_A_TT())
free_irq(instance->irq, instance);
NCR5380_exit(instance);
scsi_host_put(instance);
if (atari_dma_buffer)
atari_stram_free(atari_dma_buffer);
return 0;
}
static struct platform_driver atari_scsi_driver = {
.remove = __exit_p(atari_scsi_remove),
.driver = {
.name = DRV_MODULE_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver_probe(atari_scsi_driver, atari_scsi_probe);
MODULE_ALIAS("platform:" DRV_MODULE_NAME);
MODULE_LICENSE("GPL");
| gpl-2.0 |
BORETS24/common.git-android-3.18 | drivers/net/wireless/ath/ath10k/htc.c | 215 | 23061 | /*
* Copyright (c) 2005-2011 Atheros Communications Inc.
* Copyright (c) 2011-2013 Qualcomm Atheros, 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.
*/
#include "core.h"
#include "hif.h"
#include "debug.h"
/********/
/* Send */
/********/
static inline void ath10k_htc_send_complete_check(struct ath10k_htc_ep *ep,
int force)
{
/*
* Check whether HIF has any prior sends that have finished,
* have not had the post-processing done.
*/
ath10k_hif_send_complete_check(ep->htc->ar, ep->ul_pipe_id, force);
}
static void ath10k_htc_control_tx_complete(struct ath10k *ar,
struct sk_buff *skb)
{
kfree_skb(skb);
}
static struct sk_buff *ath10k_htc_build_tx_ctrl_skb(void *ar)
{
struct sk_buff *skb;
struct ath10k_skb_cb *skb_cb;
skb = dev_alloc_skb(ATH10K_HTC_CONTROL_BUFFER_SIZE);
if (!skb)
return NULL;
skb_reserve(skb, 20); /* FIXME: why 20 bytes? */
WARN_ONCE((unsigned long)skb->data & 3, "unaligned skb");
skb_cb = ATH10K_SKB_CB(skb);
memset(skb_cb, 0, sizeof(*skb_cb));
ath10k_dbg(ar, ATH10K_DBG_HTC, "%s: skb %p\n", __func__, skb);
return skb;
}
static inline void ath10k_htc_restore_tx_skb(struct ath10k_htc *htc,
struct sk_buff *skb)
{
struct ath10k_skb_cb *skb_cb = ATH10K_SKB_CB(skb);
dma_unmap_single(htc->ar->dev, skb_cb->paddr, skb->len, DMA_TO_DEVICE);
skb_pull(skb, sizeof(struct ath10k_htc_hdr));
}
static void ath10k_htc_notify_tx_completion(struct ath10k_htc_ep *ep,
struct sk_buff *skb)
{
struct ath10k *ar = ep->htc->ar;
ath10k_dbg(ar, ATH10K_DBG_HTC, "%s: ep %d skb %p\n", __func__,
ep->eid, skb);
ath10k_htc_restore_tx_skb(ep->htc, skb);
if (!ep->ep_ops.ep_tx_complete) {
ath10k_warn(ar, "no tx handler for eid %d\n", ep->eid);
dev_kfree_skb_any(skb);
return;
}
ep->ep_ops.ep_tx_complete(ep->htc->ar, skb);
}
/* assumes tx_lock is held */
static bool ath10k_htc_ep_need_credit_update(struct ath10k_htc_ep *ep)
{
struct ath10k *ar = ep->htc->ar;
if (!ep->tx_credit_flow_enabled)
return false;
if (ep->tx_credits >= ep->tx_credits_per_max_message)
return false;
ath10k_dbg(ar, ATH10K_DBG_HTC, "HTC: endpoint %d needs credit update\n",
ep->eid);
return true;
}
static void ath10k_htc_prepare_tx_skb(struct ath10k_htc_ep *ep,
struct sk_buff *skb)
{
struct ath10k_htc_hdr *hdr;
hdr = (struct ath10k_htc_hdr *)skb->data;
hdr->eid = ep->eid;
hdr->len = __cpu_to_le16(skb->len - sizeof(*hdr));
hdr->flags = 0;
spin_lock_bh(&ep->htc->tx_lock);
hdr->seq_no = ep->seq_no++;
if (ath10k_htc_ep_need_credit_update(ep))
hdr->flags |= ATH10K_HTC_FLAG_NEED_CREDIT_UPDATE;
spin_unlock_bh(&ep->htc->tx_lock);
}
int ath10k_htc_send(struct ath10k_htc *htc,
enum ath10k_htc_ep_id eid,
struct sk_buff *skb)
{
struct ath10k *ar = htc->ar;
struct ath10k_htc_ep *ep = &htc->endpoint[eid];
struct ath10k_skb_cb *skb_cb = ATH10K_SKB_CB(skb);
struct ath10k_hif_sg_item sg_item;
struct device *dev = htc->ar->dev;
int credits = 0;
int ret;
if (htc->ar->state == ATH10K_STATE_WEDGED)
return -ECOMM;
if (eid >= ATH10K_HTC_EP_COUNT) {
ath10k_warn(ar, "Invalid endpoint id: %d\n", eid);
return -ENOENT;
}
skb_push(skb, sizeof(struct ath10k_htc_hdr));
if (ep->tx_credit_flow_enabled) {
credits = DIV_ROUND_UP(skb->len, htc->target_credit_size);
spin_lock_bh(&htc->tx_lock);
if (ep->tx_credits < credits) {
spin_unlock_bh(&htc->tx_lock);
ret = -EAGAIN;
goto err_pull;
}
ep->tx_credits -= credits;
ath10k_dbg(ar, ATH10K_DBG_HTC,
"htc ep %d consumed %d credits (total %d)\n",
eid, credits, ep->tx_credits);
spin_unlock_bh(&htc->tx_lock);
}
ath10k_htc_prepare_tx_skb(ep, skb);
skb_cb->paddr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE);
ret = dma_mapping_error(dev, skb_cb->paddr);
if (ret)
goto err_credits;
sg_item.transfer_id = ep->eid;
sg_item.transfer_context = skb;
sg_item.vaddr = skb->data;
sg_item.paddr = skb_cb->paddr;
sg_item.len = skb->len;
ret = ath10k_hif_tx_sg(htc->ar, ep->ul_pipe_id, &sg_item, 1);
if (ret)
goto err_unmap;
return 0;
err_unmap:
dma_unmap_single(dev, skb_cb->paddr, skb->len, DMA_TO_DEVICE);
err_credits:
if (ep->tx_credit_flow_enabled) {
spin_lock_bh(&htc->tx_lock);
ep->tx_credits += credits;
ath10k_dbg(ar, ATH10K_DBG_HTC,
"htc ep %d reverted %d credits back (total %d)\n",
eid, credits, ep->tx_credits);
spin_unlock_bh(&htc->tx_lock);
if (ep->ep_ops.ep_tx_credits)
ep->ep_ops.ep_tx_credits(htc->ar);
}
err_pull:
skb_pull(skb, sizeof(struct ath10k_htc_hdr));
return ret;
}
static int ath10k_htc_tx_completion_handler(struct ath10k *ar,
struct sk_buff *skb,
unsigned int eid)
{
struct ath10k_htc *htc = &ar->htc;
struct ath10k_htc_ep *ep = &htc->endpoint[eid];
if (WARN_ON_ONCE(!skb))
return 0;
ath10k_htc_notify_tx_completion(ep, skb);
/* the skb now belongs to the completion handler */
return 0;
}
/***********/
/* Receive */
/***********/
static void
ath10k_htc_process_credit_report(struct ath10k_htc *htc,
const struct ath10k_htc_credit_report *report,
int len,
enum ath10k_htc_ep_id eid)
{
struct ath10k *ar = htc->ar;
struct ath10k_htc_ep *ep;
int i, n_reports;
if (len % sizeof(*report))
ath10k_warn(ar, "Uneven credit report len %d", len);
n_reports = len / sizeof(*report);
spin_lock_bh(&htc->tx_lock);
for (i = 0; i < n_reports; i++, report++) {
if (report->eid >= ATH10K_HTC_EP_COUNT)
break;
ep = &htc->endpoint[report->eid];
ep->tx_credits += report->credits;
ath10k_dbg(ar, ATH10K_DBG_HTC, "htc ep %d got %d credits (total %d)\n",
report->eid, report->credits, ep->tx_credits);
if (ep->ep_ops.ep_tx_credits) {
spin_unlock_bh(&htc->tx_lock);
ep->ep_ops.ep_tx_credits(htc->ar);
spin_lock_bh(&htc->tx_lock);
}
}
spin_unlock_bh(&htc->tx_lock);
}
static int ath10k_htc_process_trailer(struct ath10k_htc *htc,
u8 *buffer,
int length,
enum ath10k_htc_ep_id src_eid)
{
struct ath10k *ar = htc->ar;
int status = 0;
struct ath10k_htc_record *record;
u8 *orig_buffer;
int orig_length;
size_t len;
orig_buffer = buffer;
orig_length = length;
while (length > 0) {
record = (struct ath10k_htc_record *)buffer;
if (length < sizeof(record->hdr)) {
status = -EINVAL;
break;
}
if (record->hdr.len > length) {
/* no room left in buffer for record */
ath10k_warn(ar, "Invalid record length: %d\n",
record->hdr.len);
status = -EINVAL;
break;
}
switch (record->hdr.id) {
case ATH10K_HTC_RECORD_CREDITS:
len = sizeof(struct ath10k_htc_credit_report);
if (record->hdr.len < len) {
ath10k_warn(ar, "Credit report too long\n");
status = -EINVAL;
break;
}
ath10k_htc_process_credit_report(htc,
record->credit_report,
record->hdr.len,
src_eid);
break;
default:
ath10k_warn(ar, "Unhandled record: id:%d length:%d\n",
record->hdr.id, record->hdr.len);
break;
}
if (status)
break;
/* multiple records may be present in a trailer */
buffer += sizeof(record->hdr) + record->hdr.len;
length -= sizeof(record->hdr) + record->hdr.len;
}
if (status)
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc rx bad trailer", "",
orig_buffer, orig_length);
return status;
}
static int ath10k_htc_rx_completion_handler(struct ath10k *ar,
struct sk_buff *skb,
u8 pipe_id)
{
int status = 0;
struct ath10k_htc *htc = &ar->htc;
struct ath10k_htc_hdr *hdr;
struct ath10k_htc_ep *ep;
u16 payload_len;
u32 trailer_len = 0;
size_t min_len;
u8 eid;
bool trailer_present;
hdr = (struct ath10k_htc_hdr *)skb->data;
skb_pull(skb, sizeof(*hdr));
eid = hdr->eid;
if (eid >= ATH10K_HTC_EP_COUNT) {
ath10k_warn(ar, "HTC Rx: invalid eid %d\n", eid);
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc bad header", "",
hdr, sizeof(*hdr));
status = -EINVAL;
goto out;
}
ep = &htc->endpoint[eid];
/*
* If this endpoint that received a message from the target has
* a to-target HIF pipe whose send completions are polled rather
* than interrupt-driven, this is a good point to ask HIF to check
* whether it has any completed sends to handle.
*/
if (ep->ul_is_polled)
ath10k_htc_send_complete_check(ep, 1);
payload_len = __le16_to_cpu(hdr->len);
if (payload_len + sizeof(*hdr) > ATH10K_HTC_MAX_LEN) {
ath10k_warn(ar, "HTC rx frame too long, len: %zu\n",
payload_len + sizeof(*hdr));
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc bad rx pkt len", "",
hdr, sizeof(*hdr));
status = -EINVAL;
goto out;
}
if (skb->len < payload_len) {
ath10k_dbg(ar, ATH10K_DBG_HTC,
"HTC Rx: insufficient length, got %d, expected %d\n",
skb->len, payload_len);
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc bad rx pkt len",
"", hdr, sizeof(*hdr));
status = -EINVAL;
goto out;
}
/* get flags to check for trailer */
trailer_present = hdr->flags & ATH10K_HTC_FLAG_TRAILER_PRESENT;
if (trailer_present) {
u8 *trailer;
trailer_len = hdr->trailer_len;
min_len = sizeof(struct ath10k_ath10k_htc_record_hdr);
if ((trailer_len < min_len) ||
(trailer_len > payload_len)) {
ath10k_warn(ar, "Invalid trailer length: %d\n",
trailer_len);
status = -EPROTO;
goto out;
}
trailer = (u8 *)hdr;
trailer += sizeof(*hdr);
trailer += payload_len;
trailer -= trailer_len;
status = ath10k_htc_process_trailer(htc, trailer,
trailer_len, hdr->eid);
if (status)
goto out;
skb_trim(skb, skb->len - trailer_len);
}
if (((int)payload_len - (int)trailer_len) <= 0)
/* zero length packet with trailer data, just drop these */
goto out;
if (eid == ATH10K_HTC_EP_0) {
struct ath10k_htc_msg *msg = (struct ath10k_htc_msg *)skb->data;
switch (__le16_to_cpu(msg->hdr.message_id)) {
default:
/* handle HTC control message */
if (completion_done(&htc->ctl_resp)) {
/*
* this is a fatal error, target should not be
* sending unsolicited messages on the ep 0
*/
ath10k_warn(ar, "HTC rx ctrl still processing\n");
status = -EINVAL;
complete(&htc->ctl_resp);
goto out;
}
htc->control_resp_len =
min_t(int, skb->len,
ATH10K_HTC_MAX_CTRL_MSG_LEN);
memcpy(htc->control_resp_buffer, skb->data,
htc->control_resp_len);
complete(&htc->ctl_resp);
break;
case ATH10K_HTC_MSG_SEND_SUSPEND_COMPLETE:
htc->htc_ops.target_send_suspend_complete(ar);
}
goto out;
}
ath10k_dbg(ar, ATH10K_DBG_HTC, "htc rx completion ep %d skb %p\n",
eid, skb);
ep->ep_ops.ep_rx_complete(ar, skb);
/* skb is now owned by the rx completion handler */
skb = NULL;
out:
kfree_skb(skb);
return status;
}
static void ath10k_htc_control_rx_complete(struct ath10k *ar,
struct sk_buff *skb)
{
/* This is unexpected. FW is not supposed to send regular rx on this
* endpoint. */
ath10k_warn(ar, "unexpected htc rx\n");
kfree_skb(skb);
}
/***************/
/* Init/Deinit */
/***************/
static const char *htc_service_name(enum ath10k_htc_svc_id id)
{
switch (id) {
case ATH10K_HTC_SVC_ID_RESERVED:
return "Reserved";
case ATH10K_HTC_SVC_ID_RSVD_CTRL:
return "Control";
case ATH10K_HTC_SVC_ID_WMI_CONTROL:
return "WMI";
case ATH10K_HTC_SVC_ID_WMI_DATA_BE:
return "DATA BE";
case ATH10K_HTC_SVC_ID_WMI_DATA_BK:
return "DATA BK";
case ATH10K_HTC_SVC_ID_WMI_DATA_VI:
return "DATA VI";
case ATH10K_HTC_SVC_ID_WMI_DATA_VO:
return "DATA VO";
case ATH10K_HTC_SVC_ID_NMI_CONTROL:
return "NMI Control";
case ATH10K_HTC_SVC_ID_NMI_DATA:
return "NMI Data";
case ATH10K_HTC_SVC_ID_HTT_DATA_MSG:
return "HTT Data";
case ATH10K_HTC_SVC_ID_TEST_RAW_STREAMS:
return "RAW";
}
return "Unknown";
}
static void ath10k_htc_reset_endpoint_states(struct ath10k_htc *htc)
{
struct ath10k_htc_ep *ep;
int i;
for (i = ATH10K_HTC_EP_0; i < ATH10K_HTC_EP_COUNT; i++) {
ep = &htc->endpoint[i];
ep->service_id = ATH10K_HTC_SVC_ID_UNUSED;
ep->max_ep_message_len = 0;
ep->max_tx_queue_depth = 0;
ep->eid = i;
ep->htc = htc;
ep->tx_credit_flow_enabled = true;
}
}
static void ath10k_htc_setup_target_buffer_assignments(struct ath10k_htc *htc)
{
struct ath10k_htc_svc_tx_credits *entry;
entry = &htc->service_tx_alloc[0];
/*
* for PCIE allocate all credists/HTC buffers to WMI.
* no buffers are used/required for data. data always
* remains on host.
*/
entry++;
entry->service_id = ATH10K_HTC_SVC_ID_WMI_CONTROL;
entry->credit_allocation = htc->total_transmit_credits;
}
static u8 ath10k_htc_get_credit_allocation(struct ath10k_htc *htc,
u16 service_id)
{
u8 allocation = 0;
int i;
for (i = 0; i < ATH10K_HTC_EP_COUNT; i++) {
if (htc->service_tx_alloc[i].service_id == service_id)
allocation =
htc->service_tx_alloc[i].credit_allocation;
}
return allocation;
}
int ath10k_htc_wait_target(struct ath10k_htc *htc)
{
struct ath10k *ar = htc->ar;
int i, status = 0;
struct ath10k_htc_svc_conn_req conn_req;
struct ath10k_htc_svc_conn_resp conn_resp;
struct ath10k_htc_msg *msg;
u16 message_id;
u16 credit_count;
u16 credit_size;
status = wait_for_completion_timeout(&htc->ctl_resp,
ATH10K_HTC_WAIT_TIMEOUT_HZ);
if (status == 0) {
/* Workaround: In some cases the PCI HIF doesn't
* receive interrupt for the control response message
* even if the buffer was completed. It is suspected
* iomap writes unmasking PCI CE irqs aren't propagated
* properly in KVM PCI-passthrough sometimes.
*/
ath10k_warn(ar, "failed to receive control response completion, polling..\n");
for (i = 0; i < CE_COUNT; i++)
ath10k_hif_send_complete_check(htc->ar, i, 1);
status = wait_for_completion_timeout(&htc->ctl_resp,
ATH10K_HTC_WAIT_TIMEOUT_HZ);
if (status == 0)
status = -ETIMEDOUT;
}
if (status < 0) {
ath10k_err(ar, "ctl_resp never came in (%d)\n", status);
return status;
}
if (htc->control_resp_len < sizeof(msg->hdr) + sizeof(msg->ready)) {
ath10k_err(ar, "Invalid HTC ready msg len:%d\n",
htc->control_resp_len);
return -ECOMM;
}
msg = (struct ath10k_htc_msg *)htc->control_resp_buffer;
message_id = __le16_to_cpu(msg->hdr.message_id);
credit_count = __le16_to_cpu(msg->ready.credit_count);
credit_size = __le16_to_cpu(msg->ready.credit_size);
if (message_id != ATH10K_HTC_MSG_READY_ID) {
ath10k_err(ar, "Invalid HTC ready msg: 0x%x\n", message_id);
return -ECOMM;
}
htc->total_transmit_credits = credit_count;
htc->target_credit_size = credit_size;
ath10k_dbg(ar, ATH10K_DBG_HTC,
"Target ready! transmit resources: %d size:%d\n",
htc->total_transmit_credits,
htc->target_credit_size);
if ((htc->total_transmit_credits == 0) ||
(htc->target_credit_size == 0)) {
ath10k_err(ar, "Invalid credit size received\n");
return -ECOMM;
}
ath10k_htc_setup_target_buffer_assignments(htc);
/* setup our pseudo HTC control endpoint connection */
memset(&conn_req, 0, sizeof(conn_req));
memset(&conn_resp, 0, sizeof(conn_resp));
conn_req.ep_ops.ep_tx_complete = ath10k_htc_control_tx_complete;
conn_req.ep_ops.ep_rx_complete = ath10k_htc_control_rx_complete;
conn_req.max_send_queue_depth = ATH10K_NUM_CONTROL_TX_BUFFERS;
conn_req.service_id = ATH10K_HTC_SVC_ID_RSVD_CTRL;
/* connect fake service */
status = ath10k_htc_connect_service(htc, &conn_req, &conn_resp);
if (status) {
ath10k_err(ar, "could not connect to htc service (%d)\n",
status);
return status;
}
return 0;
}
int ath10k_htc_connect_service(struct ath10k_htc *htc,
struct ath10k_htc_svc_conn_req *conn_req,
struct ath10k_htc_svc_conn_resp *conn_resp)
{
struct ath10k *ar = htc->ar;
struct ath10k_htc_msg *msg;
struct ath10k_htc_conn_svc *req_msg;
struct ath10k_htc_conn_svc_response resp_msg_dummy;
struct ath10k_htc_conn_svc_response *resp_msg = &resp_msg_dummy;
enum ath10k_htc_ep_id assigned_eid = ATH10K_HTC_EP_COUNT;
struct ath10k_htc_ep *ep;
struct sk_buff *skb;
unsigned int max_msg_size = 0;
int length, status;
bool disable_credit_flow_ctrl = false;
u16 message_id, service_id, flags = 0;
u8 tx_alloc = 0;
/* special case for HTC pseudo control service */
if (conn_req->service_id == ATH10K_HTC_SVC_ID_RSVD_CTRL) {
disable_credit_flow_ctrl = true;
assigned_eid = ATH10K_HTC_EP_0;
max_msg_size = ATH10K_HTC_MAX_CTRL_MSG_LEN;
memset(&resp_msg_dummy, 0, sizeof(resp_msg_dummy));
goto setup;
}
tx_alloc = ath10k_htc_get_credit_allocation(htc,
conn_req->service_id);
if (!tx_alloc)
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc service %s does not allocate target credits\n",
htc_service_name(conn_req->service_id));
skb = ath10k_htc_build_tx_ctrl_skb(htc->ar);
if (!skb) {
ath10k_err(ar, "Failed to allocate HTC packet\n");
return -ENOMEM;
}
length = sizeof(msg->hdr) + sizeof(msg->connect_service);
skb_put(skb, length);
memset(skb->data, 0, length);
msg = (struct ath10k_htc_msg *)skb->data;
msg->hdr.message_id =
__cpu_to_le16(ATH10K_HTC_MSG_CONNECT_SERVICE_ID);
flags |= SM(tx_alloc, ATH10K_HTC_CONN_FLAGS_RECV_ALLOC);
/* Only enable credit flow control for WMI ctrl service */
if (conn_req->service_id != ATH10K_HTC_SVC_ID_WMI_CONTROL) {
flags |= ATH10K_HTC_CONN_FLAGS_DISABLE_CREDIT_FLOW_CTRL;
disable_credit_flow_ctrl = true;
}
req_msg = &msg->connect_service;
req_msg->flags = __cpu_to_le16(flags);
req_msg->service_id = __cpu_to_le16(conn_req->service_id);
reinit_completion(&htc->ctl_resp);
status = ath10k_htc_send(htc, ATH10K_HTC_EP_0, skb);
if (status) {
kfree_skb(skb);
return status;
}
/* wait for response */
status = wait_for_completion_timeout(&htc->ctl_resp,
ATH10K_HTC_CONN_SVC_TIMEOUT_HZ);
if (status <= 0) {
if (status == 0)
status = -ETIMEDOUT;
ath10k_err(ar, "Service connect timeout: %d\n", status);
return status;
}
/* we controlled the buffer creation, it's aligned */
msg = (struct ath10k_htc_msg *)htc->control_resp_buffer;
resp_msg = &msg->connect_service_response;
message_id = __le16_to_cpu(msg->hdr.message_id);
service_id = __le16_to_cpu(resp_msg->service_id);
if ((message_id != ATH10K_HTC_MSG_CONNECT_SERVICE_RESP_ID) ||
(htc->control_resp_len < sizeof(msg->hdr) +
sizeof(msg->connect_service_response))) {
ath10k_err(ar, "Invalid resp message ID 0x%x", message_id);
return -EPROTO;
}
ath10k_dbg(ar, ATH10K_DBG_HTC,
"HTC Service %s connect response: status: 0x%x, assigned ep: 0x%x\n",
htc_service_name(service_id),
resp_msg->status, resp_msg->eid);
conn_resp->connect_resp_code = resp_msg->status;
/* check response status */
if (resp_msg->status != ATH10K_HTC_CONN_SVC_STATUS_SUCCESS) {
ath10k_err(ar, "HTC Service %s connect request failed: 0x%x)\n",
htc_service_name(service_id),
resp_msg->status);
return -EPROTO;
}
assigned_eid = (enum ath10k_htc_ep_id)resp_msg->eid;
max_msg_size = __le16_to_cpu(resp_msg->max_msg_size);
setup:
if (assigned_eid >= ATH10K_HTC_EP_COUNT)
return -EPROTO;
if (max_msg_size == 0)
return -EPROTO;
ep = &htc->endpoint[assigned_eid];
ep->eid = assigned_eid;
if (ep->service_id != ATH10K_HTC_SVC_ID_UNUSED)
return -EPROTO;
/* return assigned endpoint to caller */
conn_resp->eid = assigned_eid;
conn_resp->max_msg_len = __le16_to_cpu(resp_msg->max_msg_size);
/* setup the endpoint */
ep->service_id = conn_req->service_id;
ep->max_tx_queue_depth = conn_req->max_send_queue_depth;
ep->max_ep_message_len = __le16_to_cpu(resp_msg->max_msg_size);
ep->tx_credits = tx_alloc;
ep->tx_credit_size = htc->target_credit_size;
ep->tx_credits_per_max_message = ep->max_ep_message_len /
htc->target_credit_size;
if (ep->max_ep_message_len % htc->target_credit_size)
ep->tx_credits_per_max_message++;
/* copy all the callbacks */
ep->ep_ops = conn_req->ep_ops;
status = ath10k_hif_map_service_to_pipe(htc->ar,
ep->service_id,
&ep->ul_pipe_id,
&ep->dl_pipe_id,
&ep->ul_is_polled,
&ep->dl_is_polled);
if (status)
return status;
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc service '%s' ul pipe %d dl pipe %d eid %d ready\n",
htc_service_name(ep->service_id), ep->ul_pipe_id,
ep->dl_pipe_id, ep->eid);
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc ep %d ul polled %d dl polled %d\n",
ep->eid, ep->ul_is_polled, ep->dl_is_polled);
if (disable_credit_flow_ctrl && ep->tx_credit_flow_enabled) {
ep->tx_credit_flow_enabled = false;
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc service '%s' eid %d TX flow control disabled\n",
htc_service_name(ep->service_id), assigned_eid);
}
return status;
}
struct sk_buff *ath10k_htc_alloc_skb(struct ath10k *ar, int size)
{
struct sk_buff *skb;
skb = dev_alloc_skb(size + sizeof(struct ath10k_htc_hdr));
if (!skb)
return NULL;
skb_reserve(skb, sizeof(struct ath10k_htc_hdr));
/* FW/HTC requires 4-byte aligned streams */
if (!IS_ALIGNED((unsigned long)skb->data, 4))
ath10k_warn(ar, "Unaligned HTC tx skb\n");
return skb;
}
int ath10k_htc_start(struct ath10k_htc *htc)
{
struct ath10k *ar = htc->ar;
struct sk_buff *skb;
int status = 0;
struct ath10k_htc_msg *msg;
skb = ath10k_htc_build_tx_ctrl_skb(htc->ar);
if (!skb)
return -ENOMEM;
skb_put(skb, sizeof(msg->hdr) + sizeof(msg->setup_complete_ext));
memset(skb->data, 0, skb->len);
msg = (struct ath10k_htc_msg *)skb->data;
msg->hdr.message_id =
__cpu_to_le16(ATH10K_HTC_MSG_SETUP_COMPLETE_EX_ID);
ath10k_dbg(ar, ATH10K_DBG_HTC, "HTC is using TX credit flow control\n");
status = ath10k_htc_send(htc, ATH10K_HTC_EP_0, skb);
if (status) {
kfree_skb(skb);
return status;
}
return 0;
}
/* registered target arrival callback from the HIF layer */
int ath10k_htc_init(struct ath10k *ar)
{
struct ath10k_hif_cb htc_callbacks;
struct ath10k_htc_ep *ep = NULL;
struct ath10k_htc *htc = &ar->htc;
spin_lock_init(&htc->tx_lock);
ath10k_htc_reset_endpoint_states(htc);
/* setup HIF layer callbacks */
htc_callbacks.rx_completion = ath10k_htc_rx_completion_handler;
htc_callbacks.tx_completion = ath10k_htc_tx_completion_handler;
htc->ar = ar;
/* Get HIF default pipe for HTC message exchange */
ep = &htc->endpoint[ATH10K_HTC_EP_0];
ath10k_hif_set_callbacks(ar, &htc_callbacks);
ath10k_hif_get_default_pipe(ar, &ep->ul_pipe_id, &ep->dl_pipe_id);
init_completion(&htc->ctl_resp);
return 0;
}
| gpl-2.0 |
jledet/linux-xlnx | drivers/staging/iio/trigger/iio-trig-bfin-timer.c | 215 | 7007 | /*
* Copyright 2011 Analog Devices Inc.
*
* Licensed under the GPL-2.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <asm/gptimers.h>
#include <asm/portmux.h>
#include <linux/iio/iio.h>
#include <linux/iio/trigger.h>
#include "iio-trig-bfin-timer.h"
struct bfin_timer {
unsigned short id, bit;
unsigned long irqbit;
int irq;
int pin;
};
/*
* this covers all hardware timer configurations on
* all Blackfin derivatives out there today
*/
static struct bfin_timer iio_bfin_timer_code[MAX_BLACKFIN_GPTIMERS] = {
{TIMER0_id, TIMER0bit, TIMER_STATUS_TIMIL0, IRQ_TIMER0, P_TMR0},
{TIMER1_id, TIMER1bit, TIMER_STATUS_TIMIL1, IRQ_TIMER1, P_TMR1},
{TIMER2_id, TIMER2bit, TIMER_STATUS_TIMIL2, IRQ_TIMER2, P_TMR2},
#if (MAX_BLACKFIN_GPTIMERS > 3)
{TIMER3_id, TIMER3bit, TIMER_STATUS_TIMIL3, IRQ_TIMER3, P_TMR3},
{TIMER4_id, TIMER4bit, TIMER_STATUS_TIMIL4, IRQ_TIMER4, P_TMR4},
{TIMER5_id, TIMER5bit, TIMER_STATUS_TIMIL5, IRQ_TIMER5, P_TMR5},
{TIMER6_id, TIMER6bit, TIMER_STATUS_TIMIL6, IRQ_TIMER6, P_TMR6},
{TIMER7_id, TIMER7bit, TIMER_STATUS_TIMIL7, IRQ_TIMER7, P_TMR7},
#endif
#if (MAX_BLACKFIN_GPTIMERS > 8)
{TIMER8_id, TIMER8bit, TIMER_STATUS_TIMIL8, IRQ_TIMER8, P_TMR8},
{TIMER9_id, TIMER9bit, TIMER_STATUS_TIMIL9, IRQ_TIMER9, P_TMR9},
{TIMER10_id, TIMER10bit, TIMER_STATUS_TIMIL10, IRQ_TIMER10, P_TMR10},
#if (MAX_BLACKFIN_GPTIMERS > 11)
{TIMER11_id, TIMER11bit, TIMER_STATUS_TIMIL11, IRQ_TIMER11, P_TMR11},
#endif
#endif
};
struct bfin_tmr_state {
struct iio_trigger *trig;
struct bfin_timer *t;
unsigned timer_num;
bool output_enable;
unsigned int duty;
int irq;
};
static int iio_bfin_tmr_set_state(struct iio_trigger *trig, bool state)
{
struct bfin_tmr_state *st = iio_trigger_get_drvdata(trig);
if (get_gptimer_period(st->t->id) == 0)
return -EINVAL;
if (state)
enable_gptimers(st->t->bit);
else
disable_gptimers(st->t->bit);
return 0;
}
static ssize_t iio_bfin_tmr_frequency_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct iio_trigger *trig = to_iio_trigger(dev);
struct bfin_tmr_state *st = iio_trigger_get_drvdata(trig);
unsigned int val;
bool enabled;
int ret;
ret = kstrtouint(buf, 10, &val);
if (ret)
return ret;
if (val > 100000)
return -EINVAL;
enabled = get_enabled_gptimers() & st->t->bit;
if (enabled)
disable_gptimers(st->t->bit);
if (!val)
return count;
val = get_sclk() / val;
if (val <= 4 || val <= st->duty)
return -EINVAL;
set_gptimer_period(st->t->id, val);
set_gptimer_pwidth(st->t->id, val - st->duty);
if (enabled)
enable_gptimers(st->t->bit);
return count;
}
static ssize_t iio_bfin_tmr_frequency_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_trigger *trig = to_iio_trigger(dev);
struct bfin_tmr_state *st = iio_trigger_get_drvdata(trig);
unsigned int period = get_gptimer_period(st->t->id);
unsigned long val;
if (!period)
val = 0;
else
val = get_sclk() / get_gptimer_period(st->t->id);
return sprintf(buf, "%lu\n", val);
}
static DEVICE_ATTR(frequency, S_IRUGO | S_IWUSR, iio_bfin_tmr_frequency_show,
iio_bfin_tmr_frequency_store);
static struct attribute *iio_bfin_tmr_trigger_attrs[] = {
&dev_attr_frequency.attr,
NULL,
};
static const struct attribute_group iio_bfin_tmr_trigger_attr_group = {
.attrs = iio_bfin_tmr_trigger_attrs,
};
static const struct attribute_group *iio_bfin_tmr_trigger_attr_groups[] = {
&iio_bfin_tmr_trigger_attr_group,
NULL
};
static irqreturn_t iio_bfin_tmr_trigger_isr(int irq, void *devid)
{
struct bfin_tmr_state *st = devid;
clear_gptimer_intr(st->t->id);
iio_trigger_poll(st->trig);
return IRQ_HANDLED;
}
static int iio_bfin_tmr_get_number(int irq)
{
int i;
for (i = 0; i < MAX_BLACKFIN_GPTIMERS; i++)
if (iio_bfin_timer_code[i].irq == irq)
return i;
return -ENODEV;
}
static const struct iio_trigger_ops iio_bfin_tmr_trigger_ops = {
.owner = THIS_MODULE,
.set_trigger_state = iio_bfin_tmr_set_state,
};
static int iio_bfin_tmr_trigger_probe(struct platform_device *pdev)
{
struct iio_bfin_timer_trigger_pdata *pdata = pdev->dev.platform_data;
struct bfin_tmr_state *st;
unsigned int config;
int ret;
st = devm_kzalloc(&pdev->dev, sizeof(*st), GFP_KERNEL);
if (!st)
return -ENOMEM;
st->irq = platform_get_irq(pdev, 0);
if (!st->irq) {
dev_err(&pdev->dev, "No IRQs specified");
return -ENODEV;
}
ret = iio_bfin_tmr_get_number(st->irq);
if (ret < 0)
return ret;
st->timer_num = ret;
st->t = &iio_bfin_timer_code[st->timer_num];
st->trig = iio_trigger_alloc("bfintmr%d", st->timer_num);
if (!st->trig)
return -ENOMEM;
st->trig->ops = &iio_bfin_tmr_trigger_ops;
st->trig->dev.groups = iio_bfin_tmr_trigger_attr_groups;
iio_trigger_set_drvdata(st->trig, st);
ret = iio_trigger_register(st->trig);
if (ret)
goto out;
ret = request_irq(st->irq, iio_bfin_tmr_trigger_isr,
0, st->trig->name, st);
if (ret) {
dev_err(&pdev->dev,
"request IRQ-%d failed", st->irq);
goto out1;
}
config = PWM_OUT | PERIOD_CNT | IRQ_ENA;
if (pdata && pdata->output_enable) {
unsigned long long val;
st->output_enable = true;
ret = peripheral_request(st->t->pin, st->trig->name);
if (ret)
goto out_free_irq;
val = (unsigned long long)get_sclk() * pdata->duty_ns;
do_div(val, NSEC_PER_SEC);
st->duty = val;
/**
* The interrupt will be generated at the end of the period,
* since we want the interrupt to be generated at end of the
* pulse we invert both polarity and duty cycle, so that the
* pulse will be generated directly before the interrupt.
*/
if (pdata->active_low)
config |= PULSE_HI;
} else {
st->duty = 1;
config |= OUT_DIS;
}
set_gptimer_config(st->t->id, config);
dev_info(&pdev->dev, "iio trigger Blackfin TMR%d, IRQ-%d",
st->timer_num, st->irq);
platform_set_drvdata(pdev, st);
return 0;
out_free_irq:
free_irq(st->irq, st);
out1:
iio_trigger_unregister(st->trig);
out:
iio_trigger_put(st->trig);
return ret;
}
static int iio_bfin_tmr_trigger_remove(struct platform_device *pdev)
{
struct bfin_tmr_state *st = platform_get_drvdata(pdev);
disable_gptimers(st->t->bit);
if (st->output_enable)
peripheral_free(st->t->pin);
free_irq(st->irq, st);
iio_trigger_unregister(st->trig);
iio_trigger_put(st->trig);
return 0;
}
static struct platform_driver iio_bfin_tmr_trigger_driver = {
.driver = {
.name = "iio_bfin_tmr_trigger",
},
.probe = iio_bfin_tmr_trigger_probe,
.remove = iio_bfin_tmr_trigger_remove,
};
module_platform_driver(iio_bfin_tmr_trigger_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Blackfin system timer based trigger for the iio subsystem");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:iio-trig-bfin-timer");
| gpl-2.0 |
TheGreatSega/Rush-Kernel | drivers/net/wireless/ath/regd.c | 471 | 15769 | /*
* Copyright (c) 2008-2009 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.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <net/cfg80211.h>
#include <net/mac80211.h>
#include "regd.h"
#include "regd_common.h"
/*
* This is a set of common rules used by our world regulatory domains.
* We have 12 world regulatory domains. To save space we consolidate
* the regulatory domains in 5 structures by frequency and change
* the flags on our reg_notifier() on a case by case basis.
*/
/* Only these channels all allow active scan on all world regulatory domains */
#define ATH9K_2GHZ_CH01_11 REG_RULE(2412-10, 2462+10, 40, 0, 20, 0)
/* We enable active scan on these a case by case basis by regulatory domain */
#define ATH9K_2GHZ_CH12_13 REG_RULE(2467-10, 2472+10, 40, 0, 20,\
NL80211_RRF_PASSIVE_SCAN)
#define ATH9K_2GHZ_CH14 REG_RULE(2484-10, 2484+10, 40, 0, 20,\
NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_OFDM)
/* We allow IBSS on these on a case by case basis by regulatory domain */
#define ATH9K_5GHZ_5150_5350 REG_RULE(5150-10, 5350+10, 40, 0, 30,\
NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS)
#define ATH9K_5GHZ_5470_5850 REG_RULE(5470-10, 5850+10, 40, 0, 30,\
NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS)
#define ATH9K_5GHZ_5725_5850 REG_RULE(5725-10, 5850+10, 40, 0, 30,\
NL80211_RRF_PASSIVE_SCAN | NL80211_RRF_NO_IBSS)
#define ATH9K_2GHZ_ALL ATH9K_2GHZ_CH01_11, \
ATH9K_2GHZ_CH12_13, \
ATH9K_2GHZ_CH14
#define ATH9K_5GHZ_ALL ATH9K_5GHZ_5150_5350, \
ATH9K_5GHZ_5470_5850
/* This one skips what we call "mid band" */
#define ATH9K_5GHZ_NO_MIDBAND ATH9K_5GHZ_5150_5350, \
ATH9K_5GHZ_5725_5850
/* Can be used for:
* 0x60, 0x61, 0x62 */
static const struct ieee80211_regdomain ath_world_regdom_60_61_62 = {
.n_reg_rules = 5,
.alpha2 = "99",
.reg_rules = {
ATH9K_2GHZ_ALL,
ATH9K_5GHZ_ALL,
}
};
/* Can be used by 0x63 and 0x65 */
static const struct ieee80211_regdomain ath_world_regdom_63_65 = {
.n_reg_rules = 4,
.alpha2 = "99",
.reg_rules = {
ATH9K_2GHZ_CH01_11,
ATH9K_2GHZ_CH12_13,
ATH9K_5GHZ_NO_MIDBAND,
}
};
/* Can be used by 0x64 only */
static const struct ieee80211_regdomain ath_world_regdom_64 = {
.n_reg_rules = 3,
.alpha2 = "99",
.reg_rules = {
ATH9K_2GHZ_CH01_11,
ATH9K_5GHZ_NO_MIDBAND,
}
};
/* Can be used by 0x66 and 0x69 */
static const struct ieee80211_regdomain ath_world_regdom_66_69 = {
.n_reg_rules = 3,
.alpha2 = "99",
.reg_rules = {
ATH9K_2GHZ_CH01_11,
ATH9K_5GHZ_ALL,
}
};
/* Can be used by 0x67, 0x6A and 0x68 */
static const struct ieee80211_regdomain ath_world_regdom_67_68_6A = {
.n_reg_rules = 4,
.alpha2 = "99",
.reg_rules = {
ATH9K_2GHZ_CH01_11,
ATH9K_2GHZ_CH12_13,
ATH9K_5GHZ_ALL,
}
};
static inline bool is_wwr_sku(u16 regd)
{
return ((regd & WORLD_SKU_MASK) == WORLD_SKU_PREFIX) ||
(regd == WORLD);
}
static u16 ath_regd_get_eepromRD(struct ath_regulatory *reg)
{
return reg->current_rd & ~WORLDWIDE_ROAMING_FLAG;
}
bool ath_is_world_regd(struct ath_regulatory *reg)
{
return is_wwr_sku(ath_regd_get_eepromRD(reg));
}
EXPORT_SYMBOL(ath_is_world_regd);
static const struct ieee80211_regdomain *ath_default_world_regdomain(void)
{
/* this is the most restrictive */
return &ath_world_regdom_64;
}
static const struct
ieee80211_regdomain *ath_world_regdomain(struct ath_regulatory *reg)
{
switch (reg->regpair->regDmnEnum) {
case 0x60:
case 0x61:
case 0x62:
return &ath_world_regdom_60_61_62;
case 0x63:
case 0x65:
return &ath_world_regdom_63_65;
case 0x64:
return &ath_world_regdom_64;
case 0x66:
case 0x69:
return &ath_world_regdom_66_69;
case 0x67:
case 0x68:
case 0x6A:
return &ath_world_regdom_67_68_6A;
default:
WARN_ON(1);
return ath_default_world_regdomain();
}
}
/* Frequency is one where radar detection is required */
static bool ath_is_radar_freq(u16 center_freq)
{
return (center_freq >= 5260 && center_freq <= 5700);
}
/*
* N.B: These exception rules do not apply radar freqs.
*
* - We enable adhoc (or beaconing) if allowed by 11d
* - We enable active scan if the channel is allowed by 11d
* - If no country IE has been processed and a we determine we have
* received a beacon on a channel we can enable active scan and
* adhoc (or beaconing).
*/
static void
ath_reg_apply_beaconing_flags(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
enum ieee80211_band band;
struct ieee80211_supported_band *sband;
const struct ieee80211_reg_rule *reg_rule;
struct ieee80211_channel *ch;
unsigned int i;
u32 bandwidth = 0;
int r;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!wiphy->bands[band])
continue;
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++) {
ch = &sband->channels[i];
if (ath_is_radar_freq(ch->center_freq) ||
(ch->flags & IEEE80211_CHAN_RADAR))
continue;
if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) {
r = freq_reg_info(wiphy,
ch->center_freq,
bandwidth,
®_rule);
if (r)
continue;
/*
* If 11d had a rule for this channel ensure
* we enable adhoc/beaconing if it allows us to
* use it. Note that we would have disabled it
* by applying our static world regdomain by
* default during init, prior to calling our
* regulatory_hint().
*/
if (!(reg_rule->flags &
NL80211_RRF_NO_IBSS))
ch->flags &=
~IEEE80211_CHAN_NO_IBSS;
if (!(reg_rule->flags &
NL80211_RRF_PASSIVE_SCAN))
ch->flags &=
~IEEE80211_CHAN_PASSIVE_SCAN;
} else {
if (ch->beacon_found)
ch->flags &= ~(IEEE80211_CHAN_NO_IBSS |
IEEE80211_CHAN_PASSIVE_SCAN);
}
}
}
}
/* Allows active scan scan on Ch 12 and 13 */
static void
ath_reg_apply_active_scan_flags(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *ch;
const struct ieee80211_reg_rule *reg_rule;
u32 bandwidth = 0;
int r;
sband = wiphy->bands[IEEE80211_BAND_2GHZ];
/*
* If no country IE has been received always enable active scan
* on these channels. This is only done for specific regulatory SKUs
*/
if (initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
ch = &sband->channels[11]; /* CH 12 */
if (ch->flags & IEEE80211_CHAN_PASSIVE_SCAN)
ch->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
ch = &sband->channels[12]; /* CH 13 */
if (ch->flags & IEEE80211_CHAN_PASSIVE_SCAN)
ch->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
return;
}
/*
* If a country IE has been recieved check its rule for this
* channel first before enabling active scan. The passive scan
* would have been enforced by the initial processing of our
* custom regulatory domain.
*/
ch = &sband->channels[11]; /* CH 12 */
r = freq_reg_info(wiphy, ch->center_freq, bandwidth, ®_rule);
if (!r) {
if (!(reg_rule->flags & NL80211_RRF_PASSIVE_SCAN))
if (ch->flags & IEEE80211_CHAN_PASSIVE_SCAN)
ch->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
}
ch = &sband->channels[12]; /* CH 13 */
r = freq_reg_info(wiphy, ch->center_freq, bandwidth, ®_rule);
if (!r) {
if (!(reg_rule->flags & NL80211_RRF_PASSIVE_SCAN))
if (ch->flags & IEEE80211_CHAN_PASSIVE_SCAN)
ch->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
}
}
/* Always apply Radar/DFS rules on freq range 5260 MHz - 5700 MHz */
static void ath_reg_apply_radar_flags(struct wiphy *wiphy)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *ch;
unsigned int i;
if (!wiphy->bands[IEEE80211_BAND_5GHZ])
return;
sband = wiphy->bands[IEEE80211_BAND_5GHZ];
for (i = 0; i < sband->n_channels; i++) {
ch = &sband->channels[i];
if (!ath_is_radar_freq(ch->center_freq))
continue;
/* We always enable radar detection/DFS on this
* frequency range. Additionally we also apply on
* this frequency range:
* - If STA mode does not yet have DFS supports disable
* active scanning
* - If adhoc mode does not support DFS yet then
* disable adhoc in the frequency.
* - If AP mode does not yet support radar detection/DFS
* do not allow AP mode
*/
if (!(ch->flags & IEEE80211_CHAN_DISABLED))
ch->flags |= IEEE80211_CHAN_RADAR |
IEEE80211_CHAN_NO_IBSS |
IEEE80211_CHAN_PASSIVE_SCAN;
}
}
static void ath_reg_apply_world_flags(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator,
struct ath_regulatory *reg)
{
switch (reg->regpair->regDmnEnum) {
case 0x60:
case 0x63:
case 0x66:
case 0x67:
ath_reg_apply_beaconing_flags(wiphy, initiator);
break;
case 0x68:
ath_reg_apply_beaconing_flags(wiphy, initiator);
ath_reg_apply_active_scan_flags(wiphy, initiator);
break;
}
return;
}
int ath_reg_notifier_apply(struct wiphy *wiphy,
struct regulatory_request *request,
struct ath_regulatory *reg)
{
/* We always apply this */
ath_reg_apply_radar_flags(wiphy);
switch (request->initiator) {
case NL80211_REGDOM_SET_BY_DRIVER:
case NL80211_REGDOM_SET_BY_CORE:
case NL80211_REGDOM_SET_BY_USER:
break;
case NL80211_REGDOM_SET_BY_COUNTRY_IE:
if (ath_is_world_regd(reg))
ath_reg_apply_world_flags(wiphy, request->initiator,
reg);
break;
}
return 0;
}
EXPORT_SYMBOL(ath_reg_notifier_apply);
static bool ath_regd_is_eeprom_valid(struct ath_regulatory *reg)
{
u16 rd = ath_regd_get_eepromRD(reg);
int i;
if (rd & COUNTRY_ERD_FLAG) {
/* EEPROM value is a country code */
u16 cc = rd & ~COUNTRY_ERD_FLAG;
printk(KERN_DEBUG
"ath: EEPROM indicates we should expect "
"a country code\n");
for (i = 0; i < ARRAY_SIZE(allCountries); i++)
if (allCountries[i].countryCode == cc)
return true;
} else {
/* EEPROM value is a regpair value */
if (rd != CTRY_DEFAULT)
printk(KERN_DEBUG "ath: EEPROM indicates we "
"should expect a direct regpair map\n");
for (i = 0; i < ARRAY_SIZE(regDomainPairs); i++)
if (regDomainPairs[i].regDmnEnum == rd)
return true;
}
printk(KERN_DEBUG
"ath: invalid regulatory domain/country code 0x%x\n", rd);
return false;
}
/* EEPROM country code to regpair mapping */
static struct country_code_to_enum_rd*
ath_regd_find_country(u16 countryCode)
{
int i;
for (i = 0; i < ARRAY_SIZE(allCountries); i++) {
if (allCountries[i].countryCode == countryCode)
return &allCountries[i];
}
return NULL;
}
/* EEPROM rd code to regpair mapping */
static struct country_code_to_enum_rd*
ath_regd_find_country_by_rd(int regdmn)
{
int i;
for (i = 0; i < ARRAY_SIZE(allCountries); i++) {
if (allCountries[i].regDmnEnum == regdmn)
return &allCountries[i];
}
return NULL;
}
/* Returns the map of the EEPROM set RD to a country code */
static u16 ath_regd_get_default_country(u16 rd)
{
if (rd & COUNTRY_ERD_FLAG) {
struct country_code_to_enum_rd *country = NULL;
u16 cc = rd & ~COUNTRY_ERD_FLAG;
country = ath_regd_find_country(cc);
if (country != NULL)
return cc;
}
return CTRY_DEFAULT;
}
static struct reg_dmn_pair_mapping*
ath_get_regpair(int regdmn)
{
int i;
if (regdmn == NO_ENUMRD)
return NULL;
for (i = 0; i < ARRAY_SIZE(regDomainPairs); i++) {
if (regDomainPairs[i].regDmnEnum == regdmn)
return ®DomainPairs[i];
}
return NULL;
}
static int
ath_regd_init_wiphy(struct ath_regulatory *reg,
struct wiphy *wiphy,
int (*reg_notifier)(struct wiphy *wiphy,
struct regulatory_request *request))
{
const struct ieee80211_regdomain *regd;
wiphy->reg_notifier = reg_notifier;
wiphy->strict_regulatory = true;
if (ath_is_world_regd(reg)) {
/*
* Anything applied here (prior to wiphy registration) gets
* saved on the wiphy orig_* parameters
*/
regd = ath_world_regdomain(reg);
wiphy->custom_regulatory = true;
wiphy->strict_regulatory = false;
} else {
/*
* This gets applied in the case of the absense of CRDA,
* it's our own custom world regulatory domain, similar to
* cfg80211's but we enable passive scanning.
*/
regd = ath_default_world_regdomain();
}
wiphy_apply_custom_regulatory(wiphy, regd);
ath_reg_apply_radar_flags(wiphy);
ath_reg_apply_world_flags(wiphy, NL80211_REGDOM_SET_BY_DRIVER, reg);
return 0;
}
/*
* Some users have reported their EEPROM programmed with
* 0x8000 set, this is not a supported regulatory domain
* but since we have more than one user with it we need
* a solution for them. We default to 0x64, which is the
* default Atheros world regulatory domain.
*/
static void ath_regd_sanitize(struct ath_regulatory *reg)
{
if (reg->current_rd != COUNTRY_ERD_FLAG)
return;
printk(KERN_DEBUG "ath: EEPROM regdomain sanitized\n");
reg->current_rd = 0x64;
}
int
ath_regd_init(struct ath_regulatory *reg,
struct wiphy *wiphy,
int (*reg_notifier)(struct wiphy *wiphy,
struct regulatory_request *request))
{
struct country_code_to_enum_rd *country = NULL;
u16 regdmn;
if (!reg)
return -EINVAL;
ath_regd_sanitize(reg);
printk(KERN_DEBUG "ath: EEPROM regdomain: 0x%0x\n", reg->current_rd);
if (!ath_regd_is_eeprom_valid(reg)) {
printk(KERN_ERR "ath: Invalid EEPROM contents\n");
return -EINVAL;
}
regdmn = ath_regd_get_eepromRD(reg);
reg->country_code = ath_regd_get_default_country(regdmn);
if (reg->country_code == CTRY_DEFAULT &&
regdmn == CTRY_DEFAULT) {
printk(KERN_DEBUG "ath: EEPROM indicates default "
"country code should be used\n");
reg->country_code = CTRY_UNITED_STATES;
}
if (reg->country_code == CTRY_DEFAULT) {
country = NULL;
} else {
printk(KERN_DEBUG "ath: doing EEPROM country->regdmn "
"map search\n");
country = ath_regd_find_country(reg->country_code);
if (country == NULL) {
printk(KERN_DEBUG
"ath: no valid country maps found for "
"country code: 0x%0x\n",
reg->country_code);
return -EINVAL;
} else {
regdmn = country->regDmnEnum;
printk(KERN_DEBUG "ath: country maps to "
"regdmn code: 0x%0x\n",
regdmn);
}
}
reg->regpair = ath_get_regpair(regdmn);
if (!reg->regpair) {
printk(KERN_DEBUG "ath: "
"No regulatory domain pair found, cannot continue\n");
return -EINVAL;
}
if (!country)
country = ath_regd_find_country_by_rd(regdmn);
if (country) {
reg->alpha2[0] = country->isoName[0];
reg->alpha2[1] = country->isoName[1];
} else {
reg->alpha2[0] = '0';
reg->alpha2[1] = '0';
}
printk(KERN_DEBUG "ath: Country alpha2 being used: %c%c\n",
reg->alpha2[0], reg->alpha2[1]);
printk(KERN_DEBUG "ath: Regpair used: 0x%0x\n",
reg->regpair->regDmnEnum);
ath_regd_init_wiphy(reg, wiphy, reg_notifier);
return 0;
}
EXPORT_SYMBOL(ath_regd_init);
u32 ath_regd_get_band_ctl(struct ath_regulatory *reg,
enum ieee80211_band band)
{
if (!reg->regpair ||
(reg->country_code == CTRY_DEFAULT &&
is_wwr_sku(ath_regd_get_eepromRD(reg)))) {
return SD_NO_CTL;
}
switch (band) {
case IEEE80211_BAND_2GHZ:
return reg->regpair->reg_2ghz_ctl;
case IEEE80211_BAND_5GHZ:
return reg->regpair->reg_5ghz_ctl;
default:
return NO_CTL;
}
}
EXPORT_SYMBOL(ath_regd_get_band_ctl);
| gpl-2.0 |
mdamt/linux-pattimura | drivers/md/dm-io.c | 1239 | 12502 | /*
* Copyright (C) 2003 Sistina Software
* Copyright (C) 2006 Red Hat GmbH
*
* This file is released under the GPL.
*/
#include "dm.h"
#include <linux/device-mapper.h>
#include <linux/bio.h>
#include <linux/mempool.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/dm-io.h>
#define DM_MSG_PREFIX "io"
#define DM_IO_MAX_REGIONS BITS_PER_LONG
#define MIN_IOS 16
#define MIN_BIOS 16
struct dm_io_client {
mempool_t *pool;
struct bio_set *bios;
};
/*
* Aligning 'struct io' reduces the number of bits required to store
* its address. Refer to store_io_and_region_in_bio() below.
*/
struct io {
unsigned long error_bits;
atomic_t count;
struct task_struct *sleeper;
struct dm_io_client *client;
io_notify_fn callback;
void *context;
void *vma_invalidate_address;
unsigned long vma_invalidate_size;
} __attribute__((aligned(DM_IO_MAX_REGIONS)));
static struct kmem_cache *_dm_io_cache;
/*
* Create a client with mempool and bioset.
*/
struct dm_io_client *dm_io_client_create(void)
{
struct dm_io_client *client;
client = kmalloc(sizeof(*client), GFP_KERNEL);
if (!client)
return ERR_PTR(-ENOMEM);
client->pool = mempool_create_slab_pool(MIN_IOS, _dm_io_cache);
if (!client->pool)
goto bad;
client->bios = bioset_create(MIN_BIOS, 0);
if (!client->bios)
goto bad;
return client;
bad:
if (client->pool)
mempool_destroy(client->pool);
kfree(client);
return ERR_PTR(-ENOMEM);
}
EXPORT_SYMBOL(dm_io_client_create);
void dm_io_client_destroy(struct dm_io_client *client)
{
mempool_destroy(client->pool);
bioset_free(client->bios);
kfree(client);
}
EXPORT_SYMBOL(dm_io_client_destroy);
/*-----------------------------------------------------------------
* We need to keep track of which region a bio is doing io for.
* To avoid a memory allocation to store just 5 or 6 bits, we
* ensure the 'struct io' pointer is aligned so enough low bits are
* always zero and then combine it with the region number directly in
* bi_private.
*---------------------------------------------------------------*/
static void store_io_and_region_in_bio(struct bio *bio, struct io *io,
unsigned region)
{
if (unlikely(!IS_ALIGNED((unsigned long)io, DM_IO_MAX_REGIONS))) {
DMCRIT("Unaligned struct io pointer %p", io);
BUG();
}
bio->bi_private = (void *)((unsigned long)io | region);
}
static void retrieve_io_and_region_from_bio(struct bio *bio, struct io **io,
unsigned *region)
{
unsigned long val = (unsigned long)bio->bi_private;
*io = (void *)(val & -(unsigned long)DM_IO_MAX_REGIONS);
*region = val & (DM_IO_MAX_REGIONS - 1);
}
/*-----------------------------------------------------------------
* We need an io object to keep track of the number of bios that
* have been dispatched for a particular io.
*---------------------------------------------------------------*/
static void dec_count(struct io *io, unsigned int region, int error)
{
if (error)
set_bit(region, &io->error_bits);
if (atomic_dec_and_test(&io->count)) {
if (io->vma_invalidate_size)
invalidate_kernel_vmap_range(io->vma_invalidate_address,
io->vma_invalidate_size);
if (io->sleeper)
wake_up_process(io->sleeper);
else {
unsigned long r = io->error_bits;
io_notify_fn fn = io->callback;
void *context = io->context;
mempool_free(io, io->client->pool);
fn(r, context);
}
}
}
static void endio(struct bio *bio, int error)
{
struct io *io;
unsigned region;
if (error && bio_data_dir(bio) == READ)
zero_fill_bio(bio);
/*
* The bio destructor in bio_put() may use the io object.
*/
retrieve_io_and_region_from_bio(bio, &io, ®ion);
bio_put(bio);
dec_count(io, region, error);
}
/*-----------------------------------------------------------------
* These little objects provide an abstraction for getting a new
* destination page for io.
*---------------------------------------------------------------*/
struct dpages {
void (*get_page)(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset);
void (*next_page)(struct dpages *dp);
unsigned context_u;
void *context_ptr;
void *vma_invalidate_address;
unsigned long vma_invalidate_size;
};
/*
* Functions for getting the pages from a list.
*/
static void list_get_page(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset)
{
unsigned o = dp->context_u;
struct page_list *pl = (struct page_list *) dp->context_ptr;
*p = pl->page;
*len = PAGE_SIZE - o;
*offset = o;
}
static void list_next_page(struct dpages *dp)
{
struct page_list *pl = (struct page_list *) dp->context_ptr;
dp->context_ptr = pl->next;
dp->context_u = 0;
}
static void list_dp_init(struct dpages *dp, struct page_list *pl, unsigned offset)
{
dp->get_page = list_get_page;
dp->next_page = list_next_page;
dp->context_u = offset;
dp->context_ptr = pl;
}
/*
* Functions for getting the pages from a bvec.
*/
static void bvec_get_page(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset)
{
struct bio_vec *bvec = (struct bio_vec *) dp->context_ptr;
*p = bvec->bv_page;
*len = bvec->bv_len;
*offset = bvec->bv_offset;
}
static void bvec_next_page(struct dpages *dp)
{
struct bio_vec *bvec = (struct bio_vec *) dp->context_ptr;
dp->context_ptr = bvec + 1;
}
static void bvec_dp_init(struct dpages *dp, struct bio_vec *bvec)
{
dp->get_page = bvec_get_page;
dp->next_page = bvec_next_page;
dp->context_ptr = bvec;
}
/*
* Functions for getting the pages from a VMA.
*/
static void vm_get_page(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset)
{
*p = vmalloc_to_page(dp->context_ptr);
*offset = dp->context_u;
*len = PAGE_SIZE - dp->context_u;
}
static void vm_next_page(struct dpages *dp)
{
dp->context_ptr += PAGE_SIZE - dp->context_u;
dp->context_u = 0;
}
static void vm_dp_init(struct dpages *dp, void *data)
{
dp->get_page = vm_get_page;
dp->next_page = vm_next_page;
dp->context_u = ((unsigned long) data) & (PAGE_SIZE - 1);
dp->context_ptr = data;
}
static void dm_bio_destructor(struct bio *bio)
{
unsigned region;
struct io *io;
retrieve_io_and_region_from_bio(bio, &io, ®ion);
bio_free(bio, io->client->bios);
}
/*
* Functions for getting the pages from kernel memory.
*/
static void km_get_page(struct dpages *dp, struct page **p, unsigned long *len,
unsigned *offset)
{
*p = virt_to_page(dp->context_ptr);
*offset = dp->context_u;
*len = PAGE_SIZE - dp->context_u;
}
static void km_next_page(struct dpages *dp)
{
dp->context_ptr += PAGE_SIZE - dp->context_u;
dp->context_u = 0;
}
static void km_dp_init(struct dpages *dp, void *data)
{
dp->get_page = km_get_page;
dp->next_page = km_next_page;
dp->context_u = ((unsigned long) data) & (PAGE_SIZE - 1);
dp->context_ptr = data;
}
/*-----------------------------------------------------------------
* IO routines that accept a list of pages.
*---------------------------------------------------------------*/
static void do_region(int rw, unsigned region, struct dm_io_region *where,
struct dpages *dp, struct io *io)
{
struct bio *bio;
struct page *page;
unsigned long len;
unsigned offset;
unsigned num_bvecs;
sector_t remaining = where->count;
/*
* where->count may be zero if rw holds a flush and we need to
* send a zero-sized flush.
*/
do {
/*
* Allocate a suitably sized-bio.
*/
num_bvecs = dm_sector_div_up(remaining,
(PAGE_SIZE >> SECTOR_SHIFT));
num_bvecs = min_t(int, bio_get_nr_vecs(where->bdev), num_bvecs);
bio = bio_alloc_bioset(GFP_NOIO, num_bvecs, io->client->bios);
bio->bi_sector = where->sector + (where->count - remaining);
bio->bi_bdev = where->bdev;
bio->bi_end_io = endio;
bio->bi_destructor = dm_bio_destructor;
store_io_and_region_in_bio(bio, io, region);
/*
* Try and add as many pages as possible.
*/
while (remaining) {
dp->get_page(dp, &page, &len, &offset);
len = min(len, to_bytes(remaining));
if (!bio_add_page(bio, page, len, offset))
break;
offset = 0;
remaining -= to_sector(len);
dp->next_page(dp);
}
atomic_inc(&io->count);
submit_bio(rw, bio);
} while (remaining);
}
static void dispatch_io(int rw, unsigned int num_regions,
struct dm_io_region *where, struct dpages *dp,
struct io *io, int sync)
{
int i;
struct dpages old_pages = *dp;
BUG_ON(num_regions > DM_IO_MAX_REGIONS);
if (sync)
rw |= REQ_SYNC;
/*
* For multiple regions we need to be careful to rewind
* the dp object for each call to do_region.
*/
for (i = 0; i < num_regions; i++) {
*dp = old_pages;
if (where[i].count || (rw & REQ_FLUSH))
do_region(rw, i, where + i, dp, io);
}
/*
* Drop the extra reference that we were holding to avoid
* the io being completed too early.
*/
dec_count(io, 0, 0);
}
static int sync_io(struct dm_io_client *client, unsigned int num_regions,
struct dm_io_region *where, int rw, struct dpages *dp,
unsigned long *error_bits)
{
/*
* gcc <= 4.3 can't do the alignment for stack variables, so we must
* align it on our own.
* volatile prevents the optimizer from removing or reusing
* "io_" field from the stack frame (allowed in ANSI C).
*/
volatile char io_[sizeof(struct io) + __alignof__(struct io) - 1];
struct io *io = (struct io *)PTR_ALIGN(&io_, __alignof__(struct io));
if (num_regions > 1 && (rw & RW_MASK) != WRITE) {
WARN_ON(1);
return -EIO;
}
io->error_bits = 0;
atomic_set(&io->count, 1); /* see dispatch_io() */
io->sleeper = current;
io->client = client;
io->vma_invalidate_address = dp->vma_invalidate_address;
io->vma_invalidate_size = dp->vma_invalidate_size;
dispatch_io(rw, num_regions, where, dp, io, 1);
while (1) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (!atomic_read(&io->count))
break;
io_schedule();
}
set_current_state(TASK_RUNNING);
if (error_bits)
*error_bits = io->error_bits;
return io->error_bits ? -EIO : 0;
}
static int async_io(struct dm_io_client *client, unsigned int num_regions,
struct dm_io_region *where, int rw, struct dpages *dp,
io_notify_fn fn, void *context)
{
struct io *io;
if (num_regions > 1 && (rw & RW_MASK) != WRITE) {
WARN_ON(1);
fn(1, context);
return -EIO;
}
io = mempool_alloc(client->pool, GFP_NOIO);
io->error_bits = 0;
atomic_set(&io->count, 1); /* see dispatch_io() */
io->sleeper = NULL;
io->client = client;
io->callback = fn;
io->context = context;
io->vma_invalidate_address = dp->vma_invalidate_address;
io->vma_invalidate_size = dp->vma_invalidate_size;
dispatch_io(rw, num_regions, where, dp, io, 0);
return 0;
}
static int dp_init(struct dm_io_request *io_req, struct dpages *dp,
unsigned long size)
{
/* Set up dpages based on memory type */
dp->vma_invalidate_address = NULL;
dp->vma_invalidate_size = 0;
switch (io_req->mem.type) {
case DM_IO_PAGE_LIST:
list_dp_init(dp, io_req->mem.ptr.pl, io_req->mem.offset);
break;
case DM_IO_BVEC:
bvec_dp_init(dp, io_req->mem.ptr.bvec);
break;
case DM_IO_VMA:
flush_kernel_vmap_range(io_req->mem.ptr.vma, size);
if ((io_req->bi_rw & RW_MASK) == READ) {
dp->vma_invalidate_address = io_req->mem.ptr.vma;
dp->vma_invalidate_size = size;
}
vm_dp_init(dp, io_req->mem.ptr.vma);
break;
case DM_IO_KMEM:
km_dp_init(dp, io_req->mem.ptr.addr);
break;
default:
return -EINVAL;
}
return 0;
}
/*
* New collapsed (a)synchronous interface.
*
* If the IO is asynchronous (i.e. it has notify.fn), you must either unplug
* the queue with blk_unplug() some time later or set REQ_SYNC in
io_req->bi_rw. If you fail to do one of these, the IO will be submitted to
* the disk after q->unplug_delay, which defaults to 3ms in blk-settings.c.
*/
int dm_io(struct dm_io_request *io_req, unsigned num_regions,
struct dm_io_region *where, unsigned long *sync_error_bits)
{
int r;
struct dpages dp;
r = dp_init(io_req, &dp, (unsigned long)where->count << SECTOR_SHIFT);
if (r)
return r;
if (!io_req->notify.fn)
return sync_io(io_req->client, num_regions, where,
io_req->bi_rw, &dp, sync_error_bits);
return async_io(io_req->client, num_regions, where, io_req->bi_rw,
&dp, io_req->notify.fn, io_req->notify.context);
}
EXPORT_SYMBOL(dm_io);
int __init dm_io_init(void)
{
_dm_io_cache = KMEM_CACHE(io, 0);
if (!_dm_io_cache)
return -ENOMEM;
return 0;
}
void dm_io_exit(void)
{
kmem_cache_destroy(_dm_io_cache);
_dm_io_cache = NULL;
}
| gpl-2.0 |
olegsvs/android_kernel_archos_persimmon_3_18 | drivers/clk/sunxi/clk-a10-hosc.c | 1495 | 1926 | /*
* Copyright 2013 Emilio López
*
* Emilio López <emilio@elopez.com.ar>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk-provider.h>
#include <linux/clkdev.h>
#include <linux/of.h>
#include <linux/of_address.h>
#define SUNXI_OSC24M_GATE 0
static DEFINE_SPINLOCK(hosc_lock);
static void __init sun4i_osc_clk_setup(struct device_node *node)
{
struct clk *clk;
struct clk_fixed_rate *fixed;
struct clk_gate *gate;
const char *clk_name = node->name;
u32 rate;
if (of_property_read_u32(node, "clock-frequency", &rate))
return;
/* allocate fixed-rate and gate clock structs */
fixed = kzalloc(sizeof(struct clk_fixed_rate), GFP_KERNEL);
if (!fixed)
return;
gate = kzalloc(sizeof(struct clk_gate), GFP_KERNEL);
if (!gate)
goto err_free_fixed;
of_property_read_string(node, "clock-output-names", &clk_name);
/* set up gate and fixed rate properties */
gate->reg = of_iomap(node, 0);
gate->bit_idx = SUNXI_OSC24M_GATE;
gate->lock = &hosc_lock;
fixed->fixed_rate = rate;
clk = clk_register_composite(NULL, clk_name,
NULL, 0,
NULL, NULL,
&fixed->hw, &clk_fixed_rate_ops,
&gate->hw, &clk_gate_ops,
CLK_IS_ROOT);
if (IS_ERR(clk))
goto err_free_gate;
of_clk_add_provider(node, of_clk_src_simple_get, clk);
clk_register_clkdev(clk, clk_name, NULL);
return;
err_free_gate:
kfree(gate);
err_free_fixed:
kfree(fixed);
}
CLK_OF_DECLARE(sun4i_osc, "allwinner,sun4i-a10-osc-clk", sun4i_osc_clk_setup);
| gpl-2.0 |
dperezde/little-penguin | linux-eudyptula/drivers/s390/cio/ccwgroup.c | 1751 | 15724 | /*
* bus driver for ccwgroup
*
* Copyright IBM Corp. 2002, 2012
*
* Author(s): Arnd Bergmann (arndb@de.ibm.com)
* Cornelia Huck (cornelia.huck@de.ibm.com)
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/ctype.h>
#include <linux/dcache.h>
#include <asm/cio.h>
#include <asm/ccwdev.h>
#include <asm/ccwgroup.h>
#include "device.h"
#define CCW_BUS_ID_SIZE 10
/* In Linux 2.4, we had a channel device layer called "chandev"
* that did all sorts of obscure stuff for networking devices.
* This is another driver that serves as a replacement for just
* one of its functions, namely the translation of single subchannels
* to devices that use multiple subchannels.
*/
static struct bus_type ccwgroup_bus_type;
static void __ccwgroup_remove_symlinks(struct ccwgroup_device *gdev)
{
int i;
char str[8];
for (i = 0; i < gdev->count; i++) {
sprintf(str, "cdev%d", i);
sysfs_remove_link(&gdev->dev.kobj, str);
sysfs_remove_link(&gdev->cdev[i]->dev.kobj, "group_device");
}
}
/*
* Remove references from ccw devices to ccw group device and from
* ccw group device to ccw devices.
*/
static void __ccwgroup_remove_cdev_refs(struct ccwgroup_device *gdev)
{
struct ccw_device *cdev;
int i;
for (i = 0; i < gdev->count; i++) {
cdev = gdev->cdev[i];
if (!cdev)
continue;
spin_lock_irq(cdev->ccwlock);
dev_set_drvdata(&cdev->dev, NULL);
spin_unlock_irq(cdev->ccwlock);
gdev->cdev[i] = NULL;
put_device(&cdev->dev);
}
}
/**
* ccwgroup_set_online() - enable a ccwgroup device
* @gdev: target ccwgroup device
*
* This function attempts to put the ccwgroup device into the online state.
* Returns:
* %0 on success and a negative error value on failure.
*/
int ccwgroup_set_online(struct ccwgroup_device *gdev)
{
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver);
int ret = -EINVAL;
if (atomic_cmpxchg(&gdev->onoff, 0, 1) != 0)
return -EAGAIN;
if (gdev->state == CCWGROUP_ONLINE)
goto out;
if (gdrv->set_online)
ret = gdrv->set_online(gdev);
if (ret)
goto out;
gdev->state = CCWGROUP_ONLINE;
out:
atomic_set(&gdev->onoff, 0);
return ret;
}
EXPORT_SYMBOL(ccwgroup_set_online);
/**
* ccwgroup_set_offline() - disable a ccwgroup device
* @gdev: target ccwgroup device
*
* This function attempts to put the ccwgroup device into the offline state.
* Returns:
* %0 on success and a negative error value on failure.
*/
int ccwgroup_set_offline(struct ccwgroup_device *gdev)
{
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver);
int ret = -EINVAL;
if (atomic_cmpxchg(&gdev->onoff, 0, 1) != 0)
return -EAGAIN;
if (gdev->state == CCWGROUP_OFFLINE)
goto out;
if (gdrv->set_offline)
ret = gdrv->set_offline(gdev);
if (ret)
goto out;
gdev->state = CCWGROUP_OFFLINE;
out:
atomic_set(&gdev->onoff, 0);
return ret;
}
EXPORT_SYMBOL(ccwgroup_set_offline);
static ssize_t ccwgroup_online_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
unsigned long value;
int ret;
device_lock(dev);
if (!dev->driver) {
ret = -EINVAL;
goto out;
}
ret = kstrtoul(buf, 0, &value);
if (ret)
goto out;
if (value == 1)
ret = ccwgroup_set_online(gdev);
else if (value == 0)
ret = ccwgroup_set_offline(gdev);
else
ret = -EINVAL;
out:
device_unlock(dev);
return (ret == 0) ? count : ret;
}
static ssize_t ccwgroup_online_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
int online;
online = (gdev->state == CCWGROUP_ONLINE) ? 1 : 0;
return scnprintf(buf, PAGE_SIZE, "%d\n", online);
}
/*
* Provide an 'ungroup' attribute so the user can remove group devices no
* longer needed or accidentially created. Saves memory :)
*/
static void ccwgroup_ungroup(struct ccwgroup_device *gdev)
{
mutex_lock(&gdev->reg_mutex);
if (device_is_registered(&gdev->dev)) {
__ccwgroup_remove_symlinks(gdev);
device_unregister(&gdev->dev);
__ccwgroup_remove_cdev_refs(gdev);
}
mutex_unlock(&gdev->reg_mutex);
}
static ssize_t ccwgroup_ungroup_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
int rc = 0;
/* Prevent concurrent online/offline processing and ungrouping. */
if (atomic_cmpxchg(&gdev->onoff, 0, 1) != 0)
return -EAGAIN;
if (gdev->state != CCWGROUP_OFFLINE) {
rc = -EINVAL;
goto out;
}
if (device_remove_file_self(dev, attr))
ccwgroup_ungroup(gdev);
else
rc = -ENODEV;
out:
if (rc) {
/* Release onoff "lock" when ungrouping failed. */
atomic_set(&gdev->onoff, 0);
return rc;
}
return count;
}
static DEVICE_ATTR(ungroup, 0200, NULL, ccwgroup_ungroup_store);
static DEVICE_ATTR(online, 0644, ccwgroup_online_show, ccwgroup_online_store);
static struct attribute *ccwgroup_attrs[] = {
&dev_attr_online.attr,
&dev_attr_ungroup.attr,
NULL,
};
static struct attribute_group ccwgroup_attr_group = {
.attrs = ccwgroup_attrs,
};
static const struct attribute_group *ccwgroup_attr_groups[] = {
&ccwgroup_attr_group,
NULL,
};
static void ccwgroup_ungroup_workfn(struct work_struct *work)
{
struct ccwgroup_device *gdev =
container_of(work, struct ccwgroup_device, ungroup_work);
ccwgroup_ungroup(gdev);
put_device(&gdev->dev);
}
static void ccwgroup_release(struct device *dev)
{
kfree(to_ccwgroupdev(dev));
}
static int __ccwgroup_create_symlinks(struct ccwgroup_device *gdev)
{
char str[8];
int i, rc;
for (i = 0; i < gdev->count; i++) {
rc = sysfs_create_link(&gdev->cdev[i]->dev.kobj,
&gdev->dev.kobj, "group_device");
if (rc) {
for (--i; i >= 0; i--)
sysfs_remove_link(&gdev->cdev[i]->dev.kobj,
"group_device");
return rc;
}
}
for (i = 0; i < gdev->count; i++) {
sprintf(str, "cdev%d", i);
rc = sysfs_create_link(&gdev->dev.kobj,
&gdev->cdev[i]->dev.kobj, str);
if (rc) {
for (--i; i >= 0; i--) {
sprintf(str, "cdev%d", i);
sysfs_remove_link(&gdev->dev.kobj, str);
}
for (i = 0; i < gdev->count; i++)
sysfs_remove_link(&gdev->cdev[i]->dev.kobj,
"group_device");
return rc;
}
}
return 0;
}
static int __get_next_id(const char **buf, struct ccw_dev_id *id)
{
unsigned int cssid, ssid, devno;
int ret = 0, len;
char *start, *end;
start = (char *)*buf;
end = strchr(start, ',');
if (!end) {
/* Last entry. Strip trailing newline, if applicable. */
end = strchr(start, '\n');
if (end)
*end = '\0';
len = strlen(start) + 1;
} else {
len = end - start + 1;
end++;
}
if (len <= CCW_BUS_ID_SIZE) {
if (sscanf(start, "%2x.%1x.%04x", &cssid, &ssid, &devno) != 3)
ret = -EINVAL;
} else
ret = -EINVAL;
if (!ret) {
id->ssid = ssid;
id->devno = devno;
}
*buf = end;
return ret;
}
/**
* ccwgroup_create_dev() - create and register a ccw group device
* @parent: parent device for the new device
* @gdrv: driver for the new group device
* @num_devices: number of slave devices
* @buf: buffer containing comma separated bus ids of slave devices
*
* Create and register a new ccw group device as a child of @parent. Slave
* devices are obtained from the list of bus ids given in @buf.
* Returns:
* %0 on success and an error code on failure.
* Context:
* non-atomic
*/
int ccwgroup_create_dev(struct device *parent, struct ccwgroup_driver *gdrv,
int num_devices, const char *buf)
{
struct ccwgroup_device *gdev;
struct ccw_dev_id dev_id;
int rc, i;
gdev = kzalloc(sizeof(*gdev) + num_devices * sizeof(gdev->cdev[0]),
GFP_KERNEL);
if (!gdev)
return -ENOMEM;
atomic_set(&gdev->onoff, 0);
mutex_init(&gdev->reg_mutex);
mutex_lock(&gdev->reg_mutex);
INIT_WORK(&gdev->ungroup_work, ccwgroup_ungroup_workfn);
gdev->count = num_devices;
gdev->dev.bus = &ccwgroup_bus_type;
gdev->dev.parent = parent;
gdev->dev.release = ccwgroup_release;
device_initialize(&gdev->dev);
for (i = 0; i < num_devices && buf; i++) {
rc = __get_next_id(&buf, &dev_id);
if (rc != 0)
goto error;
gdev->cdev[i] = get_ccwdev_by_dev_id(&dev_id);
/*
* All devices have to be of the same type in
* order to be grouped.
*/
if (!gdev->cdev[i] || !gdev->cdev[i]->drv ||
gdev->cdev[i]->drv != gdev->cdev[0]->drv ||
gdev->cdev[i]->id.driver_info !=
gdev->cdev[0]->id.driver_info) {
rc = -EINVAL;
goto error;
}
/* Don't allow a device to belong to more than one group. */
spin_lock_irq(gdev->cdev[i]->ccwlock);
if (dev_get_drvdata(&gdev->cdev[i]->dev)) {
spin_unlock_irq(gdev->cdev[i]->ccwlock);
rc = -EINVAL;
goto error;
}
dev_set_drvdata(&gdev->cdev[i]->dev, gdev);
spin_unlock_irq(gdev->cdev[i]->ccwlock);
}
/* Check for sufficient number of bus ids. */
if (i < num_devices) {
rc = -EINVAL;
goto error;
}
/* Check for trailing stuff. */
if (i == num_devices && strlen(buf) > 0) {
rc = -EINVAL;
goto error;
}
dev_set_name(&gdev->dev, "%s", dev_name(&gdev->cdev[0]->dev));
gdev->dev.groups = ccwgroup_attr_groups;
if (gdrv) {
gdev->dev.driver = &gdrv->driver;
rc = gdrv->setup ? gdrv->setup(gdev) : 0;
if (rc)
goto error;
}
rc = device_add(&gdev->dev);
if (rc)
goto error;
rc = __ccwgroup_create_symlinks(gdev);
if (rc) {
device_del(&gdev->dev);
goto error;
}
mutex_unlock(&gdev->reg_mutex);
return 0;
error:
for (i = 0; i < num_devices; i++)
if (gdev->cdev[i]) {
spin_lock_irq(gdev->cdev[i]->ccwlock);
if (dev_get_drvdata(&gdev->cdev[i]->dev) == gdev)
dev_set_drvdata(&gdev->cdev[i]->dev, NULL);
spin_unlock_irq(gdev->cdev[i]->ccwlock);
put_device(&gdev->cdev[i]->dev);
gdev->cdev[i] = NULL;
}
mutex_unlock(&gdev->reg_mutex);
put_device(&gdev->dev);
return rc;
}
EXPORT_SYMBOL(ccwgroup_create_dev);
static int ccwgroup_notifier(struct notifier_block *nb, unsigned long action,
void *data)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(data);
if (action == BUS_NOTIFY_UNBIND_DRIVER) {
get_device(&gdev->dev);
schedule_work(&gdev->ungroup_work);
}
return NOTIFY_OK;
}
static struct notifier_block ccwgroup_nb = {
.notifier_call = ccwgroup_notifier
};
static int __init init_ccwgroup(void)
{
int ret;
ret = bus_register(&ccwgroup_bus_type);
if (ret)
return ret;
ret = bus_register_notifier(&ccwgroup_bus_type, &ccwgroup_nb);
if (ret)
bus_unregister(&ccwgroup_bus_type);
return ret;
}
static void __exit cleanup_ccwgroup(void)
{
bus_unregister_notifier(&ccwgroup_bus_type, &ccwgroup_nb);
bus_unregister(&ccwgroup_bus_type);
}
module_init(init_ccwgroup);
module_exit(cleanup_ccwgroup);
/************************** driver stuff ******************************/
static int ccwgroup_remove(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver);
if (!dev->driver)
return 0;
if (gdrv->remove)
gdrv->remove(gdev);
return 0;
}
static void ccwgroup_shutdown(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver);
if (!dev->driver)
return;
if (gdrv->shutdown)
gdrv->shutdown(gdev);
}
static int ccwgroup_pm_prepare(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver);
/* Fail while device is being set online/offline. */
if (atomic_read(&gdev->onoff))
return -EAGAIN;
if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE)
return 0;
return gdrv->prepare ? gdrv->prepare(gdev) : 0;
}
static void ccwgroup_pm_complete(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(dev->driver);
if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE)
return;
if (gdrv->complete)
gdrv->complete(gdev);
}
static int ccwgroup_pm_freeze(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver);
if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE)
return 0;
return gdrv->freeze ? gdrv->freeze(gdev) : 0;
}
static int ccwgroup_pm_thaw(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver);
if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE)
return 0;
return gdrv->thaw ? gdrv->thaw(gdev) : 0;
}
static int ccwgroup_pm_restore(struct device *dev)
{
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
struct ccwgroup_driver *gdrv = to_ccwgroupdrv(gdev->dev.driver);
if (!gdev->dev.driver || gdev->state != CCWGROUP_ONLINE)
return 0;
return gdrv->restore ? gdrv->restore(gdev) : 0;
}
static const struct dev_pm_ops ccwgroup_pm_ops = {
.prepare = ccwgroup_pm_prepare,
.complete = ccwgroup_pm_complete,
.freeze = ccwgroup_pm_freeze,
.thaw = ccwgroup_pm_thaw,
.restore = ccwgroup_pm_restore,
};
static struct bus_type ccwgroup_bus_type = {
.name = "ccwgroup",
.remove = ccwgroup_remove,
.shutdown = ccwgroup_shutdown,
.pm = &ccwgroup_pm_ops,
};
/**
* ccwgroup_driver_register() - register a ccw group driver
* @cdriver: driver to be registered
*
* This function is mainly a wrapper around driver_register().
*/
int ccwgroup_driver_register(struct ccwgroup_driver *cdriver)
{
/* register our new driver with the core */
cdriver->driver.bus = &ccwgroup_bus_type;
return driver_register(&cdriver->driver);
}
EXPORT_SYMBOL(ccwgroup_driver_register);
static int __ccwgroup_match_all(struct device *dev, void *data)
{
return 1;
}
/**
* ccwgroup_driver_unregister() - deregister a ccw group driver
* @cdriver: driver to be deregistered
*
* This function is mainly a wrapper around driver_unregister().
*/
void ccwgroup_driver_unregister(struct ccwgroup_driver *cdriver)
{
struct device *dev;
/* We don't want ccwgroup devices to live longer than their driver. */
while ((dev = driver_find_device(&cdriver->driver, NULL, NULL,
__ccwgroup_match_all))) {
struct ccwgroup_device *gdev = to_ccwgroupdev(dev);
ccwgroup_ungroup(gdev);
put_device(dev);
}
driver_unregister(&cdriver->driver);
}
EXPORT_SYMBOL(ccwgroup_driver_unregister);
/**
* ccwgroup_probe_ccwdev() - probe function for slave devices
* @cdev: ccw device to be probed
*
* This is a dummy probe function for ccw devices that are slave devices in
* a ccw group device.
* Returns:
* always %0
*/
int ccwgroup_probe_ccwdev(struct ccw_device *cdev)
{
return 0;
}
EXPORT_SYMBOL(ccwgroup_probe_ccwdev);
/**
* ccwgroup_remove_ccwdev() - remove function for slave devices
* @cdev: ccw device to be removed
*
* This is a remove function for ccw devices that are slave devices in a ccw
* group device. It sets the ccw device offline and also deregisters the
* embedding ccw group device.
*/
void ccwgroup_remove_ccwdev(struct ccw_device *cdev)
{
struct ccwgroup_device *gdev;
/* Ignore offlining errors, device is gone anyway. */
ccw_device_set_offline(cdev);
/* If one of its devices is gone, the whole group is done for. */
spin_lock_irq(cdev->ccwlock);
gdev = dev_get_drvdata(&cdev->dev);
if (!gdev) {
spin_unlock_irq(cdev->ccwlock);
return;
}
/* Get ccwgroup device reference for local processing. */
get_device(&gdev->dev);
spin_unlock_irq(cdev->ccwlock);
/* Unregister group device. */
ccwgroup_ungroup(gdev);
/* Release ccwgroup device reference for local processing. */
put_device(&gdev->dev);
}
EXPORT_SYMBOL(ccwgroup_remove_ccwdev);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Jackeagle/slte_kernel | drivers/media/parport/c-qcam.c | 3031 | 21580 | /*
* Video4Linux Colour QuickCam driver
* Copyright 1997-2000 Philip Blundell <philb@gnu.org>
*
* Module parameters:
*
* parport=auto -- probe all parports (default)
* parport=0 -- parport0 becomes qcam1
* parport=2,0,1 -- parports 2,0,1 are tried in that order
*
* probe=0 -- do no probing, assume camera is present
* probe=1 -- use IEEE-1284 autoprobe data only (default)
* probe=2 -- probe aggressively for cameras
*
* force_rgb=1 -- force data format to RGB (default is BGR)
*
* The parport parameter controls which parports will be scanned.
* Scanning all parports causes some printers to print a garbage page.
* -- March 14, 1999 Billy Donahue <billy@escape.com>
*
* Fixed data format to BGR, added force_rgb parameter. Added missing
* parport_unregister_driver() on module removal.
* -- May 28, 2000 Claudio Matsuoka <claudio@conectiva.com>
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/parport.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/jiffies.h>
#include <linux/videodev2.h>
#include <asm/uaccess.h>
#include <media/v4l2-device.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
struct qcam {
struct v4l2_device v4l2_dev;
struct video_device vdev;
struct v4l2_ctrl_handler hdl;
struct pardevice *pdev;
struct parport *pport;
int width, height;
int ccd_width, ccd_height;
int mode;
int contrast, brightness, whitebal;
int top, left;
unsigned int bidirectional;
struct mutex lock;
};
/* cameras maximum */
#define MAX_CAMS 4
/* The three possible QuickCam modes */
#define QC_MILLIONS 0x18
#define QC_BILLIONS 0x10
#define QC_THOUSANDS 0x08 /* with VIDEC compression (not supported) */
/* The three possible decimations */
#define QC_DECIMATION_1 0
#define QC_DECIMATION_2 2
#define QC_DECIMATION_4 4
#define BANNER "Colour QuickCam for Video4Linux v0.06"
static int parport[MAX_CAMS] = { [1 ... MAX_CAMS-1] = -1 };
static int probe = 2;
static bool force_rgb;
static int video_nr = -1;
/* FIXME: parport=auto would never have worked, surely? --RR */
MODULE_PARM_DESC(parport, "parport=<auto|n[,n]...> for port detection method\n"
"probe=<0|1|2> for camera detection method\n"
"force_rgb=<0|1> for RGB data format (default BGR)");
module_param_array(parport, int, NULL, 0);
module_param(probe, int, 0);
module_param(force_rgb, bool, 0);
module_param(video_nr, int, 0);
static struct qcam *qcams[MAX_CAMS];
static unsigned int num_cams;
static inline void qcam_set_ack(struct qcam *qcam, unsigned int i)
{
/* note: the QC specs refer to the PCAck pin by voltage, not
software level. PC ports have builtin inverters. */
parport_frob_control(qcam->pport, 8, i ? 8 : 0);
}
static inline unsigned int qcam_ready1(struct qcam *qcam)
{
return (parport_read_status(qcam->pport) & 0x8) ? 1 : 0;
}
static inline unsigned int qcam_ready2(struct qcam *qcam)
{
return (parport_read_data(qcam->pport) & 0x1) ? 1 : 0;
}
static unsigned int qcam_await_ready1(struct qcam *qcam, int value)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned long oldjiffies = jiffies;
unsigned int i;
for (oldjiffies = jiffies;
time_before(jiffies, oldjiffies + msecs_to_jiffies(40));)
if (qcam_ready1(qcam) == value)
return 0;
/* If the camera didn't respond within 1/25 second, poll slowly
for a while. */
for (i = 0; i < 50; i++) {
if (qcam_ready1(qcam) == value)
return 0;
msleep_interruptible(100);
}
/* Probably somebody pulled the plug out. Not much we can do. */
v4l2_err(v4l2_dev, "ready1 timeout (%d) %x %x\n", value,
parport_read_status(qcam->pport),
parport_read_control(qcam->pport));
return 1;
}
static unsigned int qcam_await_ready2(struct qcam *qcam, int value)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned long oldjiffies = jiffies;
unsigned int i;
for (oldjiffies = jiffies;
time_before(jiffies, oldjiffies + msecs_to_jiffies(40));)
if (qcam_ready2(qcam) == value)
return 0;
/* If the camera didn't respond within 1/25 second, poll slowly
for a while. */
for (i = 0; i < 50; i++) {
if (qcam_ready2(qcam) == value)
return 0;
msleep_interruptible(100);
}
/* Probably somebody pulled the plug out. Not much we can do. */
v4l2_err(v4l2_dev, "ready2 timeout (%d) %x %x %x\n", value,
parport_read_status(qcam->pport),
parport_read_control(qcam->pport),
parport_read_data(qcam->pport));
return 1;
}
static int qcam_read_data(struct qcam *qcam)
{
unsigned int idata;
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1))
return -1;
idata = parport_read_status(qcam->pport) & 0xf0;
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0))
return -1;
idata |= parport_read_status(qcam->pport) >> 4;
return idata;
}
static int qcam_write_data(struct qcam *qcam, unsigned int data)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned int idata;
parport_write_data(qcam->pport, data);
idata = qcam_read_data(qcam);
if (data != idata) {
v4l2_warn(v4l2_dev, "sent %x but received %x\n", data,
idata);
return 1;
}
return 0;
}
static inline int qcam_set(struct qcam *qcam, unsigned int cmd, unsigned int data)
{
if (qcam_write_data(qcam, cmd))
return -1;
if (qcam_write_data(qcam, data))
return -1;
return 0;
}
static inline int qcam_get(struct qcam *qcam, unsigned int cmd)
{
if (qcam_write_data(qcam, cmd))
return -1;
return qcam_read_data(qcam);
}
static int qc_detect(struct qcam *qcam)
{
unsigned int stat, ostat, i, count = 0;
/* The probe routine below is not very reliable. The IEEE-1284
probe takes precedence. */
/* XXX Currently parport provides no way to distinguish between
"the IEEE probe was not done" and "the probe was done, but
no device was found". Fix this one day. */
if (qcam->pport->probe_info[0].class == PARPORT_CLASS_MEDIA
&& qcam->pport->probe_info[0].model
&& !strcmp(qcam->pdev->port->probe_info[0].model,
"Color QuickCam 2.0")) {
printk(KERN_DEBUG "QuickCam: Found by IEEE1284 probe.\n");
return 1;
}
if (probe < 2)
return 0;
parport_write_control(qcam->pport, 0xc);
/* look for a heartbeat */
ostat = stat = parport_read_status(qcam->pport);
for (i = 0; i < 250; i++) {
mdelay(1);
stat = parport_read_status(qcam->pport);
if (ostat != stat) {
if (++count >= 3)
return 1;
ostat = stat;
}
}
/* Reset the camera and try again */
parport_write_control(qcam->pport, 0xc);
parport_write_control(qcam->pport, 0x8);
mdelay(1);
parport_write_control(qcam->pport, 0xc);
mdelay(1);
count = 0;
ostat = stat = parport_read_status(qcam->pport);
for (i = 0; i < 250; i++) {
mdelay(1);
stat = parport_read_status(qcam->pport);
if (ostat != stat) {
if (++count >= 3)
return 1;
ostat = stat;
}
}
/* no (or flatline) camera, give up */
return 0;
}
static void qc_reset(struct qcam *qcam)
{
parport_write_control(qcam->pport, 0xc);
parport_write_control(qcam->pport, 0x8);
mdelay(1);
parport_write_control(qcam->pport, 0xc);
mdelay(1);
}
/* Reset the QuickCam and program for brightness, contrast,
* white-balance, and resolution. */
static void qc_setup(struct qcam *qcam)
{
qc_reset(qcam);
/* Set the brightness. */
qcam_set(qcam, 11, qcam->brightness);
/* Set the height and width. These refer to the actual
CCD area *before* applying the selected decimation. */
qcam_set(qcam, 17, qcam->ccd_height);
qcam_set(qcam, 19, qcam->ccd_width / 2);
/* Set top and left. */
qcam_set(qcam, 0xd, qcam->top);
qcam_set(qcam, 0xf, qcam->left);
/* Set contrast and white balance. */
qcam_set(qcam, 0x19, qcam->contrast);
qcam_set(qcam, 0x1f, qcam->whitebal);
/* Set the speed. */
qcam_set(qcam, 45, 2);
}
/* Read some bytes from the camera and put them in the buffer.
nbytes should be a multiple of 3, because bidirectional mode gives
us three bytes at a time. */
static unsigned int qcam_read_bytes(struct qcam *qcam, unsigned char *buf, unsigned int nbytes)
{
unsigned int bytes = 0;
qcam_set_ack(qcam, 0);
if (qcam->bidirectional) {
/* It's a bidirectional port */
while (bytes < nbytes) {
unsigned int lo1, hi1, lo2, hi2;
unsigned char r, g, b;
if (qcam_await_ready2(qcam, 1))
return bytes;
lo1 = parport_read_data(qcam->pport) >> 1;
hi1 = ((parport_read_status(qcam->pport) >> 3) & 0x1f) ^ 0x10;
qcam_set_ack(qcam, 1);
if (qcam_await_ready2(qcam, 0))
return bytes;
lo2 = parport_read_data(qcam->pport) >> 1;
hi2 = ((parport_read_status(qcam->pport) >> 3) & 0x1f) ^ 0x10;
qcam_set_ack(qcam, 0);
r = lo1 | ((hi1 & 1) << 7);
g = ((hi1 & 0x1e) << 3) | ((hi2 & 0x1e) >> 1);
b = lo2 | ((hi2 & 1) << 7);
if (force_rgb) {
buf[bytes++] = r;
buf[bytes++] = g;
buf[bytes++] = b;
} else {
buf[bytes++] = b;
buf[bytes++] = g;
buf[bytes++] = r;
}
}
} else {
/* It's a unidirectional port */
int i = 0, n = bytes;
unsigned char rgb[3];
while (bytes < nbytes) {
unsigned int hi, lo;
if (qcam_await_ready1(qcam, 1))
return bytes;
hi = (parport_read_status(qcam->pport) & 0xf0);
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0))
return bytes;
lo = (parport_read_status(qcam->pport) & 0xf0);
qcam_set_ack(qcam, 0);
/* flip some bits */
rgb[(i = bytes++ % 3)] = (hi | (lo >> 4)) ^ 0x88;
if (i >= 2) {
get_fragment:
if (force_rgb) {
buf[n++] = rgb[0];
buf[n++] = rgb[1];
buf[n++] = rgb[2];
} else {
buf[n++] = rgb[2];
buf[n++] = rgb[1];
buf[n++] = rgb[0];
}
}
}
if (i) {
i = 0;
goto get_fragment;
}
}
return bytes;
}
#define BUFSZ 150
static long qc_capture(struct qcam *qcam, char __user *buf, unsigned long len)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned lines, pixelsperline;
unsigned int is_bi_dir = qcam->bidirectional;
size_t wantlen, outptr = 0;
char tmpbuf[BUFSZ];
if (!access_ok(VERIFY_WRITE, buf, len))
return -EFAULT;
/* Wait for camera to become ready */
for (;;) {
int i = qcam_get(qcam, 41);
if (i == -1) {
qc_setup(qcam);
return -EIO;
}
if ((i & 0x80) == 0)
break;
schedule();
}
if (qcam_set(qcam, 7, (qcam->mode | (is_bi_dir ? 1 : 0)) + 1))
return -EIO;
lines = qcam->height;
pixelsperline = qcam->width;
if (is_bi_dir) {
/* Turn the port around */
parport_data_reverse(qcam->pport);
mdelay(3);
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1)) {
qc_setup(qcam);
return -EIO;
}
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0)) {
qc_setup(qcam);
return -EIO;
}
}
wantlen = lines * pixelsperline * 24 / 8;
while (wantlen) {
size_t t, s;
s = (wantlen > BUFSZ) ? BUFSZ : wantlen;
t = qcam_read_bytes(qcam, tmpbuf, s);
if (outptr < len) {
size_t sz = len - outptr;
if (sz > t)
sz = t;
if (__copy_to_user(buf + outptr, tmpbuf, sz))
break;
outptr += sz;
}
wantlen -= t;
if (t < s)
break;
cond_resched();
}
len = outptr;
if (wantlen) {
v4l2_err(v4l2_dev, "short read.\n");
if (is_bi_dir)
parport_data_forward(qcam->pport);
qc_setup(qcam);
return len;
}
if (is_bi_dir) {
int l;
do {
l = qcam_read_bytes(qcam, tmpbuf, 3);
cond_resched();
} while (l && (tmpbuf[0] == 0x7e || tmpbuf[1] == 0x7e || tmpbuf[2] == 0x7e));
if (force_rgb) {
if (tmpbuf[0] != 0xe || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xf)
v4l2_err(v4l2_dev, "bad EOF\n");
} else {
if (tmpbuf[0] != 0xf || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xe)
v4l2_err(v4l2_dev, "bad EOF\n");
}
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1)) {
v4l2_err(v4l2_dev, "no ack after EOF\n");
parport_data_forward(qcam->pport);
qc_setup(qcam);
return len;
}
parport_data_forward(qcam->pport);
mdelay(3);
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0)) {
v4l2_err(v4l2_dev, "no ack to port turnaround\n");
qc_setup(qcam);
return len;
}
} else {
int l;
do {
l = qcam_read_bytes(qcam, tmpbuf, 1);
cond_resched();
} while (l && tmpbuf[0] == 0x7e);
l = qcam_read_bytes(qcam, tmpbuf + 1, 2);
if (force_rgb) {
if (tmpbuf[0] != 0xe || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xf)
v4l2_err(v4l2_dev, "bad EOF\n");
} else {
if (tmpbuf[0] != 0xf || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xe)
v4l2_err(v4l2_dev, "bad EOF\n");
}
}
qcam_write_data(qcam, 0);
return len;
}
/*
* Video4linux interfacing
*/
static int qcam_querycap(struct file *file, void *priv,
struct v4l2_capability *vcap)
{
struct qcam *qcam = video_drvdata(file);
strlcpy(vcap->driver, qcam->v4l2_dev.name, sizeof(vcap->driver));
strlcpy(vcap->card, "Color Quickcam", sizeof(vcap->card));
strlcpy(vcap->bus_info, "parport", sizeof(vcap->bus_info));
vcap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE;
vcap->capabilities = vcap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int qcam_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
{
if (vin->index > 0)
return -EINVAL;
strlcpy(vin->name, "Camera", sizeof(vin->name));
vin->type = V4L2_INPUT_TYPE_CAMERA;
vin->audioset = 0;
vin->tuner = 0;
vin->std = 0;
vin->status = 0;
return 0;
}
static int qcam_g_input(struct file *file, void *fh, unsigned int *inp)
{
*inp = 0;
return 0;
}
static int qcam_s_input(struct file *file, void *fh, unsigned int inp)
{
return (inp > 0) ? -EINVAL : 0;
}
static int qcam_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
pix->width = qcam->width;
pix->height = qcam->height;
pix->pixelformat = V4L2_PIX_FMT_RGB24;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 3 * qcam->width;
pix->sizeimage = 3 * qcam->width * qcam->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
return 0;
}
static int qcam_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_pix_format *pix = &fmt->fmt.pix;
if (pix->height < 60 || pix->width < 80) {
pix->height = 60;
pix->width = 80;
} else if (pix->height < 120 || pix->width < 160) {
pix->height = 120;
pix->width = 160;
} else {
pix->height = 240;
pix->width = 320;
}
pix->pixelformat = V4L2_PIX_FMT_RGB24;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 3 * pix->width;
pix->sizeimage = 3 * pix->width * pix->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
return 0;
}
static int qcam_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
int ret = qcam_try_fmt_vid_cap(file, fh, fmt);
if (ret)
return ret;
switch (pix->height) {
case 60:
qcam->mode = QC_DECIMATION_4;
break;
case 120:
qcam->mode = QC_DECIMATION_2;
break;
default:
qcam->mode = QC_DECIMATION_1;
break;
}
mutex_lock(&qcam->lock);
qcam->mode |= QC_MILLIONS;
qcam->height = pix->height;
qcam->width = pix->width;
parport_claim_or_block(qcam->pdev);
qc_setup(qcam);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
return 0;
}
static int qcam_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"RGB 8:8:8", V4L2_PIX_FMT_RGB24,
{ 0, 0, 0, 0 }
},
};
enum v4l2_buf_type type = fmt->type;
if (fmt->index > 0)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
static ssize_t qcam_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qcam *qcam = video_drvdata(file);
int len;
mutex_lock(&qcam->lock);
parport_claim_or_block(qcam->pdev);
/* Probably should have a semaphore against multiple users */
len = qc_capture(qcam, buf, count);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
return len;
}
static int qcam_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct qcam *qcam =
container_of(ctrl->handler, struct qcam, hdl);
int ret = 0;
mutex_lock(&qcam->lock);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
qcam->brightness = ctrl->val;
break;
case V4L2_CID_CONTRAST:
qcam->contrast = ctrl->val;
break;
case V4L2_CID_GAMMA:
qcam->whitebal = ctrl->val;
break;
default:
ret = -EINVAL;
break;
}
if (ret == 0) {
parport_claim_or_block(qcam->pdev);
qc_setup(qcam);
parport_release(qcam->pdev);
}
mutex_unlock(&qcam->lock);
return ret;
}
static const struct v4l2_file_operations qcam_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = v4l2_fh_release,
.poll = v4l2_ctrl_poll,
.unlocked_ioctl = video_ioctl2,
.read = qcam_read,
};
static const struct v4l2_ioctl_ops qcam_ioctl_ops = {
.vidioc_querycap = qcam_querycap,
.vidioc_g_input = qcam_g_input,
.vidioc_s_input = qcam_s_input,
.vidioc_enum_input = qcam_enum_input,
.vidioc_enum_fmt_vid_cap = qcam_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = qcam_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = qcam_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = qcam_try_fmt_vid_cap,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
static const struct v4l2_ctrl_ops qcam_ctrl_ops = {
.s_ctrl = qcam_s_ctrl,
};
/* Initialize the QuickCam driver control structure. */
static struct qcam *qcam_init(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
qcam = kzalloc(sizeof(*qcam), GFP_KERNEL);
if (qcam == NULL)
return NULL;
v4l2_dev = &qcam->v4l2_dev;
strlcpy(v4l2_dev->name, "c-qcam", sizeof(v4l2_dev->name));
if (v4l2_device_register(NULL, v4l2_dev) < 0) {
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
kfree(qcam);
return NULL;
}
v4l2_ctrl_handler_init(&qcam->hdl, 3);
v4l2_ctrl_new_std(&qcam->hdl, &qcam_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 255, 1, 240);
v4l2_ctrl_new_std(&qcam->hdl, &qcam_ctrl_ops,
V4L2_CID_CONTRAST, 0, 255, 1, 192);
v4l2_ctrl_new_std(&qcam->hdl, &qcam_ctrl_ops,
V4L2_CID_GAMMA, 0, 255, 1, 128);
if (qcam->hdl.error) {
v4l2_err(v4l2_dev, "couldn't register controls\n");
v4l2_ctrl_handler_free(&qcam->hdl);
kfree(qcam);
return NULL;
}
qcam->pport = port;
qcam->pdev = parport_register_device(port, "c-qcam", NULL, NULL,
NULL, 0, NULL);
qcam->bidirectional = (qcam->pport->modes & PARPORT_MODE_TRISTATE) ? 1 : 0;
if (qcam->pdev == NULL) {
v4l2_err(v4l2_dev, "couldn't register for %s.\n", port->name);
v4l2_ctrl_handler_free(&qcam->hdl);
kfree(qcam);
return NULL;
}
strlcpy(qcam->vdev.name, "Colour QuickCam", sizeof(qcam->vdev.name));
qcam->vdev.v4l2_dev = v4l2_dev;
qcam->vdev.fops = &qcam_fops;
qcam->vdev.ioctl_ops = &qcam_ioctl_ops;
qcam->vdev.release = video_device_release_empty;
qcam->vdev.ctrl_handler = &qcam->hdl;
set_bit(V4L2_FL_USE_FH_PRIO, &qcam->vdev.flags);
video_set_drvdata(&qcam->vdev, qcam);
mutex_init(&qcam->lock);
qcam->width = qcam->ccd_width = 320;
qcam->height = qcam->ccd_height = 240;
qcam->mode = QC_MILLIONS | QC_DECIMATION_1;
qcam->contrast = 192;
qcam->brightness = 240;
qcam->whitebal = 128;
qcam->top = 1;
qcam->left = 14;
return qcam;
}
static int init_cqcam(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
if (parport[0] != -1) {
/* The user gave specific instructions */
int i, found = 0;
for (i = 0; i < MAX_CAMS && parport[i] != -1; i++) {
if (parport[0] == port->number)
found = 1;
}
if (!found)
return -ENODEV;
}
if (num_cams == MAX_CAMS)
return -ENOSPC;
qcam = qcam_init(port);
if (qcam == NULL)
return -ENODEV;
v4l2_dev = &qcam->v4l2_dev;
parport_claim_or_block(qcam->pdev);
qc_reset(qcam);
if (probe && qc_detect(qcam) == 0) {
parport_release(qcam->pdev);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
qc_setup(qcam);
parport_release(qcam->pdev);
if (video_register_device(&qcam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
v4l2_err(v4l2_dev, "Unable to register Colour QuickCam on %s\n",
qcam->pport->name);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
v4l2_info(v4l2_dev, "%s: Colour QuickCam found on %s\n",
video_device_node_name(&qcam->vdev), qcam->pport->name);
qcams[num_cams++] = qcam;
return 0;
}
static void close_cqcam(struct qcam *qcam)
{
video_unregister_device(&qcam->vdev);
v4l2_ctrl_handler_free(&qcam->hdl);
parport_unregister_device(qcam->pdev);
kfree(qcam);
}
static void cq_attach(struct parport *port)
{
init_cqcam(port);
}
static void cq_detach(struct parport *port)
{
/* Write this some day. */
}
static struct parport_driver cqcam_driver = {
.name = "cqcam",
.attach = cq_attach,
.detach = cq_detach,
};
static int __init cqcam_init(void)
{
printk(KERN_INFO BANNER "\n");
return parport_register_driver(&cqcam_driver);
}
static void __exit cqcam_cleanup(void)
{
unsigned int i;
for (i = 0; i < num_cams; i++)
close_cqcam(qcams[i]);
parport_unregister_driver(&cqcam_driver);
}
MODULE_AUTHOR("Philip Blundell <philb@gnu.org>");
MODULE_DESCRIPTION(BANNER);
MODULE_LICENSE("GPL");
MODULE_VERSION("0.0.4");
module_init(cqcam_init);
module_exit(cqcam_cleanup);
| gpl-2.0 |
lujji/JXD-7800b-JB-kernel | drivers/media/video/gspca/konica.c | 3031 | 16212 | /*
* Driver for USB webcams based on Konica chipset. This
* chipset is used in Intel YC76 camera.
*
* Copyright (C) 2010 Hans de Goede <hdegoede@redhat.com>
*
* Based on the usbvideo v4l1 konicawc driver which is:
*
* Copyright (C) 2002 Simon Evans <spse@secret.org.uk>
*
* The code for making gspca work with a webcam with 2 isoc endpoints was
* taken from the benq gspca subdriver which is:
*
* Copyright (C) 2009 Jean-Francois Moine (http://moinejf.free.fr)
*
* 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
* 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
*/
#define MODULE_NAME "konica"
#include <linux/input.h>
#include "gspca.h"
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_DESCRIPTION("Konica chipset USB Camera Driver");
MODULE_LICENSE("GPL");
#define WHITEBAL_REG 0x01
#define BRIGHTNESS_REG 0x02
#define SHARPNESS_REG 0x03
#define CONTRAST_REG 0x04
#define SATURATION_REG 0x05
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct urb *last_data_urb;
u8 snapshot_pressed;
u8 brightness;
u8 contrast;
u8 saturation;
u8 whitebal;
u8 sharpness;
};
/* V4L2 controls supported by the driver */
static int sd_setbrightness(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getbrightness(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setcontrast(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getcontrast(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setsaturation(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getsaturation(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setwhitebal(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getwhitebal(struct gspca_dev *gspca_dev, __s32 *val);
static int sd_setsharpness(struct gspca_dev *gspca_dev, __s32 val);
static int sd_getsharpness(struct gspca_dev *gspca_dev, __s32 *val);
static const struct ctrl sd_ctrls[] = {
#define SD_BRIGHTNESS 0
{
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 9,
.step = 1,
#define BRIGHTNESS_DEFAULT 4
.default_value = BRIGHTNESS_DEFAULT,
.flags = 0,
},
.set = sd_setbrightness,
.get = sd_getbrightness,
},
#define SD_CONTRAST 1
{
{
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
.maximum = 9,
.step = 4,
#define CONTRAST_DEFAULT 10
.default_value = CONTRAST_DEFAULT,
.flags = 0,
},
.set = sd_setcontrast,
.get = sd_getcontrast,
},
#define SD_SATURATION 2
{
{
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Saturation",
.minimum = 0,
.maximum = 9,
.step = 1,
#define SATURATION_DEFAULT 4
.default_value = SATURATION_DEFAULT,
.flags = 0,
},
.set = sd_setsaturation,
.get = sd_getsaturation,
},
#define SD_WHITEBAL 3
{
{
.id = V4L2_CID_WHITE_BALANCE_TEMPERATURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "White Balance",
.minimum = 0,
.maximum = 33,
.step = 1,
#define WHITEBAL_DEFAULT 25
.default_value = WHITEBAL_DEFAULT,
.flags = 0,
},
.set = sd_setwhitebal,
.get = sd_getwhitebal,
},
#define SD_SHARPNESS 4
{
{
.id = V4L2_CID_SHARPNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Sharpness",
.minimum = 0,
.maximum = 9,
.step = 1,
#define SHARPNESS_DEFAULT 4
.default_value = SHARPNESS_DEFAULT,
.flags = 0,
},
.set = sd_setsharpness,
.get = sd_getsharpness,
},
};
/* .priv is what goes to register 8 for this mode, known working values:
0x00 -> 176x144, cropped
0x01 -> 176x144, cropped
0x02 -> 176x144, cropped
0x03 -> 176x144, cropped
0x04 -> 176x144, binned
0x05 -> 320x240
0x06 -> 320x240
0x07 -> 160x120, cropped
0x08 -> 160x120, cropped
0x09 -> 160x120, binned (note has 136 lines)
0x0a -> 160x120, binned (note has 136 lines)
0x0b -> 160x120, cropped
*/
static const struct v4l2_pix_format vga_mode[] = {
{160, 120, V4L2_PIX_FMT_KONICA420, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 136 * 3 / 2 + 960,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0x0a},
{176, 144, V4L2_PIX_FMT_KONICA420, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 960,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0x04},
{320, 240, V4L2_PIX_FMT_KONICA420, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 2 + 960,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0x05},
};
static void sd_isoc_irq(struct urb *urb);
static void reg_w(struct gspca_dev *gspca_dev, u16 value, u16 index)
{
struct usb_device *dev = gspca_dev->dev;
int ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0x02,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value,
index,
NULL,
0,
1000);
if (ret < 0) {
err("reg_w err %d", ret);
gspca_dev->usb_err = ret;
}
}
static void reg_r(struct gspca_dev *gspca_dev, u16 value, u16 index)
{
struct usb_device *dev = gspca_dev->dev;
int ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
0x03,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value,
index,
gspca_dev->usb_buf,
2,
1000);
if (ret < 0) {
err("reg_w err %d", ret);
gspca_dev->usb_err = ret;
}
}
static void konica_stream_on(struct gspca_dev *gspca_dev)
{
reg_w(gspca_dev, 1, 0x0b);
}
static void konica_stream_off(struct gspca_dev *gspca_dev)
{
reg_w(gspca_dev, 0, 0x0b);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dev->cam.cam_mode = vga_mode;
gspca_dev->cam.nmodes = ARRAY_SIZE(vga_mode);
gspca_dev->cam.no_urb_create = 1;
/* The highest alt setting has an isoc packetsize of 0, so we
don't want to use it */
gspca_dev->nbalt--;
sd->brightness = BRIGHTNESS_DEFAULT;
sd->contrast = CONTRAST_DEFAULT;
sd->saturation = SATURATION_DEFAULT;
sd->whitebal = WHITEBAL_DEFAULT;
sd->sharpness = SHARPNESS_DEFAULT;
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
/* HDG not sure if these 2 reads are needed */
reg_r(gspca_dev, 0, 0x10);
PDEBUG(D_PROBE, "Reg 0x10 reads: %02x %02x",
gspca_dev->usb_buf[0], gspca_dev->usb_buf[1]);
reg_r(gspca_dev, 0, 0x10);
PDEBUG(D_PROBE, "Reg 0x10 reads: %02x %02x",
gspca_dev->usb_buf[0], gspca_dev->usb_buf[1]);
reg_w(gspca_dev, 0, 0x0d);
return 0;
}
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
struct urb *urb;
int i, n, packet_size;
struct usb_host_interface *alt;
struct usb_interface *intf;
intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);
alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);
if (!alt) {
err("Couldn't get altsetting");
return -EIO;
}
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
reg_w(gspca_dev, sd->brightness, BRIGHTNESS_REG);
reg_w(gspca_dev, sd->whitebal, WHITEBAL_REG);
reg_w(gspca_dev, sd->contrast, CONTRAST_REG);
reg_w(gspca_dev, sd->saturation, SATURATION_REG);
reg_w(gspca_dev, sd->sharpness, SHARPNESS_REG);
n = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv;
reg_w(gspca_dev, n, 0x08);
konica_stream_on(gspca_dev);
if (gspca_dev->usb_err)
return gspca_dev->usb_err;
/* create 4 URBs - 2 on endpoint 0x83 and 2 on 0x082 */
#if MAX_NURBS < 4
#error "Not enough URBs in the gspca table"
#endif
#define SD_NPKT 32
for (n = 0; n < 4; n++) {
i = n & 1 ? 0 : 1;
packet_size =
le16_to_cpu(alt->endpoint[i].desc.wMaxPacketSize);
urb = usb_alloc_urb(SD_NPKT, GFP_KERNEL);
if (!urb) {
err("usb_alloc_urb failed");
return -ENOMEM;
}
gspca_dev->urb[n] = urb;
urb->transfer_buffer = usb_alloc_coherent(gspca_dev->dev,
packet_size * SD_NPKT,
GFP_KERNEL,
&urb->transfer_dma);
if (urb->transfer_buffer == NULL) {
err("usb_buffer_alloc failed");
return -ENOMEM;
}
urb->dev = gspca_dev->dev;
urb->context = gspca_dev;
urb->transfer_buffer_length = packet_size * SD_NPKT;
urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
n & 1 ? 0x81 : 0x82);
urb->transfer_flags = URB_ISO_ASAP
| URB_NO_TRANSFER_DMA_MAP;
urb->interval = 1;
urb->complete = sd_isoc_irq;
urb->number_of_packets = SD_NPKT;
for (i = 0; i < SD_NPKT; i++) {
urb->iso_frame_desc[i].length = packet_size;
urb->iso_frame_desc[i].offset = packet_size * i;
}
}
return 0;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
konica_stream_off(gspca_dev);
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
/* Don't keep the button in the pressed state "forever" if it was
pressed when streaming is stopped */
if (sd->snapshot_pressed) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
sd->snapshot_pressed = 0;
}
#endif
}
/* reception of an URB */
static void sd_isoc_irq(struct urb *urb)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
struct sd *sd = (struct sd *) gspca_dev;
struct urb *data_urb, *status_urb;
u8 *data;
int i, st;
PDEBUG(D_PACK, "sd isoc irq");
if (!gspca_dev->streaming)
return;
if (urb->status != 0) {
if (urb->status == -ESHUTDOWN)
return; /* disconnection */
#ifdef CONFIG_PM
if (gspca_dev->frozen)
return;
#endif
PDEBUG(D_ERR, "urb status: %d", urb->status);
st = usb_submit_urb(urb, GFP_ATOMIC);
if (st < 0)
err("resubmit urb error %d", st);
return;
}
/* if this is a data URB (ep 0x82), wait */
if (urb->transfer_buffer_length > 32) {
sd->last_data_urb = urb;
return;
}
status_urb = urb;
data_urb = sd->last_data_urb;
sd->last_data_urb = NULL;
if (!data_urb || data_urb->start_frame != status_urb->start_frame) {
PDEBUG(D_ERR|D_PACK, "lost sync on frames");
goto resubmit;
}
if (data_urb->number_of_packets != status_urb->number_of_packets) {
PDEBUG(D_ERR|D_PACK,
"no packets does not match, data: %d, status: %d",
data_urb->number_of_packets,
status_urb->number_of_packets);
goto resubmit;
}
for (i = 0; i < status_urb->number_of_packets; i++) {
if (data_urb->iso_frame_desc[i].status ||
status_urb->iso_frame_desc[i].status) {
PDEBUG(D_ERR|D_PACK,
"pkt %d data-status %d, status-status %d", i,
data_urb->iso_frame_desc[i].status,
status_urb->iso_frame_desc[i].status);
gspca_dev->last_packet_type = DISCARD_PACKET;
continue;
}
if (status_urb->iso_frame_desc[i].actual_length != 1) {
PDEBUG(D_ERR|D_PACK,
"bad status packet length %d",
status_urb->iso_frame_desc[i].actual_length);
gspca_dev->last_packet_type = DISCARD_PACKET;
continue;
}
st = *((u8 *)status_urb->transfer_buffer
+ status_urb->iso_frame_desc[i].offset);
data = (u8 *)data_urb->transfer_buffer
+ data_urb->iso_frame_desc[i].offset;
/* st: 0x80-0xff: frame start with frame number (ie 0-7f)
* otherwise:
* bit 0 0: keep packet
* 1: drop packet (padding data)
*
* bit 4 0 button not clicked
* 1 button clicked
* button is used to `take a picture' (in software)
*/
if (st & 0x80) {
gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0);
gspca_frame_add(gspca_dev, FIRST_PACKET, NULL, 0);
} else {
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
u8 button_state = st & 0x40 ? 1 : 0;
if (sd->snapshot_pressed != button_state) {
input_report_key(gspca_dev->input_dev,
KEY_CAMERA,
button_state);
input_sync(gspca_dev->input_dev);
sd->snapshot_pressed = button_state;
}
#endif
if (st & 0x01)
continue;
}
gspca_frame_add(gspca_dev, INTER_PACKET, data,
data_urb->iso_frame_desc[i].actual_length);
}
resubmit:
if (data_urb) {
st = usb_submit_urb(data_urb, GFP_ATOMIC);
if (st < 0)
PDEBUG(D_ERR|D_PACK,
"usb_submit_urb(data_urb) ret %d", st);
}
st = usb_submit_urb(status_urb, GFP_ATOMIC);
if (st < 0)
err("usb_submit_urb(status_urb) ret %d", st);
}
static int sd_setbrightness(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->brightness = val;
if (gspca_dev->streaming) {
konica_stream_off(gspca_dev);
reg_w(gspca_dev, sd->brightness, BRIGHTNESS_REG);
konica_stream_on(gspca_dev);
}
return 0;
}
static int sd_getbrightness(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->brightness;
return 0;
}
static int sd_setcontrast(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->contrast = val;
if (gspca_dev->streaming) {
konica_stream_off(gspca_dev);
reg_w(gspca_dev, sd->contrast, CONTRAST_REG);
konica_stream_on(gspca_dev);
}
return 0;
}
static int sd_getcontrast(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->contrast;
return 0;
}
static int sd_setsaturation(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->saturation = val;
if (gspca_dev->streaming) {
konica_stream_off(gspca_dev);
reg_w(gspca_dev, sd->saturation, SATURATION_REG);
konica_stream_on(gspca_dev);
}
return 0;
}
static int sd_getsaturation(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->saturation;
return 0;
}
static int sd_setwhitebal(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->whitebal = val;
if (gspca_dev->streaming) {
konica_stream_off(gspca_dev);
reg_w(gspca_dev, sd->whitebal, WHITEBAL_REG);
konica_stream_on(gspca_dev);
}
return 0;
}
static int sd_getwhitebal(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->whitebal;
return 0;
}
static int sd_setsharpness(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->sharpness = val;
if (gspca_dev->streaming) {
konica_stream_off(gspca_dev);
reg_w(gspca_dev, sd->sharpness, SHARPNESS_REG);
konica_stream_on(gspca_dev);
}
return 0;
}
static int sd_getsharpness(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
*val = sd->sharpness;
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.ctrls = sd_ctrls,
.nctrls = ARRAY_SIZE(sd_ctrls),
.config = sd_config,
.init = sd_init,
.start = sd_start,
.stopN = sd_stopN,
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
.other_input = 1,
#endif
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x04c8, 0x0720)}, /* Intel YC 76 */
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
#endif
};
/* -- module insert / remove -- */
static int __init sd_mod_init(void)
{
return usb_register(&sd_driver);
}
static void __exit sd_mod_exit(void)
{
usb_deregister(&sd_driver);
}
module_init(sd_mod_init);
module_exit(sd_mod_exit);
| gpl-2.0 |
Ander-Alvarez/android_kernel_motorola_msm8226 | arch/mips/alchemy/common/gpiolib.c | 4823 | 5467 | /*
* Copyright (C) 2007-2009, OpenWrt.org, Florian Fainelli <florian@openwrt.org>
* GPIOLIB support for Alchemy chips.
*
* 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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR 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.
*
* 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.
*
* Notes :
* This file must ONLY be built when CONFIG_GPIOLIB=y and
* CONFIG_ALCHEMY_GPIO_INDIRECT=n, otherwise compilation will fail!
* au1000 SoC have only one GPIO block : GPIO1
* Au1100, Au15x0, Au12x0 have a second one : GPIO2
* Au1300 is totally different: 1 block with up to 128 GPIOs
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/gpio.h>
#include <asm/mach-au1x00/gpio-au1000.h>
#include <asm/mach-au1x00/gpio-au1300.h>
static int gpio2_get(struct gpio_chip *chip, unsigned offset)
{
return alchemy_gpio2_get_value(offset + ALCHEMY_GPIO2_BASE);
}
static void gpio2_set(struct gpio_chip *chip, unsigned offset, int value)
{
alchemy_gpio2_set_value(offset + ALCHEMY_GPIO2_BASE, value);
}
static int gpio2_direction_input(struct gpio_chip *chip, unsigned offset)
{
return alchemy_gpio2_direction_input(offset + ALCHEMY_GPIO2_BASE);
}
static int gpio2_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
return alchemy_gpio2_direction_output(offset + ALCHEMY_GPIO2_BASE,
value);
}
static int gpio2_to_irq(struct gpio_chip *chip, unsigned offset)
{
return alchemy_gpio2_to_irq(offset + ALCHEMY_GPIO2_BASE);
}
static int gpio1_get(struct gpio_chip *chip, unsigned offset)
{
return alchemy_gpio1_get_value(offset + ALCHEMY_GPIO1_BASE);
}
static void gpio1_set(struct gpio_chip *chip,
unsigned offset, int value)
{
alchemy_gpio1_set_value(offset + ALCHEMY_GPIO1_BASE, value);
}
static int gpio1_direction_input(struct gpio_chip *chip, unsigned offset)
{
return alchemy_gpio1_direction_input(offset + ALCHEMY_GPIO1_BASE);
}
static int gpio1_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
return alchemy_gpio1_direction_output(offset + ALCHEMY_GPIO1_BASE,
value);
}
static int gpio1_to_irq(struct gpio_chip *chip, unsigned offset)
{
return alchemy_gpio1_to_irq(offset + ALCHEMY_GPIO1_BASE);
}
struct gpio_chip alchemy_gpio_chip[] = {
[0] = {
.label = "alchemy-gpio1",
.direction_input = gpio1_direction_input,
.direction_output = gpio1_direction_output,
.get = gpio1_get,
.set = gpio1_set,
.to_irq = gpio1_to_irq,
.base = ALCHEMY_GPIO1_BASE,
.ngpio = ALCHEMY_GPIO1_NUM,
},
[1] = {
.label = "alchemy-gpio2",
.direction_input = gpio2_direction_input,
.direction_output = gpio2_direction_output,
.get = gpio2_get,
.set = gpio2_set,
.to_irq = gpio2_to_irq,
.base = ALCHEMY_GPIO2_BASE,
.ngpio = ALCHEMY_GPIO2_NUM,
},
};
static int alchemy_gpic_get(struct gpio_chip *chip, unsigned int off)
{
return au1300_gpio_get_value(off + AU1300_GPIO_BASE);
}
static void alchemy_gpic_set(struct gpio_chip *chip, unsigned int off, int v)
{
au1300_gpio_set_value(off + AU1300_GPIO_BASE, v);
}
static int alchemy_gpic_dir_input(struct gpio_chip *chip, unsigned int off)
{
return au1300_gpio_direction_input(off + AU1300_GPIO_BASE);
}
static int alchemy_gpic_dir_output(struct gpio_chip *chip, unsigned int off,
int v)
{
return au1300_gpio_direction_output(off + AU1300_GPIO_BASE, v);
}
static int alchemy_gpic_gpio_to_irq(struct gpio_chip *chip, unsigned int off)
{
return au1300_gpio_to_irq(off + AU1300_GPIO_BASE);
}
static struct gpio_chip au1300_gpiochip = {
.label = "alchemy-gpic",
.direction_input = alchemy_gpic_dir_input,
.direction_output = alchemy_gpic_dir_output,
.get = alchemy_gpic_get,
.set = alchemy_gpic_set,
.to_irq = alchemy_gpic_gpio_to_irq,
.base = AU1300_GPIO_BASE,
.ngpio = AU1300_GPIO_NUM,
};
static int __init alchemy_gpiochip_init(void)
{
int ret = 0;
switch (alchemy_get_cputype()) {
case ALCHEMY_CPU_AU1000:
ret = gpiochip_add(&alchemy_gpio_chip[0]);
break;
case ALCHEMY_CPU_AU1500...ALCHEMY_CPU_AU1200:
ret = gpiochip_add(&alchemy_gpio_chip[0]);
ret |= gpiochip_add(&alchemy_gpio_chip[1]);
break;
case ALCHEMY_CPU_AU1300:
ret = gpiochip_add(&au1300_gpiochip);
break;
}
return ret;
}
arch_initcall(alchemy_gpiochip_init);
| gpl-2.0 |
sohkis/android_kernel_lge_hammerhead | drivers/watchdog/ibmasr.c | 7383 | 9666 | /*
* IBM Automatic Server Restart driver.
*
* Copyright (c) 2005 Andrey Panin <pazke@donpac.ru>
*
* Based on driver written by Pete Reynolds.
* Copyright (c) IBM Corporation, 1998-2004.
*
* This software may be used and distributed according to the terms
* of the GNU Public License, incorporated herein by reference.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/timer.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/dmi.h>
#include <linux/io.h>
#include <linux/uaccess.h>
enum {
ASMTYPE_UNKNOWN,
ASMTYPE_TOPAZ,
ASMTYPE_JASPER,
ASMTYPE_PEARL,
ASMTYPE_JUNIPER,
ASMTYPE_SPRUCE,
};
#define TOPAZ_ASR_REG_OFFSET 4
#define TOPAZ_ASR_TOGGLE 0x40
#define TOPAZ_ASR_DISABLE 0x80
/* PEARL ASR S/W REGISTER SUPERIO PORT ADDRESSES */
#define PEARL_BASE 0xe04
#define PEARL_WRITE 0xe06
#define PEARL_READ 0xe07
#define PEARL_ASR_DISABLE_MASK 0x80 /* bit 7: disable = 1, enable = 0 */
#define PEARL_ASR_TOGGLE_MASK 0x40 /* bit 6: 0, then 1, then 0 */
/* JASPER OFFSET FROM SIO BASE ADDR TO ASR S/W REGISTERS. */
#define JASPER_ASR_REG_OFFSET 0x38
#define JASPER_ASR_DISABLE_MASK 0x01 /* bit 0: disable = 1, enable = 0 */
#define JASPER_ASR_TOGGLE_MASK 0x02 /* bit 1: 0, then 1, then 0 */
#define JUNIPER_BASE_ADDRESS 0x54b /* Base address of Juniper ASR */
#define JUNIPER_ASR_DISABLE_MASK 0x01 /* bit 0: disable = 1 enable = 0 */
#define JUNIPER_ASR_TOGGLE_MASK 0x02 /* bit 1: 0, then 1, then 0 */
#define SPRUCE_BASE_ADDRESS 0x118e /* Base address of Spruce ASR */
#define SPRUCE_ASR_DISABLE_MASK 0x01 /* bit 1: disable = 1 enable = 0 */
#define SPRUCE_ASR_TOGGLE_MASK 0x02 /* bit 0: 0, then 1, then 0 */
static bool nowayout = WATCHDOG_NOWAYOUT;
static unsigned long asr_is_open;
static char asr_expect_close;
static unsigned int asr_type, asr_base, asr_length;
static unsigned int asr_read_addr, asr_write_addr;
static unsigned char asr_toggle_mask, asr_disable_mask;
static DEFINE_SPINLOCK(asr_lock);
static void __asr_toggle(void)
{
unsigned char reg;
reg = inb(asr_read_addr);
outb(reg & ~asr_toggle_mask, asr_write_addr);
reg = inb(asr_read_addr);
outb(reg | asr_toggle_mask, asr_write_addr);
reg = inb(asr_read_addr);
outb(reg & ~asr_toggle_mask, asr_write_addr);
reg = inb(asr_read_addr);
}
static void asr_toggle(void)
{
spin_lock(&asr_lock);
__asr_toggle();
spin_unlock(&asr_lock);
}
static void asr_enable(void)
{
unsigned char reg;
spin_lock(&asr_lock);
if (asr_type == ASMTYPE_TOPAZ) {
/* asr_write_addr == asr_read_addr */
reg = inb(asr_read_addr);
outb(reg & ~(TOPAZ_ASR_TOGGLE | TOPAZ_ASR_DISABLE),
asr_read_addr);
} else {
/*
* First make sure the hardware timer is reset by toggling
* ASR hardware timer line.
*/
__asr_toggle();
reg = inb(asr_read_addr);
outb(reg & ~asr_disable_mask, asr_write_addr);
}
reg = inb(asr_read_addr);
spin_unlock(&asr_lock);
}
static void asr_disable(void)
{
unsigned char reg;
spin_lock(&asr_lock);
reg = inb(asr_read_addr);
if (asr_type == ASMTYPE_TOPAZ)
/* asr_write_addr == asr_read_addr */
outb(reg | TOPAZ_ASR_TOGGLE | TOPAZ_ASR_DISABLE,
asr_read_addr);
else {
outb(reg | asr_toggle_mask, asr_write_addr);
reg = inb(asr_read_addr);
outb(reg | asr_disable_mask, asr_write_addr);
}
reg = inb(asr_read_addr);
spin_unlock(&asr_lock);
}
static int __init asr_get_base_address(void)
{
unsigned char low, high;
const char *type = "";
asr_length = 1;
switch (asr_type) {
case ASMTYPE_TOPAZ:
/* SELECT SuperIO CHIP FOR QUERYING
(WRITE 0x07 TO BOTH 0x2E and 0x2F) */
outb(0x07, 0x2e);
outb(0x07, 0x2f);
/* SELECT AND READ THE HIGH-NIBBLE OF THE GPIO BASE ADDRESS */
outb(0x60, 0x2e);
high = inb(0x2f);
/* SELECT AND READ THE LOW-NIBBLE OF THE GPIO BASE ADDRESS */
outb(0x61, 0x2e);
low = inb(0x2f);
asr_base = (high << 16) | low;
asr_read_addr = asr_write_addr =
asr_base + TOPAZ_ASR_REG_OFFSET;
asr_length = 5;
break;
case ASMTYPE_JASPER:
type = "Jaspers ";
#if 0
u32 r;
/* Suggested fix */
pdev = pci_get_bus_and_slot(0, DEVFN(0x1f, 0));
if (pdev == NULL)
return -ENODEV;
pci_read_config_dword(pdev, 0x58, &r);
asr_base = r & 0xFFFE;
pci_dev_put(pdev);
#else
/* FIXME: need to use pci_config_lock here,
but it's not exported */
/* spin_lock_irqsave(&pci_config_lock, flags);*/
/* Select the SuperIO chip in the PCI I/O port register */
outl(0x8000f858, 0xcf8);
/* BUS 0, Slot 1F, fnc 0, offset 58 */
/*
* Read the base address for the SuperIO chip.
* Only the lower 16 bits are valid, but the address is word
* aligned so the last bit must be masked off.
*/
asr_base = inl(0xcfc) & 0xfffe;
/* spin_unlock_irqrestore(&pci_config_lock, flags);*/
#endif
asr_read_addr = asr_write_addr =
asr_base + JASPER_ASR_REG_OFFSET;
asr_toggle_mask = JASPER_ASR_TOGGLE_MASK;
asr_disable_mask = JASPER_ASR_DISABLE_MASK;
asr_length = JASPER_ASR_REG_OFFSET + 1;
break;
case ASMTYPE_PEARL:
type = "Pearls ";
asr_base = PEARL_BASE;
asr_read_addr = PEARL_READ;
asr_write_addr = PEARL_WRITE;
asr_toggle_mask = PEARL_ASR_TOGGLE_MASK;
asr_disable_mask = PEARL_ASR_DISABLE_MASK;
asr_length = 4;
break;
case ASMTYPE_JUNIPER:
type = "Junipers ";
asr_base = JUNIPER_BASE_ADDRESS;
asr_read_addr = asr_write_addr = asr_base;
asr_toggle_mask = JUNIPER_ASR_TOGGLE_MASK;
asr_disable_mask = JUNIPER_ASR_DISABLE_MASK;
break;
case ASMTYPE_SPRUCE:
type = "Spruce's ";
asr_base = SPRUCE_BASE_ADDRESS;
asr_read_addr = asr_write_addr = asr_base;
asr_toggle_mask = SPRUCE_ASR_TOGGLE_MASK;
asr_disable_mask = SPRUCE_ASR_DISABLE_MASK;
break;
}
if (!request_region(asr_base, asr_length, "ibmasr")) {
pr_err("address %#x already in use\n", asr_base);
return -EBUSY;
}
pr_info("found %sASR @ addr %#x\n", type, asr_base);
return 0;
}
static ssize_t asr_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
if (count) {
if (!nowayout) {
size_t i;
/* In case it was set long ago */
asr_expect_close = 0;
for (i = 0; i != count; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V')
asr_expect_close = 42;
}
}
asr_toggle();
}
return count;
}
static long asr_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
static const struct watchdog_info ident = {
.options = WDIOF_KEEPALIVEPING |
WDIOF_MAGICCLOSE,
.identity = "IBM ASR",
};
void __user *argp = (void __user *)arg;
int __user *p = argp;
int heartbeat;
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_SETOPTIONS:
{
int new_options, retval = -EINVAL;
if (get_user(new_options, p))
return -EFAULT;
if (new_options & WDIOS_DISABLECARD) {
asr_disable();
retval = 0;
}
if (new_options & WDIOS_ENABLECARD) {
asr_enable();
asr_toggle();
retval = 0;
}
return retval;
}
case WDIOC_KEEPALIVE:
asr_toggle();
return 0;
/*
* The hardware has a fixed timeout value, so no WDIOC_SETTIMEOUT
* and WDIOC_GETTIMEOUT always returns 256.
*/
case WDIOC_GETTIMEOUT:
heartbeat = 256;
return put_user(heartbeat, p);
default:
return -ENOTTY;
}
}
static int asr_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &asr_is_open))
return -EBUSY;
asr_toggle();
asr_enable();
return nonseekable_open(inode, file);
}
static int asr_release(struct inode *inode, struct file *file)
{
if (asr_expect_close == 42)
asr_disable();
else {
pr_crit("unexpected close, not stopping watchdog!\n");
asr_toggle();
}
clear_bit(0, &asr_is_open);
asr_expect_close = 0;
return 0;
}
static const struct file_operations asr_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = asr_write,
.unlocked_ioctl = asr_ioctl,
.open = asr_open,
.release = asr_release,
};
static struct miscdevice asr_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &asr_fops,
};
struct ibmasr_id {
const char *desc;
int type;
};
static struct ibmasr_id __initdata ibmasr_id_table[] = {
{ "IBM Automatic Server Restart - eserver xSeries 220", ASMTYPE_TOPAZ },
{ "IBM Automatic Server Restart - Machine Type 8673", ASMTYPE_PEARL },
{ "IBM Automatic Server Restart - Machine Type 8480", ASMTYPE_JASPER },
{ "IBM Automatic Server Restart - Machine Type 8482", ASMTYPE_JUNIPER },
{ "IBM Automatic Server Restart - Machine Type 8648", ASMTYPE_SPRUCE },
{ NULL }
};
static int __init ibmasr_init(void)
{
struct ibmasr_id *id;
int rc;
for (id = ibmasr_id_table; id->desc; id++) {
if (dmi_find_device(DMI_DEV_TYPE_OTHER, id->desc, NULL)) {
asr_type = id->type;
break;
}
}
if (!asr_type)
return -ENODEV;
rc = asr_get_base_address();
if (rc)
return rc;
rc = misc_register(&asr_miscdev);
if (rc < 0) {
release_region(asr_base, asr_length);
pr_err("failed to register misc device\n");
return rc;
}
return 0;
}
static void __exit ibmasr_exit(void)
{
if (!nowayout)
asr_disable();
misc_deregister(&asr_miscdev);
release_region(asr_base, asr_length);
}
module_init(ibmasr_init);
module_exit(ibmasr_exit);
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
MODULE_DESCRIPTION("IBM Automatic Server Restart driver");
MODULE_AUTHOR("Andrey Panin");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
| gpl-2.0 |
MaxiCM/android_kernel_motorola_msm8610 | fs/exportfs/expfs.c | 7383 | 12608 | /*
* Copyright (C) Neil Brown 2002
* Copyright (C) Christoph Hellwig 2007
*
* This file contains the code mapping from inodes to NFS file handles,
* and for mapping back from file handles to dentries.
*
* For details on why we do all the strange and hairy things in here
* take a look at Documentation/filesystems/nfs/Exporting.
*/
#include <linux/exportfs.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/module.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/sched.h>
#define dprintk(fmt, args...) do{}while(0)
static int get_name(struct vfsmount *mnt, struct dentry *dentry, char *name,
struct dentry *child);
static int exportfs_get_name(struct vfsmount *mnt, struct dentry *dir,
char *name, struct dentry *child)
{
const struct export_operations *nop = dir->d_sb->s_export_op;
if (nop->get_name)
return nop->get_name(dir, name, child);
else
return get_name(mnt, dir, name, child);
}
/*
* Check if the dentry or any of it's aliases is acceptable.
*/
static struct dentry *
find_acceptable_alias(struct dentry *result,
int (*acceptable)(void *context, struct dentry *dentry),
void *context)
{
struct dentry *dentry, *toput = NULL;
struct inode *inode;
if (acceptable(context, result))
return result;
inode = result->d_inode;
spin_lock(&inode->i_lock);
list_for_each_entry(dentry, &inode->i_dentry, d_alias) {
dget(dentry);
spin_unlock(&inode->i_lock);
if (toput)
dput(toput);
if (dentry != result && acceptable(context, dentry)) {
dput(result);
return dentry;
}
spin_lock(&inode->i_lock);
toput = dentry;
}
spin_unlock(&inode->i_lock);
if (toput)
dput(toput);
return NULL;
}
/*
* Find root of a disconnected subtree and return a reference to it.
*/
static struct dentry *
find_disconnected_root(struct dentry *dentry)
{
dget(dentry);
while (!IS_ROOT(dentry)) {
struct dentry *parent = dget_parent(dentry);
if (!(parent->d_flags & DCACHE_DISCONNECTED)) {
dput(parent);
break;
}
dput(dentry);
dentry = parent;
}
return dentry;
}
/*
* Make sure target_dir is fully connected to the dentry tree.
*
* It may already be, as the flag isn't always updated when connection happens.
*/
static int
reconnect_path(struct vfsmount *mnt, struct dentry *target_dir, char *nbuf)
{
int noprogress = 0;
int err = -ESTALE;
/*
* It is possible that a confused file system might not let us complete
* the path to the root. For example, if get_parent returns a directory
* in which we cannot find a name for the child. While this implies a
* very sick filesystem we don't want it to cause knfsd to spin. Hence
* the noprogress counter. If we go through the loop 10 times (2 is
* probably enough) without getting anywhere, we just give up
*/
while (target_dir->d_flags & DCACHE_DISCONNECTED && noprogress++ < 10) {
struct dentry *pd = find_disconnected_root(target_dir);
if (!IS_ROOT(pd)) {
/* must have found a connected parent - great */
spin_lock(&pd->d_lock);
pd->d_flags &= ~DCACHE_DISCONNECTED;
spin_unlock(&pd->d_lock);
noprogress = 0;
} else if (pd == mnt->mnt_sb->s_root) {
printk(KERN_ERR "export: Eeek filesystem root is not connected, impossible\n");
spin_lock(&pd->d_lock);
pd->d_flags &= ~DCACHE_DISCONNECTED;
spin_unlock(&pd->d_lock);
noprogress = 0;
} else {
/*
* We have hit the top of a disconnected path, try to
* find parent and connect.
*
* Racing with some other process renaming a directory
* isn't much of a problem here. If someone renames
* the directory, it will end up properly connected,
* which is what we want
*
* Getting the parent can't be supported generically,
* the locking is too icky.
*
* Instead we just return EACCES. If server reboots
* or inodes get flushed, you lose
*/
struct dentry *ppd = ERR_PTR(-EACCES);
struct dentry *npd;
mutex_lock(&pd->d_inode->i_mutex);
if (mnt->mnt_sb->s_export_op->get_parent)
ppd = mnt->mnt_sb->s_export_op->get_parent(pd);
mutex_unlock(&pd->d_inode->i_mutex);
if (IS_ERR(ppd)) {
err = PTR_ERR(ppd);
dprintk("%s: get_parent of %ld failed, err %d\n",
__func__, pd->d_inode->i_ino, err);
dput(pd);
break;
}
dprintk("%s: find name of %lu in %lu\n", __func__,
pd->d_inode->i_ino, ppd->d_inode->i_ino);
err = exportfs_get_name(mnt, ppd, nbuf, pd);
if (err) {
dput(ppd);
dput(pd);
if (err == -ENOENT)
/* some race between get_parent and
* get_name? just try again
*/
continue;
break;
}
dprintk("%s: found name: %s\n", __func__, nbuf);
mutex_lock(&ppd->d_inode->i_mutex);
npd = lookup_one_len(nbuf, ppd, strlen(nbuf));
mutex_unlock(&ppd->d_inode->i_mutex);
if (IS_ERR(npd)) {
err = PTR_ERR(npd);
dprintk("%s: lookup failed: %d\n",
__func__, err);
dput(ppd);
dput(pd);
break;
}
/* we didn't really want npd, we really wanted
* a side-effect of the lookup.
* hopefully, npd == pd, though it isn't really
* a problem if it isn't
*/
if (npd == pd)
noprogress = 0;
else
printk("%s: npd != pd\n", __func__);
dput(npd);
dput(ppd);
if (IS_ROOT(pd)) {
/* something went wrong, we have to give up */
dput(pd);
break;
}
}
dput(pd);
}
if (target_dir->d_flags & DCACHE_DISCONNECTED) {
/* something went wrong - oh-well */
if (!err)
err = -ESTALE;
return err;
}
return 0;
}
struct getdents_callback {
char *name; /* name that was found. It already points to a
buffer NAME_MAX+1 is size */
unsigned long ino; /* the inum we are looking for */
int found; /* inode matched? */
int sequence; /* sequence counter */
};
/*
* A rather strange filldir function to capture
* the name matching the specified inode number.
*/
static int filldir_one(void * __buf, const char * name, int len,
loff_t pos, u64 ino, unsigned int d_type)
{
struct getdents_callback *buf = __buf;
int result = 0;
buf->sequence++;
if (buf->ino == ino) {
memcpy(buf->name, name, len);
buf->name[len] = '\0';
buf->found = 1;
result = -1;
}
return result;
}
/**
* get_name - default export_operations->get_name function
* @dentry: the directory in which to find a name
* @name: a pointer to a %NAME_MAX+1 char buffer to store the name
* @child: the dentry for the child directory.
*
* calls readdir on the parent until it finds an entry with
* the same inode number as the child, and returns that.
*/
static int get_name(struct vfsmount *mnt, struct dentry *dentry,
char *name, struct dentry *child)
{
const struct cred *cred = current_cred();
struct inode *dir = dentry->d_inode;
int error;
struct file *file;
struct getdents_callback buffer;
error = -ENOTDIR;
if (!dir || !S_ISDIR(dir->i_mode))
goto out;
error = -EINVAL;
if (!dir->i_fop)
goto out;
/*
* Open the directory ...
*/
file = dentry_open(dget(dentry), mntget(mnt), O_RDONLY, cred);
error = PTR_ERR(file);
if (IS_ERR(file))
goto out;
error = -EINVAL;
if (!file->f_op->readdir)
goto out_close;
buffer.name = name;
buffer.ino = child->d_inode->i_ino;
buffer.found = 0;
buffer.sequence = 0;
while (1) {
int old_seq = buffer.sequence;
error = vfs_readdir(file, filldir_one, &buffer);
if (buffer.found) {
error = 0;
break;
}
if (error < 0)
break;
error = -ENOENT;
if (old_seq == buffer.sequence)
break;
}
out_close:
fput(file);
out:
return error;
}
/**
* export_encode_fh - default export_operations->encode_fh function
* @dentry: the dentry to encode
* @fh: where to store the file handle fragment
* @max_len: maximum length to store there
* @connectable: whether to store parent information
*
* This default encode_fh function assumes that the 32 inode number
* is suitable for locating an inode, and that the generation number
* can be used to check that it is still valid. It places them in the
* filehandle fragment where export_decode_fh expects to find them.
*/
static int export_encode_fh(struct dentry *dentry, struct fid *fid,
int *max_len, int connectable)
{
struct inode * inode = dentry->d_inode;
int len = *max_len;
int type = FILEID_INO32_GEN;
if (connectable && (len < 4)) {
*max_len = 4;
return 255;
} else if (len < 2) {
*max_len = 2;
return 255;
}
len = 2;
fid->i32.ino = inode->i_ino;
fid->i32.gen = inode->i_generation;
if (connectable && !S_ISDIR(inode->i_mode)) {
struct inode *parent;
spin_lock(&dentry->d_lock);
parent = dentry->d_parent->d_inode;
fid->i32.parent_ino = parent->i_ino;
fid->i32.parent_gen = parent->i_generation;
spin_unlock(&dentry->d_lock);
len = 4;
type = FILEID_INO32_GEN_PARENT;
}
*max_len = len;
return type;
}
int exportfs_encode_fh(struct dentry *dentry, struct fid *fid, int *max_len,
int connectable)
{
const struct export_operations *nop = dentry->d_sb->s_export_op;
int error;
if (nop->encode_fh)
error = nop->encode_fh(dentry, fid->raw, max_len, connectable);
else
error = export_encode_fh(dentry, fid, max_len, connectable);
return error;
}
EXPORT_SYMBOL_GPL(exportfs_encode_fh);
struct dentry *exportfs_decode_fh(struct vfsmount *mnt, struct fid *fid,
int fh_len, int fileid_type,
int (*acceptable)(void *, struct dentry *), void *context)
{
const struct export_operations *nop = mnt->mnt_sb->s_export_op;
struct dentry *result, *alias;
char nbuf[NAME_MAX+1];
int err;
/*
* Try to get any dentry for the given file handle from the filesystem.
*/
if (!nop || !nop->fh_to_dentry)
return ERR_PTR(-ESTALE);
result = nop->fh_to_dentry(mnt->mnt_sb, fid, fh_len, fileid_type);
if (!result)
result = ERR_PTR(-ESTALE);
if (IS_ERR(result))
return result;
if (S_ISDIR(result->d_inode->i_mode)) {
/*
* This request is for a directory.
*
* On the positive side there is only one dentry for each
* directory inode. On the negative side this implies that we
* to ensure our dentry is connected all the way up to the
* filesystem root.
*/
if (result->d_flags & DCACHE_DISCONNECTED) {
err = reconnect_path(mnt, result, nbuf);
if (err)
goto err_result;
}
if (!acceptable(context, result)) {
err = -EACCES;
goto err_result;
}
return result;
} else {
/*
* It's not a directory. Life is a little more complicated.
*/
struct dentry *target_dir, *nresult;
/*
* See if either the dentry we just got from the filesystem
* or any alias for it is acceptable. This is always true
* if this filesystem is exported without the subtreecheck
* option. If the filesystem is exported with the subtree
* check option there's a fair chance we need to look at
* the parent directory in the file handle and make sure
* it's connected to the filesystem root.
*/
alias = find_acceptable_alias(result, acceptable, context);
if (alias)
return alias;
/*
* Try to extract a dentry for the parent directory from the
* file handle. If this fails we'll have to give up.
*/
err = -ESTALE;
if (!nop->fh_to_parent)
goto err_result;
target_dir = nop->fh_to_parent(mnt->mnt_sb, fid,
fh_len, fileid_type);
if (!target_dir)
goto err_result;
err = PTR_ERR(target_dir);
if (IS_ERR(target_dir))
goto err_result;
/*
* And as usual we need to make sure the parent directory is
* connected to the filesystem root. The VFS really doesn't
* like disconnected directories..
*/
err = reconnect_path(mnt, target_dir, nbuf);
if (err) {
dput(target_dir);
goto err_result;
}
/*
* Now that we've got both a well-connected parent and a
* dentry for the inode we're after, make sure that our
* inode is actually connected to the parent.
*/
err = exportfs_get_name(mnt, target_dir, nbuf, result);
if (!err) {
mutex_lock(&target_dir->d_inode->i_mutex);
nresult = lookup_one_len(nbuf, target_dir,
strlen(nbuf));
mutex_unlock(&target_dir->d_inode->i_mutex);
if (!IS_ERR(nresult)) {
if (nresult->d_inode) {
dput(result);
result = nresult;
} else
dput(nresult);
}
}
/*
* At this point we are done with the parent, but it's pinned
* by the child dentry anyway.
*/
dput(target_dir);
/*
* And finally make sure the dentry is actually acceptable
* to NFSD.
*/
alias = find_acceptable_alias(result, acceptable, context);
if (!alias) {
err = -EACCES;
goto err_result;
}
return alias;
}
err_result:
dput(result);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(exportfs_decode_fh);
MODULE_LICENSE("GPL");
| gpl-2.0 |
PlatinumMaster/SM-G360T1_kernel | arch/x86/xen/trace.c | 8919 | 1153 | #include <linux/ftrace.h>
#include <xen/interface/xen.h>
#define N(x) [__HYPERVISOR_##x] = "("#x")"
static const char *xen_hypercall_names[] = {
N(set_trap_table),
N(mmu_update),
N(set_gdt),
N(stack_switch),
N(set_callbacks),
N(fpu_taskswitch),
N(sched_op_compat),
N(dom0_op),
N(set_debugreg),
N(get_debugreg),
N(update_descriptor),
N(memory_op),
N(multicall),
N(update_va_mapping),
N(set_timer_op),
N(event_channel_op_compat),
N(xen_version),
N(console_io),
N(physdev_op_compat),
N(grant_table_op),
N(vm_assist),
N(update_va_mapping_otherdomain),
N(iret),
N(vcpu_op),
N(set_segment_base),
N(mmuext_op),
N(acm_op),
N(nmi_op),
N(sched_op),
N(callback_op),
N(xenoprof_op),
N(event_channel_op),
N(physdev_op),
N(hvm_op),
/* Architecture-specific hypercall definitions. */
N(arch_0),
N(arch_1),
N(arch_2),
N(arch_3),
N(arch_4),
N(arch_5),
N(arch_6),
N(arch_7),
};
#undef N
static const char *xen_hypercall_name(unsigned op)
{
if (op < ARRAY_SIZE(xen_hypercall_names) && xen_hypercall_names[op] != NULL)
return xen_hypercall_names[op];
return "";
}
#define CREATE_TRACE_POINTS
#include <trace/events/xen.h>
| gpl-2.0 |
beats4x/kernel_lge_g3-v10m | arch/powerpc/math-emu/math.c | 11479 | 12176 | /*
* Copyright (C) 1999 Eddie C. Dost (ecd@atecom.com)
*/
#include <linux/types.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include <asm/reg.h>
#include <asm/sfp-machine.h>
#include <math-emu/double.h>
#define FLOATFUNC(x) extern int x(void *, void *, void *, void *)
FLOATFUNC(fadd);
FLOATFUNC(fadds);
FLOATFUNC(fdiv);
FLOATFUNC(fdivs);
FLOATFUNC(fmul);
FLOATFUNC(fmuls);
FLOATFUNC(fsub);
FLOATFUNC(fsubs);
FLOATFUNC(fmadd);
FLOATFUNC(fmadds);
FLOATFUNC(fmsub);
FLOATFUNC(fmsubs);
FLOATFUNC(fnmadd);
FLOATFUNC(fnmadds);
FLOATFUNC(fnmsub);
FLOATFUNC(fnmsubs);
FLOATFUNC(fctiw);
FLOATFUNC(fctiwz);
FLOATFUNC(frsp);
FLOATFUNC(fcmpo);
FLOATFUNC(fcmpu);
FLOATFUNC(mcrfs);
FLOATFUNC(mffs);
FLOATFUNC(mtfsb0);
FLOATFUNC(mtfsb1);
FLOATFUNC(mtfsf);
FLOATFUNC(mtfsfi);
FLOATFUNC(lfd);
FLOATFUNC(lfs);
FLOATFUNC(stfd);
FLOATFUNC(stfs);
FLOATFUNC(stfiwx);
FLOATFUNC(fabs);
FLOATFUNC(fmr);
FLOATFUNC(fnabs);
FLOATFUNC(fneg);
/* Optional */
FLOATFUNC(fres);
FLOATFUNC(frsqrte);
FLOATFUNC(fsel);
FLOATFUNC(fsqrt);
FLOATFUNC(fsqrts);
#define OP31 0x1f /* 31 */
#define LFS 0x30 /* 48 */
#define LFSU 0x31 /* 49 */
#define LFD 0x32 /* 50 */
#define LFDU 0x33 /* 51 */
#define STFS 0x34 /* 52 */
#define STFSU 0x35 /* 53 */
#define STFD 0x36 /* 54 */
#define STFDU 0x37 /* 55 */
#define OP59 0x3b /* 59 */
#define OP63 0x3f /* 63 */
/* Opcode 31: */
/* X-Form: */
#define LFSX 0x217 /* 535 */
#define LFSUX 0x237 /* 567 */
#define LFDX 0x257 /* 599 */
#define LFDUX 0x277 /* 631 */
#define STFSX 0x297 /* 663 */
#define STFSUX 0x2b7 /* 695 */
#define STFDX 0x2d7 /* 727 */
#define STFDUX 0x2f7 /* 759 */
#define STFIWX 0x3d7 /* 983 */
/* Opcode 59: */
/* A-Form: */
#define FDIVS 0x012 /* 18 */
#define FSUBS 0x014 /* 20 */
#define FADDS 0x015 /* 21 */
#define FSQRTS 0x016 /* 22 */
#define FRES 0x018 /* 24 */
#define FMULS 0x019 /* 25 */
#define FMSUBS 0x01c /* 28 */
#define FMADDS 0x01d /* 29 */
#define FNMSUBS 0x01e /* 30 */
#define FNMADDS 0x01f /* 31 */
/* Opcode 63: */
/* A-Form: */
#define FDIV 0x012 /* 18 */
#define FSUB 0x014 /* 20 */
#define FADD 0x015 /* 21 */
#define FSQRT 0x016 /* 22 */
#define FSEL 0x017 /* 23 */
#define FMUL 0x019 /* 25 */
#define FRSQRTE 0x01a /* 26 */
#define FMSUB 0x01c /* 28 */
#define FMADD 0x01d /* 29 */
#define FNMSUB 0x01e /* 30 */
#define FNMADD 0x01f /* 31 */
/* X-Form: */
#define FCMPU 0x000 /* 0 */
#define FRSP 0x00c /* 12 */
#define FCTIW 0x00e /* 14 */
#define FCTIWZ 0x00f /* 15 */
#define FCMPO 0x020 /* 32 */
#define MTFSB1 0x026 /* 38 */
#define FNEG 0x028 /* 40 */
#define MCRFS 0x040 /* 64 */
#define MTFSB0 0x046 /* 70 */
#define FMR 0x048 /* 72 */
#define MTFSFI 0x086 /* 134 */
#define FNABS 0x088 /* 136 */
#define FABS 0x108 /* 264 */
#define MFFS 0x247 /* 583 */
#define MTFSF 0x2c7 /* 711 */
#define AB 2
#define AC 3
#define ABC 4
#define D 5
#define DU 6
#define X 7
#define XA 8
#define XB 9
#define XCR 11
#define XCRB 12
#define XCRI 13
#define XCRL 16
#define XE 14
#define XEU 15
#define XFLB 10
#ifdef CONFIG_MATH_EMULATION
static int
record_exception(struct pt_regs *regs, int eflag)
{
u32 fpscr;
fpscr = __FPU_FPSCR;
if (eflag) {
fpscr |= FPSCR_FX;
if (eflag & EFLAG_OVERFLOW)
fpscr |= FPSCR_OX;
if (eflag & EFLAG_UNDERFLOW)
fpscr |= FPSCR_UX;
if (eflag & EFLAG_DIVZERO)
fpscr |= FPSCR_ZX;
if (eflag & EFLAG_INEXACT)
fpscr |= FPSCR_XX;
if (eflag & EFLAG_INVALID)
fpscr |= FPSCR_VX;
if (eflag & EFLAG_VXSNAN)
fpscr |= FPSCR_VXSNAN;
if (eflag & EFLAG_VXISI)
fpscr |= FPSCR_VXISI;
if (eflag & EFLAG_VXIDI)
fpscr |= FPSCR_VXIDI;
if (eflag & EFLAG_VXZDZ)
fpscr |= FPSCR_VXZDZ;
if (eflag & EFLAG_VXIMZ)
fpscr |= FPSCR_VXIMZ;
if (eflag & EFLAG_VXVC)
fpscr |= FPSCR_VXVC;
if (eflag & EFLAG_VXSOFT)
fpscr |= FPSCR_VXSOFT;
if (eflag & EFLAG_VXSQRT)
fpscr |= FPSCR_VXSQRT;
if (eflag & EFLAG_VXCVI)
fpscr |= FPSCR_VXCVI;
}
// fpscr &= ~(FPSCR_VX);
if (fpscr & (FPSCR_VXSNAN | FPSCR_VXISI | FPSCR_VXIDI |
FPSCR_VXZDZ | FPSCR_VXIMZ | FPSCR_VXVC |
FPSCR_VXSOFT | FPSCR_VXSQRT | FPSCR_VXCVI))
fpscr |= FPSCR_VX;
fpscr &= ~(FPSCR_FEX);
if (((fpscr & FPSCR_VX) && (fpscr & FPSCR_VE)) ||
((fpscr & FPSCR_OX) && (fpscr & FPSCR_OE)) ||
((fpscr & FPSCR_UX) && (fpscr & FPSCR_UE)) ||
((fpscr & FPSCR_ZX) && (fpscr & FPSCR_ZE)) ||
((fpscr & FPSCR_XX) && (fpscr & FPSCR_XE)))
fpscr |= FPSCR_FEX;
__FPU_FPSCR = fpscr;
return (fpscr & FPSCR_FEX) ? 1 : 0;
}
#endif /* CONFIG_MATH_EMULATION */
int
do_mathemu(struct pt_regs *regs)
{
void *op0 = 0, *op1 = 0, *op2 = 0, *op3 = 0;
unsigned long pc = regs->nip;
signed short sdisp;
u32 insn = 0;
int idx = 0;
#ifdef CONFIG_MATH_EMULATION
int (*func)(void *, void *, void *, void *);
int type = 0;
int eflag, trap;
#endif
if (get_user(insn, (u32 *)pc))
return -EFAULT;
#ifndef CONFIG_MATH_EMULATION
switch (insn >> 26) {
case LFD:
idx = (insn >> 16) & 0x1f;
sdisp = (insn & 0xffff);
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp);
lfd(op0, op1, op2, op3);
break;
case LFDU:
idx = (insn >> 16) & 0x1f;
sdisp = (insn & 0xffff);
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp);
lfd(op0, op1, op2, op3);
regs->gpr[idx] = (unsigned long)op1;
break;
case STFD:
idx = (insn >> 16) & 0x1f;
sdisp = (insn & 0xffff);
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp);
stfd(op0, op1, op2, op3);
break;
case STFDU:
idx = (insn >> 16) & 0x1f;
sdisp = (insn & 0xffff);
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp);
stfd(op0, op1, op2, op3);
regs->gpr[idx] = (unsigned long)op1;
break;
case OP63:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)¤t->thread.TS_FPR((insn >> 11) & 0x1f);
fmr(op0, op1, op2, op3);
break;
default:
goto illegal;
}
#else /* CONFIG_MATH_EMULATION */
switch (insn >> 26) {
case LFS: func = lfs; type = D; break;
case LFSU: func = lfs; type = DU; break;
case LFD: func = lfd; type = D; break;
case LFDU: func = lfd; type = DU; break;
case STFS: func = stfs; type = D; break;
case STFSU: func = stfs; type = DU; break;
case STFD: func = stfd; type = D; break;
case STFDU: func = stfd; type = DU; break;
case OP31:
switch ((insn >> 1) & 0x3ff) {
case LFSX: func = lfs; type = XE; break;
case LFSUX: func = lfs; type = XEU; break;
case LFDX: func = lfd; type = XE; break;
case LFDUX: func = lfd; type = XEU; break;
case STFSX: func = stfs; type = XE; break;
case STFSUX: func = stfs; type = XEU; break;
case STFDX: func = stfd; type = XE; break;
case STFDUX: func = stfd; type = XEU; break;
case STFIWX: func = stfiwx; type = XE; break;
default:
goto illegal;
}
break;
case OP59:
switch ((insn >> 1) & 0x1f) {
case FDIVS: func = fdivs; type = AB; break;
case FSUBS: func = fsubs; type = AB; break;
case FADDS: func = fadds; type = AB; break;
case FSQRTS: func = fsqrts; type = AB; break;
case FRES: func = fres; type = AB; break;
case FMULS: func = fmuls; type = AC; break;
case FMSUBS: func = fmsubs; type = ABC; break;
case FMADDS: func = fmadds; type = ABC; break;
case FNMSUBS: func = fnmsubs; type = ABC; break;
case FNMADDS: func = fnmadds; type = ABC; break;
default:
goto illegal;
}
break;
case OP63:
if (insn & 0x20) {
switch ((insn >> 1) & 0x1f) {
case FDIV: func = fdiv; type = AB; break;
case FSUB: func = fsub; type = AB; break;
case FADD: func = fadd; type = AB; break;
case FSQRT: func = fsqrt; type = AB; break;
case FSEL: func = fsel; type = ABC; break;
case FMUL: func = fmul; type = AC; break;
case FRSQRTE: func = frsqrte; type = AB; break;
case FMSUB: func = fmsub; type = ABC; break;
case FMADD: func = fmadd; type = ABC; break;
case FNMSUB: func = fnmsub; type = ABC; break;
case FNMADD: func = fnmadd; type = ABC; break;
default:
goto illegal;
}
break;
}
switch ((insn >> 1) & 0x3ff) {
case FCMPU: func = fcmpu; type = XCR; break;
case FRSP: func = frsp; type = XB; break;
case FCTIW: func = fctiw; type = XB; break;
case FCTIWZ: func = fctiwz; type = XB; break;
case FCMPO: func = fcmpo; type = XCR; break;
case MTFSB1: func = mtfsb1; type = XCRB; break;
case FNEG: func = fneg; type = XB; break;
case MCRFS: func = mcrfs; type = XCRL; break;
case MTFSB0: func = mtfsb0; type = XCRB; break;
case FMR: func = fmr; type = XB; break;
case MTFSFI: func = mtfsfi; type = XCRI; break;
case FNABS: func = fnabs; type = XB; break;
case FABS: func = fabs; type = XB; break;
case MFFS: func = mffs; type = X; break;
case MTFSF: func = mtfsf; type = XFLB; break;
default:
goto illegal;
}
break;
default:
goto illegal;
}
switch (type) {
case AB:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)¤t->thread.TS_FPR((insn >> 16) & 0x1f);
op2 = (void *)¤t->thread.TS_FPR((insn >> 11) & 0x1f);
break;
case AC:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)¤t->thread.TS_FPR((insn >> 16) & 0x1f);
op2 = (void *)¤t->thread.TS_FPR((insn >> 6) & 0x1f);
break;
case ABC:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)¤t->thread.TS_FPR((insn >> 16) & 0x1f);
op2 = (void *)¤t->thread.TS_FPR((insn >> 11) & 0x1f);
op3 = (void *)¤t->thread.TS_FPR((insn >> 6) & 0x1f);
break;
case D:
idx = (insn >> 16) & 0x1f;
sdisp = (insn & 0xffff);
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)((idx ? regs->gpr[idx] : 0) + sdisp);
break;
case DU:
idx = (insn >> 16) & 0x1f;
if (!idx)
goto illegal;
sdisp = (insn & 0xffff);
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)(regs->gpr[idx] + sdisp);
break;
case X:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
break;
case XA:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)¤t->thread.TS_FPR((insn >> 16) & 0x1f);
break;
case XB:
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)¤t->thread.TS_FPR((insn >> 11) & 0x1f);
break;
case XE:
idx = (insn >> 16) & 0x1f;
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
if (!idx) {
if (((insn >> 1) & 0x3ff) == STFIWX)
op1 = (void *)(regs->gpr[(insn >> 11) & 0x1f]);
else
goto illegal;
} else {
op1 = (void *)(regs->gpr[idx] + regs->gpr[(insn >> 11) & 0x1f]);
}
break;
case XEU:
idx = (insn >> 16) & 0x1f;
op0 = (void *)¤t->thread.TS_FPR((insn >> 21) & 0x1f);
op1 = (void *)((idx ? regs->gpr[idx] : 0)
+ regs->gpr[(insn >> 11) & 0x1f]);
break;
case XCR:
op0 = (void *)®s->ccr;
op1 = (void *)((insn >> 23) & 0x7);
op2 = (void *)¤t->thread.TS_FPR((insn >> 16) & 0x1f);
op3 = (void *)¤t->thread.TS_FPR((insn >> 11) & 0x1f);
break;
case XCRL:
op0 = (void *)®s->ccr;
op1 = (void *)((insn >> 23) & 0x7);
op2 = (void *)((insn >> 18) & 0x7);
break;
case XCRB:
op0 = (void *)((insn >> 21) & 0x1f);
break;
case XCRI:
op0 = (void *)((insn >> 23) & 0x7);
op1 = (void *)((insn >> 12) & 0xf);
break;
case XFLB:
op0 = (void *)((insn >> 17) & 0xff);
op1 = (void *)¤t->thread.TS_FPR((insn >> 11) & 0x1f);
break;
default:
goto illegal;
}
eflag = func(op0, op1, op2, op3);
if (insn & 1) {
regs->ccr &= ~(0x0f000000);
regs->ccr |= (__FPU_FPSCR >> 4) & 0x0f000000;
}
trap = record_exception(regs, eflag);
if (trap)
return 1;
switch (type) {
case DU:
case XEU:
regs->gpr[idx] = (unsigned long)op1;
break;
default:
break;
}
#endif /* CONFIG_MATH_EMULATION */
regs->nip += 4;
return 0;
illegal:
return -ENOSYS;
}
| gpl-2.0 |
wanghao-xznu/vte | openlibs/binutils-2.19.51.0.12/gprof/tahoe.c | 216 | 9171 | /*
* Copyright (c) 1983, 1993, 2001
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "gprof.h"
#include "search_list.h"
#include "source.h"
#include "symtab.h"
#include "cg_arcs.h"
#include "corefile.h"
#include "hist.h"
/*
* opcode of the `callf' instruction
*/
#define CALLF 0xfe
/*
* register for pc relative addressing
*/
#define PC 0xf
enum tahoe_opermodes
{
literal, indexed, reg, regdef, autodec, autoinc, autoincdef,
bytedisp, bytedispdef, worddisp, worddispdef, longdisp, longdispdef,
immediate, absolute, byterel, bytereldef, wordrel, wordreldef,
longrel, longreldef
};
typedef enum tahoe_opermodes tahoe_operandenum;
/*
* A symbol to be the child of indirect callf:
*/
static Sym indirectchild;
static tahoe_operandenum tahoe_operandmode (unsigned char *);
static char *tahoe_operandname (tahoe_operandenum);
static long tahoe_operandlength (unsigned char *);
static bfd_signed_vma tahoe_offset (unsigned char *);
void tahoe_find_call (Sym *, bfd_vma, bfd_vma);
static tahoe_operandenum
tahoe_operandmode (unsigned char *modep)
{
long usesreg = *modep & 0xf;
switch ((*modep >> 4) & 0xf)
{
case 0:
case 1:
case 2:
case 3:
return literal;
case 4:
return indexed;
case 5:
return reg;
case 6:
return regdef;
case 7:
return autodec;
case 8:
return usesreg != 0xe ? autoinc : immediate;
case 9:
return usesreg != PC ? autoincdef : absolute;
case 10:
return usesreg != PC ? bytedisp : byterel;
case 11:
return usesreg != PC ? bytedispdef : bytereldef;
case 12:
return usesreg != PC ? worddisp : wordrel;
case 13:
return usesreg != PC ? worddispdef : wordreldef;
case 14:
return usesreg != PC ? longdisp : longrel;
case 15:
return usesreg != PC ? longdispdef : longreldef;
}
/* NOTREACHED */
abort ();
}
static char *
tahoe_operandname (tahoe_operandenum mode)
{
switch (mode)
{
case literal:
return "literal";
case indexed:
return "indexed";
case reg:
return "register";
case regdef:
return "register deferred";
case autodec:
return "autodecrement";
case autoinc:
return "autoincrement";
case autoincdef:
return "autoincrement deferred";
case bytedisp:
return "byte displacement";
case bytedispdef:
return "byte displacement deferred";
case byterel:
return "byte relative";
case bytereldef:
return "byte relative deferred";
case worddisp:
return "word displacement";
case worddispdef:
return "word displacement deferred";
case wordrel:
return "word relative";
case wordreldef:
return "word relative deferred";
case immediate:
return "immediate";
case absolute:
return "absolute";
case longdisp:
return "long displacement";
case longdispdef:
return "long displacement deferred";
case longrel:
return "long relative";
case longreldef:
return "long relative deferred";
}
/* NOTREACHED */
abort ();
}
static long
tahoe_operandlength (unsigned char *modep
)
{
switch (tahoe_operandmode (modep))
{
case literal:
case reg:
case regdef:
case autodec:
case autoinc:
case autoincdef:
return 1;
case bytedisp:
case bytedispdef:
case byterel:
case bytereldef:
return 2;
case worddisp:
case worddispdef:
case wordrel:
case wordreldef:
return 3;
case immediate:
case absolute:
case longdisp:
case longdispdef:
case longrel:
case longreldef:
return 5;
case indexed:
return 1 + tahoe_operandlength (modep + 1);
}
/* NOTREACHED */
abort ();
}
static bfd_signed_vma
tahoe_offset (unsigned char *modep)
{
tahoe_operandenum mode = tahoe_operandmode (modep);
++modep; /* skip over the mode */
switch (mode)
{
default:
fprintf (stderr, "[reladdr] not relative address\n");
return 0;
case byterel:
return 1 + bfd_get_signed_8 (core_bfd, modep);
case wordrel:
return 2 + bfd_get_signed_16 (core_bfd, modep);
case longrel:
return 4 + bfd_get_signed_32 (core_bfd, modep);
}
}
void
tahoe_find_call (Sym *parent, bfd_vma p_lowpc, bfd_vma p_highpc)
{
unsigned char *instructp;
long length;
Sym *child;
tahoe_operandenum mode;
tahoe_operandenum firstmode;
bfd_vma pc, destpc;
static bfd_boolean inited = FALSE;
if (!inited)
{
inited = TRUE;
sym_init (&indirectchild);
indirectchild.cg.prop.fract = 1.0;
indirectchild.cg.cyc.head = &indirectchild;
}
DBG (CALLDEBUG, printf ("[findcall] %s: 0x%lx to 0x%lx\n",
parent->name, (unsigned long) p_lowpc,
(unsigned long) p_highpc));
for (pc = p_lowpc; pc < p_highpc; pc += length)
{
length = 1;
instructp = ((unsigned char *) core_text_space
+ pc - core_text_sect->vma);
if ((*instructp & 0xff) == CALLF)
{
/*
* maybe a callf, better check it out.
* skip the count of the number of arguments.
*/
DBG (CALLDEBUG, printf ("[findcall]\t0x%lx:callf",
(unsigned long) pc));
firstmode = tahoe_operandmode (instructp + length);
switch (firstmode)
{
case literal:
case immediate:
break;
default:
goto botched;
}
length += tahoe_operandlength (instructp + length);
mode = tahoe_operandmode (instructp + length);
DBG (CALLDEBUG,
printf ("\tfirst operand is %s", tahoe_operandname (firstmode));
printf ("\tsecond operand is %s\n", tahoe_operandname (mode));
);
switch (mode)
{
case regdef:
case bytedispdef:
case worddispdef:
case longdispdef:
case bytereldef:
case wordreldef:
case longreldef:
/*
* indirect call: call through pointer
* either *d(r) as a parameter or local
* (r) as a return value
* *f as a global pointer
* [are there others that we miss?,
* e.g. arrays of pointers to functions???]
*/
arc_add (parent, &indirectchild, (unsigned long) 0);
length += tahoe_operandlength (instructp + length);
continue;
case byterel:
case wordrel:
case longrel:
/*
* regular pc relative addressing
* check that this is the address of
* a function.
*/
destpc = pc + tahoe_offset (instructp + length);
if (hist_check_address (destpc))
{
child = sym_lookup (&symtab, destpc);
if (child)
{
DBG (CALLDEBUG,
printf ("[findcall]\tdestpc 0x%lx",
(unsigned long) destpc);
printf (" child->name %s", child->name);
printf (" child->addr 0x%lx\n",
(unsigned long) child->addr);
);
if (child->addr == destpc)
{
/*
* a hit
*/
arc_add (parent, child, (unsigned long) 0);
length += tahoe_operandlength (instructp + length);
continue;
}
}
goto botched;
}
/*
* else:
* it looked like a callf,
* but it wasn't to anywhere.
*/
goto botched;
default:
botched:
/*
* something funny going on.
*/
DBG (CALLDEBUG, printf ("[findcall]\tbut it's a botch\n"));
length = 1;
continue;
}
}
}
}
| gpl-2.0 |
FlorentRevest/linux-sunxi-cedrus | drivers/media/usb/dvb-usb/af9005-fe.c | 216 | 36147 | /* Frontend part of the Linux driver for the Afatech 9005
* USB1.1 DVB-T receiver.
*
* Copyright (C) 2007 Luca Olivetti (luca@ventoso.org)
*
* Thanks to Afatech who kindly provided information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "af9005.h"
#include "af9005-script.h"
#include "mt2060.h"
#include "qt1010.h"
#include <asm/div64.h>
struct af9005_fe_state {
struct dvb_usb_device *d;
enum fe_status stat;
/* retraining parameters */
u32 original_fcw;
u16 original_rf_top;
u16 original_if_top;
u16 original_if_min;
u16 original_aci0_if_top;
u16 original_aci1_if_top;
u16 original_aci0_if_min;
u8 original_if_unplug_th;
u8 original_rf_unplug_th;
u8 original_dtop_if_unplug_th;
u8 original_dtop_rf_unplug_th;
/* statistics */
u32 pre_vit_error_count;
u32 pre_vit_bit_count;
u32 ber;
u32 post_vit_error_count;
u32 post_vit_bit_count;
u32 unc;
u16 abort_count;
int opened;
int strong;
unsigned long next_status_check;
struct dvb_frontend frontend;
};
static int af9005_write_word_agc(struct dvb_usb_device *d, u16 reghi,
u16 reglo, u8 pos, u8 len, u16 value)
{
int ret;
if ((ret = af9005_write_ofdm_register(d, reglo, (u8) (value & 0xff))))
return ret;
return af9005_write_register_bits(d, reghi, pos, len,
(u8) ((value & 0x300) >> 8));
}
static int af9005_read_word_agc(struct dvb_usb_device *d, u16 reghi,
u16 reglo, u8 pos, u8 len, u16 * value)
{
int ret;
u8 temp0, temp1;
if ((ret = af9005_read_ofdm_register(d, reglo, &temp0)))
return ret;
if ((ret = af9005_read_ofdm_register(d, reghi, &temp1)))
return ret;
switch (pos) {
case 0:
*value = ((u16) (temp1 & 0x03) << 8) + (u16) temp0;
break;
case 2:
*value = ((u16) (temp1 & 0x0C) << 6) + (u16) temp0;
break;
case 4:
*value = ((u16) (temp1 & 0x30) << 4) + (u16) temp0;
break;
case 6:
*value = ((u16) (temp1 & 0xC0) << 2) + (u16) temp0;
break;
default:
err("invalid pos in read word agc");
return -EINVAL;
}
return 0;
}
static int af9005_is_fecmon_available(struct dvb_frontend *fe, int *available)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 temp;
*available = false;
ret = af9005_read_register_bits(state->d, xd_p_fec_vtb_rsd_mon_en,
fec_vtb_rsd_mon_en_pos,
fec_vtb_rsd_mon_en_len, &temp);
if (ret)
return ret;
if (temp & 1) {
ret =
af9005_read_register_bits(state->d,
xd_p_reg_ofsm_read_rbc_en,
reg_ofsm_read_rbc_en_pos,
reg_ofsm_read_rbc_en_len, &temp);
if (ret)
return ret;
if ((temp & 1) == 0)
*available = true;
}
return 0;
}
static int af9005_get_post_vit_err_cw_count(struct dvb_frontend *fe,
u32 * post_err_count,
u32 * post_cw_count,
u16 * abort_count)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u32 err_count;
u32 cw_count;
u8 temp, temp0, temp1, temp2;
u16 loc_abort_count;
*post_err_count = 0;
*post_cw_count = 0;
/* check if error bit count is ready */
ret =
af9005_read_register_bits(state->d, xd_r_fec_rsd_ber_rdy,
fec_rsd_ber_rdy_pos, fec_rsd_ber_rdy_len,
&temp);
if (ret)
return ret;
if (!temp) {
deb_info("rsd counter not ready\n");
return 100;
}
/* get abort count */
ret =
af9005_read_ofdm_register(state->d,
xd_r_fec_rsd_abort_packet_cnt_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d,
xd_r_fec_rsd_abort_packet_cnt_15_8,
&temp1);
if (ret)
return ret;
loc_abort_count = ((u16) temp1 << 8) + temp0;
/* get error count */
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_rsd_bit_err_cnt_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_rsd_bit_err_cnt_15_8,
&temp1);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_rsd_bit_err_cnt_23_16,
&temp2);
if (ret)
return ret;
err_count = ((u32) temp2 << 16) + ((u32) temp1 << 8) + temp0;
*post_err_count = err_count - (u32) loc_abort_count *8 * 8;
/* get RSD packet number */
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_15_8,
&temp1);
if (ret)
return ret;
cw_count = ((u32) temp1 << 8) + temp0;
if (cw_count == 0) {
err("wrong RSD packet count");
return -EIO;
}
deb_info("POST abort count %d err count %d rsd packets %d\n",
loc_abort_count, err_count, cw_count);
*post_cw_count = cw_count - (u32) loc_abort_count;
*abort_count = loc_abort_count;
return 0;
}
static int af9005_get_post_vit_ber(struct dvb_frontend *fe,
u32 * post_err_count, u32 * post_cw_count,
u16 * abort_count)
{
u32 loc_cw_count = 0, loc_err_count;
u16 loc_abort_count = 0;
int ret;
ret =
af9005_get_post_vit_err_cw_count(fe, &loc_err_count, &loc_cw_count,
&loc_abort_count);
if (ret)
return ret;
*post_err_count = loc_err_count;
*post_cw_count = loc_cw_count * 204 * 8;
*abort_count = loc_abort_count;
return 0;
}
static int af9005_get_pre_vit_err_bit_count(struct dvb_frontend *fe,
u32 * pre_err_count,
u32 * pre_bit_count)
{
struct af9005_fe_state *state = fe->demodulator_priv;
u8 temp, temp0, temp1, temp2;
u32 super_frame_count, x, bits;
int ret;
ret =
af9005_read_register_bits(state->d, xd_r_fec_vtb_ber_rdy,
fec_vtb_ber_rdy_pos, fec_vtb_ber_rdy_len,
&temp);
if (ret)
return ret;
if (!temp) {
deb_info("viterbi counter not ready\n");
return 101; /* ERR_APO_VTB_COUNTER_NOT_READY; */
}
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_vtb_err_bit_cnt_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_vtb_err_bit_cnt_15_8,
&temp1);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_vtb_err_bit_cnt_23_16,
&temp2);
if (ret)
return ret;
*pre_err_count = ((u32) temp2 << 16) + ((u32) temp1 << 8) + temp0;
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_super_frm_unit_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_super_frm_unit_15_8,
&temp1);
if (ret)
return ret;
super_frame_count = ((u32) temp1 << 8) + temp0;
if (super_frame_count == 0) {
deb_info("super frame count 0\n");
return 102;
}
/* read fft mode */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_txmod,
reg_tpsd_txmod_pos, reg_tpsd_txmod_len,
&temp);
if (ret)
return ret;
if (temp == 0) {
/* 2K */
x = 1512;
} else if (temp == 1) {
/* 8k */
x = 6048;
} else {
err("Invalid fft mode");
return -EINVAL;
}
/* read modulation mode */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_const,
reg_tpsd_const_pos, reg_tpsd_const_len,
&temp);
if (ret)
return ret;
switch (temp) {
case 0: /* QPSK */
bits = 2;
break;
case 1: /* QAM_16 */
bits = 4;
break;
case 2: /* QAM_64 */
bits = 6;
break;
default:
err("invalid modulation mode");
return -EINVAL;
}
*pre_bit_count = super_frame_count * 68 * 4 * x * bits;
deb_info("PRE err count %d frame count %d bit count %d\n",
*pre_err_count, super_frame_count, *pre_bit_count);
return 0;
}
static int af9005_reset_pre_viterbi(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
/* set super frame count to 1 */
ret =
af9005_write_ofdm_register(state->d, xd_p_fec_super_frm_unit_7_0,
1 & 0xff);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, xd_p_fec_super_frm_unit_15_8,
1 >> 8);
if (ret)
return ret;
/* reset pre viterbi error count */
ret =
af9005_write_register_bits(state->d, xd_p_fec_vtb_ber_rst,
fec_vtb_ber_rst_pos, fec_vtb_ber_rst_len,
1);
return ret;
}
static int af9005_reset_post_viterbi(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
/* set packet unit */
ret =
af9005_write_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_7_0,
10000 & 0xff);
if (ret)
return ret;
ret =
af9005_write_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_15_8,
10000 >> 8);
if (ret)
return ret;
/* reset post viterbi error count */
ret =
af9005_write_register_bits(state->d, xd_p_fec_rsd_ber_rst,
fec_rsd_ber_rst_pos, fec_rsd_ber_rst_len,
1);
return ret;
}
static int af9005_get_statistic(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret, fecavailable;
u64 numerator, denominator;
deb_info("GET STATISTIC\n");
ret = af9005_is_fecmon_available(fe, &fecavailable);
if (ret)
return ret;
if (!fecavailable) {
deb_info("fecmon not available\n");
return 0;
}
ret = af9005_get_pre_vit_err_bit_count(fe, &state->pre_vit_error_count,
&state->pre_vit_bit_count);
if (ret == 0) {
af9005_reset_pre_viterbi(fe);
if (state->pre_vit_bit_count > 0) {
/* according to v 0.0.4 of the dvb api ber should be a multiple
of 10E-9 so we have to multiply the error count by
10E9=1000000000 */
numerator =
(u64) state->pre_vit_error_count * (u64) 1000000000;
denominator = (u64) state->pre_vit_bit_count;
state->ber = do_div(numerator, denominator);
} else {
state->ber = 0xffffffff;
}
}
ret = af9005_get_post_vit_ber(fe, &state->post_vit_error_count,
&state->post_vit_bit_count,
&state->abort_count);
if (ret == 0) {
ret = af9005_reset_post_viterbi(fe);
state->unc += state->abort_count;
if (ret)
return ret;
}
return 0;
}
static int af9005_fe_refresh_state(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (time_after(jiffies, state->next_status_check)) {
deb_info("REFRESH STATE\n");
/* statistics */
if (af9005_get_statistic(fe))
err("get_statistic_failed");
state->next_status_check = jiffies + 250 * HZ / 1000;
}
return 0;
}
static int af9005_fe_read_status(struct dvb_frontend *fe,
enum fe_status *stat)
{
struct af9005_fe_state *state = fe->demodulator_priv;
u8 temp;
int ret;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
*stat = 0;
ret = af9005_read_register_bits(state->d, xd_p_agc_lock,
agc_lock_pos, agc_lock_len, &temp);
if (ret)
return ret;
if (temp)
*stat |= FE_HAS_SIGNAL;
ret = af9005_read_register_bits(state->d, xd_p_fd_tpsd_lock,
fd_tpsd_lock_pos, fd_tpsd_lock_len,
&temp);
if (ret)
return ret;
if (temp)
*stat |= FE_HAS_CARRIER;
ret = af9005_read_register_bits(state->d,
xd_r_mp2if_sync_byte_locked,
mp2if_sync_byte_locked_pos,
mp2if_sync_byte_locked_pos, &temp);
if (ret)
return ret;
if (temp)
*stat |= FE_HAS_SYNC | FE_HAS_VITERBI | FE_HAS_LOCK;
if (state->opened)
af9005_led_control(state->d, *stat & FE_HAS_LOCK);
ret =
af9005_read_register_bits(state->d, xd_p_reg_strong_sginal_detected,
reg_strong_sginal_detected_pos,
reg_strong_sginal_detected_len, &temp);
if (ret)
return ret;
if (temp != state->strong) {
deb_info("adjust for strong signal %d\n", temp);
state->strong = temp;
}
return 0;
}
static int af9005_fe_read_ber(struct dvb_frontend *fe, u32 * ber)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
af9005_fe_refresh_state(fe);
*ber = state->ber;
return 0;
}
static int af9005_fe_read_unc_blocks(struct dvb_frontend *fe, u32 * unc)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
af9005_fe_refresh_state(fe);
*unc = state->unc;
return 0;
}
static int af9005_fe_read_signal_strength(struct dvb_frontend *fe,
u16 * strength)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 if_gain, rf_gain;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
ret =
af9005_read_ofdm_register(state->d, xd_r_reg_aagc_rf_gain,
&rf_gain);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_reg_aagc_if_gain,
&if_gain);
if (ret)
return ret;
/* this value has no real meaning, but i don't have the tables that relate
the rf and if gain with the dbm, so I just scale the value */
*strength = (512 - rf_gain - if_gain) << 7;
return 0;
}
static int af9005_fe_read_snr(struct dvb_frontend *fe, u16 * snr)
{
/* the snr can be derived from the ber and the modulation
but I don't think this kind of complex calculations belong
in the driver. I may be wrong.... */
return -ENOSYS;
}
static int af9005_fe_program_cfoe(struct dvb_usb_device *d, u32 bw)
{
u8 temp0, temp1, temp2, temp3, buf[4];
int ret;
u32 NS_coeff1_2048Nu;
u32 NS_coeff1_8191Nu;
u32 NS_coeff1_8192Nu;
u32 NS_coeff1_8193Nu;
u32 NS_coeff2_2k;
u32 NS_coeff2_8k;
switch (bw) {
case 6000000:
NS_coeff1_2048Nu = 0x2ADB6DC;
NS_coeff1_8191Nu = 0xAB7313;
NS_coeff1_8192Nu = 0xAB6DB7;
NS_coeff1_8193Nu = 0xAB685C;
NS_coeff2_2k = 0x156DB6E;
NS_coeff2_8k = 0x55B6DC;
break;
case 7000000:
NS_coeff1_2048Nu = 0x3200001;
NS_coeff1_8191Nu = 0xC80640;
NS_coeff1_8192Nu = 0xC80000;
NS_coeff1_8193Nu = 0xC7F9C0;
NS_coeff2_2k = 0x1900000;
NS_coeff2_8k = 0x640000;
break;
case 8000000:
NS_coeff1_2048Nu = 0x3924926;
NS_coeff1_8191Nu = 0xE4996E;
NS_coeff1_8192Nu = 0xE49249;
NS_coeff1_8193Nu = 0xE48B25;
NS_coeff2_2k = 0x1C92493;
NS_coeff2_8k = 0x724925;
break;
default:
err("Invalid bandwidth %d.", bw);
return -EINVAL;
}
/*
* write NS_coeff1_2048Nu
*/
temp0 = (u8) (NS_coeff1_2048Nu & 0x000000FF);
temp1 = (u8) ((NS_coeff1_2048Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_2048Nu & 0x00FF0000) >> 16);
temp3 = (u8) ((NS_coeff1_2048Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
/* cfoe_NS_2k_coeff1_25_24 */
ret = af9005_write_ofdm_register(d, 0xAE00, buf[0]);
if (ret)
return ret;
/* cfoe_NS_2k_coeff1_23_16 */
ret = af9005_write_ofdm_register(d, 0xAE01, buf[1]);
if (ret)
return ret;
/* cfoe_NS_2k_coeff1_15_8 */
ret = af9005_write_ofdm_register(d, 0xAE02, buf[2]);
if (ret)
return ret;
/* cfoe_NS_2k_coeff1_7_0 */
ret = af9005_write_ofdm_register(d, 0xAE03, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff2_2k
*/
temp0 = (u8) ((NS_coeff2_2k & 0x0000003F));
temp1 = (u8) ((NS_coeff2_2k & 0x00003FC0) >> 6);
temp2 = (u8) ((NS_coeff2_2k & 0x003FC000) >> 14);
temp3 = (u8) ((NS_coeff2_2k & 0x01C00000) >> 22);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE04, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE05, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE06, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE07, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff1_8191Nu
*/
temp0 = (u8) ((NS_coeff1_8191Nu & 0x000000FF));
temp1 = (u8) ((NS_coeff1_8191Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_8191Nu & 0x00FFC000) >> 16);
temp3 = (u8) ((NS_coeff1_8191Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE08, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE09, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0A, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0B, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff1_8192Nu
*/
temp0 = (u8) (NS_coeff1_8192Nu & 0x000000FF);
temp1 = (u8) ((NS_coeff1_8192Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_8192Nu & 0x00FFC000) >> 16);
temp3 = (u8) ((NS_coeff1_8192Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE0C, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0D, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0E, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0F, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff1_8193Nu
*/
temp0 = (u8) ((NS_coeff1_8193Nu & 0x000000FF));
temp1 = (u8) ((NS_coeff1_8193Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_8193Nu & 0x00FFC000) >> 16);
temp3 = (u8) ((NS_coeff1_8193Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE10, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE11, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE12, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE13, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff2_8k
*/
temp0 = (u8) ((NS_coeff2_8k & 0x0000003F));
temp1 = (u8) ((NS_coeff2_8k & 0x00003FC0) >> 6);
temp2 = (u8) ((NS_coeff2_8k & 0x003FC000) >> 14);
temp3 = (u8) ((NS_coeff2_8k & 0x01C00000) >> 22);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE14, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE15, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE16, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE17, buf[3]);
return ret;
}
static int af9005_fe_select_bw(struct dvb_usb_device *d, u32 bw)
{
u8 temp;
switch (bw) {
case 6000000:
temp = 0;
break;
case 7000000:
temp = 1;
break;
case 8000000:
temp = 2;
break;
default:
err("Invalid bandwidth %d.", bw);
return -EINVAL;
}
return af9005_write_register_bits(d, xd_g_reg_bw, reg_bw_pos,
reg_bw_len, temp);
}
static int af9005_fe_power(struct dvb_frontend *fe, int on)
{
struct af9005_fe_state *state = fe->demodulator_priv;
u8 temp = on;
int ret;
deb_info("power %s tuner\n", on ? "on" : "off");
ret = af9005_send_command(state->d, 0x03, &temp, 1, NULL, 0);
return ret;
}
static struct mt2060_config af9005_mt2060_config = {
0xC0
};
static struct qt1010_config af9005_qt1010_config = {
0xC4
};
static int af9005_fe_init(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
struct dvb_usb_adapter *adap = fe->dvb->priv;
int ret, i, scriptlen;
u8 temp, temp0 = 0, temp1 = 0, temp2 = 0;
u8 buf[2];
u16 if1;
deb_info("in af9005_fe_init\n");
/* reset */
deb_info("reset\n");
if ((ret =
af9005_write_register_bits(state->d, xd_I2C_reg_ofdm_rst_en,
4, 1, 0x01)))
return ret;
if ((ret = af9005_write_ofdm_register(state->d, APO_REG_RESET, 0)))
return ret;
/* clear ofdm reset */
deb_info("clear ofdm reset\n");
for (i = 0; i < 150; i++) {
if ((ret =
af9005_read_ofdm_register(state->d,
xd_I2C_reg_ofdm_rst, &temp)))
return ret;
if (temp & (regmask[reg_ofdm_rst_len - 1] << reg_ofdm_rst_pos))
break;
msleep(10);
}
if (i == 150)
return -ETIMEDOUT;
/*FIXME in the dump
write B200 A9
write xd_g_reg_ofsm_clk 7
read eepr c6 (2)
read eepr c7 (2)
misc ctrl 3 -> 1
read eepr ca (6)
write xd_g_reg_ofsm_clk 0
write B200 a1
*/
ret = af9005_write_ofdm_register(state->d, 0xb200, 0xa9);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, xd_g_reg_ofsm_clk, 0x07);
if (ret)
return ret;
temp = 0x01;
ret = af9005_send_command(state->d, 0x03, &temp, 1, NULL, 0);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, xd_g_reg_ofsm_clk, 0x00);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xb200, 0xa1);
if (ret)
return ret;
temp = regmask[reg_ofdm_rst_len - 1] << reg_ofdm_rst_pos;
if ((ret =
af9005_write_register_bits(state->d, xd_I2C_reg_ofdm_rst,
reg_ofdm_rst_pos, reg_ofdm_rst_len, 1)))
return ret;
ret = af9005_write_register_bits(state->d, xd_I2C_reg_ofdm_rst,
reg_ofdm_rst_pos, reg_ofdm_rst_len, 0);
if (ret)
return ret;
/* don't know what register aefc is, but this is what the windows driver does */
ret = af9005_write_ofdm_register(state->d, 0xaefc, 0);
if (ret)
return ret;
/* set stand alone chip */
deb_info("set stand alone chip\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_stand_alone,
reg_dca_stand_alone_pos,
reg_dca_stand_alone_len, 1)))
return ret;
/* set dca upper & lower chip */
deb_info("set dca upper & lower chip\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_upper_chip,
reg_dca_upper_chip_pos,
reg_dca_upper_chip_len, 0)))
return ret;
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_lower_chip,
reg_dca_lower_chip_pos,
reg_dca_lower_chip_len, 0)))
return ret;
/* set 2wire master clock to 0x14 (for 60KHz) */
deb_info("set 2wire master clock to 0x14 (for 60KHz)\n");
if ((ret =
af9005_write_ofdm_register(state->d, xd_I2C_i2c_m_period, 0x14)))
return ret;
/* clear dca enable chip */
deb_info("clear dca enable chip\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_en,
reg_dca_en_pos, reg_dca_en_len, 0)))
return ret;
/* FIXME these are register bits, but I don't know which ones */
ret = af9005_write_ofdm_register(state->d, 0xa16c, 1);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xa3c1, 0);
if (ret)
return ret;
/* init other parameters: program cfoe and select bandwidth */
deb_info("program cfoe\n");
ret = af9005_fe_program_cfoe(state->d, 6000000);
if (ret)
return ret;
/* set read-update bit for modulation */
deb_info("set read-update bit for modulation\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_feq_read_update,
reg_feq_read_update_pos,
reg_feq_read_update_len, 1)))
return ret;
/* sample code has a set MPEG TS code here
but sniffing reveals that it doesn't do it */
/* set read-update bit to 1 for DCA modulation */
deb_info("set read-update bit 1 for DCA modulation\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_read_update,
reg_dca_read_update_pos,
reg_dca_read_update_len, 1)))
return ret;
/* enable fec monitor */
deb_info("enable fec monitor\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_fec_vtb_rsd_mon_en,
fec_vtb_rsd_mon_en_pos,
fec_vtb_rsd_mon_en_len, 1)))
return ret;
/* FIXME should be register bits, I don't know which ones */
ret = af9005_write_ofdm_register(state->d, 0xa601, 0);
/* set api_retrain_never_freeze */
deb_info("set api_retrain_never_freeze\n");
if ((ret = af9005_write_ofdm_register(state->d, 0xaefb, 0x01)))
return ret;
/* load init script */
deb_info("load init script\n");
scriptlen = sizeof(script) / sizeof(RegDesc);
for (i = 0; i < scriptlen; i++) {
if ((ret =
af9005_write_register_bits(state->d, script[i].reg,
script[i].pos,
script[i].len, script[i].val)))
return ret;
/* save 3 bytes of original fcw */
if (script[i].reg == 0xae18)
temp2 = script[i].val;
if (script[i].reg == 0xae19)
temp1 = script[i].val;
if (script[i].reg == 0xae1a)
temp0 = script[i].val;
/* save original unplug threshold */
if (script[i].reg == xd_p_reg_unplug_th)
state->original_if_unplug_th = script[i].val;
if (script[i].reg == xd_p_reg_unplug_rf_gain_th)
state->original_rf_unplug_th = script[i].val;
if (script[i].reg == xd_p_reg_unplug_dtop_if_gain_th)
state->original_dtop_if_unplug_th = script[i].val;
if (script[i].reg == xd_p_reg_unplug_dtop_rf_gain_th)
state->original_dtop_rf_unplug_th = script[i].val;
}
state->original_fcw =
((u32) temp2 << 16) + ((u32) temp1 << 8) + (u32) temp0;
/* save original TOPs */
deb_info("save original TOPs\n");
/* RF TOP */
ret =
af9005_read_word_agc(state->d,
xd_p_reg_aagc_rf_top_numerator_9_8,
xd_p_reg_aagc_rf_top_numerator_7_0, 0, 2,
&state->original_rf_top);
if (ret)
return ret;
/* IF TOP */
ret =
af9005_read_word_agc(state->d,
xd_p_reg_aagc_if_top_numerator_9_8,
xd_p_reg_aagc_if_top_numerator_7_0, 0, 2,
&state->original_if_top);
if (ret)
return ret;
/* ACI 0 IF TOP */
ret =
af9005_read_word_agc(state->d, 0xA60E, 0xA60A, 4, 2,
&state->original_aci0_if_top);
if (ret)
return ret;
/* ACI 1 IF TOP */
ret =
af9005_read_word_agc(state->d, 0xA60E, 0xA60B, 6, 2,
&state->original_aci1_if_top);
if (ret)
return ret;
/* attach tuner and init */
if (fe->ops.tuner_ops.release == NULL) {
/* read tuner and board id from eeprom */
ret = af9005_read_eeprom(adap->dev, 0xc6, buf, 2);
if (ret) {
err("Impossible to read EEPROM\n");
return ret;
}
deb_info("Tuner id %d, board id %d\n", buf[0], buf[1]);
switch (buf[0]) {
case 2: /* MT2060 */
/* read if1 from eeprom */
ret = af9005_read_eeprom(adap->dev, 0xc8, buf, 2);
if (ret) {
err("Impossible to read EEPROM\n");
return ret;
}
if1 = (u16) (buf[0] << 8) + buf[1];
if (dvb_attach(mt2060_attach, fe, &adap->dev->i2c_adap,
&af9005_mt2060_config, if1) == NULL) {
deb_info("MT2060 attach failed\n");
return -ENODEV;
}
break;
case 3: /* QT1010 */
case 9: /* QT1010B */
if (dvb_attach(qt1010_attach, fe, &adap->dev->i2c_adap,
&af9005_qt1010_config) ==NULL) {
deb_info("QT1010 attach failed\n");
return -ENODEV;
}
break;
default:
err("Unsupported tuner type %d", buf[0]);
return -ENODEV;
}
ret = fe->ops.tuner_ops.init(fe);
if (ret)
return ret;
}
deb_info("profit!\n");
return 0;
}
static int af9005_fe_sleep(struct dvb_frontend *fe)
{
return af9005_fe_power(fe, 0);
}
static int af9005_ts_bus_ctrl(struct dvb_frontend *fe, int acquire)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (acquire) {
state->opened++;
} else {
state->opened--;
if (!state->opened)
af9005_led_control(state->d, 0);
}
return 0;
}
static int af9005_fe_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *fep = &fe->dtv_property_cache;
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 temp, temp0, temp1, temp2;
deb_info("af9005_fe_set_frontend freq %d bw %d\n", fep->frequency,
fep->bandwidth_hz);
if (fe->ops.tuner_ops.release == NULL) {
err("Tuner not attached");
return -ENODEV;
}
deb_info("turn off led\n");
/* not in the log */
ret = af9005_led_control(state->d, 0);
if (ret)
return ret;
/* not sure about the bits */
ret = af9005_write_register_bits(state->d, XD_MP2IF_MISC, 2, 1, 0);
if (ret)
return ret;
/* set FCW to default value */
deb_info("set FCW to default value\n");
temp0 = (u8) (state->original_fcw & 0x000000ff);
temp1 = (u8) ((state->original_fcw & 0x0000ff00) >> 8);
temp2 = (u8) ((state->original_fcw & 0x00ff0000) >> 16);
ret = af9005_write_ofdm_register(state->d, 0xae1a, temp0);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xae19, temp1);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xae18, temp2);
if (ret)
return ret;
/* restore original TOPs */
deb_info("restore original TOPs\n");
ret =
af9005_write_word_agc(state->d,
xd_p_reg_aagc_rf_top_numerator_9_8,
xd_p_reg_aagc_rf_top_numerator_7_0, 0, 2,
state->original_rf_top);
if (ret)
return ret;
ret =
af9005_write_word_agc(state->d,
xd_p_reg_aagc_if_top_numerator_9_8,
xd_p_reg_aagc_if_top_numerator_7_0, 0, 2,
state->original_if_top);
if (ret)
return ret;
ret =
af9005_write_word_agc(state->d, 0xA60E, 0xA60A, 4, 2,
state->original_aci0_if_top);
if (ret)
return ret;
ret =
af9005_write_word_agc(state->d, 0xA60E, 0xA60B, 6, 2,
state->original_aci1_if_top);
if (ret)
return ret;
/* select bandwidth */
deb_info("select bandwidth");
ret = af9005_fe_select_bw(state->d, fep->bandwidth_hz);
if (ret)
return ret;
ret = af9005_fe_program_cfoe(state->d, fep->bandwidth_hz);
if (ret)
return ret;
/* clear easy mode flag */
deb_info("clear easy mode flag\n");
ret = af9005_write_ofdm_register(state->d, 0xaefd, 0);
if (ret)
return ret;
/* set unplug threshold to original value */
deb_info("set unplug threshold to original value\n");
ret =
af9005_write_ofdm_register(state->d, xd_p_reg_unplug_th,
state->original_if_unplug_th);
if (ret)
return ret;
/* set tuner */
deb_info("set tuner\n");
ret = fe->ops.tuner_ops.set_params(fe);
if (ret)
return ret;
/* trigger ofsm */
deb_info("trigger ofsm\n");
temp = 0;
ret = af9005_write_tuner_registers(state->d, 0xffff, &temp, 1);
if (ret)
return ret;
/* clear retrain and freeze flag */
deb_info("clear retrain and freeze flag\n");
ret =
af9005_write_register_bits(state->d,
xd_p_reg_api_retrain_request,
reg_api_retrain_request_pos, 2, 0);
if (ret)
return ret;
/* reset pre viterbi and post viterbi registers and statistics */
af9005_reset_pre_viterbi(fe);
af9005_reset_post_viterbi(fe);
state->pre_vit_error_count = 0;
state->pre_vit_bit_count = 0;
state->ber = 0;
state->post_vit_error_count = 0;
/* state->unc = 0; commented out since it should be ever increasing */
state->abort_count = 0;
state->next_status_check = jiffies;
state->strong = -1;
return 0;
}
static int af9005_fe_get_frontend(struct dvb_frontend *fe,
struct dtv_frontend_properties *fep)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 temp;
/* mode */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_const,
reg_tpsd_const_pos, reg_tpsd_const_len,
&temp);
if (ret)
return ret;
deb_info("===== fe_get_frontend_legacy = =============\n");
deb_info("CONSTELLATION ");
switch (temp) {
case 0:
fep->modulation = QPSK;
deb_info("QPSK\n");
break;
case 1:
fep->modulation = QAM_16;
deb_info("QAM_16\n");
break;
case 2:
fep->modulation = QAM_64;
deb_info("QAM_64\n");
break;
}
/* tps hierarchy and alpha value */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_hier,
reg_tpsd_hier_pos, reg_tpsd_hier_len,
&temp);
if (ret)
return ret;
deb_info("HIERARCHY ");
switch (temp) {
case 0:
fep->hierarchy = HIERARCHY_NONE;
deb_info("NONE\n");
break;
case 1:
fep->hierarchy = HIERARCHY_1;
deb_info("1\n");
break;
case 2:
fep->hierarchy = HIERARCHY_2;
deb_info("2\n");
break;
case 3:
fep->hierarchy = HIERARCHY_4;
deb_info("4\n");
break;
}
/* high/low priority */
ret =
af9005_read_register_bits(state->d, xd_g_reg_dec_pri,
reg_dec_pri_pos, reg_dec_pri_len, &temp);
if (ret)
return ret;
/* if temp is set = high priority */
deb_info("PRIORITY %s\n", temp ? "high" : "low");
/* high coderate */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_hpcr,
reg_tpsd_hpcr_pos, reg_tpsd_hpcr_len,
&temp);
if (ret)
return ret;
deb_info("CODERATE HP ");
switch (temp) {
case 0:
fep->code_rate_HP = FEC_1_2;
deb_info("FEC_1_2\n");
break;
case 1:
fep->code_rate_HP = FEC_2_3;
deb_info("FEC_2_3\n");
break;
case 2:
fep->code_rate_HP = FEC_3_4;
deb_info("FEC_3_4\n");
break;
case 3:
fep->code_rate_HP = FEC_5_6;
deb_info("FEC_5_6\n");
break;
case 4:
fep->code_rate_HP = FEC_7_8;
deb_info("FEC_7_8\n");
break;
}
/* low coderate */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_lpcr,
reg_tpsd_lpcr_pos, reg_tpsd_lpcr_len,
&temp);
if (ret)
return ret;
deb_info("CODERATE LP ");
switch (temp) {
case 0:
fep->code_rate_LP = FEC_1_2;
deb_info("FEC_1_2\n");
break;
case 1:
fep->code_rate_LP = FEC_2_3;
deb_info("FEC_2_3\n");
break;
case 2:
fep->code_rate_LP = FEC_3_4;
deb_info("FEC_3_4\n");
break;
case 3:
fep->code_rate_LP = FEC_5_6;
deb_info("FEC_5_6\n");
break;
case 4:
fep->code_rate_LP = FEC_7_8;
deb_info("FEC_7_8\n");
break;
}
/* guard interval */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_gi,
reg_tpsd_gi_pos, reg_tpsd_gi_len, &temp);
if (ret)
return ret;
deb_info("GUARD INTERVAL ");
switch (temp) {
case 0:
fep->guard_interval = GUARD_INTERVAL_1_32;
deb_info("1_32\n");
break;
case 1:
fep->guard_interval = GUARD_INTERVAL_1_16;
deb_info("1_16\n");
break;
case 2:
fep->guard_interval = GUARD_INTERVAL_1_8;
deb_info("1_8\n");
break;
case 3:
fep->guard_interval = GUARD_INTERVAL_1_4;
deb_info("1_4\n");
break;
}
/* fft */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_txmod,
reg_tpsd_txmod_pos, reg_tpsd_txmod_len,
&temp);
if (ret)
return ret;
deb_info("TRANSMISSION MODE ");
switch (temp) {
case 0:
fep->transmission_mode = TRANSMISSION_MODE_2K;
deb_info("2K\n");
break;
case 1:
fep->transmission_mode = TRANSMISSION_MODE_8K;
deb_info("8K\n");
break;
}
/* bandwidth */
ret =
af9005_read_register_bits(state->d, xd_g_reg_bw, reg_bw_pos,
reg_bw_len, &temp);
deb_info("BANDWIDTH ");
switch (temp) {
case 0:
fep->bandwidth_hz = 6000000;
deb_info("6\n");
break;
case 1:
fep->bandwidth_hz = 7000000;
deb_info("7\n");
break;
case 2:
fep->bandwidth_hz = 8000000;
deb_info("8\n");
break;
}
return 0;
}
static void af9005_fe_release(struct dvb_frontend *fe)
{
struct af9005_fe_state *state =
(struct af9005_fe_state *)fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops af9005_fe_ops;
struct dvb_frontend *af9005_fe_attach(struct dvb_usb_device *d)
{
struct af9005_fe_state *state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct af9005_fe_state), GFP_KERNEL);
if (state == NULL)
goto error;
deb_info("attaching frontend af9005\n");
state->d = d;
state->opened = 0;
memcpy(&state->frontend.ops, &af9005_fe_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
return NULL;
}
static struct dvb_frontend_ops af9005_fe_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "AF9005 USB DVB-T",
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 250000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 |
FE_CAN_QAM_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_RECOVER |
FE_CAN_HIERARCHY_AUTO,
},
.release = af9005_fe_release,
.init = af9005_fe_init,
.sleep = af9005_fe_sleep,
.ts_bus_ctrl = af9005_ts_bus_ctrl,
.set_frontend = af9005_fe_set_frontend,
.get_frontend = af9005_fe_get_frontend,
.read_status = af9005_fe_read_status,
.read_ber = af9005_fe_read_ber,
.read_signal_strength = af9005_fe_read_signal_strength,
.read_snr = af9005_fe_read_snr,
.read_ucblocks = af9005_fe_read_unc_blocks,
};
| gpl-2.0 |
mpalmer/linux-2.6 | drivers/video/via/dvi.c | 216 | 18260 | /*
* Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved.
* Copyright 2001-2008 S3 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, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTIES OR REPRESENTATIONS; 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 "global.h"
static void tmds_register_write(int index, u8 data);
static int tmds_register_read(int index);
static int tmds_register_read_bytes(int index, u8 *buff, int buff_len);
static int check_reduce_blanking_mode(int mode_index,
int refresh_rate);
static int dvi_get_panel_size_from_DDCv1(void);
static int dvi_get_panel_size_from_DDCv2(void);
static unsigned char dvi_get_panel_info(void);
static int viafb_dvi_query_EDID(void);
static int check_tmds_chip(int device_id_subaddr, int device_id)
{
if (tmds_register_read(device_id_subaddr) == device_id)
return OK;
else
return FAIL;
}
void viafb_init_dvi_size(void)
{
DEBUG_MSG(KERN_INFO "viafb_init_dvi_size()\n");
DEBUG_MSG(KERN_INFO
"viaparinfo->tmds_setting_info->get_dvi_size_method %d\n",
viaparinfo->tmds_setting_info->get_dvi_size_method);
switch (viaparinfo->tmds_setting_info->get_dvi_size_method) {
case GET_DVI_SIZE_BY_SYSTEM_BIOS:
break;
case GET_DVI_SZIE_BY_HW_STRAPPING:
break;
case GET_DVI_SIZE_BY_VGA_BIOS:
default:
dvi_get_panel_info();
break;
}
return;
}
int viafb_tmds_trasmitter_identify(void)
{
unsigned char sr2a = 0, sr1e = 0, sr3e = 0;
/* Turn on ouputting pad */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_K8M890:
/*=* DFP Low Pad on *=*/
sr2a = viafb_read_reg(VIASR, SR2A);
viafb_write_reg_mask(SR2A, VIASR, 0x03, BIT0 + BIT1);
break;
case UNICHROME_P4M900:
case UNICHROME_P4M890:
/* DFP Low Pad on */
sr2a = viafb_read_reg(VIASR, SR2A);
viafb_write_reg_mask(SR2A, VIASR, 0x03, BIT0 + BIT1);
/* DVP0 Pad on */
sr1e = viafb_read_reg(VIASR, SR1E);
viafb_write_reg_mask(SR1E, VIASR, 0xC0, BIT6 + BIT7);
break;
default:
/* DVP0/DVP1 Pad on */
sr1e = viafb_read_reg(VIASR, SR1E);
viafb_write_reg_mask(SR1E, VIASR, 0xF0, BIT4 +
BIT5 + BIT6 + BIT7);
/* SR3E[1]Multi-function selection:
0 = Emulate I2C and DDC bus by GPIO2/3/4. */
sr3e = viafb_read_reg(VIASR, SR3E);
viafb_write_reg_mask(SR3E, VIASR, 0x0, BIT5);
break;
}
/* Check for VT1632: */
viaparinfo->chip_info->tmds_chip_info.tmds_chip_name = VT1632_TMDS;
viaparinfo->chip_info->
tmds_chip_info.tmds_chip_slave_addr = VT1632_TMDS_I2C_ADDR;
viaparinfo->chip_info->tmds_chip_info.i2c_port = I2CPORTINDEX;
if (check_tmds_chip(VT1632_DEVICE_ID_REG, VT1632_DEVICE_ID) != FAIL) {
/*
* Currently only support 12bits,dual edge,add 24bits mode later
*/
tmds_register_write(0x08, 0x3b);
DEBUG_MSG(KERN_INFO "\n VT1632 TMDS ! \n");
DEBUG_MSG(KERN_INFO "\n %2d",
viaparinfo->chip_info->tmds_chip_info.tmds_chip_name);
DEBUG_MSG(KERN_INFO "\n %2d",
viaparinfo->chip_info->tmds_chip_info.i2c_port);
return OK;
} else {
viaparinfo->chip_info->tmds_chip_info.i2c_port = GPIOPORTINDEX;
if (check_tmds_chip(VT1632_DEVICE_ID_REG, VT1632_DEVICE_ID)
!= FAIL) {
tmds_register_write(0x08, 0x3b);
DEBUG_MSG(KERN_INFO "\n VT1632 TMDS ! \n");
DEBUG_MSG(KERN_INFO "\n %2d",
viaparinfo->chip_info->
tmds_chip_info.tmds_chip_name);
DEBUG_MSG(KERN_INFO "\n %2d",
viaparinfo->chip_info->
tmds_chip_info.i2c_port);
return OK;
}
}
viaparinfo->chip_info->tmds_chip_info.tmds_chip_name = INTEGRATED_TMDS;
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) &&
((viafb_display_hardware_layout == HW_LAYOUT_DVI_ONLY) ||
(viafb_display_hardware_layout == HW_LAYOUT_LCD_DVI))) {
DEBUG_MSG(KERN_INFO "\n Integrated TMDS ! \n");
return OK;
}
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_K8M890:
viafb_write_reg(SR2A, VIASR, sr2a);
break;
case UNICHROME_P4M900:
case UNICHROME_P4M890:
viafb_write_reg(SR2A, VIASR, sr2a);
viafb_write_reg(SR1E, VIASR, sr1e);
break;
default:
viafb_write_reg(SR1E, VIASR, sr1e);
viafb_write_reg(SR3E, VIASR, sr3e);
break;
}
viaparinfo->chip_info->
tmds_chip_info.tmds_chip_name = NON_TMDS_TRANSMITTER;
viaparinfo->chip_info->tmds_chip_info.
tmds_chip_slave_addr = VT1632_TMDS_I2C_ADDR;
return FAIL;
}
static void tmds_register_write(int index, u8 data)
{
viaparinfo->i2c_stuff.i2c_port =
viaparinfo->chip_info->tmds_chip_info.i2c_port;
viafb_i2c_writebyte(viaparinfo->chip_info->tmds_chip_info.
tmds_chip_slave_addr, index,
data);
}
static int tmds_register_read(int index)
{
u8 data;
viaparinfo->i2c_stuff.i2c_port =
viaparinfo->chip_info->tmds_chip_info.i2c_port;
viafb_i2c_readbyte((u8) viaparinfo->chip_info->
tmds_chip_info.tmds_chip_slave_addr,
(u8) index, &data);
return data;
}
static int tmds_register_read_bytes(int index, u8 *buff, int buff_len)
{
viaparinfo->i2c_stuff.i2c_port =
viaparinfo->chip_info->tmds_chip_info.i2c_port;
viafb_i2c_readbytes((u8) viaparinfo->chip_info->tmds_chip_info.
tmds_chip_slave_addr, (u8) index, buff, buff_len);
return 0;
}
static int check_reduce_blanking_mode(int mode_index,
int refresh_rate)
{
if (refresh_rate != 60)
return false;
switch (mode_index) {
/* Following modes have reduce blanking mode. */
case VIA_RES_1360X768:
case VIA_RES_1400X1050:
case VIA_RES_1440X900:
case VIA_RES_1600X900:
case VIA_RES_1680X1050:
case VIA_RES_1920X1080:
case VIA_RES_1920X1200:
break;
default:
DEBUG_MSG(KERN_INFO
"This dvi mode %d have no reduce blanking mode!\n",
mode_index);
return false;
}
return true;
}
/* DVI Set Mode */
void viafb_dvi_set_mode(int video_index, int mode_bpp, int set_iga)
{
struct VideoModeTable *videoMode = NULL;
struct crt_mode_table *pDviTiming;
unsigned long desirePixelClock, maxPixelClock;
int status = 0;
videoMode = viafb_get_modetbl_pointer(video_index);
pDviTiming = videoMode->crtc;
desirePixelClock = pDviTiming->clk / 1000000;
maxPixelClock = (unsigned long)viaparinfo->
tmds_setting_info->max_pixel_clock;
DEBUG_MSG(KERN_INFO "\nDVI_set_mode!!\n");
if ((maxPixelClock != 0) && (desirePixelClock > maxPixelClock)) {
/*Check if reduce-blanking mode is exist */
status =
check_reduce_blanking_mode(video_index,
pDviTiming->refresh_rate);
if (status) {
video_index += 100; /*Use reduce-blanking mode */
videoMode = viafb_get_modetbl_pointer(video_index);
pDviTiming = videoMode->crtc;
DEBUG_MSG(KERN_INFO
"DVI use reduce blanking mode %d!!\n",
video_index);
}
}
viafb_fill_crtc_timing(pDviTiming, video_index, mode_bpp / 8, set_iga);
viafb_set_output_path(DEVICE_DVI, set_iga,
viaparinfo->chip_info->tmds_chip_info.output_interface);
}
/* Sense DVI Connector */
int viafb_dvi_sense(void)
{
u8 RegSR1E = 0, RegSR3E = 0, RegCR6B = 0, RegCR91 = 0,
RegCR93 = 0, RegCR9B = 0, data;
int ret = false;
DEBUG_MSG(KERN_INFO "viafb_dvi_sense!!\n");
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
/* DI1 Pad on */
RegSR1E = viafb_read_reg(VIASR, SR1E);
viafb_write_reg(SR1E, VIASR, RegSR1E | 0x30);
/* CR6B[0]VCK Input Selection: 1 = External clock. */
RegCR6B = viafb_read_reg(VIACR, CR6B);
viafb_write_reg(CR6B, VIACR, RegCR6B | 0x08);
/* CR91[4] VDD On [3] Data On [2] VEE On [1] Back Light Off
[0] Software Control Power Sequence */
RegCR91 = viafb_read_reg(VIACR, CR91);
viafb_write_reg(CR91, VIACR, 0x1D);
/* CR93[7] DI1 Data Source Selection: 1 = DSP2.
CR93[5] DI1 Clock Source: 1 = internal.
CR93[4] DI1 Clock Polarity.
CR93[3:1] DI1 Clock Adjust. CR93[0] DI1 enable */
RegCR93 = viafb_read_reg(VIACR, CR93);
viafb_write_reg(CR93, VIACR, 0x01);
} else {
/* DVP0/DVP1 Pad on */
RegSR1E = viafb_read_reg(VIASR, SR1E);
viafb_write_reg(SR1E, VIASR, RegSR1E | 0xF0);
/* SR3E[1]Multi-function selection:
0 = Emulate I2C and DDC bus by GPIO2/3/4. */
RegSR3E = viafb_read_reg(VIASR, SR3E);
viafb_write_reg(SR3E, VIASR, RegSR3E & (~0x20));
/* CR91[4] VDD On [3] Data On [2] VEE On [1] Back Light Off
[0] Software Control Power Sequence */
RegCR91 = viafb_read_reg(VIACR, CR91);
viafb_write_reg(CR91, VIACR, 0x1D);
/*CR9B[4] DVP1 Data Source Selection: 1 = From secondary
display.CR9B[2:0] DVP1 Clock Adjust */
RegCR9B = viafb_read_reg(VIACR, CR9B);
viafb_write_reg(CR9B, VIACR, 0x01);
}
data = (u8) tmds_register_read(0x09);
if (data & 0x04)
ret = true;
if (ret == false) {
if (viafb_dvi_query_EDID())
ret = true;
}
/* Restore status */
viafb_write_reg(SR1E, VIASR, RegSR1E);
viafb_write_reg(CR91, VIACR, RegCR91);
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
viafb_write_reg(CR6B, VIACR, RegCR6B);
viafb_write_reg(CR93, VIACR, RegCR93);
} else {
viafb_write_reg(SR3E, VIASR, RegSR3E);
viafb_write_reg(CR9B, VIACR, RegCR9B);
}
return ret;
}
/* Query Flat Panel's EDID Table Version Through DVI Connector */
static int viafb_dvi_query_EDID(void)
{
u8 data0, data1;
int restore;
DEBUG_MSG(KERN_INFO "viafb_dvi_query_EDID!!\n");
restore = viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr;
viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr = 0xA0;
data0 = (u8) tmds_register_read(0x00);
data1 = (u8) tmds_register_read(0x01);
if ((data0 == 0) && (data1 == 0xFF)) {
viaparinfo->chip_info->
tmds_chip_info.tmds_chip_slave_addr = restore;
return EDID_VERSION_1; /* Found EDID1 Table */
}
data0 = (u8) tmds_register_read(0x00);
viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr = restore;
if (data0 == 0x20)
return EDID_VERSION_2; /* Found EDID2 Table */
else
return false;
}
/*
*
* int dvi_get_panel_size_from_DDCv1(void)
*
* - Get Panel Size Using EDID1 Table
*
* Return Type: int
*
*/
static int dvi_get_panel_size_from_DDCv1(void)
{
int i, max_h = 0, max_v = 0, tmp, restore;
unsigned char rData;
unsigned char EDID_DATA[18];
DEBUG_MSG(KERN_INFO "\n dvi_get_panel_size_from_DDCv1 \n");
restore = viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr;
viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr = 0xA0;
rData = tmds_register_read(0x23);
if (rData & 0x3C)
max_h = 640;
if (rData & 0xC0)
max_h = 720;
if (rData & 0x03)
max_h = 800;
rData = tmds_register_read(0x24);
if (rData & 0xC0)
max_h = 800;
if (rData & 0x1E)
max_h = 1024;
if (rData & 0x01)
max_h = 1280;
for (i = 0x25; i < 0x6D; i++) {
switch (i) {
case 0x26:
case 0x28:
case 0x2A:
case 0x2C:
case 0x2E:
case 0x30:
case 0x32:
case 0x34:
rData = tmds_register_read(i);
if (rData == 1)
break;
/* data = (data + 31) * 8 */
tmp = (rData + 31) << 3;
if (tmp > max_h)
max_h = tmp;
break;
case 0x36:
case 0x48:
case 0x5A:
case 0x6C:
tmds_register_read_bytes(i, EDID_DATA, 10);
if (!(EDID_DATA[0] || EDID_DATA[1])) {
/* The first two byte must be zero. */
if (EDID_DATA[3] == 0xFD) {
/* To get max pixel clock. */
viaparinfo->tmds_setting_info->
max_pixel_clock = EDID_DATA[9] * 10;
}
}
break;
default:
break;
}
}
switch (max_h) {
case 640:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_640X480;
break;
case 800:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_800X600;
break;
case 1024:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1024X768;
break;
case 1280:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1280X1024;
break;
case 1400:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1400X1050;
break;
case 1440:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1440X1050;
break;
case 1600:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1600X1200;
break;
case 1920:
if (max_v == 1200) {
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1920X1200;
} else {
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1920X1080;
}
break;
default:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1024X768;
DEBUG_MSG(KERN_INFO "Unknow panel size max resolution = %d !\
set default panel size.\n", max_h);
break;
}
DEBUG_MSG(KERN_INFO "DVI max pixelclock = %d\n",
viaparinfo->tmds_setting_info->max_pixel_clock);
viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr = restore;
return viaparinfo->tmds_setting_info->dvi_panel_size;
}
/*
*
* int dvi_get_panel_size_from_DDCv2(void)
*
* - Get Panel Size Using EDID2 Table
*
* Return Type: int
*
*/
static int dvi_get_panel_size_from_DDCv2(void)
{
int HSize = 0, restore;
unsigned char R_Buffer[2];
DEBUG_MSG(KERN_INFO "\n dvi_get_panel_size_from_DDCv2 \n");
restore = viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr;
viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr = 0xA2;
/* Horizontal: 0x76, 0x77 */
tmds_register_read_bytes(0x76, R_Buffer, 2);
HSize = R_Buffer[0];
HSize += R_Buffer[1] << 8;
switch (HSize) {
case 640:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_640X480;
break;
case 800:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_800X600;
break;
case 1024:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1024X768;
break;
case 1280:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1280X1024;
break;
case 1400:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1400X1050;
break;
case 1440:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1440X1050;
break;
case 1600:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1600X1200;
break;
default:
viaparinfo->tmds_setting_info->dvi_panel_size =
VIA_RES_1024X768;
DEBUG_MSG(KERN_INFO "Unknow panel size max resolution = %d!\
set default panel size.\n", HSize);
break;
}
viaparinfo->chip_info->tmds_chip_info.tmds_chip_slave_addr = restore;
return viaparinfo->tmds_setting_info->dvi_panel_size;
}
/*
*
* unsigned char dvi_get_panel_info(void)
*
* - Get Panel Size
*
* Return Type: unsigned char
*/
static unsigned char dvi_get_panel_info(void)
{
unsigned char dvipanelsize;
DEBUG_MSG(KERN_INFO "dvi_get_panel_info! \n");
viafb_dvi_sense();
switch (viafb_dvi_query_EDID()) {
case 1:
dvi_get_panel_size_from_DDCv1();
break;
case 2:
dvi_get_panel_size_from_DDCv2();
break;
default:
break;
}
DEBUG_MSG(KERN_INFO "dvi panel size is %2d \n",
viaparinfo->tmds_setting_info->dvi_panel_size);
dvipanelsize = (unsigned char)(viaparinfo->
tmds_setting_info->dvi_panel_size);
return dvipanelsize;
}
/* If Disable DVI, turn off pad */
void viafb_dvi_disable(void)
{
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DVP0)
viafb_write_reg(SR1E, VIASR,
viafb_read_reg(VIASR, SR1E) & (~0xC0));
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DVP1)
viafb_write_reg(SR1E, VIASR,
viafb_read_reg(VIASR, SR1E) & (~0x30));
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DFP_HIGH)
viafb_write_reg(SR2A, VIASR,
viafb_read_reg(VIASR, SR2A) & (~0x0C));
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DFP_LOW)
viafb_write_reg(SR2A, VIASR,
viafb_read_reg(VIASR, SR2A) & (~0x03));
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_TMDS)
/* Turn off TMDS power. */
viafb_write_reg(CRD2, VIACR,
viafb_read_reg(VIACR, CRD2) | 0x08);
}
/* If Enable DVI, turn off pad */
void viafb_dvi_enable(void)
{
u8 data;
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DVP0) {
viafb_write_reg(SR1E, VIASR,
viafb_read_reg(VIASR, SR1E) | 0xC0);
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
tmds_register_write(0x88, 0x3b);
else
/*clear CR91[5] to direct on display period
in the secondary diplay path */
viafb_write_reg(CR91, VIACR,
viafb_read_reg(VIACR, CR91) & 0xDF);
}
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DVP1) {
viafb_write_reg(SR1E, VIASR,
viafb_read_reg(VIASR, SR1E) | 0x30);
/*fix dvi cann't be enabled with MB VT5718C4 - Al Zhang */
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
tmds_register_write(0x88, 0x3b);
} else {
/*clear CR91[5] to direct on display period
in the secondary diplay path */
viafb_write_reg(CR91, VIACR,
viafb_read_reg(VIACR, CR91) & 0xDF);
}
/*fix DVI cannot enable on EPIA-M board */
if (viafb_platform_epia_dvi == 1) {
viafb_write_reg_mask(CR91, VIACR, 0x1f, 0x1f);
viafb_write_reg_mask(CR88, VIACR, 0x00, BIT6 + BIT0);
if (viafb_bus_width == 24) {
if (viafb_device_lcd_dualedge == 1)
data = 0x3F;
else
data = 0x37;
viafb_i2c_writebyte(viaparinfo->chip_info->
tmds_chip_info.
tmds_chip_slave_addr,
0x08, data);
}
}
}
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DFP_HIGH) {
viafb_write_reg(SR2A, VIASR,
viafb_read_reg(VIASR, SR2A) | 0x0C);
viafb_write_reg(CR91, VIACR,
viafb_read_reg(VIACR, CR91) & 0xDF);
}
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_DFP_LOW) {
viafb_write_reg(SR2A, VIASR,
viafb_read_reg(VIASR, SR2A) | 0x03);
viafb_write_reg(CR91, VIACR,
viafb_read_reg(VIACR, CR91) & 0xDF);
}
if (viaparinfo->chip_info->
tmds_chip_info.output_interface == INTERFACE_TMDS) {
/* Turn on Display period in the panel path. */
viafb_write_reg_mask(CR91, VIACR, 0, BIT7);
/* Turn on TMDS power. */
viafb_write_reg_mask(CRD2, VIACR, 0, BIT3);
}
}
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE500CL | linux/kernel/fs/btrfs/tree-log.c | 216 | 109812 | /*
* Copyright (C) 2008 Oracle. 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 v2 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 021110-1307, USA.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/list_sort.h>
#include "ctree.h"
#include "transaction.h"
#include "disk-io.h"
#include "locking.h"
#include "print-tree.h"
#include "backref.h"
#include "compat.h"
#include "tree-log.h"
#include "hash.h"
/* magic values for the inode_only field in btrfs_log_inode:
*
* LOG_INODE_ALL means to log everything
* LOG_INODE_EXISTS means to log just enough to recreate the inode
* during log replay
*/
#define LOG_INODE_ALL 0
#define LOG_INODE_EXISTS 1
/*
* directory trouble cases
*
* 1) on rename or unlink, if the inode being unlinked isn't in the fsync
* log, we must force a full commit before doing an fsync of the directory
* where the unlink was done.
* ---> record transid of last unlink/rename per directory
*
* mkdir foo/some_dir
* normal commit
* rename foo/some_dir foo2/some_dir
* mkdir foo/some_dir
* fsync foo/some_dir/some_file
*
* The fsync above will unlink the original some_dir without recording
* it in its new location (foo2). After a crash, some_dir will be gone
* unless the fsync of some_file forces a full commit
*
* 2) we must log any new names for any file or dir that is in the fsync
* log. ---> check inode while renaming/linking.
*
* 2a) we must log any new names for any file or dir during rename
* when the directory they are being removed from was logged.
* ---> check inode and old parent dir during rename
*
* 2a is actually the more important variant. With the extra logging
* a crash might unlink the old name without recreating the new one
*
* 3) after a crash, we must go through any directories with a link count
* of zero and redo the rm -rf
*
* mkdir f1/foo
* normal commit
* rm -rf f1/foo
* fsync(f1)
*
* The directory f1 was fully removed from the FS, but fsync was never
* called on f1, only its parent dir. After a crash the rm -rf must
* be replayed. This must be able to recurse down the entire
* directory tree. The inode link count fixup code takes care of the
* ugly details.
*/
/*
* stages for the tree walking. The first
* stage (0) is to only pin down the blocks we find
* the second stage (1) is to make sure that all the inodes
* we find in the log are created in the subvolume.
*
* The last stage is to deal with directories and links and extents
* and all the other fun semantics
*/
#define LOG_WALK_PIN_ONLY 0
#define LOG_WALK_REPLAY_INODES 1
#define LOG_WALK_REPLAY_ALL 2
static int btrfs_log_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
int inode_only);
static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, u64 objectid);
static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_root *log,
struct btrfs_path *path,
u64 dirid, int del_all);
/*
* tree logging is a special write ahead log used to make sure that
* fsyncs and O_SYNCs can happen without doing full tree commits.
*
* Full tree commits are expensive because they require commonly
* modified blocks to be recowed, creating many dirty pages in the
* extent tree an 4x-6x higher write load than ext3.
*
* Instead of doing a tree commit on every fsync, we use the
* key ranges and transaction ids to find items for a given file or directory
* that have changed in this transaction. Those items are copied into
* a special tree (one per subvolume root), that tree is written to disk
* and then the fsync is considered complete.
*
* After a crash, items are copied out of the log-tree back into the
* subvolume tree. Any file data extents found are recorded in the extent
* allocation tree, and the log-tree freed.
*
* The log tree is read three times, once to pin down all the extents it is
* using in ram and once, once to create all the inodes logged in the tree
* and once to do all the other items.
*/
/*
* start a sub transaction and setup the log tree
* this increments the log tree writer count to make the people
* syncing the tree wait for us to finish
*/
static int start_log_trans(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int ret;
int err = 0;
mutex_lock(&root->log_mutex);
if (root->log_root) {
if (!root->log_start_pid) {
root->log_start_pid = current->pid;
root->log_multiple_pids = false;
} else if (root->log_start_pid != current->pid) {
root->log_multiple_pids = true;
}
atomic_inc(&root->log_batch);
atomic_inc(&root->log_writers);
mutex_unlock(&root->log_mutex);
return 0;
}
root->log_multiple_pids = false;
root->log_start_pid = current->pid;
mutex_lock(&root->fs_info->tree_log_mutex);
if (!root->fs_info->log_root_tree) {
ret = btrfs_init_log_root_tree(trans, root->fs_info);
if (ret)
err = ret;
}
if (err == 0 && !root->log_root) {
ret = btrfs_add_log_tree(trans, root);
if (ret)
err = ret;
}
mutex_unlock(&root->fs_info->tree_log_mutex);
atomic_inc(&root->log_batch);
atomic_inc(&root->log_writers);
mutex_unlock(&root->log_mutex);
return err;
}
/*
* returns 0 if there was a log transaction running and we were able
* to join, or returns -ENOENT if there were not transactions
* in progress
*/
static int join_running_log_trans(struct btrfs_root *root)
{
int ret = -ENOENT;
smp_mb();
if (!root->log_root)
return -ENOENT;
mutex_lock(&root->log_mutex);
if (root->log_root) {
ret = 0;
atomic_inc(&root->log_writers);
}
mutex_unlock(&root->log_mutex);
return ret;
}
/*
* This either makes the current running log transaction wait
* until you call btrfs_end_log_trans() or it makes any future
* log transactions wait until you call btrfs_end_log_trans()
*/
int btrfs_pin_log_trans(struct btrfs_root *root)
{
int ret = -ENOENT;
mutex_lock(&root->log_mutex);
atomic_inc(&root->log_writers);
mutex_unlock(&root->log_mutex);
return ret;
}
/*
* indicate we're done making changes to the log tree
* and wake up anyone waiting to do a sync
*/
void btrfs_end_log_trans(struct btrfs_root *root)
{
if (atomic_dec_and_test(&root->log_writers)) {
smp_mb();
if (waitqueue_active(&root->log_writer_wait))
wake_up(&root->log_writer_wait);
}
}
/*
* the walk control struct is used to pass state down the chain when
* processing the log tree. The stage field tells us which part
* of the log tree processing we are currently doing. The others
* are state fields used for that specific part
*/
struct walk_control {
/* should we free the extent on disk when done? This is used
* at transaction commit time while freeing a log tree
*/
int free;
/* should we write out the extent buffer? This is used
* while flushing the log tree to disk during a sync
*/
int write;
/* should we wait for the extent buffer io to finish? Also used
* while flushing the log tree to disk for a sync
*/
int wait;
/* pin only walk, we record which extents on disk belong to the
* log trees
*/
int pin;
/* what stage of the replay code we're currently in */
int stage;
/* the root we are currently replaying */
struct btrfs_root *replay_dest;
/* the trans handle for the current replay */
struct btrfs_trans_handle *trans;
/* the function that gets used to process blocks we find in the
* tree. Note the extent_buffer might not be up to date when it is
* passed in, and it must be checked or read if you need the data
* inside it
*/
int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
struct walk_control *wc, u64 gen);
};
/*
* process_func used to pin down extents, write them or wait on them
*/
static int process_one_buffer(struct btrfs_root *log,
struct extent_buffer *eb,
struct walk_control *wc, u64 gen)
{
int ret = 0;
if (wc->pin)
ret = btrfs_pin_extent_for_log_replay(log->fs_info->extent_root,
eb->start, eb->len);
if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
if (wc->write)
btrfs_write_tree_block(eb);
if (wc->wait)
btrfs_wait_tree_block_writeback(eb);
}
return ret;
}
/*
* Item overwrite used by replay and tree logging. eb, slot and key all refer
* to the src data we are copying out.
*
* root is the tree we are copying into, and path is a scratch
* path for use in this function (it should be released on entry and
* will be released on exit).
*
* If the key is already in the destination tree the existing item is
* overwritten. If the existing item isn't big enough, it is extended.
* If it is too large, it is truncated.
*
* If the key isn't in the destination yet, a new item is inserted.
*/
static noinline int overwrite_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct extent_buffer *eb, int slot,
struct btrfs_key *key)
{
int ret;
u32 item_size;
u64 saved_i_size = 0;
int save_old_i_size = 0;
unsigned long src_ptr;
unsigned long dst_ptr;
int overwrite_root = 0;
bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
overwrite_root = 1;
item_size = btrfs_item_size_nr(eb, slot);
src_ptr = btrfs_item_ptr_offset(eb, slot);
/* look for the key in the destination tree */
ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
if (ret < 0)
return ret;
if (ret == 0) {
char *src_copy;
char *dst_copy;
u32 dst_size = btrfs_item_size_nr(path->nodes[0],
path->slots[0]);
if (dst_size != item_size)
goto insert;
if (item_size == 0) {
btrfs_release_path(path);
return 0;
}
dst_copy = kmalloc(item_size, GFP_NOFS);
src_copy = kmalloc(item_size, GFP_NOFS);
if (!dst_copy || !src_copy) {
btrfs_release_path(path);
kfree(dst_copy);
kfree(src_copy);
return -ENOMEM;
}
read_extent_buffer(eb, src_copy, src_ptr, item_size);
dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
item_size);
ret = memcmp(dst_copy, src_copy, item_size);
kfree(dst_copy);
kfree(src_copy);
/*
* they have the same contents, just return, this saves
* us from cowing blocks in the destination tree and doing
* extra writes that may not have been done by a previous
* sync
*/
if (ret == 0) {
btrfs_release_path(path);
return 0;
}
/*
* We need to load the old nbytes into the inode so when we
* replay the extents we've logged we get the right nbytes.
*/
if (inode_item) {
struct btrfs_inode_item *item;
u64 nbytes;
item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_inode_item);
nbytes = btrfs_inode_nbytes(path->nodes[0], item);
item = btrfs_item_ptr(eb, slot,
struct btrfs_inode_item);
btrfs_set_inode_nbytes(eb, item, nbytes);
}
} else if (inode_item) {
struct btrfs_inode_item *item;
/*
* New inode, set nbytes to 0 so that the nbytes comes out
* properly when we replay the extents.
*/
item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
btrfs_set_inode_nbytes(eb, item, 0);
}
insert:
btrfs_release_path(path);
/* try to insert the key into the destination tree */
ret = btrfs_insert_empty_item(trans, root, path,
key, item_size);
/* make sure any existing item is the correct size */
if (ret == -EEXIST) {
u32 found_size;
found_size = btrfs_item_size_nr(path->nodes[0],
path->slots[0]);
if (found_size > item_size)
btrfs_truncate_item(root, path, item_size, 1);
else if (found_size < item_size)
btrfs_extend_item(root, path,
item_size - found_size);
} else if (ret) {
return ret;
}
dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
path->slots[0]);
/* don't overwrite an existing inode if the generation number
* was logged as zero. This is done when the tree logging code
* is just logging an inode to make sure it exists after recovery.
*
* Also, don't overwrite i_size on directories during replay.
* log replay inserts and removes directory items based on the
* state of the tree found in the subvolume, and i_size is modified
* as it goes
*/
if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
struct btrfs_inode_item *src_item;
struct btrfs_inode_item *dst_item;
src_item = (struct btrfs_inode_item *)src_ptr;
dst_item = (struct btrfs_inode_item *)dst_ptr;
if (btrfs_inode_generation(eb, src_item) == 0)
goto no_copy;
if (overwrite_root &&
S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
save_old_i_size = 1;
saved_i_size = btrfs_inode_size(path->nodes[0],
dst_item);
}
}
copy_extent_buffer(path->nodes[0], eb, dst_ptr,
src_ptr, item_size);
if (save_old_i_size) {
struct btrfs_inode_item *dst_item;
dst_item = (struct btrfs_inode_item *)dst_ptr;
btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
}
/* make sure the generation is filled in */
if (key->type == BTRFS_INODE_ITEM_KEY) {
struct btrfs_inode_item *dst_item;
dst_item = (struct btrfs_inode_item *)dst_ptr;
if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
btrfs_set_inode_generation(path->nodes[0], dst_item,
trans->transid);
}
}
no_copy:
btrfs_mark_buffer_dirty(path->nodes[0]);
btrfs_release_path(path);
return 0;
}
/*
* simple helper to read an inode off the disk from a given root
* This can only be called for subvolume roots and not for the log
*/
static noinline struct inode *read_one_inode(struct btrfs_root *root,
u64 objectid)
{
struct btrfs_key key;
struct inode *inode;
key.objectid = objectid;
key.type = BTRFS_INODE_ITEM_KEY;
key.offset = 0;
inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
if (IS_ERR(inode)) {
inode = NULL;
} else if (is_bad_inode(inode)) {
iput(inode);
inode = NULL;
}
return inode;
}
/* replays a single extent in 'eb' at 'slot' with 'key' into the
* subvolume 'root'. path is released on entry and should be released
* on exit.
*
* extents in the log tree have not been allocated out of the extent
* tree yet. So, this completes the allocation, taking a reference
* as required if the extent already exists or creating a new extent
* if it isn't in the extent allocation tree yet.
*
* The extent is inserted into the file, dropping any existing extents
* from the file that overlap the new one.
*/
static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct extent_buffer *eb, int slot,
struct btrfs_key *key)
{
int found_type;
u64 extent_end;
u64 start = key->offset;
u64 nbytes = 0;
struct btrfs_file_extent_item *item;
struct inode *inode = NULL;
unsigned long size;
int ret = 0;
item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
found_type = btrfs_file_extent_type(eb, item);
if (found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC) {
nbytes = btrfs_file_extent_num_bytes(eb, item);
extent_end = start + nbytes;
/*
* We don't add to the inodes nbytes if we are prealloc or a
* hole.
*/
if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
nbytes = 0;
} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
size = btrfs_file_extent_inline_len(eb, item);
nbytes = btrfs_file_extent_ram_bytes(eb, item);
extent_end = ALIGN(start + size, root->sectorsize);
} else {
ret = 0;
goto out;
}
inode = read_one_inode(root, key->objectid);
if (!inode) {
ret = -EIO;
goto out;
}
/*
* first check to see if we already have this extent in the
* file. This must be done before the btrfs_drop_extents run
* so we don't try to drop this extent.
*/
ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
start, 0);
if (ret == 0 &&
(found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
struct btrfs_file_extent_item cmp1;
struct btrfs_file_extent_item cmp2;
struct btrfs_file_extent_item *existing;
struct extent_buffer *leaf;
leaf = path->nodes[0];
existing = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
read_extent_buffer(eb, &cmp1, (unsigned long)item,
sizeof(cmp1));
read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
sizeof(cmp2));
/*
* we already have a pointer to this exact extent,
* we don't have to do anything
*/
if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
btrfs_release_path(path);
goto out;
}
}
btrfs_release_path(path);
/* drop any overlapping extents */
ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
if (ret)
goto out;
if (found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC) {
u64 offset;
unsigned long dest_offset;
struct btrfs_key ins;
ret = btrfs_insert_empty_item(trans, root, path, key,
sizeof(*item));
if (ret)
goto out;
dest_offset = btrfs_item_ptr_offset(path->nodes[0],
path->slots[0]);
copy_extent_buffer(path->nodes[0], eb, dest_offset,
(unsigned long)item, sizeof(*item));
ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
ins.type = BTRFS_EXTENT_ITEM_KEY;
offset = key->offset - btrfs_file_extent_offset(eb, item);
if (ins.objectid > 0) {
u64 csum_start;
u64 csum_end;
LIST_HEAD(ordered_sums);
/*
* is this extent already allocated in the extent
* allocation tree? If so, just add a reference
*/
ret = btrfs_lookup_extent(root, ins.objectid,
ins.offset);
if (ret == 0) {
ret = btrfs_inc_extent_ref(trans, root,
ins.objectid, ins.offset,
0, root->root_key.objectid,
key->objectid, offset, 0);
if (ret)
goto out;
} else {
/*
* insert the extent pointer in the extent
* allocation tree
*/
ret = btrfs_alloc_logged_file_extent(trans,
root, root->root_key.objectid,
key->objectid, offset, &ins);
if (ret)
goto out;
}
btrfs_release_path(path);
if (btrfs_file_extent_compression(eb, item)) {
csum_start = ins.objectid;
csum_end = csum_start + ins.offset;
} else {
csum_start = ins.objectid +
btrfs_file_extent_offset(eb, item);
csum_end = csum_start +
btrfs_file_extent_num_bytes(eb, item);
}
ret = btrfs_lookup_csums_range(root->log_root,
csum_start, csum_end - 1,
&ordered_sums, 0);
if (ret)
goto out;
while (!list_empty(&ordered_sums)) {
struct btrfs_ordered_sum *sums;
sums = list_entry(ordered_sums.next,
struct btrfs_ordered_sum,
list);
if (!ret)
ret = btrfs_csum_file_blocks(trans,
root->fs_info->csum_root,
sums);
list_del(&sums->list);
kfree(sums);
}
if (ret)
goto out;
} else {
btrfs_release_path(path);
}
} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
/* inline extents are easy, we just overwrite them */
ret = overwrite_item(trans, root, path, eb, slot, key);
if (ret)
goto out;
}
inode_add_bytes(inode, nbytes);
ret = btrfs_update_inode(trans, root, inode);
out:
if (inode)
iput(inode);
return ret;
}
/*
* when cleaning up conflicts between the directory names in the
* subvolume, directory names in the log and directory names in the
* inode back references, we may have to unlink inodes from directories.
*
* This is a helper function to do the unlink of a specific directory
* item
*/
static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct inode *dir,
struct btrfs_dir_item *di)
{
struct inode *inode;
char *name;
int name_len;
struct extent_buffer *leaf;
struct btrfs_key location;
int ret;
leaf = path->nodes[0];
btrfs_dir_item_key_to_cpu(leaf, di, &location);
name_len = btrfs_dir_name_len(leaf, di);
name = kmalloc(name_len, GFP_NOFS);
if (!name)
return -ENOMEM;
read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
btrfs_release_path(path);
inode = read_one_inode(root, location.objectid);
if (!inode) {
ret = -EIO;
goto out;
}
ret = link_to_fixup_dir(trans, root, path, location.objectid);
if (ret)
goto out;
ret = btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
if (ret)
goto out;
btrfs_run_delayed_items(trans, root);
out:
kfree(name);
iput(inode);
return ret;
}
/*
* helper function to see if a given name and sequence number found
* in an inode back reference are already in a directory and correctly
* point to this inode
*/
static noinline int inode_in_dir(struct btrfs_root *root,
struct btrfs_path *path,
u64 dirid, u64 objectid, u64 index,
const char *name, int name_len)
{
struct btrfs_dir_item *di;
struct btrfs_key location;
int match = 0;
di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
index, name, name_len, 0);
if (di && !IS_ERR(di)) {
btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
if (location.objectid != objectid)
goto out;
} else
goto out;
btrfs_release_path(path);
di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
if (di && !IS_ERR(di)) {
btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
if (location.objectid != objectid)
goto out;
} else
goto out;
match = 1;
out:
btrfs_release_path(path);
return match;
}
/*
* helper function to check a log tree for a named back reference in
* an inode. This is used to decide if a back reference that is
* found in the subvolume conflicts with what we find in the log.
*
* inode backreferences may have multiple refs in a single item,
* during replay we process one reference at a time, and we don't
* want to delete valid links to a file from the subvolume if that
* link is also in the log.
*/
static noinline int backref_in_log(struct btrfs_root *log,
struct btrfs_key *key,
u64 ref_objectid,
char *name, int namelen)
{
struct btrfs_path *path;
struct btrfs_inode_ref *ref;
unsigned long ptr;
unsigned long ptr_end;
unsigned long name_ptr;
int found_name_len;
int item_size;
int ret;
int match = 0;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
if (ret != 0)
goto out;
ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
if (key->type == BTRFS_INODE_EXTREF_KEY) {
if (btrfs_find_name_in_ext_backref(path, ref_objectid,
name, namelen, NULL))
match = 1;
goto out;
}
item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
ptr_end = ptr + item_size;
while (ptr < ptr_end) {
ref = (struct btrfs_inode_ref *)ptr;
found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
if (found_name_len == namelen) {
name_ptr = (unsigned long)(ref + 1);
ret = memcmp_extent_buffer(path->nodes[0], name,
name_ptr, namelen);
if (ret == 0) {
match = 1;
goto out;
}
}
ptr = (unsigned long)(ref + 1) + found_name_len;
}
out:
btrfs_free_path(path);
return match;
}
static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_root *log_root,
struct inode *dir, struct inode *inode,
struct extent_buffer *eb,
u64 inode_objectid, u64 parent_objectid,
u64 ref_index, char *name, int namelen,
int *search_done)
{
int ret;
char *victim_name;
int victim_name_len;
struct extent_buffer *leaf;
struct btrfs_dir_item *di;
struct btrfs_key search_key;
struct btrfs_inode_extref *extref;
again:
/* Search old style refs */
search_key.objectid = inode_objectid;
search_key.type = BTRFS_INODE_REF_KEY;
search_key.offset = parent_objectid;
ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
if (ret == 0) {
struct btrfs_inode_ref *victim_ref;
unsigned long ptr;
unsigned long ptr_end;
leaf = path->nodes[0];
/* are we trying to overwrite a back ref for the root directory
* if so, just jump out, we're done
*/
if (search_key.objectid == search_key.offset)
return 1;
/* check all the names in this back reference to see
* if they are in the log. if so, we allow them to stay
* otherwise they must be unlinked as a conflict
*/
ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
while (ptr < ptr_end) {
victim_ref = (struct btrfs_inode_ref *)ptr;
victim_name_len = btrfs_inode_ref_name_len(leaf,
victim_ref);
victim_name = kmalloc(victim_name_len, GFP_NOFS);
if (!victim_name)
return -ENOMEM;
read_extent_buffer(leaf, victim_name,
(unsigned long)(victim_ref + 1),
victim_name_len);
if (!backref_in_log(log_root, &search_key,
parent_objectid,
victim_name,
victim_name_len)) {
btrfs_inc_nlink(inode);
btrfs_release_path(path);
ret = btrfs_unlink_inode(trans, root, dir,
inode, victim_name,
victim_name_len);
kfree(victim_name);
if (ret)
return ret;
btrfs_run_delayed_items(trans, root);
*search_done = 1;
goto again;
}
kfree(victim_name);
ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
}
/*
* NOTE: we have searched root tree and checked the
* coresponding ref, it does not need to check again.
*/
*search_done = 1;
}
btrfs_release_path(path);
/* Same search but for extended refs */
extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
inode_objectid, parent_objectid, 0,
0);
if (!IS_ERR_OR_NULL(extref)) {
u32 item_size;
u32 cur_offset = 0;
unsigned long base;
struct inode *victim_parent;
leaf = path->nodes[0];
item_size = btrfs_item_size_nr(leaf, path->slots[0]);
base = btrfs_item_ptr_offset(leaf, path->slots[0]);
while (cur_offset < item_size) {
extref = (struct btrfs_inode_extref *)base + cur_offset;
victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
goto next;
victim_name = kmalloc(victim_name_len, GFP_NOFS);
if (!victim_name)
return -ENOMEM;
read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
victim_name_len);
search_key.objectid = inode_objectid;
search_key.type = BTRFS_INODE_EXTREF_KEY;
search_key.offset = btrfs_extref_hash(parent_objectid,
victim_name,
victim_name_len);
ret = 0;
if (!backref_in_log(log_root, &search_key,
parent_objectid, victim_name,
victim_name_len)) {
ret = -ENOENT;
victim_parent = read_one_inode(root,
parent_objectid);
if (victim_parent) {
btrfs_inc_nlink(inode);
btrfs_release_path(path);
ret = btrfs_unlink_inode(trans, root,
victim_parent,
inode,
victim_name,
victim_name_len);
btrfs_run_delayed_items(trans, root);
}
iput(victim_parent);
kfree(victim_name);
if (ret)
return ret;
*search_done = 1;
goto again;
}
kfree(victim_name);
if (ret)
return ret;
next:
cur_offset += victim_name_len + sizeof(*extref);
}
*search_done = 1;
}
btrfs_release_path(path);
/* look for a conflicting sequence number */
di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
ref_index, name, namelen, 0);
if (di && !IS_ERR(di)) {
ret = drop_one_dir_item(trans, root, path, dir, di);
if (ret)
return ret;
}
btrfs_release_path(path);
/* look for a conflicing name */
di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
name, namelen, 0);
if (di && !IS_ERR(di)) {
ret = drop_one_dir_item(trans, root, path, dir, di);
if (ret)
return ret;
}
btrfs_release_path(path);
return 0;
}
static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
u32 *namelen, char **name, u64 *index,
u64 *parent_objectid)
{
struct btrfs_inode_extref *extref;
extref = (struct btrfs_inode_extref *)ref_ptr;
*namelen = btrfs_inode_extref_name_len(eb, extref);
*name = kmalloc(*namelen, GFP_NOFS);
if (*name == NULL)
return -ENOMEM;
read_extent_buffer(eb, *name, (unsigned long)&extref->name,
*namelen);
*index = btrfs_inode_extref_index(eb, extref);
if (parent_objectid)
*parent_objectid = btrfs_inode_extref_parent(eb, extref);
return 0;
}
static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
u32 *namelen, char **name, u64 *index)
{
struct btrfs_inode_ref *ref;
ref = (struct btrfs_inode_ref *)ref_ptr;
*namelen = btrfs_inode_ref_name_len(eb, ref);
*name = kmalloc(*namelen, GFP_NOFS);
if (*name == NULL)
return -ENOMEM;
read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
*index = btrfs_inode_ref_index(eb, ref);
return 0;
}
/*
* replay one inode back reference item found in the log tree.
* eb, slot and key refer to the buffer and key found in the log tree.
* root is the destination we are replaying into, and path is for temp
* use by this function. (it should be released on return).
*/
static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_root *log,
struct btrfs_path *path,
struct extent_buffer *eb, int slot,
struct btrfs_key *key)
{
struct inode *dir;
struct inode *inode;
unsigned long ref_ptr;
unsigned long ref_end;
char *name;
int namelen;
int ret;
int search_done = 0;
int log_ref_ver = 0;
u64 parent_objectid;
u64 inode_objectid;
u64 ref_index = 0;
int ref_struct_size;
ref_ptr = btrfs_item_ptr_offset(eb, slot);
ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
if (key->type == BTRFS_INODE_EXTREF_KEY) {
struct btrfs_inode_extref *r;
ref_struct_size = sizeof(struct btrfs_inode_extref);
log_ref_ver = 1;
r = (struct btrfs_inode_extref *)ref_ptr;
parent_objectid = btrfs_inode_extref_parent(eb, r);
} else {
ref_struct_size = sizeof(struct btrfs_inode_ref);
parent_objectid = key->offset;
}
inode_objectid = key->objectid;
/*
* it is possible that we didn't log all the parent directories
* for a given inode. If we don't find the dir, just don't
* copy the back ref in. The link count fixup code will take
* care of the rest
*/
dir = read_one_inode(root, parent_objectid);
if (!dir)
return -ENOENT;
inode = read_one_inode(root, inode_objectid);
if (!inode) {
iput(dir);
return -EIO;
}
while (ref_ptr < ref_end) {
if (log_ref_ver) {
ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
&ref_index, &parent_objectid);
/*
* parent object can change from one array
* item to another.
*/
if (!dir)
dir = read_one_inode(root, parent_objectid);
if (!dir)
return -ENOENT;
} else {
ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
&ref_index);
}
if (ret)
return ret;
/* if we already have a perfect match, we're done */
if (!inode_in_dir(root, path, btrfs_ino(dir), btrfs_ino(inode),
ref_index, name, namelen)) {
/*
* look for a conflicting back reference in the
* metadata. if we find one we have to unlink that name
* of the file before we add our new link. Later on, we
* overwrite any existing back reference, and we don't
* want to create dangling pointers in the directory.
*/
if (!search_done) {
ret = __add_inode_ref(trans, root, path, log,
dir, inode, eb,
inode_objectid,
parent_objectid,
ref_index, name, namelen,
&search_done);
if (ret == 1) {
ret = 0;
goto out;
}
if (ret)
goto out;
}
/* insert our name */
ret = btrfs_add_link(trans, dir, inode, name, namelen,
0, ref_index);
if (ret)
goto out;
btrfs_update_inode(trans, root, inode);
}
ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
kfree(name);
if (log_ref_ver) {
iput(dir);
dir = NULL;
}
}
/* finally write the back reference in the inode */
ret = overwrite_item(trans, root, path, eb, slot, key);
out:
btrfs_release_path(path);
iput(dir);
iput(inode);
return ret;
}
static int insert_orphan_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root, u64 offset)
{
int ret;
ret = btrfs_find_orphan_item(root, offset);
if (ret > 0)
ret = btrfs_insert_orphan_item(trans, root, offset);
return ret;
}
static int count_inode_extrefs(struct btrfs_root *root,
struct inode *inode, struct btrfs_path *path)
{
int ret = 0;
int name_len;
unsigned int nlink = 0;
u32 item_size;
u32 cur_offset = 0;
u64 inode_objectid = btrfs_ino(inode);
u64 offset = 0;
unsigned long ptr;
struct btrfs_inode_extref *extref;
struct extent_buffer *leaf;
while (1) {
ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
&extref, &offset);
if (ret)
break;
leaf = path->nodes[0];
item_size = btrfs_item_size_nr(leaf, path->slots[0]);
ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
while (cur_offset < item_size) {
extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
name_len = btrfs_inode_extref_name_len(leaf, extref);
nlink++;
cur_offset += name_len + sizeof(*extref);
}
offset++;
btrfs_release_path(path);
}
btrfs_release_path(path);
if (ret < 0)
return ret;
return nlink;
}
static int count_inode_refs(struct btrfs_root *root,
struct inode *inode, struct btrfs_path *path)
{
int ret;
struct btrfs_key key;
unsigned int nlink = 0;
unsigned long ptr;
unsigned long ptr_end;
int name_len;
u64 ino = btrfs_ino(inode);
key.objectid = ino;
key.type = BTRFS_INODE_REF_KEY;
key.offset = (u64)-1;
while (1) {
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
break;
if (ret > 0) {
if (path->slots[0] == 0)
break;
path->slots[0]--;
}
btrfs_item_key_to_cpu(path->nodes[0], &key,
path->slots[0]);
if (key.objectid != ino ||
key.type != BTRFS_INODE_REF_KEY)
break;
ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
path->slots[0]);
while (ptr < ptr_end) {
struct btrfs_inode_ref *ref;
ref = (struct btrfs_inode_ref *)ptr;
name_len = btrfs_inode_ref_name_len(path->nodes[0],
ref);
ptr = (unsigned long)(ref + 1) + name_len;
nlink++;
}
if (key.offset == 0)
break;
key.offset--;
btrfs_release_path(path);
}
btrfs_release_path(path);
return nlink;
}
/*
* There are a few corners where the link count of the file can't
* be properly maintained during replay. So, instead of adding
* lots of complexity to the log code, we just scan the backrefs
* for any file that has been through replay.
*
* The scan will update the link count on the inode to reflect the
* number of back refs found. If it goes down to zero, the iput
* will free the inode.
*/
static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *inode)
{
struct btrfs_path *path;
int ret;
u64 nlink = 0;
u64 ino = btrfs_ino(inode);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = count_inode_refs(root, inode, path);
if (ret < 0)
goto out;
nlink = ret;
ret = count_inode_extrefs(root, inode, path);
if (ret == -ENOENT)
ret = 0;
if (ret < 0)
goto out;
nlink += ret;
ret = 0;
if (nlink != inode->i_nlink) {
set_nlink(inode, nlink);
btrfs_update_inode(trans, root, inode);
}
BTRFS_I(inode)->index_cnt = (u64)-1;
if (inode->i_nlink == 0) {
if (S_ISDIR(inode->i_mode)) {
ret = replay_dir_deletes(trans, root, NULL, path,
ino, 1);
if (ret)
goto out;
}
ret = insert_orphan_item(trans, root, ino);
}
out:
btrfs_free_path(path);
return ret;
}
static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path)
{
int ret;
struct btrfs_key key;
struct inode *inode;
key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
key.type = BTRFS_ORPHAN_ITEM_KEY;
key.offset = (u64)-1;
while (1) {
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
if (ret < 0)
break;
if (ret == 1) {
if (path->slots[0] == 0)
break;
path->slots[0]--;
}
btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
key.type != BTRFS_ORPHAN_ITEM_KEY)
break;
ret = btrfs_del_item(trans, root, path);
if (ret)
goto out;
btrfs_release_path(path);
inode = read_one_inode(root, key.offset);
if (!inode)
return -EIO;
ret = fixup_inode_link_count(trans, root, inode);
iput(inode);
if (ret)
goto out;
/*
* fixup on a directory may create new entries,
* make sure we always look for the highset possible
* offset
*/
key.offset = (u64)-1;
}
ret = 0;
out:
btrfs_release_path(path);
return ret;
}
/*
* record a given inode in the fixup dir so we can check its link
* count when replay is done. The link count is incremented here
* so the inode won't go away until we check it
*/
static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
u64 objectid)
{
struct btrfs_key key;
int ret = 0;
struct inode *inode;
inode = read_one_inode(root, objectid);
if (!inode)
return -EIO;
key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
key.offset = objectid;
ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
btrfs_release_path(path);
if (ret == 0) {
if (!inode->i_nlink)
set_nlink(inode, 1);
else
btrfs_inc_nlink(inode);
ret = btrfs_update_inode(trans, root, inode);
} else if (ret == -EEXIST) {
ret = 0;
} else {
BUG(); /* Logic Error */
}
iput(inode);
return ret;
}
/*
* when replaying the log for a directory, we only insert names
* for inodes that actually exist. This means an fsync on a directory
* does not implicitly fsync all the new files in it
*/
static noinline int insert_one_name(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
u64 dirid, u64 index,
char *name, int name_len, u8 type,
struct btrfs_key *location)
{
struct inode *inode;
struct inode *dir;
int ret;
inode = read_one_inode(root, location->objectid);
if (!inode)
return -ENOENT;
dir = read_one_inode(root, dirid);
if (!dir) {
iput(inode);
return -EIO;
}
ret = btrfs_add_link(trans, dir, inode, name, name_len, 1, index);
/* FIXME, put inode into FIXUP list */
iput(inode);
iput(dir);
return ret;
}
/*
* take a single entry in a log directory item and replay it into
* the subvolume.
*
* if a conflicting item exists in the subdirectory already,
* the inode it points to is unlinked and put into the link count
* fix up tree.
*
* If a name from the log points to a file or directory that does
* not exist in the FS, it is skipped. fsyncs on directories
* do not force down inodes inside that directory, just changes to the
* names or unlinks in a directory.
*/
static noinline int replay_one_name(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct extent_buffer *eb,
struct btrfs_dir_item *di,
struct btrfs_key *key)
{
char *name;
int name_len;
struct btrfs_dir_item *dst_di;
struct btrfs_key found_key;
struct btrfs_key log_key;
struct inode *dir;
u8 log_type;
int exists;
int ret = 0;
dir = read_one_inode(root, key->objectid);
if (!dir)
return -EIO;
name_len = btrfs_dir_name_len(eb, di);
name = kmalloc(name_len, GFP_NOFS);
if (!name)
return -ENOMEM;
log_type = btrfs_dir_type(eb, di);
read_extent_buffer(eb, name, (unsigned long)(di + 1),
name_len);
btrfs_dir_item_key_to_cpu(eb, di, &log_key);
exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
if (exists == 0)
exists = 1;
else
exists = 0;
btrfs_release_path(path);
if (key->type == BTRFS_DIR_ITEM_KEY) {
dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
name, name_len, 1);
} else if (key->type == BTRFS_DIR_INDEX_KEY) {
dst_di = btrfs_lookup_dir_index_item(trans, root, path,
key->objectid,
key->offset, name,
name_len, 1);
} else {
/* Corruption */
ret = -EINVAL;
goto out;
}
if (IS_ERR_OR_NULL(dst_di)) {
/* we need a sequence number to insert, so we only
* do inserts for the BTRFS_DIR_INDEX_KEY types
*/
if (key->type != BTRFS_DIR_INDEX_KEY)
goto out;
goto insert;
}
btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
/* the existing item matches the logged item */
if (found_key.objectid == log_key.objectid &&
found_key.type == log_key.type &&
found_key.offset == log_key.offset &&
btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
goto out;
}
/*
* don't drop the conflicting directory entry if the inode
* for the new entry doesn't exist
*/
if (!exists)
goto out;
ret = drop_one_dir_item(trans, root, path, dir, dst_di);
if (ret)
goto out;
if (key->type == BTRFS_DIR_INDEX_KEY)
goto insert;
out:
btrfs_release_path(path);
kfree(name);
iput(dir);
return ret;
insert:
btrfs_release_path(path);
ret = insert_one_name(trans, root, path, key->objectid, key->offset,
name, name_len, log_type, &log_key);
if (ret && ret != -ENOENT)
goto out;
ret = 0;
goto out;
}
/*
* find all the names in a directory item and reconcile them into
* the subvolume. Only BTRFS_DIR_ITEM_KEY types will have more than
* one name in a directory item, but the same code gets used for
* both directory index types
*/
static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct extent_buffer *eb, int slot,
struct btrfs_key *key)
{
int ret;
u32 item_size = btrfs_item_size_nr(eb, slot);
struct btrfs_dir_item *di;
int name_len;
unsigned long ptr;
unsigned long ptr_end;
ptr = btrfs_item_ptr_offset(eb, slot);
ptr_end = ptr + item_size;
while (ptr < ptr_end) {
di = (struct btrfs_dir_item *)ptr;
if (verify_dir_item(root, eb, di))
return -EIO;
name_len = btrfs_dir_name_len(eb, di);
ret = replay_one_name(trans, root, path, eb, di, key);
if (ret)
return ret;
ptr = (unsigned long)(di + 1);
ptr += name_len;
}
return 0;
}
/*
* directory replay has two parts. There are the standard directory
* items in the log copied from the subvolume, and range items
* created in the log while the subvolume was logged.
*
* The range items tell us which parts of the key space the log
* is authoritative for. During replay, if a key in the subvolume
* directory is in a logged range item, but not actually in the log
* that means it was deleted from the directory before the fsync
* and should be removed.
*/
static noinline int find_dir_range(struct btrfs_root *root,
struct btrfs_path *path,
u64 dirid, int key_type,
u64 *start_ret, u64 *end_ret)
{
struct btrfs_key key;
u64 found_end;
struct btrfs_dir_log_item *item;
int ret;
int nritems;
if (*start_ret == (u64)-1)
return 1;
key.objectid = dirid;
key.type = key_type;
key.offset = *start_ret;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out;
if (ret > 0) {
if (path->slots[0] == 0)
goto out;
path->slots[0]--;
}
if (ret != 0)
btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
if (key.type != key_type || key.objectid != dirid) {
ret = 1;
goto next;
}
item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_dir_log_item);
found_end = btrfs_dir_log_end(path->nodes[0], item);
if (*start_ret >= key.offset && *start_ret <= found_end) {
ret = 0;
*start_ret = key.offset;
*end_ret = found_end;
goto out;
}
ret = 1;
next:
/* check the next slot in the tree to see if it is a valid item */
nritems = btrfs_header_nritems(path->nodes[0]);
if (path->slots[0] >= nritems) {
ret = btrfs_next_leaf(root, path);
if (ret)
goto out;
} else {
path->slots[0]++;
}
btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
if (key.type != key_type || key.objectid != dirid) {
ret = 1;
goto out;
}
item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_dir_log_item);
found_end = btrfs_dir_log_end(path->nodes[0], item);
*start_ret = key.offset;
*end_ret = found_end;
ret = 0;
out:
btrfs_release_path(path);
return ret;
}
/*
* this looks for a given directory item in the log. If the directory
* item is not in the log, the item is removed and the inode it points
* to is unlinked
*/
static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_root *log,
struct btrfs_path *path,
struct btrfs_path *log_path,
struct inode *dir,
struct btrfs_key *dir_key)
{
int ret;
struct extent_buffer *eb;
int slot;
u32 item_size;
struct btrfs_dir_item *di;
struct btrfs_dir_item *log_di;
int name_len;
unsigned long ptr;
unsigned long ptr_end;
char *name;
struct inode *inode;
struct btrfs_key location;
again:
eb = path->nodes[0];
slot = path->slots[0];
item_size = btrfs_item_size_nr(eb, slot);
ptr = btrfs_item_ptr_offset(eb, slot);
ptr_end = ptr + item_size;
while (ptr < ptr_end) {
di = (struct btrfs_dir_item *)ptr;
if (verify_dir_item(root, eb, di)) {
ret = -EIO;
goto out;
}
name_len = btrfs_dir_name_len(eb, di);
name = kmalloc(name_len, GFP_NOFS);
if (!name) {
ret = -ENOMEM;
goto out;
}
read_extent_buffer(eb, name, (unsigned long)(di + 1),
name_len);
log_di = NULL;
if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
log_di = btrfs_lookup_dir_item(trans, log, log_path,
dir_key->objectid,
name, name_len, 0);
} else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
log_di = btrfs_lookup_dir_index_item(trans, log,
log_path,
dir_key->objectid,
dir_key->offset,
name, name_len, 0);
}
if (IS_ERR_OR_NULL(log_di)) {
btrfs_dir_item_key_to_cpu(eb, di, &location);
btrfs_release_path(path);
btrfs_release_path(log_path);
inode = read_one_inode(root, location.objectid);
if (!inode) {
kfree(name);
return -EIO;
}
ret = link_to_fixup_dir(trans, root,
path, location.objectid);
if (ret) {
kfree(name);
iput(inode);
goto out;
}
btrfs_inc_nlink(inode);
ret = btrfs_unlink_inode(trans, root, dir, inode,
name, name_len);
if (!ret)
btrfs_run_delayed_items(trans, root);
kfree(name);
iput(inode);
if (ret)
goto out;
/* there might still be more names under this key
* check and repeat if required
*/
ret = btrfs_search_slot(NULL, root, dir_key, path,
0, 0);
if (ret == 0)
goto again;
ret = 0;
goto out;
}
btrfs_release_path(log_path);
kfree(name);
ptr = (unsigned long)(di + 1);
ptr += name_len;
}
ret = 0;
out:
btrfs_release_path(path);
btrfs_release_path(log_path);
return ret;
}
/*
* deletion replay happens before we copy any new directory items
* out of the log or out of backreferences from inodes. It
* scans the log to find ranges of keys that log is authoritative for,
* and then scans the directory to find items in those ranges that are
* not present in the log.
*
* Anything we don't find in the log is unlinked and removed from the
* directory.
*/
static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_root *log,
struct btrfs_path *path,
u64 dirid, int del_all)
{
u64 range_start;
u64 range_end;
int key_type = BTRFS_DIR_LOG_ITEM_KEY;
int ret = 0;
struct btrfs_key dir_key;
struct btrfs_key found_key;
struct btrfs_path *log_path;
struct inode *dir;
dir_key.objectid = dirid;
dir_key.type = BTRFS_DIR_ITEM_KEY;
log_path = btrfs_alloc_path();
if (!log_path)
return -ENOMEM;
dir = read_one_inode(root, dirid);
/* it isn't an error if the inode isn't there, that can happen
* because we replay the deletes before we copy in the inode item
* from the log
*/
if (!dir) {
btrfs_free_path(log_path);
return 0;
}
again:
range_start = 0;
range_end = 0;
while (1) {
if (del_all)
range_end = (u64)-1;
else {
ret = find_dir_range(log, path, dirid, key_type,
&range_start, &range_end);
if (ret != 0)
break;
}
dir_key.offset = range_start;
while (1) {
int nritems;
ret = btrfs_search_slot(NULL, root, &dir_key, path,
0, 0);
if (ret < 0)
goto out;
nritems = btrfs_header_nritems(path->nodes[0]);
if (path->slots[0] >= nritems) {
ret = btrfs_next_leaf(root, path);
if (ret)
break;
}
btrfs_item_key_to_cpu(path->nodes[0], &found_key,
path->slots[0]);
if (found_key.objectid != dirid ||
found_key.type != dir_key.type)
goto next_type;
if (found_key.offset > range_end)
break;
ret = check_item_in_log(trans, root, log, path,
log_path, dir,
&found_key);
if (ret)
goto out;
if (found_key.offset == (u64)-1)
break;
dir_key.offset = found_key.offset + 1;
}
btrfs_release_path(path);
if (range_end == (u64)-1)
break;
range_start = range_end + 1;
}
next_type:
ret = 0;
if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
key_type = BTRFS_DIR_LOG_INDEX_KEY;
dir_key.type = BTRFS_DIR_INDEX_KEY;
btrfs_release_path(path);
goto again;
}
out:
btrfs_release_path(path);
btrfs_free_path(log_path);
iput(dir);
return ret;
}
/*
* the process_func used to replay items from the log tree. This
* gets called in two different stages. The first stage just looks
* for inodes and makes sure they are all copied into the subvolume.
*
* The second stage copies all the other item types from the log into
* the subvolume. The two stage approach is slower, but gets rid of
* lots of complexity around inodes referencing other inodes that exist
* only in the log (references come from either directory items or inode
* back refs).
*/
static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
struct walk_control *wc, u64 gen)
{
int nritems;
struct btrfs_path *path;
struct btrfs_root *root = wc->replay_dest;
struct btrfs_key key;
int level;
int i;
int ret;
ret = btrfs_read_buffer(eb, gen);
if (ret)
return ret;
level = btrfs_header_level(eb);
if (level != 0)
return 0;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
nritems = btrfs_header_nritems(eb);
for (i = 0; i < nritems; i++) {
btrfs_item_key_to_cpu(eb, &key, i);
/* inode keys are done during the first stage */
if (key.type == BTRFS_INODE_ITEM_KEY &&
wc->stage == LOG_WALK_REPLAY_INODES) {
struct btrfs_inode_item *inode_item;
u32 mode;
inode_item = btrfs_item_ptr(eb, i,
struct btrfs_inode_item);
mode = btrfs_inode_mode(eb, inode_item);
if (S_ISDIR(mode)) {
ret = replay_dir_deletes(wc->trans,
root, log, path, key.objectid, 0);
if (ret)
break;
}
ret = overwrite_item(wc->trans, root, path,
eb, i, &key);
if (ret)
break;
/* for regular files, make sure corresponding
* orhpan item exist. extents past the new EOF
* will be truncated later by orphan cleanup.
*/
if (S_ISREG(mode)) {
ret = insert_orphan_item(wc->trans, root,
key.objectid);
if (ret)
break;
}
ret = link_to_fixup_dir(wc->trans, root,
path, key.objectid);
if (ret)
break;
}
if (wc->stage < LOG_WALK_REPLAY_ALL)
continue;
/* these keys are simply copied */
if (key.type == BTRFS_XATTR_ITEM_KEY) {
ret = overwrite_item(wc->trans, root, path,
eb, i, &key);
if (ret)
break;
} else if (key.type == BTRFS_INODE_REF_KEY) {
ret = add_inode_ref(wc->trans, root, log, path,
eb, i, &key);
if (ret && ret != -ENOENT)
break;
ret = 0;
} else if (key.type == BTRFS_INODE_EXTREF_KEY) {
ret = add_inode_ref(wc->trans, root, log, path,
eb, i, &key);
if (ret && ret != -ENOENT)
break;
ret = 0;
} else if (key.type == BTRFS_EXTENT_DATA_KEY) {
ret = replay_one_extent(wc->trans, root, path,
eb, i, &key);
if (ret)
break;
} else if (key.type == BTRFS_DIR_ITEM_KEY ||
key.type == BTRFS_DIR_INDEX_KEY) {
ret = replay_one_dir_item(wc->trans, root, path,
eb, i, &key);
if (ret)
break;
}
}
btrfs_free_path(path);
return ret;
}
static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int *level,
struct walk_control *wc)
{
u64 root_owner;
u64 bytenr;
u64 ptr_gen;
struct extent_buffer *next;
struct extent_buffer *cur;
struct extent_buffer *parent;
u32 blocksize;
int ret = 0;
WARN_ON(*level < 0);
WARN_ON(*level >= BTRFS_MAX_LEVEL);
while (*level > 0) {
WARN_ON(*level < 0);
WARN_ON(*level >= BTRFS_MAX_LEVEL);
cur = path->nodes[*level];
if (btrfs_header_level(cur) != *level)
WARN_ON(1);
if (path->slots[*level] >=
btrfs_header_nritems(cur))
break;
bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
blocksize = btrfs_level_size(root, *level - 1);
parent = path->nodes[*level];
root_owner = btrfs_header_owner(parent);
next = btrfs_find_create_tree_block(root, bytenr, blocksize);
if (!next)
return -ENOMEM;
if (*level == 1) {
ret = wc->process_func(root, next, wc, ptr_gen);
if (ret) {
free_extent_buffer(next);
return ret;
}
path->slots[*level]++;
if (wc->free) {
ret = btrfs_read_buffer(next, ptr_gen);
if (ret) {
free_extent_buffer(next);
return ret;
}
btrfs_tree_lock(next);
btrfs_set_lock_blocking(next);
clean_tree_block(trans, root, next);
btrfs_wait_tree_block_writeback(next);
btrfs_tree_unlock(next);
WARN_ON(root_owner !=
BTRFS_TREE_LOG_OBJECTID);
ret = btrfs_free_and_pin_reserved_extent(root,
bytenr, blocksize);
if (ret) {
free_extent_buffer(next);
return ret;
}
}
free_extent_buffer(next);
continue;
}
ret = btrfs_read_buffer(next, ptr_gen);
if (ret) {
free_extent_buffer(next);
return ret;
}
WARN_ON(*level <= 0);
if (path->nodes[*level-1])
free_extent_buffer(path->nodes[*level-1]);
path->nodes[*level-1] = next;
*level = btrfs_header_level(next);
path->slots[*level] = 0;
cond_resched();
}
WARN_ON(*level < 0);
WARN_ON(*level >= BTRFS_MAX_LEVEL);
path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
cond_resched();
return 0;
}
static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int *level,
struct walk_control *wc)
{
u64 root_owner;
int i;
int slot;
int ret;
for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
slot = path->slots[i];
if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
path->slots[i]++;
*level = i;
WARN_ON(*level == 0);
return 0;
} else {
struct extent_buffer *parent;
if (path->nodes[*level] == root->node)
parent = path->nodes[*level];
else
parent = path->nodes[*level + 1];
root_owner = btrfs_header_owner(parent);
ret = wc->process_func(root, path->nodes[*level], wc,
btrfs_header_generation(path->nodes[*level]));
if (ret)
return ret;
if (wc->free) {
struct extent_buffer *next;
next = path->nodes[*level];
btrfs_tree_lock(next);
btrfs_set_lock_blocking(next);
clean_tree_block(trans, root, next);
btrfs_wait_tree_block_writeback(next);
btrfs_tree_unlock(next);
WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
ret = btrfs_free_and_pin_reserved_extent(root,
path->nodes[*level]->start,
path->nodes[*level]->len);
if (ret)
return ret;
}
free_extent_buffer(path->nodes[*level]);
path->nodes[*level] = NULL;
*level = i + 1;
}
}
return 1;
}
/*
* drop the reference count on the tree rooted at 'snap'. This traverses
* the tree freeing any blocks that have a ref count of zero after being
* decremented.
*/
static int walk_log_tree(struct btrfs_trans_handle *trans,
struct btrfs_root *log, struct walk_control *wc)
{
int ret = 0;
int wret;
int level;
struct btrfs_path *path;
int orig_level;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
level = btrfs_header_level(log->node);
orig_level = level;
path->nodes[level] = log->node;
extent_buffer_get(log->node);
path->slots[level] = 0;
while (1) {
wret = walk_down_log_tree(trans, log, path, &level, wc);
if (wret > 0)
break;
if (wret < 0) {
ret = wret;
goto out;
}
wret = walk_up_log_tree(trans, log, path, &level, wc);
if (wret > 0)
break;
if (wret < 0) {
ret = wret;
goto out;
}
}
/* was the root node processed? if not, catch it here */
if (path->nodes[orig_level]) {
ret = wc->process_func(log, path->nodes[orig_level], wc,
btrfs_header_generation(path->nodes[orig_level]));
if (ret)
goto out;
if (wc->free) {
struct extent_buffer *next;
next = path->nodes[orig_level];
btrfs_tree_lock(next);
btrfs_set_lock_blocking(next);
clean_tree_block(trans, log, next);
btrfs_wait_tree_block_writeback(next);
btrfs_tree_unlock(next);
WARN_ON(log->root_key.objectid !=
BTRFS_TREE_LOG_OBJECTID);
ret = btrfs_free_and_pin_reserved_extent(log, next->start,
next->len);
if (ret)
goto out;
}
}
out:
btrfs_free_path(path);
return ret;
}
/*
* helper function to update the item for a given subvolumes log root
* in the tree of log roots
*/
static int update_log_root(struct btrfs_trans_handle *trans,
struct btrfs_root *log)
{
int ret;
if (log->log_transid == 1) {
/* insert root item on the first sync */
ret = btrfs_insert_root(trans, log->fs_info->log_root_tree,
&log->root_key, &log->root_item);
} else {
ret = btrfs_update_root(trans, log->fs_info->log_root_tree,
&log->root_key, &log->root_item);
}
return ret;
}
static int wait_log_commit(struct btrfs_trans_handle *trans,
struct btrfs_root *root, unsigned long transid)
{
DEFINE_WAIT(wait);
int index = transid % 2;
/*
* we only allow two pending log transactions at a time,
* so we know that if ours is more than 2 older than the
* current transaction, we're done
*/
do {
prepare_to_wait(&root->log_commit_wait[index],
&wait, TASK_UNINTERRUPTIBLE);
mutex_unlock(&root->log_mutex);
if (root->fs_info->last_trans_log_full_commit !=
trans->transid && root->log_transid < transid + 2 &&
atomic_read(&root->log_commit[index]))
schedule();
finish_wait(&root->log_commit_wait[index], &wait);
mutex_lock(&root->log_mutex);
} while (root->fs_info->last_trans_log_full_commit !=
trans->transid && root->log_transid < transid + 2 &&
atomic_read(&root->log_commit[index]));
return 0;
}
static void wait_for_writer(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
DEFINE_WAIT(wait);
while (root->fs_info->last_trans_log_full_commit !=
trans->transid && atomic_read(&root->log_writers)) {
prepare_to_wait(&root->log_writer_wait,
&wait, TASK_UNINTERRUPTIBLE);
mutex_unlock(&root->log_mutex);
if (root->fs_info->last_trans_log_full_commit !=
trans->transid && atomic_read(&root->log_writers))
schedule();
mutex_lock(&root->log_mutex);
finish_wait(&root->log_writer_wait, &wait);
}
}
/*
* btrfs_sync_log does sends a given tree log down to the disk and
* updates the super blocks to record it. When this call is done,
* you know that any inodes previously logged are safely on disk only
* if it returns 0.
*
* Any other return value means you need to call btrfs_commit_transaction.
* Some of the edge cases for fsyncing directories that have had unlinks
* or renames done in the past mean that sometimes the only safe
* fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
* that has happened.
*/
int btrfs_sync_log(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int index1;
int index2;
int mark;
int ret;
struct btrfs_root *log = root->log_root;
struct btrfs_root *log_root_tree = root->fs_info->log_root_tree;
unsigned long log_transid = 0;
mutex_lock(&root->log_mutex);
log_transid = root->log_transid;
index1 = root->log_transid % 2;
if (atomic_read(&root->log_commit[index1])) {
wait_log_commit(trans, root, root->log_transid);
mutex_unlock(&root->log_mutex);
return 0;
}
atomic_set(&root->log_commit[index1], 1);
/* wait for previous tree log sync to complete */
if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
wait_log_commit(trans, root, root->log_transid - 1);
while (1) {
int batch = atomic_read(&root->log_batch);
/* when we're on an ssd, just kick the log commit out */
if (!btrfs_test_opt(root, SSD) && root->log_multiple_pids) {
mutex_unlock(&root->log_mutex);
schedule_timeout_uninterruptible(1);
mutex_lock(&root->log_mutex);
}
wait_for_writer(trans, root);
if (batch == atomic_read(&root->log_batch))
break;
}
/* bail out if we need to do a full commit */
if (root->fs_info->last_trans_log_full_commit == trans->transid) {
ret = -EAGAIN;
btrfs_free_logged_extents(log, log_transid);
mutex_unlock(&root->log_mutex);
goto out;
}
if (log_transid % 2 == 0)
mark = EXTENT_DIRTY;
else
mark = EXTENT_NEW;
/* we start IO on all the marked extents here, but we don't actually
* wait for them until later.
*/
ret = btrfs_write_marked_extents(log, &log->dirty_log_pages, mark);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
btrfs_free_logged_extents(log, log_transid);
mutex_unlock(&root->log_mutex);
goto out;
}
btrfs_set_root_node(&log->root_item, log->node);
root->log_transid++;
log->log_transid = root->log_transid;
root->log_start_pid = 0;
smp_mb();
/*
* IO has been started, blocks of the log tree have WRITTEN flag set
* in their headers. new modifications of the log will be written to
* new positions. so it's safe to allow log writers to go in.
*/
mutex_unlock(&root->log_mutex);
mutex_lock(&log_root_tree->log_mutex);
atomic_inc(&log_root_tree->log_batch);
atomic_inc(&log_root_tree->log_writers);
mutex_unlock(&log_root_tree->log_mutex);
ret = update_log_root(trans, log);
mutex_lock(&log_root_tree->log_mutex);
if (atomic_dec_and_test(&log_root_tree->log_writers)) {
smp_mb();
if (waitqueue_active(&log_root_tree->log_writer_wait))
wake_up(&log_root_tree->log_writer_wait);
}
if (ret) {
if (ret != -ENOSPC) {
btrfs_abort_transaction(trans, root, ret);
mutex_unlock(&log_root_tree->log_mutex);
goto out;
}
root->fs_info->last_trans_log_full_commit = trans->transid;
btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
btrfs_free_logged_extents(log, log_transid);
mutex_unlock(&log_root_tree->log_mutex);
ret = -EAGAIN;
goto out;
}
index2 = log_root_tree->log_transid % 2;
if (atomic_read(&log_root_tree->log_commit[index2])) {
btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
wait_log_commit(trans, log_root_tree,
log_root_tree->log_transid);
btrfs_free_logged_extents(log, log_transid);
mutex_unlock(&log_root_tree->log_mutex);
ret = 0;
goto out;
}
atomic_set(&log_root_tree->log_commit[index2], 1);
if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
wait_log_commit(trans, log_root_tree,
log_root_tree->log_transid - 1);
}
wait_for_writer(trans, log_root_tree);
/*
* now that we've moved on to the tree of log tree roots,
* check the full commit flag again
*/
if (root->fs_info->last_trans_log_full_commit == trans->transid) {
btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
btrfs_free_logged_extents(log, log_transid);
mutex_unlock(&log_root_tree->log_mutex);
ret = -EAGAIN;
goto out_wake_log_root;
}
ret = btrfs_write_and_wait_marked_extents(log_root_tree,
&log_root_tree->dirty_log_pages,
EXTENT_DIRTY | EXTENT_NEW);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
btrfs_free_logged_extents(log, log_transid);
mutex_unlock(&log_root_tree->log_mutex);
goto out_wake_log_root;
}
btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
btrfs_wait_logged_extents(log, log_transid);
btrfs_set_super_log_root(root->fs_info->super_for_commit,
log_root_tree->node->start);
btrfs_set_super_log_root_level(root->fs_info->super_for_commit,
btrfs_header_level(log_root_tree->node));
log_root_tree->log_transid++;
smp_mb();
mutex_unlock(&log_root_tree->log_mutex);
/*
* nobody else is going to jump in and write the the ctree
* super here because the log_commit atomic below is protecting
* us. We must be called with a transaction handle pinning
* the running transaction open, so a full commit can't hop
* in and cause problems either.
*/
btrfs_scrub_pause_super(root);
ret = write_ctree_super(trans, root->fs_info->tree_root, 1);
btrfs_scrub_continue_super(root);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_wake_log_root;
}
mutex_lock(&root->log_mutex);
if (root->last_log_commit < log_transid)
root->last_log_commit = log_transid;
mutex_unlock(&root->log_mutex);
out_wake_log_root:
atomic_set(&log_root_tree->log_commit[index2], 0);
smp_mb();
if (waitqueue_active(&log_root_tree->log_commit_wait[index2]))
wake_up(&log_root_tree->log_commit_wait[index2]);
out:
atomic_set(&root->log_commit[index1], 0);
smp_mb();
if (waitqueue_active(&root->log_commit_wait[index1]))
wake_up(&root->log_commit_wait[index1]);
return ret;
}
static void free_log_tree(struct btrfs_trans_handle *trans,
struct btrfs_root *log)
{
int ret;
u64 start;
u64 end;
struct walk_control wc = {
.free = 1,
.process_func = process_one_buffer
};
if (trans) {
ret = walk_log_tree(trans, log, &wc);
/* I don't think this can happen but just in case */
if (ret)
btrfs_abort_transaction(trans, log, ret);
}
while (1) {
ret = find_first_extent_bit(&log->dirty_log_pages,
0, &start, &end, EXTENT_DIRTY | EXTENT_NEW,
NULL);
if (ret)
break;
clear_extent_bits(&log->dirty_log_pages, start, end,
EXTENT_DIRTY | EXTENT_NEW, GFP_NOFS);
}
/*
* We may have short-circuited the log tree with the full commit logic
* and left ordered extents on our list, so clear these out to keep us
* from leaking inodes and memory.
*/
btrfs_free_logged_extents(log, 0);
btrfs_free_logged_extents(log, 1);
free_extent_buffer(log->node);
kfree(log);
}
/*
* free all the extents used by the tree log. This should be called
* at commit time of the full transaction
*/
int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
{
if (root->log_root) {
free_log_tree(trans, root->log_root);
root->log_root = NULL;
}
return 0;
}
int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info)
{
if (fs_info->log_root_tree) {
free_log_tree(trans, fs_info->log_root_tree);
fs_info->log_root_tree = NULL;
}
return 0;
}
/*
* If both a file and directory are logged, and unlinks or renames are
* mixed in, we have a few interesting corners:
*
* create file X in dir Y
* link file X to X.link in dir Y
* fsync file X
* unlink file X but leave X.link
* fsync dir Y
*
* After a crash we would expect only X.link to exist. But file X
* didn't get fsync'd again so the log has back refs for X and X.link.
*
* We solve this by removing directory entries and inode backrefs from the
* log when a file that was logged in the current transaction is
* unlinked. Any later fsync will include the updated log entries, and
* we'll be able to reconstruct the proper directory items from backrefs.
*
* This optimizations allows us to avoid relogging the entire inode
* or the entire directory.
*/
int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
const char *name, int name_len,
struct inode *dir, u64 index)
{
struct btrfs_root *log;
struct btrfs_dir_item *di;
struct btrfs_path *path;
int ret;
int err = 0;
int bytes_del = 0;
u64 dir_ino = btrfs_ino(dir);
if (BTRFS_I(dir)->logged_trans < trans->transid)
return 0;
ret = join_running_log_trans(root);
if (ret)
return 0;
mutex_lock(&BTRFS_I(dir)->log_mutex);
log = root->log_root;
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
goto out_unlock;
}
di = btrfs_lookup_dir_item(trans, log, path, dir_ino,
name, name_len, -1);
if (IS_ERR(di)) {
err = PTR_ERR(di);
goto fail;
}
if (di) {
ret = btrfs_delete_one_dir_name(trans, log, path, di);
bytes_del += name_len;
if (ret) {
err = ret;
goto fail;
}
}
btrfs_release_path(path);
di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
index, name, name_len, -1);
if (IS_ERR(di)) {
err = PTR_ERR(di);
goto fail;
}
if (di) {
ret = btrfs_delete_one_dir_name(trans, log, path, di);
bytes_del += name_len;
if (ret) {
err = ret;
goto fail;
}
}
/* update the directory size in the log to reflect the names
* we have removed
*/
if (bytes_del) {
struct btrfs_key key;
key.objectid = dir_ino;
key.offset = 0;
key.type = BTRFS_INODE_ITEM_KEY;
btrfs_release_path(path);
ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
if (ret < 0) {
err = ret;
goto fail;
}
if (ret == 0) {
struct btrfs_inode_item *item;
u64 i_size;
item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_inode_item);
i_size = btrfs_inode_size(path->nodes[0], item);
if (i_size > bytes_del)
i_size -= bytes_del;
else
i_size = 0;
btrfs_set_inode_size(path->nodes[0], item, i_size);
btrfs_mark_buffer_dirty(path->nodes[0]);
} else
ret = 0;
btrfs_release_path(path);
}
fail:
btrfs_free_path(path);
out_unlock:
mutex_unlock(&BTRFS_I(dir)->log_mutex);
if (ret == -ENOSPC) {
root->fs_info->last_trans_log_full_commit = trans->transid;
ret = 0;
} else if (ret < 0)
btrfs_abort_transaction(trans, root, ret);
btrfs_end_log_trans(root);
return err;
}
/* see comments for btrfs_del_dir_entries_in_log */
int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
const char *name, int name_len,
struct inode *inode, u64 dirid)
{
struct btrfs_root *log;
u64 index;
int ret;
if (BTRFS_I(inode)->logged_trans < trans->transid)
return 0;
ret = join_running_log_trans(root);
if (ret)
return 0;
log = root->log_root;
mutex_lock(&BTRFS_I(inode)->log_mutex);
ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
dirid, &index);
mutex_unlock(&BTRFS_I(inode)->log_mutex);
if (ret == -ENOSPC) {
root->fs_info->last_trans_log_full_commit = trans->transid;
ret = 0;
} else if (ret < 0 && ret != -ENOENT)
btrfs_abort_transaction(trans, root, ret);
btrfs_end_log_trans(root);
return ret;
}
/*
* creates a range item in the log for 'dirid'. first_offset and
* last_offset tell us which parts of the key space the log should
* be considered authoritative for.
*/
static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
struct btrfs_root *log,
struct btrfs_path *path,
int key_type, u64 dirid,
u64 first_offset, u64 last_offset)
{
int ret;
struct btrfs_key key;
struct btrfs_dir_log_item *item;
key.objectid = dirid;
key.offset = first_offset;
if (key_type == BTRFS_DIR_ITEM_KEY)
key.type = BTRFS_DIR_LOG_ITEM_KEY;
else
key.type = BTRFS_DIR_LOG_INDEX_KEY;
ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
if (ret)
return ret;
item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_dir_log_item);
btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
btrfs_mark_buffer_dirty(path->nodes[0]);
btrfs_release_path(path);
return 0;
}
/*
* log all the items included in the current transaction for a given
* directory. This also creates the range items in the log tree required
* to replay anything deleted before the fsync
*/
static noinline int log_dir_items(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
struct btrfs_path *path,
struct btrfs_path *dst_path, int key_type,
u64 min_offset, u64 *last_offset_ret)
{
struct btrfs_key min_key;
struct btrfs_key max_key;
struct btrfs_root *log = root->log_root;
struct extent_buffer *src;
int err = 0;
int ret;
int i;
int nritems;
u64 first_offset = min_offset;
u64 last_offset = (u64)-1;
u64 ino = btrfs_ino(inode);
log = root->log_root;
max_key.objectid = ino;
max_key.offset = (u64)-1;
max_key.type = key_type;
min_key.objectid = ino;
min_key.type = key_type;
min_key.offset = min_offset;
path->keep_locks = 1;
ret = btrfs_search_forward(root, &min_key, &max_key,
path, trans->transid);
/*
* we didn't find anything from this transaction, see if there
* is anything at all
*/
if (ret != 0 || min_key.objectid != ino || min_key.type != key_type) {
min_key.objectid = ino;
min_key.type = key_type;
min_key.offset = (u64)-1;
btrfs_release_path(path);
ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
if (ret < 0) {
btrfs_release_path(path);
return ret;
}
ret = btrfs_previous_item(root, path, ino, key_type);
/* if ret == 0 there are items for this type,
* create a range to tell us the last key of this type.
* otherwise, there are no items in this directory after
* *min_offset, and we create a range to indicate that.
*/
if (ret == 0) {
struct btrfs_key tmp;
btrfs_item_key_to_cpu(path->nodes[0], &tmp,
path->slots[0]);
if (key_type == tmp.type)
first_offset = max(min_offset, tmp.offset) + 1;
}
goto done;
}
/* go backward to find any previous key */
ret = btrfs_previous_item(root, path, ino, key_type);
if (ret == 0) {
struct btrfs_key tmp;
btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
if (key_type == tmp.type) {
first_offset = tmp.offset;
ret = overwrite_item(trans, log, dst_path,
path->nodes[0], path->slots[0],
&tmp);
if (ret) {
err = ret;
goto done;
}
}
}
btrfs_release_path(path);
/* find the first key from this transaction again */
ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
if (ret != 0) {
WARN_ON(1);
goto done;
}
/*
* we have a block from this transaction, log every item in it
* from our directory
*/
while (1) {
struct btrfs_key tmp;
src = path->nodes[0];
nritems = btrfs_header_nritems(src);
for (i = path->slots[0]; i < nritems; i++) {
btrfs_item_key_to_cpu(src, &min_key, i);
if (min_key.objectid != ino || min_key.type != key_type)
goto done;
ret = overwrite_item(trans, log, dst_path, src, i,
&min_key);
if (ret) {
err = ret;
goto done;
}
}
path->slots[0] = nritems;
/*
* look ahead to the next item and see if it is also
* from this directory and from this transaction
*/
ret = btrfs_next_leaf(root, path);
if (ret == 1) {
last_offset = (u64)-1;
goto done;
}
btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
if (tmp.objectid != ino || tmp.type != key_type) {
last_offset = (u64)-1;
goto done;
}
if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
ret = overwrite_item(trans, log, dst_path,
path->nodes[0], path->slots[0],
&tmp);
if (ret)
err = ret;
else
last_offset = tmp.offset;
goto done;
}
}
done:
btrfs_release_path(path);
btrfs_release_path(dst_path);
if (err == 0) {
*last_offset_ret = last_offset;
/*
* insert the log range keys to indicate where the log
* is valid
*/
ret = insert_dir_log_key(trans, log, path, key_type,
ino, first_offset, last_offset);
if (ret)
err = ret;
}
return err;
}
/*
* logging directories is very similar to logging inodes, We find all the items
* from the current transaction and write them to the log.
*
* The recovery code scans the directory in the subvolume, and if it finds a
* key in the range logged that is not present in the log tree, then it means
* that dir entry was unlinked during the transaction.
*
* In order for that scan to work, we must include one key smaller than
* the smallest logged by this transaction and one key larger than the largest
* key logged by this transaction.
*/
static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
struct btrfs_path *path,
struct btrfs_path *dst_path)
{
u64 min_key;
u64 max_key;
int ret;
int key_type = BTRFS_DIR_ITEM_KEY;
again:
min_key = 0;
max_key = 0;
while (1) {
ret = log_dir_items(trans, root, inode, path,
dst_path, key_type, min_key,
&max_key);
if (ret)
return ret;
if (max_key == (u64)-1)
break;
min_key = max_key + 1;
}
if (key_type == BTRFS_DIR_ITEM_KEY) {
key_type = BTRFS_DIR_INDEX_KEY;
goto again;
}
return 0;
}
/*
* a helper function to drop items from the log before we relog an
* inode. max_key_type indicates the highest item type to remove.
* This cannot be run for file data extents because it does not
* free the extents they point to.
*/
static int drop_objectid_items(struct btrfs_trans_handle *trans,
struct btrfs_root *log,
struct btrfs_path *path,
u64 objectid, int max_key_type)
{
int ret;
struct btrfs_key key;
struct btrfs_key found_key;
int start_slot;
key.objectid = objectid;
key.type = max_key_type;
key.offset = (u64)-1;
while (1) {
ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
BUG_ON(ret == 0); /* Logic error */
if (ret < 0)
break;
if (path->slots[0] == 0)
break;
path->slots[0]--;
btrfs_item_key_to_cpu(path->nodes[0], &found_key,
path->slots[0]);
if (found_key.objectid != objectid)
break;
found_key.offset = 0;
found_key.type = 0;
ret = btrfs_bin_search(path->nodes[0], &found_key, 0,
&start_slot);
ret = btrfs_del_items(trans, log, path, start_slot,
path->slots[0] - start_slot + 1);
/*
* If start slot isn't 0 then we don't need to re-search, we've
* found the last guy with the objectid in this tree.
*/
if (ret || start_slot != 0)
break;
btrfs_release_path(path);
}
btrfs_release_path(path);
if (ret > 0)
ret = 0;
return ret;
}
static void fill_inode_item(struct btrfs_trans_handle *trans,
struct extent_buffer *leaf,
struct btrfs_inode_item *item,
struct inode *inode, int log_inode_only)
{
struct btrfs_map_token token;
btrfs_init_map_token(&token);
if (log_inode_only) {
/* set the generation to zero so the recover code
* can tell the difference between an logging
* just to say 'this inode exists' and a logging
* to say 'update this inode with these values'
*/
btrfs_set_token_inode_generation(leaf, item, 0, &token);
btrfs_set_token_inode_size(leaf, item, 0, &token);
} else {
btrfs_set_token_inode_generation(leaf, item,
BTRFS_I(inode)->generation,
&token);
btrfs_set_token_inode_size(leaf, item, inode->i_size, &token);
}
btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
inode->i_atime.tv_sec, &token);
btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
inode->i_atime.tv_nsec, &token);
btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
inode->i_mtime.tv_sec, &token);
btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
inode->i_mtime.tv_nsec, &token);
btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
inode->i_ctime.tv_sec, &token);
btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
inode->i_ctime.tv_nsec, &token);
btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
&token);
btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
btrfs_set_token_inode_block_group(leaf, item, 0, &token);
}
static int log_inode_item(struct btrfs_trans_handle *trans,
struct btrfs_root *log, struct btrfs_path *path,
struct inode *inode)
{
struct btrfs_inode_item *inode_item;
struct btrfs_key key;
int ret;
memcpy(&key, &BTRFS_I(inode)->location, sizeof(key));
ret = btrfs_insert_empty_item(trans, log, path, &key,
sizeof(*inode_item));
if (ret && ret != -EEXIST)
return ret;
inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_inode_item);
fill_inode_item(trans, path->nodes[0], inode_item, inode, 0);
btrfs_release_path(path);
return 0;
}
static noinline int copy_items(struct btrfs_trans_handle *trans,
struct inode *inode,
struct btrfs_path *dst_path,
struct extent_buffer *src,
int start_slot, int nr, int inode_only)
{
unsigned long src_offset;
unsigned long dst_offset;
struct btrfs_root *log = BTRFS_I(inode)->root->log_root;
struct btrfs_file_extent_item *extent;
struct btrfs_inode_item *inode_item;
int ret;
struct btrfs_key *ins_keys;
u32 *ins_sizes;
char *ins_data;
int i;
struct list_head ordered_sums;
int skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
INIT_LIST_HEAD(&ordered_sums);
ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
nr * sizeof(u32), GFP_NOFS);
if (!ins_data)
return -ENOMEM;
ins_sizes = (u32 *)ins_data;
ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
for (i = 0; i < nr; i++) {
ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
}
ret = btrfs_insert_empty_items(trans, log, dst_path,
ins_keys, ins_sizes, nr);
if (ret) {
kfree(ins_data);
return ret;
}
for (i = 0; i < nr; i++, dst_path->slots[0]++) {
dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
dst_path->slots[0]);
src_offset = btrfs_item_ptr_offset(src, start_slot + i);
if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
inode_item = btrfs_item_ptr(dst_path->nodes[0],
dst_path->slots[0],
struct btrfs_inode_item);
fill_inode_item(trans, dst_path->nodes[0], inode_item,
inode, inode_only == LOG_INODE_EXISTS);
} else {
copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
src_offset, ins_sizes[i]);
}
/* take a reference on file data extents so that truncates
* or deletes of this inode don't have to relog the inode
* again
*/
if (btrfs_key_type(ins_keys + i) == BTRFS_EXTENT_DATA_KEY &&
!skip_csum) {
int found_type;
extent = btrfs_item_ptr(src, start_slot + i,
struct btrfs_file_extent_item);
if (btrfs_file_extent_generation(src, extent) < trans->transid)
continue;
found_type = btrfs_file_extent_type(src, extent);
if (found_type == BTRFS_FILE_EXTENT_REG) {
u64 ds, dl, cs, cl;
ds = btrfs_file_extent_disk_bytenr(src,
extent);
/* ds == 0 is a hole */
if (ds == 0)
continue;
dl = btrfs_file_extent_disk_num_bytes(src,
extent);
cs = btrfs_file_extent_offset(src, extent);
cl = btrfs_file_extent_num_bytes(src,
extent);
if (btrfs_file_extent_compression(src,
extent)) {
cs = 0;
cl = dl;
}
ret = btrfs_lookup_csums_range(
log->fs_info->csum_root,
ds + cs, ds + cs + cl - 1,
&ordered_sums, 0);
if (ret) {
btrfs_release_path(dst_path);
kfree(ins_data);
return ret;
}
}
}
}
btrfs_mark_buffer_dirty(dst_path->nodes[0]);
btrfs_release_path(dst_path);
kfree(ins_data);
/*
* we have to do this after the loop above to avoid changing the
* log tree while trying to change the log tree.
*/
ret = 0;
while (!list_empty(&ordered_sums)) {
struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
struct btrfs_ordered_sum,
list);
if (!ret)
ret = btrfs_csum_file_blocks(trans, log, sums);
list_del(&sums->list);
kfree(sums);
}
return ret;
}
static int extent_cmp(void *priv, struct list_head *a, struct list_head *b)
{
struct extent_map *em1, *em2;
em1 = list_entry(a, struct extent_map, list);
em2 = list_entry(b, struct extent_map, list);
if (em1->start < em2->start)
return -1;
else if (em1->start > em2->start)
return 1;
return 0;
}
static int log_one_extent(struct btrfs_trans_handle *trans,
struct inode *inode, struct btrfs_root *root,
struct extent_map *em, struct btrfs_path *path)
{
struct btrfs_root *log = root->log_root;
struct btrfs_file_extent_item *fi;
struct extent_buffer *leaf;
struct btrfs_ordered_extent *ordered;
struct list_head ordered_sums;
struct btrfs_map_token token;
struct btrfs_key key;
u64 mod_start = em->mod_start;
u64 mod_len = em->mod_len;
u64 csum_offset;
u64 csum_len;
u64 extent_offset = em->start - em->orig_start;
u64 block_len;
int ret;
int index = log->log_transid % 2;
bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
ret = __btrfs_drop_extents(trans, log, inode, path, em->start,
em->start + em->len, NULL, 0);
if (ret)
return ret;
INIT_LIST_HEAD(&ordered_sums);
btrfs_init_map_token(&token);
key.objectid = btrfs_ino(inode);
key.type = BTRFS_EXTENT_DATA_KEY;
key.offset = em->start;
ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*fi));
if (ret)
return ret;
leaf = path->nodes[0];
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_token_file_extent_generation(leaf, fi, em->generation,
&token);
if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
skip_csum = true;
btrfs_set_token_file_extent_type(leaf, fi,
BTRFS_FILE_EXTENT_PREALLOC,
&token);
} else {
btrfs_set_token_file_extent_type(leaf, fi,
BTRFS_FILE_EXTENT_REG,
&token);
if (em->block_start == 0)
skip_csum = true;
}
block_len = max(em->block_len, em->orig_block_len);
if (em->compress_type != BTRFS_COMPRESS_NONE) {
btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
em->block_start,
&token);
btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
&token);
} else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
em->block_start -
extent_offset, &token);
btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
&token);
} else {
btrfs_set_token_file_extent_disk_bytenr(leaf, fi, 0, &token);
btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, 0,
&token);
}
btrfs_set_token_file_extent_offset(leaf, fi,
em->start - em->orig_start,
&token);
btrfs_set_token_file_extent_num_bytes(leaf, fi, em->len, &token);
btrfs_set_token_file_extent_ram_bytes(leaf, fi, em->ram_bytes, &token);
btrfs_set_token_file_extent_compression(leaf, fi, em->compress_type,
&token);
btrfs_set_token_file_extent_encryption(leaf, fi, 0, &token);
btrfs_set_token_file_extent_other_encoding(leaf, fi, 0, &token);
btrfs_mark_buffer_dirty(leaf);
btrfs_release_path(path);
if (ret) {
return ret;
}
if (skip_csum)
return 0;
if (em->compress_type) {
csum_offset = 0;
csum_len = block_len;
}
/*
* First check and see if our csums are on our outstanding ordered
* extents.
*/
again:
spin_lock_irq(&log->log_extents_lock[index]);
list_for_each_entry(ordered, &log->logged_list[index], log_list) {
struct btrfs_ordered_sum *sum;
if (!mod_len)
break;
if (ordered->inode != inode)
continue;
if (ordered->file_offset + ordered->len <= mod_start ||
mod_start + mod_len <= ordered->file_offset)
continue;
/*
* We are going to copy all the csums on this ordered extent, so
* go ahead and adjust mod_start and mod_len in case this
* ordered extent has already been logged.
*/
if (ordered->file_offset > mod_start) {
if (ordered->file_offset + ordered->len >=
mod_start + mod_len)
mod_len = ordered->file_offset - mod_start;
/*
* If we have this case
*
* |--------- logged extent ---------|
* |----- ordered extent ----|
*
* Just don't mess with mod_start and mod_len, we'll
* just end up logging more csums than we need and it
* will be ok.
*/
} else {
if (ordered->file_offset + ordered->len <
mod_start + mod_len) {
mod_len = (mod_start + mod_len) -
(ordered->file_offset + ordered->len);
mod_start = ordered->file_offset +
ordered->len;
} else {
mod_len = 0;
}
}
/*
* To keep us from looping for the above case of an ordered
* extent that falls inside of the logged extent.
*/
if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM,
&ordered->flags))
continue;
atomic_inc(&ordered->refs);
spin_unlock_irq(&log->log_extents_lock[index]);
/*
* we've dropped the lock, we must either break or
* start over after this.
*/
wait_event(ordered->wait, ordered->csum_bytes_left == 0);
list_for_each_entry(sum, &ordered->list, list) {
ret = btrfs_csum_file_blocks(trans, log, sum);
if (ret) {
btrfs_put_ordered_extent(ordered);
goto unlocked;
}
}
btrfs_put_ordered_extent(ordered);
goto again;
}
spin_unlock_irq(&log->log_extents_lock[index]);
unlocked:
if (!mod_len || ret)
return ret;
csum_offset = mod_start - em->start;
csum_len = mod_len;
/* block start is already adjusted for the file extent offset. */
ret = btrfs_lookup_csums_range(log->fs_info->csum_root,
em->block_start + csum_offset,
em->block_start + csum_offset +
csum_len - 1, &ordered_sums, 0);
if (ret)
return ret;
while (!list_empty(&ordered_sums)) {
struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
struct btrfs_ordered_sum,
list);
if (!ret)
ret = btrfs_csum_file_blocks(trans, log, sums);
list_del(&sums->list);
kfree(sums);
}
return ret;
}
static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *inode,
struct btrfs_path *path)
{
struct extent_map *em, *n;
struct list_head extents;
struct extent_map_tree *tree = &BTRFS_I(inode)->extent_tree;
u64 test_gen;
int ret = 0;
int num = 0;
INIT_LIST_HEAD(&extents);
write_lock(&tree->lock);
test_gen = root->fs_info->last_trans_committed;
list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
list_del_init(&em->list);
/*
* Just an arbitrary number, this can be really CPU intensive
* once we start getting a lot of extents, and really once we
* have a bunch of extents we just want to commit since it will
* be faster.
*/
if (++num > 32768) {
list_del_init(&tree->modified_extents);
ret = -EFBIG;
goto process;
}
if (em->generation <= test_gen)
continue;
/* Need a ref to keep it from getting evicted from cache */
atomic_inc(&em->refs);
set_bit(EXTENT_FLAG_LOGGING, &em->flags);
list_add_tail(&em->list, &extents);
num++;
}
list_sort(NULL, &extents, extent_cmp);
process:
while (!list_empty(&extents)) {
em = list_entry(extents.next, struct extent_map, list);
list_del_init(&em->list);
/*
* If we had an error we just need to delete everybody from our
* private list.
*/
if (ret) {
clear_em_logging(tree, em);
free_extent_map(em);
continue;
}
write_unlock(&tree->lock);
ret = log_one_extent(trans, inode, root, em, path);
write_lock(&tree->lock);
clear_em_logging(tree, em);
free_extent_map(em);
}
WARN_ON(!list_empty(&extents));
write_unlock(&tree->lock);
btrfs_release_path(path);
return ret;
}
/* log a single inode in the tree log.
* At least one parent directory for this inode must exist in the tree
* or be logged already.
*
* Any items from this inode changed by the current transaction are copied
* to the log tree. An extra reference is taken on any extents in this
* file, allowing us to avoid a whole pile of corner cases around logging
* blocks that have been removed from the tree.
*
* See LOG_INODE_ALL and related defines for a description of what inode_only
* does.
*
* This handles both files and directories.
*/
static int btrfs_log_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
int inode_only)
{
struct btrfs_path *path;
struct btrfs_path *dst_path;
struct btrfs_key min_key;
struct btrfs_key max_key;
struct btrfs_root *log = root->log_root;
struct extent_buffer *src = NULL;
int err = 0;
int ret;
int nritems;
int ins_start_slot = 0;
int ins_nr;
bool fast_search = false;
u64 ino = btrfs_ino(inode);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
dst_path = btrfs_alloc_path();
if (!dst_path) {
btrfs_free_path(path);
return -ENOMEM;
}
min_key.objectid = ino;
min_key.type = BTRFS_INODE_ITEM_KEY;
min_key.offset = 0;
max_key.objectid = ino;
/* today the code can only do partial logging of directories */
if (S_ISDIR(inode->i_mode) ||
(!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags) &&
inode_only == LOG_INODE_EXISTS))
max_key.type = BTRFS_XATTR_ITEM_KEY;
else
max_key.type = (u8)-1;
max_key.offset = (u64)-1;
/* Only run delayed items if we are a dir or a new file */
if (S_ISDIR(inode->i_mode) ||
BTRFS_I(inode)->generation > root->fs_info->last_trans_committed) {
ret = btrfs_commit_inode_delayed_items(trans, inode);
if (ret) {
btrfs_free_path(path);
btrfs_free_path(dst_path);
return ret;
}
}
mutex_lock(&BTRFS_I(inode)->log_mutex);
btrfs_get_logged_extents(log, inode);
/*
* a brute force approach to making sure we get the most uptodate
* copies of everything.
*/
if (S_ISDIR(inode->i_mode)) {
int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
if (inode_only == LOG_INODE_EXISTS)
max_key_type = BTRFS_XATTR_ITEM_KEY;
ret = drop_objectid_items(trans, log, path, ino, max_key_type);
} else {
if (test_and_clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags)) {
clear_bit(BTRFS_INODE_COPY_EVERYTHING,
&BTRFS_I(inode)->runtime_flags);
ret = btrfs_truncate_inode_items(trans, log,
inode, 0, 0);
} else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
&BTRFS_I(inode)->runtime_flags)) {
if (inode_only == LOG_INODE_ALL)
fast_search = true;
max_key.type = BTRFS_XATTR_ITEM_KEY;
ret = drop_objectid_items(trans, log, path, ino,
max_key.type);
} else {
if (inode_only == LOG_INODE_ALL)
fast_search = true;
ret = log_inode_item(trans, log, dst_path, inode);
if (ret) {
err = ret;
goto out_unlock;
}
goto log_extents;
}
}
if (ret) {
err = ret;
goto out_unlock;
}
path->keep_locks = 1;
while (1) {
ins_nr = 0;
ret = btrfs_search_forward(root, &min_key, &max_key,
path, trans->transid);
if (ret != 0)
break;
again:
/* note, ins_nr might be > 0 here, cleanup outside the loop */
if (min_key.objectid != ino)
break;
if (min_key.type > max_key.type)
break;
src = path->nodes[0];
if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
ins_nr++;
goto next_slot;
} else if (!ins_nr) {
ins_start_slot = path->slots[0];
ins_nr = 1;
goto next_slot;
}
ret = copy_items(trans, inode, dst_path, src, ins_start_slot,
ins_nr, inode_only);
if (ret) {
err = ret;
goto out_unlock;
}
ins_nr = 1;
ins_start_slot = path->slots[0];
next_slot:
nritems = btrfs_header_nritems(path->nodes[0]);
path->slots[0]++;
if (path->slots[0] < nritems) {
btrfs_item_key_to_cpu(path->nodes[0], &min_key,
path->slots[0]);
goto again;
}
if (ins_nr) {
ret = copy_items(trans, inode, dst_path, src,
ins_start_slot,
ins_nr, inode_only);
if (ret) {
err = ret;
goto out_unlock;
}
ins_nr = 0;
}
btrfs_release_path(path);
if (min_key.offset < (u64)-1)
min_key.offset++;
else if (min_key.type < (u8)-1)
min_key.type++;
else if (min_key.objectid < (u64)-1)
min_key.objectid++;
else
break;
}
if (ins_nr) {
ret = copy_items(trans, inode, dst_path, src, ins_start_slot,
ins_nr, inode_only);
if (ret) {
err = ret;
goto out_unlock;
}
ins_nr = 0;
}
log_extents:
btrfs_release_path(path);
btrfs_release_path(dst_path);
if (fast_search) {
ret = btrfs_log_changed_extents(trans, root, inode, dst_path);
if (ret) {
err = ret;
goto out_unlock;
}
} else {
struct extent_map_tree *tree = &BTRFS_I(inode)->extent_tree;
struct extent_map *em, *n;
write_lock(&tree->lock);
list_for_each_entry_safe(em, n, &tree->modified_extents, list)
list_del_init(&em->list);
write_unlock(&tree->lock);
}
if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->i_mode)) {
ret = log_directory_changes(trans, root, inode, path, dst_path);
if (ret) {
err = ret;
goto out_unlock;
}
}
BTRFS_I(inode)->logged_trans = trans->transid;
BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->last_sub_trans;
out_unlock:
if (err)
btrfs_free_logged_extents(log, log->log_transid);
mutex_unlock(&BTRFS_I(inode)->log_mutex);
btrfs_free_path(path);
btrfs_free_path(dst_path);
return err;
}
/*
* follow the dentry parent pointers up the chain and see if any
* of the directories in it require a full commit before they can
* be logged. Returns zero if nothing special needs to be done or 1 if
* a full commit is required.
*/
static noinline int check_parent_dirs_for_sync(struct btrfs_trans_handle *trans,
struct inode *inode,
struct dentry *parent,
struct super_block *sb,
u64 last_committed)
{
int ret = 0;
struct btrfs_root *root;
struct dentry *old_parent = NULL;
/*
* for regular files, if its inode is already on disk, we don't
* have to worry about the parents at all. This is because
* we can use the last_unlink_trans field to record renames
* and other fun in this file.
*/
if (S_ISREG(inode->i_mode) &&
BTRFS_I(inode)->generation <= last_committed &&
BTRFS_I(inode)->last_unlink_trans <= last_committed)
goto out;
if (!S_ISDIR(inode->i_mode)) {
if (!parent || !parent->d_inode || sb != parent->d_inode->i_sb)
goto out;
inode = parent->d_inode;
}
while (1) {
BTRFS_I(inode)->logged_trans = trans->transid;
smp_mb();
if (BTRFS_I(inode)->last_unlink_trans > last_committed) {
root = BTRFS_I(inode)->root;
/*
* make sure any commits to the log are forced
* to be full commits
*/
root->fs_info->last_trans_log_full_commit =
trans->transid;
ret = 1;
break;
}
if (!parent || !parent->d_inode || sb != parent->d_inode->i_sb)
break;
if (IS_ROOT(parent))
break;
parent = dget_parent(parent);
dput(old_parent);
old_parent = parent;
inode = parent->d_inode;
}
dput(old_parent);
out:
return ret;
}
/*
* helper function around btrfs_log_inode to make sure newly created
* parent directories also end up in the log. A minimal inode and backref
* only logging is done of any parent directories that are older than
* the last committed transaction
*/
static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
struct dentry *parent, int exists_only)
{
int inode_only = exists_only ? LOG_INODE_EXISTS : LOG_INODE_ALL;
struct super_block *sb;
struct dentry *old_parent = NULL;
int ret = 0;
u64 last_committed = root->fs_info->last_trans_committed;
sb = inode->i_sb;
if (btrfs_test_opt(root, NOTREELOG)) {
ret = 1;
goto end_no_trans;
}
if (root->fs_info->last_trans_log_full_commit >
root->fs_info->last_trans_committed) {
ret = 1;
goto end_no_trans;
}
if (root != BTRFS_I(inode)->root ||
btrfs_root_refs(&root->root_item) == 0) {
ret = 1;
goto end_no_trans;
}
ret = check_parent_dirs_for_sync(trans, inode, parent,
sb, last_committed);
if (ret)
goto end_no_trans;
if (btrfs_inode_in_log(inode, trans->transid)) {
ret = BTRFS_NO_LOG_SYNC;
goto end_no_trans;
}
ret = start_log_trans(trans, root);
if (ret)
goto end_trans;
ret = btrfs_log_inode(trans, root, inode, inode_only);
if (ret)
goto end_trans;
/*
* for regular files, if its inode is already on disk, we don't
* have to worry about the parents at all. This is because
* we can use the last_unlink_trans field to record renames
* and other fun in this file.
*/
if (S_ISREG(inode->i_mode) &&
BTRFS_I(inode)->generation <= last_committed &&
BTRFS_I(inode)->last_unlink_trans <= last_committed) {
ret = 0;
goto end_trans;
}
inode_only = LOG_INODE_EXISTS;
while (1) {
if (!parent || !parent->d_inode || sb != parent->d_inode->i_sb)
break;
inode = parent->d_inode;
if (root != BTRFS_I(inode)->root)
break;
if (BTRFS_I(inode)->generation >
root->fs_info->last_trans_committed) {
ret = btrfs_log_inode(trans, root, inode, inode_only);
if (ret)
goto end_trans;
}
if (IS_ROOT(parent))
break;
parent = dget_parent(parent);
dput(old_parent);
old_parent = parent;
}
ret = 0;
end_trans:
dput(old_parent);
if (ret < 0) {
root->fs_info->last_trans_log_full_commit = trans->transid;
ret = 1;
}
btrfs_end_log_trans(root);
end_no_trans:
return ret;
}
/*
* it is not safe to log dentry if the chunk root has added new
* chunks. This returns 0 if the dentry was logged, and 1 otherwise.
* If this returns 1, you must commit the transaction to safely get your
* data on disk.
*/
int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct dentry *dentry)
{
struct dentry *parent = dget_parent(dentry);
int ret;
ret = btrfs_log_inode_parent(trans, root, dentry->d_inode, parent, 0);
dput(parent);
return ret;
}
/*
* should be called during mount to recover any replay any log trees
* from the FS
*/
int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
{
int ret;
struct btrfs_path *path;
struct btrfs_trans_handle *trans;
struct btrfs_key key;
struct btrfs_key found_key;
struct btrfs_key tmp_key;
struct btrfs_root *log;
struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
struct walk_control wc = {
.process_func = process_one_buffer,
.stage = 0,
};
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
fs_info->log_root_recovering = 1;
trans = btrfs_start_transaction(fs_info->tree_root, 0);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto error;
}
wc.trans = trans;
wc.pin = 1;
ret = walk_log_tree(trans, log_root_tree, &wc);
if (ret) {
btrfs_error(fs_info, ret, "Failed to pin buffers while "
"recovering log root tree.");
goto error;
}
again:
key.objectid = BTRFS_TREE_LOG_OBJECTID;
key.offset = (u64)-1;
btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
while (1) {
ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
if (ret < 0) {
btrfs_error(fs_info, ret,
"Couldn't find tree log root.");
goto error;
}
if (ret > 0) {
if (path->slots[0] == 0)
break;
path->slots[0]--;
}
btrfs_item_key_to_cpu(path->nodes[0], &found_key,
path->slots[0]);
btrfs_release_path(path);
if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
break;
log = btrfs_read_fs_root_no_radix(log_root_tree,
&found_key);
if (IS_ERR(log)) {
ret = PTR_ERR(log);
btrfs_error(fs_info, ret,
"Couldn't read tree log root.");
goto error;
}
tmp_key.objectid = found_key.offset;
tmp_key.type = BTRFS_ROOT_ITEM_KEY;
tmp_key.offset = (u64)-1;
wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
if (IS_ERR(wc.replay_dest)) {
ret = PTR_ERR(wc.replay_dest);
free_extent_buffer(log->node);
free_extent_buffer(log->commit_root);
kfree(log);
btrfs_error(fs_info, ret, "Couldn't read target root "
"for tree log recovery.");
goto error;
}
wc.replay_dest->log_root = log;
btrfs_record_root_in_trans(trans, wc.replay_dest);
ret = walk_log_tree(trans, log, &wc);
if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
ret = fixup_inode_link_counts(trans, wc.replay_dest,
path);
}
key.offset = found_key.offset - 1;
wc.replay_dest->log_root = NULL;
free_extent_buffer(log->node);
free_extent_buffer(log->commit_root);
kfree(log);
if (ret)
goto error;
if (found_key.offset == 0)
break;
}
btrfs_release_path(path);
/* step one is to pin it all, step two is to replay just inodes */
if (wc.pin) {
wc.pin = 0;
wc.process_func = replay_one_buffer;
wc.stage = LOG_WALK_REPLAY_INODES;
goto again;
}
/* step three is to replay everything */
if (wc.stage < LOG_WALK_REPLAY_ALL) {
wc.stage++;
goto again;
}
btrfs_free_path(path);
/* step 4: commit the transaction, which also unpins the blocks */
ret = btrfs_commit_transaction(trans, fs_info->tree_root);
if (ret)
return ret;
free_extent_buffer(log_root_tree->node);
log_root_tree->log_root = NULL;
fs_info->log_root_recovering = 0;
kfree(log_root_tree);
return 0;
error:
if (wc.trans)
btrfs_end_transaction(wc.trans, fs_info->tree_root);
btrfs_free_path(path);
return ret;
}
/*
* there are some corner cases where we want to force a full
* commit instead of allowing a directory to be logged.
*
* They revolve around files there were unlinked from the directory, and
* this function updates the parent directory so that a full commit is
* properly done if it is fsync'd later after the unlinks are done.
*/
void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
struct inode *dir, struct inode *inode,
int for_rename)
{
/*
* when we're logging a file, if it hasn't been renamed
* or unlinked, and its inode is fully committed on disk,
* we don't have to worry about walking up the directory chain
* to log its parents.
*
* So, we use the last_unlink_trans field to put this transid
* into the file. When the file is logged we check it and
* don't log the parents if the file is fully on disk.
*/
if (S_ISREG(inode->i_mode))
BTRFS_I(inode)->last_unlink_trans = trans->transid;
/*
* if this directory was already logged any new
* names for this file/dir will get recorded
*/
smp_mb();
if (BTRFS_I(dir)->logged_trans == trans->transid)
return;
/*
* if the inode we're about to unlink was logged,
* the log will be properly updated for any new names
*/
if (BTRFS_I(inode)->logged_trans == trans->transid)
return;
/*
* when renaming files across directories, if the directory
* there we're unlinking from gets fsync'd later on, there's
* no way to find the destination directory later and fsync it
* properly. So, we have to be conservative and force commits
* so the new name gets discovered.
*/
if (for_rename)
goto record;
/* we can safely do the unlink without any special recording */
return;
record:
BTRFS_I(dir)->last_unlink_trans = trans->transid;
}
/*
* Call this after adding a new name for a file and it will properly
* update the log to reflect the new name.
*
* It will return zero if all goes well, and it will return 1 if a
* full transaction commit is required.
*/
int btrfs_log_new_name(struct btrfs_trans_handle *trans,
struct inode *inode, struct inode *old_dir,
struct dentry *parent)
{
struct btrfs_root * root = BTRFS_I(inode)->root;
/*
* this will force the logging code to walk the dentry chain
* up for the file
*/
if (S_ISREG(inode->i_mode))
BTRFS_I(inode)->last_unlink_trans = trans->transid;
/*
* if this inode hasn't been logged and directory we're renaming it
* from hasn't been logged, we don't need to log it
*/
if (BTRFS_I(inode)->logged_trans <=
root->fs_info->last_trans_committed &&
(!old_dir || BTRFS_I(old_dir)->logged_trans <=
root->fs_info->last_trans_committed))
return 0;
return btrfs_log_inode_parent(trans, root, inode, parent, 1);
}
| gpl-2.0 |
chonix/trinity | fs/statfs.c | 472 | 5171 | #include <linux/syscalls.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/statfs.h>
#include <linux/security.h>
#include <linux/uaccess.h>
static int flags_by_mnt(int mnt_flags)
{
int flags = 0;
if (mnt_flags & MNT_READONLY)
flags |= ST_RDONLY;
if (mnt_flags & MNT_NOSUID)
flags |= ST_NOSUID;
if (mnt_flags & MNT_NODEV)
flags |= ST_NODEV;
if (mnt_flags & MNT_NOEXEC)
flags |= ST_NOEXEC;
if (mnt_flags & MNT_NOATIME)
flags |= ST_NOATIME;
if (mnt_flags & MNT_NODIRATIME)
flags |= ST_NODIRATIME;
if (mnt_flags & MNT_RELATIME)
flags |= ST_RELATIME;
return flags;
}
static int flags_by_sb(int s_flags)
{
int flags = 0;
if (s_flags & MS_SYNCHRONOUS)
flags |= ST_SYNCHRONOUS;
if (s_flags & MS_MANDLOCK)
flags |= ST_MANDLOCK;
return flags;
}
static int calculate_f_flags(struct vfsmount *mnt)
{
return ST_VALID | flags_by_mnt(mnt->mnt_flags) |
flags_by_sb(mnt->mnt_sb->s_flags);
}
int statfs_by_dentry(struct dentry *dentry, struct kstatfs *buf)
{
int retval;
if (!dentry->d_sb->s_op->statfs)
return -ENOSYS;
memset(buf, 0, sizeof(*buf));
retval = security_sb_statfs(dentry);
if (retval)
return retval;
retval = dentry->d_sb->s_op->statfs(dentry, buf);
if (retval == 0 && buf->f_frsize == 0)
buf->f_frsize = buf->f_bsize;
return retval;
}
int vfs_statfs(struct path *path, struct kstatfs *buf)
{
int error;
error = statfs_by_dentry(path->dentry, buf);
if (!error)
buf->f_flags = calculate_f_flags(path->mnt);
return error;
}
EXPORT_SYMBOL(vfs_statfs);
int user_statfs(const char __user *pathname, struct kstatfs *st)
{
struct path path;
int error = user_path_at(AT_FDCWD, pathname, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path);
if (!error) {
error = vfs_statfs(&path, st);
path_put(&path);
}
return error;
}
int fd_statfs(int fd, struct kstatfs *st)
{
struct file *file = fget_raw(fd);
int error = -EBADF;
if (file) {
error = vfs_statfs(&file->f_path, st);
fput(file);
}
return error;
}
static int do_statfs_native(struct kstatfs *st, struct statfs __user *p)
{
struct statfs buf;
if (sizeof(buf) == sizeof(*st))
memcpy(&buf, st, sizeof(*st));
else {
if (sizeof buf.f_blocks == 4) {
if ((st->f_blocks | st->f_bfree | st->f_bavail |
st->f_bsize | st->f_frsize) &
0xffffffff00000000ULL)
return -EOVERFLOW;
/*
* f_files and f_ffree may be -1; it's okay to stuff
* that into 32 bits
*/
if (st->f_files != -1 &&
(st->f_files & 0xffffffff00000000ULL))
return -EOVERFLOW;
if (st->f_ffree != -1 &&
(st->f_ffree & 0xffffffff00000000ULL))
return -EOVERFLOW;
}
buf.f_type = st->f_type;
buf.f_bsize = st->f_bsize;
buf.f_blocks = st->f_blocks;
buf.f_bfree = st->f_bfree;
buf.f_bavail = st->f_bavail;
buf.f_files = st->f_files;
buf.f_ffree = st->f_ffree;
buf.f_fsid = st->f_fsid;
buf.f_namelen = st->f_namelen;
buf.f_frsize = st->f_frsize;
buf.f_flags = st->f_flags;
memset(buf.f_spare, 0, sizeof(buf.f_spare));
}
if (copy_to_user(p, &buf, sizeof(buf)))
return -EFAULT;
return 0;
}
static int do_statfs64(struct kstatfs *st, struct statfs64 __user *p)
{
struct statfs64 buf;
if (sizeof(buf) == sizeof(*st))
memcpy(&buf, st, sizeof(*st));
else {
buf.f_type = st->f_type;
buf.f_bsize = st->f_bsize;
buf.f_blocks = st->f_blocks;
buf.f_bfree = st->f_bfree;
buf.f_bavail = st->f_bavail;
buf.f_files = st->f_files;
buf.f_ffree = st->f_ffree;
buf.f_fsid = st->f_fsid;
buf.f_namelen = st->f_namelen;
buf.f_frsize = st->f_frsize;
buf.f_flags = st->f_flags;
memset(buf.f_spare, 0, sizeof(buf.f_spare));
}
if (copy_to_user(p, &buf, sizeof(buf)))
return -EFAULT;
return 0;
}
SYSCALL_DEFINE2(statfs, const char __user *, pathname, struct statfs __user *, buf)
{
struct kstatfs st;
int error = user_statfs(pathname, &st);
if (!error)
error = do_statfs_native(&st, buf);
return error;
}
SYSCALL_DEFINE3(statfs64, const char __user *, pathname, size_t, sz, struct statfs64 __user *, buf)
{
struct kstatfs st;
int error;
if (sz != sizeof(*buf))
return -EINVAL;
error = user_statfs(pathname, &st);
if (!error)
error = do_statfs64(&st, buf);
return error;
}
SYSCALL_DEFINE2(fstatfs, unsigned int, fd, struct statfs __user *, buf)
{
struct kstatfs st;
int error = fd_statfs(fd, &st);
if (!error)
error = do_statfs_native(&st, buf);
return error;
}
SYSCALL_DEFINE3(fstatfs64, unsigned int, fd, size_t, sz, struct statfs64 __user *, buf)
{
struct kstatfs st;
int error;
if (sz != sizeof(*buf))
return -EINVAL;
error = fd_statfs(fd, &st);
if (!error)
error = do_statfs64(&st, buf);
return error;
}
SYSCALL_DEFINE2(ustat, unsigned, dev, struct ustat __user *, ubuf)
{
struct super_block *s;
struct ustat tmp;
struct kstatfs sbuf;
int err;
s = user_get_super(new_decode_dev(dev));
if (!s)
return -EINVAL;
err = statfs_by_dentry(s->s_root, &sbuf);
drop_super(s);
if (err)
return err;
memset(&tmp,0,sizeof(struct ustat));
tmp.f_tfree = sbuf.f_bfree;
tmp.f_tinode = sbuf.f_ffree;
return copy_to_user(ubuf, &tmp, sizeof(struct ustat)) ? -EFAULT : 0;
}
| gpl-2.0 |
andi34/samsung_espresso_kernel | fs/partitions/ldm.c | 2776 | 45136 | /**
* ldm - Support for Windows Logical Disk Manager (Dynamic Disks)
*
* Copyright (C) 2001,2002 Richard Russon <ldm@flatcap.org>
* Copyright (c) 2001-2007 Anton Altaparmakov
* Copyright (C) 2001,2002 Jakob Kemi <jakob.kemi@telia.com>
*
* Documentation is available at http://www.linux-ntfs.org/doku.php?id=downloads
*
* 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 (in the main directory of the source in the file COPYING); if
* not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/stringify.h>
#include <linux/kernel.h>
#include "ldm.h"
#include "check.h"
#include "msdos.h"
/**
* ldm_debug/info/error/crit - Output an error message
* @f: A printf format string containing the message
* @...: Variables to substitute into @f
*
* ldm_debug() writes a DEBUG level message to the syslog but only if the
* driver was compiled with debug enabled. Otherwise, the call turns into a NOP.
*/
#ifndef CONFIG_LDM_DEBUG
#define ldm_debug(...) do {} while (0)
#else
#define ldm_debug(f, a...) _ldm_printk (KERN_DEBUG, __func__, f, ##a)
#endif
#define ldm_crit(f, a...) _ldm_printk (KERN_CRIT, __func__, f, ##a)
#define ldm_error(f, a...) _ldm_printk (KERN_ERR, __func__, f, ##a)
#define ldm_info(f, a...) _ldm_printk (KERN_INFO, __func__, f, ##a)
__attribute__ ((format (printf, 3, 4)))
static void _ldm_printk (const char *level, const char *function,
const char *fmt, ...)
{
static char buf[128];
va_list args;
va_start (args, fmt);
vsnprintf (buf, sizeof (buf), fmt, args);
va_end (args);
printk ("%s%s(): %s\n", level, function, buf);
}
/**
* ldm_parse_hexbyte - Convert a ASCII hex number to a byte
* @src: Pointer to at least 2 characters to convert.
*
* Convert a two character ASCII hex string to a number.
*
* Return: 0-255 Success, the byte was parsed correctly
* -1 Error, an invalid character was supplied
*/
static int ldm_parse_hexbyte (const u8 *src)
{
unsigned int x; /* For correct wrapping */
int h;
/* high part */
x = h = hex_to_bin(src[0]);
if (h < 0)
return -1;
/* low part */
h = hex_to_bin(src[1]);
if (h < 0)
return -1;
return (x << 4) + h;
}
/**
* ldm_parse_guid - Convert GUID from ASCII to binary
* @src: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
* @dest: Memory block to hold binary GUID (16 bytes)
*
* N.B. The GUID need not be NULL terminated.
*
* Return: 'true' @dest contains binary GUID
* 'false' @dest contents are undefined
*/
static bool ldm_parse_guid (const u8 *src, u8 *dest)
{
static const int size[] = { 4, 2, 2, 2, 6 };
int i, j, v;
if (src[8] != '-' || src[13] != '-' ||
src[18] != '-' || src[23] != '-')
return false;
for (j = 0; j < 5; j++, src++)
for (i = 0; i < size[j]; i++, src+=2, *dest++ = v)
if ((v = ldm_parse_hexbyte (src)) < 0)
return false;
return true;
}
/**
* ldm_parse_privhead - Read the LDM Database PRIVHEAD structure
* @data: Raw database PRIVHEAD structure loaded from the device
* @ph: In-memory privhead structure in which to return parsed information
*
* This parses the LDM database PRIVHEAD structure supplied in @data and
* sets up the in-memory privhead structure @ph with the obtained information.
*
* Return: 'true' @ph contains the PRIVHEAD data
* 'false' @ph contents are undefined
*/
static bool ldm_parse_privhead(const u8 *data, struct privhead *ph)
{
bool is_vista = false;
BUG_ON(!data || !ph);
if (MAGIC_PRIVHEAD != get_unaligned_be64(data)) {
ldm_error("Cannot find PRIVHEAD structure. LDM database is"
" corrupt. Aborting.");
return false;
}
ph->ver_major = get_unaligned_be16(data + 0x000C);
ph->ver_minor = get_unaligned_be16(data + 0x000E);
ph->logical_disk_start = get_unaligned_be64(data + 0x011B);
ph->logical_disk_size = get_unaligned_be64(data + 0x0123);
ph->config_start = get_unaligned_be64(data + 0x012B);
ph->config_size = get_unaligned_be64(data + 0x0133);
/* Version 2.11 is Win2k/XP and version 2.12 is Vista. */
if (ph->ver_major == 2 && ph->ver_minor == 12)
is_vista = true;
if (!is_vista && (ph->ver_major != 2 || ph->ver_minor != 11)) {
ldm_error("Expected PRIVHEAD version 2.11 or 2.12, got %d.%d."
" Aborting.", ph->ver_major, ph->ver_minor);
return false;
}
ldm_debug("PRIVHEAD version %d.%d (Windows %s).", ph->ver_major,
ph->ver_minor, is_vista ? "Vista" : "2000/XP");
if (ph->config_size != LDM_DB_SIZE) { /* 1 MiB in sectors. */
/* Warn the user and continue, carefully. */
ldm_info("Database is normally %u bytes, it claims to "
"be %llu bytes.", LDM_DB_SIZE,
(unsigned long long)ph->config_size);
}
if ((ph->logical_disk_size == 0) || (ph->logical_disk_start +
ph->logical_disk_size > ph->config_start)) {
ldm_error("PRIVHEAD disk size doesn't match real disk size");
return false;
}
if (!ldm_parse_guid(data + 0x0030, ph->disk_id)) {
ldm_error("PRIVHEAD contains an invalid GUID.");
return false;
}
ldm_debug("Parsed PRIVHEAD successfully.");
return true;
}
/**
* ldm_parse_tocblock - Read the LDM Database TOCBLOCK structure
* @data: Raw database TOCBLOCK structure loaded from the device
* @toc: In-memory toc structure in which to return parsed information
*
* This parses the LDM Database TOCBLOCK (table of contents) structure supplied
* in @data and sets up the in-memory tocblock structure @toc with the obtained
* information.
*
* N.B. The *_start and *_size values returned in @toc are not range-checked.
*
* Return: 'true' @toc contains the TOCBLOCK data
* 'false' @toc contents are undefined
*/
static bool ldm_parse_tocblock (const u8 *data, struct tocblock *toc)
{
BUG_ON (!data || !toc);
if (MAGIC_TOCBLOCK != get_unaligned_be64(data)) {
ldm_crit ("Cannot find TOCBLOCK, database may be corrupt.");
return false;
}
strncpy (toc->bitmap1_name, data + 0x24, sizeof (toc->bitmap1_name));
toc->bitmap1_name[sizeof (toc->bitmap1_name) - 1] = 0;
toc->bitmap1_start = get_unaligned_be64(data + 0x2E);
toc->bitmap1_size = get_unaligned_be64(data + 0x36);
if (strncmp (toc->bitmap1_name, TOC_BITMAP1,
sizeof (toc->bitmap1_name)) != 0) {
ldm_crit ("TOCBLOCK's first bitmap is '%s', should be '%s'.",
TOC_BITMAP1, toc->bitmap1_name);
return false;
}
strncpy (toc->bitmap2_name, data + 0x46, sizeof (toc->bitmap2_name));
toc->bitmap2_name[sizeof (toc->bitmap2_name) - 1] = 0;
toc->bitmap2_start = get_unaligned_be64(data + 0x50);
toc->bitmap2_size = get_unaligned_be64(data + 0x58);
if (strncmp (toc->bitmap2_name, TOC_BITMAP2,
sizeof (toc->bitmap2_name)) != 0) {
ldm_crit ("TOCBLOCK's second bitmap is '%s', should be '%s'.",
TOC_BITMAP2, toc->bitmap2_name);
return false;
}
ldm_debug ("Parsed TOCBLOCK successfully.");
return true;
}
/**
* ldm_parse_vmdb - Read the LDM Database VMDB structure
* @data: Raw database VMDB structure loaded from the device
* @vm: In-memory vmdb structure in which to return parsed information
*
* This parses the LDM Database VMDB structure supplied in @data and sets up
* the in-memory vmdb structure @vm with the obtained information.
*
* N.B. The *_start, *_size and *_seq values will be range-checked later.
*
* Return: 'true' @vm contains VMDB info
* 'false' @vm contents are undefined
*/
static bool ldm_parse_vmdb (const u8 *data, struct vmdb *vm)
{
BUG_ON (!data || !vm);
if (MAGIC_VMDB != get_unaligned_be32(data)) {
ldm_crit ("Cannot find the VMDB, database may be corrupt.");
return false;
}
vm->ver_major = get_unaligned_be16(data + 0x12);
vm->ver_minor = get_unaligned_be16(data + 0x14);
if ((vm->ver_major != 4) || (vm->ver_minor != 10)) {
ldm_error ("Expected VMDB version %d.%d, got %d.%d. "
"Aborting.", 4, 10, vm->ver_major, vm->ver_minor);
return false;
}
vm->vblk_size = get_unaligned_be32(data + 0x08);
if (vm->vblk_size == 0) {
ldm_error ("Illegal VBLK size");
return false;
}
vm->vblk_offset = get_unaligned_be32(data + 0x0C);
vm->last_vblk_seq = get_unaligned_be32(data + 0x04);
ldm_debug ("Parsed VMDB successfully.");
return true;
}
/**
* ldm_compare_privheads - Compare two privhead objects
* @ph1: First privhead
* @ph2: Second privhead
*
* This compares the two privhead structures @ph1 and @ph2.
*
* Return: 'true' Identical
* 'false' Different
*/
static bool ldm_compare_privheads (const struct privhead *ph1,
const struct privhead *ph2)
{
BUG_ON (!ph1 || !ph2);
return ((ph1->ver_major == ph2->ver_major) &&
(ph1->ver_minor == ph2->ver_minor) &&
(ph1->logical_disk_start == ph2->logical_disk_start) &&
(ph1->logical_disk_size == ph2->logical_disk_size) &&
(ph1->config_start == ph2->config_start) &&
(ph1->config_size == ph2->config_size) &&
!memcmp (ph1->disk_id, ph2->disk_id, GUID_SIZE));
}
/**
* ldm_compare_tocblocks - Compare two tocblock objects
* @toc1: First toc
* @toc2: Second toc
*
* This compares the two tocblock structures @toc1 and @toc2.
*
* Return: 'true' Identical
* 'false' Different
*/
static bool ldm_compare_tocblocks (const struct tocblock *toc1,
const struct tocblock *toc2)
{
BUG_ON (!toc1 || !toc2);
return ((toc1->bitmap1_start == toc2->bitmap1_start) &&
(toc1->bitmap1_size == toc2->bitmap1_size) &&
(toc1->bitmap2_start == toc2->bitmap2_start) &&
(toc1->bitmap2_size == toc2->bitmap2_size) &&
!strncmp (toc1->bitmap1_name, toc2->bitmap1_name,
sizeof (toc1->bitmap1_name)) &&
!strncmp (toc1->bitmap2_name, toc2->bitmap2_name,
sizeof (toc1->bitmap2_name)));
}
/**
* ldm_validate_privheads - Compare the primary privhead with its backups
* @state: Partition check state including device holding the LDM Database
* @ph1: Memory struct to fill with ph contents
*
* Read and compare all three privheads from disk.
*
* The privheads on disk show the size and location of the main disk area and
* the configuration area (the database). The values are range-checked against
* @hd, which contains the real size of the disk.
*
* Return: 'true' Success
* 'false' Error
*/
static bool ldm_validate_privheads(struct parsed_partitions *state,
struct privhead *ph1)
{
static const int off[3] = { OFF_PRIV1, OFF_PRIV2, OFF_PRIV3 };
struct privhead *ph[3] = { ph1 };
Sector sect;
u8 *data;
bool result = false;
long num_sects;
int i;
BUG_ON (!state || !ph1);
ph[1] = kmalloc (sizeof (*ph[1]), GFP_KERNEL);
ph[2] = kmalloc (sizeof (*ph[2]), GFP_KERNEL);
if (!ph[1] || !ph[2]) {
ldm_crit ("Out of memory.");
goto out;
}
/* off[1 & 2] are relative to ph[0]->config_start */
ph[0]->config_start = 0;
/* Read and parse privheads */
for (i = 0; i < 3; i++) {
data = read_part_sector(state, ph[0]->config_start + off[i],
§);
if (!data) {
ldm_crit ("Disk read failed.");
goto out;
}
result = ldm_parse_privhead (data, ph[i]);
put_dev_sector (sect);
if (!result) {
ldm_error ("Cannot find PRIVHEAD %d.", i+1); /* Log again */
if (i < 2)
goto out; /* Already logged */
else
break; /* FIXME ignore for now, 3rd PH can fail on odd-sized disks */
}
}
num_sects = state->bdev->bd_inode->i_size >> 9;
if ((ph[0]->config_start > num_sects) ||
((ph[0]->config_start + ph[0]->config_size) > num_sects)) {
ldm_crit ("Database extends beyond the end of the disk.");
goto out;
}
if ((ph[0]->logical_disk_start > ph[0]->config_start) ||
((ph[0]->logical_disk_start + ph[0]->logical_disk_size)
> ph[0]->config_start)) {
ldm_crit ("Disk and database overlap.");
goto out;
}
if (!ldm_compare_privheads (ph[0], ph[1])) {
ldm_crit ("Primary and backup PRIVHEADs don't match.");
goto out;
}
/* FIXME ignore this for now
if (!ldm_compare_privheads (ph[0], ph[2])) {
ldm_crit ("Primary and backup PRIVHEADs don't match.");
goto out;
}*/
ldm_debug ("Validated PRIVHEADs successfully.");
result = true;
out:
kfree (ph[1]);
kfree (ph[2]);
return result;
}
/**
* ldm_validate_tocblocks - Validate the table of contents and its backups
* @state: Partition check state including device holding the LDM Database
* @base: Offset, into @state->bdev, of the database
* @ldb: Cache of the database structures
*
* Find and compare the four tables of contents of the LDM Database stored on
* @state->bdev and return the parsed information into @toc1.
*
* The offsets and sizes of the configs are range-checked against a privhead.
*
* Return: 'true' @toc1 contains validated TOCBLOCK info
* 'false' @toc1 contents are undefined
*/
static bool ldm_validate_tocblocks(struct parsed_partitions *state,
unsigned long base, struct ldmdb *ldb)
{
static const int off[4] = { OFF_TOCB1, OFF_TOCB2, OFF_TOCB3, OFF_TOCB4};
struct tocblock *tb[4];
struct privhead *ph;
Sector sect;
u8 *data;
int i, nr_tbs;
bool result = false;
BUG_ON(!state || !ldb);
ph = &ldb->ph;
tb[0] = &ldb->toc;
tb[1] = kmalloc(sizeof(*tb[1]) * 3, GFP_KERNEL);
if (!tb[1]) {
ldm_crit("Out of memory.");
goto err;
}
tb[2] = (struct tocblock*)((u8*)tb[1] + sizeof(*tb[1]));
tb[3] = (struct tocblock*)((u8*)tb[2] + sizeof(*tb[2]));
/*
* Try to read and parse all four TOCBLOCKs.
*
* Windows Vista LDM v2.12 does not always have all four TOCBLOCKs so
* skip any that fail as long as we get at least one valid TOCBLOCK.
*/
for (nr_tbs = i = 0; i < 4; i++) {
data = read_part_sector(state, base + off[i], §);
if (!data) {
ldm_error("Disk read failed for TOCBLOCK %d.", i);
continue;
}
if (ldm_parse_tocblock(data, tb[nr_tbs]))
nr_tbs++;
put_dev_sector(sect);
}
if (!nr_tbs) {
ldm_crit("Failed to find a valid TOCBLOCK.");
goto err;
}
/* Range check the TOCBLOCK against a privhead. */
if (((tb[0]->bitmap1_start + tb[0]->bitmap1_size) > ph->config_size) ||
((tb[0]->bitmap2_start + tb[0]->bitmap2_size) >
ph->config_size)) {
ldm_crit("The bitmaps are out of range. Giving up.");
goto err;
}
/* Compare all loaded TOCBLOCKs. */
for (i = 1; i < nr_tbs; i++) {
if (!ldm_compare_tocblocks(tb[0], tb[i])) {
ldm_crit("TOCBLOCKs 0 and %d do not match.", i);
goto err;
}
}
ldm_debug("Validated %d TOCBLOCKs successfully.", nr_tbs);
result = true;
err:
kfree(tb[1]);
return result;
}
/**
* ldm_validate_vmdb - Read the VMDB and validate it
* @state: Partition check state including device holding the LDM Database
* @base: Offset, into @bdev, of the database
* @ldb: Cache of the database structures
*
* Find the vmdb of the LDM Database stored on @bdev and return the parsed
* information in @ldb.
*
* Return: 'true' @ldb contains validated VBDB info
* 'false' @ldb contents are undefined
*/
static bool ldm_validate_vmdb(struct parsed_partitions *state,
unsigned long base, struct ldmdb *ldb)
{
Sector sect;
u8 *data;
bool result = false;
struct vmdb *vm;
struct tocblock *toc;
BUG_ON (!state || !ldb);
vm = &ldb->vm;
toc = &ldb->toc;
data = read_part_sector(state, base + OFF_VMDB, §);
if (!data) {
ldm_crit ("Disk read failed.");
return false;
}
if (!ldm_parse_vmdb (data, vm))
goto out; /* Already logged */
/* Are there uncommitted transactions? */
if (get_unaligned_be16(data + 0x10) != 0x01) {
ldm_crit ("Database is not in a consistent state. Aborting.");
goto out;
}
if (vm->vblk_offset != 512)
ldm_info ("VBLKs start at offset 0x%04x.", vm->vblk_offset);
/*
* The last_vblkd_seq can be before the end of the vmdb, just make sure
* it is not out of bounds.
*/
if ((vm->vblk_size * vm->last_vblk_seq) > (toc->bitmap1_size << 9)) {
ldm_crit ("VMDB exceeds allowed size specified by TOCBLOCK. "
"Database is corrupt. Aborting.");
goto out;
}
result = true;
out:
put_dev_sector (sect);
return result;
}
/**
* ldm_validate_partition_table - Determine whether bdev might be a dynamic disk
* @state: Partition check state including device holding the LDM Database
*
* This function provides a weak test to decide whether the device is a dynamic
* disk or not. It looks for an MS-DOS-style partition table containing at
* least one partition of type 0x42 (formerly SFS, now used by Windows for
* dynamic disks).
*
* N.B. The only possible error can come from the read_part_sector and that is
* only likely to happen if the underlying device is strange. If that IS
* the case we should return zero to let someone else try.
*
* Return: 'true' @state->bdev is a dynamic disk
* 'false' @state->bdev is not a dynamic disk, or an error occurred
*/
static bool ldm_validate_partition_table(struct parsed_partitions *state)
{
Sector sect;
u8 *data;
struct partition *p;
int i;
bool result = false;
BUG_ON(!state);
data = read_part_sector(state, 0, §);
if (!data) {
ldm_info ("Disk read failed.");
return false;
}
if (*(__le16*) (data + 0x01FE) != cpu_to_le16 (MSDOS_LABEL_MAGIC))
goto out;
p = (struct partition*)(data + 0x01BE);
for (i = 0; i < 4; i++, p++)
if (SYS_IND (p) == LDM_PARTITION) {
result = true;
break;
}
if (result)
ldm_debug ("Found W2K dynamic disk partition type.");
out:
put_dev_sector (sect);
return result;
}
/**
* ldm_get_disk_objid - Search a linked list of vblk's for a given Disk Id
* @ldb: Cache of the database structures
*
* The LDM Database contains a list of all partitions on all dynamic disks.
* The primary PRIVHEAD, at the beginning of the physical disk, tells us
* the GUID of this disk. This function searches for the GUID in a linked
* list of vblk's.
*
* Return: Pointer, A matching vblk was found
* NULL, No match, or an error
*/
static struct vblk * ldm_get_disk_objid (const struct ldmdb *ldb)
{
struct list_head *item;
BUG_ON (!ldb);
list_for_each (item, &ldb->v_disk) {
struct vblk *v = list_entry (item, struct vblk, list);
if (!memcmp (v->vblk.disk.disk_id, ldb->ph.disk_id, GUID_SIZE))
return v;
}
return NULL;
}
/**
* ldm_create_data_partitions - Create data partitions for this device
* @pp: List of the partitions parsed so far
* @ldb: Cache of the database structures
*
* The database contains ALL the partitions for ALL disk groups, so we need to
* filter out this specific disk. Using the disk's object id, we can find all
* the partitions in the database that belong to this disk.
*
* Add each partition in our database, to the parsed_partitions structure.
*
* N.B. This function creates the partitions in the order it finds partition
* objects in the linked list.
*
* Return: 'true' Partition created
* 'false' Error, probably a range checking problem
*/
static bool ldm_create_data_partitions (struct parsed_partitions *pp,
const struct ldmdb *ldb)
{
struct list_head *item;
struct vblk *vb;
struct vblk *disk;
struct vblk_part *part;
int part_num = 1;
BUG_ON (!pp || !ldb);
disk = ldm_get_disk_objid (ldb);
if (!disk) {
ldm_crit ("Can't find the ID of this disk in the database.");
return false;
}
strlcat(pp->pp_buf, " [LDM]", PAGE_SIZE);
/* Create the data partitions */
list_for_each (item, &ldb->v_part) {
vb = list_entry (item, struct vblk, list);
part = &vb->vblk.part;
if (part->disk_id != disk->obj_id)
continue;
put_partition (pp, part_num, ldb->ph.logical_disk_start +
part->start, part->size);
part_num++;
}
strlcat(pp->pp_buf, "\n", PAGE_SIZE);
return true;
}
/**
* ldm_relative - Calculate the next relative offset
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @base: Size of the previous fixed width fields
* @offset: Cumulative size of the previous variable-width fields
*
* Because many of the VBLK fields are variable-width, it's necessary
* to calculate each offset based on the previous one and the length
* of the field it pointed to.
*
* Return: -1 Error, the calculated offset exceeded the size of the buffer
* n OK, a range-checked offset into buffer
*/
static int ldm_relative(const u8 *buffer, int buflen, int base, int offset)
{
base += offset;
if (!buffer || offset < 0 || base > buflen) {
if (!buffer)
ldm_error("!buffer");
if (offset < 0)
ldm_error("offset (%d) < 0", offset);
if (base > buflen)
ldm_error("base (%d) > buflen (%d)", base, buflen);
return -1;
}
if (base + buffer[base] >= buflen) {
ldm_error("base (%d) + buffer[base] (%d) >= buflen (%d)", base,
buffer[base], buflen);
return -1;
}
return buffer[base] + offset + 1;
}
/**
* ldm_get_vnum - Convert a variable-width, big endian number, into cpu order
* @block: Pointer to the variable-width number to convert
*
* Large numbers in the LDM Database are often stored in a packed format. Each
* number is prefixed by a one byte width marker. All numbers in the database
* are stored in big-endian byte order. This function reads one of these
* numbers and returns the result
*
* N.B. This function DOES NOT perform any range checking, though the most
* it will read is eight bytes.
*
* Return: n A number
* 0 Zero, or an error occurred
*/
static u64 ldm_get_vnum (const u8 *block)
{
u64 tmp = 0;
u8 length;
BUG_ON (!block);
length = *block++;
if (length && length <= 8)
while (length--)
tmp = (tmp << 8) | *block++;
else
ldm_error ("Illegal length %d.", length);
return tmp;
}
/**
* ldm_get_vstr - Read a length-prefixed string into a buffer
* @block: Pointer to the length marker
* @buffer: Location to copy string to
* @buflen: Size of the output buffer
*
* Many of the strings in the LDM Database are not NULL terminated. Instead
* they are prefixed by a one byte length marker. This function copies one of
* these strings into a buffer.
*
* N.B. This function DOES NOT perform any range checking on the input.
* If the buffer is too small, the output will be truncated.
*
* Return: 0, Error and @buffer contents are undefined
* n, String length in characters (excluding NULL)
* buflen-1, String was truncated.
*/
static int ldm_get_vstr (const u8 *block, u8 *buffer, int buflen)
{
int length;
BUG_ON (!block || !buffer);
length = block[0];
if (length >= buflen) {
ldm_error ("Truncating string %d -> %d.", length, buflen);
length = buflen - 1;
}
memcpy (buffer, block + 1, length);
buffer[length] = 0;
return length;
}
/**
* ldm_parse_cmp3 - Read a raw VBLK Component object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Component object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Component VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_cmp3 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_vstate, r_child, r_parent, r_stripe, r_cols, len;
struct vblk_comp *comp;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
r_vstate = ldm_relative (buffer, buflen, 0x18, r_name);
r_child = ldm_relative (buffer, buflen, 0x1D, r_vstate);
r_parent = ldm_relative (buffer, buflen, 0x2D, r_child);
if (buffer[0x12] & VBLK_FLAG_COMP_STRIPE) {
r_stripe = ldm_relative (buffer, buflen, 0x2E, r_parent);
r_cols = ldm_relative (buffer, buflen, 0x2E, r_stripe);
len = r_cols;
} else {
r_stripe = 0;
r_cols = 0;
len = r_parent;
}
if (len < 0)
return false;
len += VBLK_SIZE_CMP3;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
comp = &vb->vblk.comp;
ldm_get_vstr (buffer + 0x18 + r_name, comp->state,
sizeof (comp->state));
comp->type = buffer[0x18 + r_vstate];
comp->children = ldm_get_vnum (buffer + 0x1D + r_vstate);
comp->parent_id = ldm_get_vnum (buffer + 0x2D + r_child);
comp->chunksize = r_stripe ? ldm_get_vnum (buffer+r_parent+0x2E) : 0;
return true;
}
/**
* ldm_parse_dgr3 - Read a raw VBLK Disk Group object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk Group object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Disk Group VBLK
* 'false' @vb contents are not defined
*/
static int ldm_parse_dgr3 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_diskid, r_id1, r_id2, len;
struct vblk_dgrp *dgrp;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
r_diskid = ldm_relative (buffer, buflen, 0x18, r_name);
if (buffer[0x12] & VBLK_FLAG_DGR3_IDS) {
r_id1 = ldm_relative (buffer, buflen, 0x24, r_diskid);
r_id2 = ldm_relative (buffer, buflen, 0x24, r_id1);
len = r_id2;
} else {
r_id1 = 0;
r_id2 = 0;
len = r_diskid;
}
if (len < 0)
return false;
len += VBLK_SIZE_DGR3;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
dgrp = &vb->vblk.dgrp;
ldm_get_vstr (buffer + 0x18 + r_name, dgrp->disk_id,
sizeof (dgrp->disk_id));
return true;
}
/**
* ldm_parse_dgr4 - Read a raw VBLK Disk Group object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk Group object (version 4) into a vblk structure.
*
* Return: 'true' @vb contains a Disk Group VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_dgr4 (const u8 *buffer, int buflen, struct vblk *vb)
{
char buf[64];
int r_objid, r_name, r_id1, r_id2, len;
struct vblk_dgrp *dgrp;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
if (buffer[0x12] & VBLK_FLAG_DGR4_IDS) {
r_id1 = ldm_relative (buffer, buflen, 0x44, r_name);
r_id2 = ldm_relative (buffer, buflen, 0x44, r_id1);
len = r_id2;
} else {
r_id1 = 0;
r_id2 = 0;
len = r_name;
}
if (len < 0)
return false;
len += VBLK_SIZE_DGR4;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
dgrp = &vb->vblk.dgrp;
ldm_get_vstr (buffer + 0x18 + r_objid, buf, sizeof (buf));
return true;
}
/**
* ldm_parse_dsk3 - Read a raw VBLK Disk object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Disk VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_dsk3 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_diskid, r_altname, len;
struct vblk_disk *disk;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
r_diskid = ldm_relative (buffer, buflen, 0x18, r_name);
r_altname = ldm_relative (buffer, buflen, 0x18, r_diskid);
len = r_altname;
if (len < 0)
return false;
len += VBLK_SIZE_DSK3;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
disk = &vb->vblk.disk;
ldm_get_vstr (buffer + 0x18 + r_diskid, disk->alt_name,
sizeof (disk->alt_name));
if (!ldm_parse_guid (buffer + 0x19 + r_name, disk->disk_id))
return false;
return true;
}
/**
* ldm_parse_dsk4 - Read a raw VBLK Disk object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk object (version 4) into a vblk structure.
*
* Return: 'true' @vb contains a Disk VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_dsk4 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, len;
struct vblk_disk *disk;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
len = r_name;
if (len < 0)
return false;
len += VBLK_SIZE_DSK4;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
disk = &vb->vblk.disk;
memcpy (disk->disk_id, buffer + 0x18 + r_name, GUID_SIZE);
return true;
}
/**
* ldm_parse_prt3 - Read a raw VBLK Partition object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Partition object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Partition VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_prt3(const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_size, r_parent, r_diskid, r_index, len;
struct vblk_part *part;
BUG_ON(!buffer || !vb);
r_objid = ldm_relative(buffer, buflen, 0x18, 0);
if (r_objid < 0) {
ldm_error("r_objid %d < 0", r_objid);
return false;
}
r_name = ldm_relative(buffer, buflen, 0x18, r_objid);
if (r_name < 0) {
ldm_error("r_name %d < 0", r_name);
return false;
}
r_size = ldm_relative(buffer, buflen, 0x34, r_name);
if (r_size < 0) {
ldm_error("r_size %d < 0", r_size);
return false;
}
r_parent = ldm_relative(buffer, buflen, 0x34, r_size);
if (r_parent < 0) {
ldm_error("r_parent %d < 0", r_parent);
return false;
}
r_diskid = ldm_relative(buffer, buflen, 0x34, r_parent);
if (r_diskid < 0) {
ldm_error("r_diskid %d < 0", r_diskid);
return false;
}
if (buffer[0x12] & VBLK_FLAG_PART_INDEX) {
r_index = ldm_relative(buffer, buflen, 0x34, r_diskid);
if (r_index < 0) {
ldm_error("r_index %d < 0", r_index);
return false;
}
len = r_index;
} else {
r_index = 0;
len = r_diskid;
}
if (len < 0) {
ldm_error("len %d < 0", len);
return false;
}
len += VBLK_SIZE_PRT3;
if (len > get_unaligned_be32(buffer + 0x14)) {
ldm_error("len %d > BE32(buffer + 0x14) %d", len,
get_unaligned_be32(buffer + 0x14));
return false;
}
part = &vb->vblk.part;
part->start = get_unaligned_be64(buffer + 0x24 + r_name);
part->volume_offset = get_unaligned_be64(buffer + 0x2C + r_name);
part->size = ldm_get_vnum(buffer + 0x34 + r_name);
part->parent_id = ldm_get_vnum(buffer + 0x34 + r_size);
part->disk_id = ldm_get_vnum(buffer + 0x34 + r_parent);
if (vb->flags & VBLK_FLAG_PART_INDEX)
part->partnum = buffer[0x35 + r_diskid];
else
part->partnum = 0;
return true;
}
/**
* ldm_parse_vol5 - Read a raw VBLK Volume object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Volume object (version 5) into a vblk structure.
*
* Return: 'true' @vb contains a Volume VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_vol5(const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_vtype, r_disable_drive_letter, r_child, r_size;
int r_id1, r_id2, r_size2, r_drive, len;
struct vblk_volu *volu;
BUG_ON(!buffer || !vb);
r_objid = ldm_relative(buffer, buflen, 0x18, 0);
if (r_objid < 0) {
ldm_error("r_objid %d < 0", r_objid);
return false;
}
r_name = ldm_relative(buffer, buflen, 0x18, r_objid);
if (r_name < 0) {
ldm_error("r_name %d < 0", r_name);
return false;
}
r_vtype = ldm_relative(buffer, buflen, 0x18, r_name);
if (r_vtype < 0) {
ldm_error("r_vtype %d < 0", r_vtype);
return false;
}
r_disable_drive_letter = ldm_relative(buffer, buflen, 0x18, r_vtype);
if (r_disable_drive_letter < 0) {
ldm_error("r_disable_drive_letter %d < 0",
r_disable_drive_letter);
return false;
}
r_child = ldm_relative(buffer, buflen, 0x2D, r_disable_drive_letter);
if (r_child < 0) {
ldm_error("r_child %d < 0", r_child);
return false;
}
r_size = ldm_relative(buffer, buflen, 0x3D, r_child);
if (r_size < 0) {
ldm_error("r_size %d < 0", r_size);
return false;
}
if (buffer[0x12] & VBLK_FLAG_VOLU_ID1) {
r_id1 = ldm_relative(buffer, buflen, 0x52, r_size);
if (r_id1 < 0) {
ldm_error("r_id1 %d < 0", r_id1);
return false;
}
} else
r_id1 = r_size;
if (buffer[0x12] & VBLK_FLAG_VOLU_ID2) {
r_id2 = ldm_relative(buffer, buflen, 0x52, r_id1);
if (r_id2 < 0) {
ldm_error("r_id2 %d < 0", r_id2);
return false;
}
} else
r_id2 = r_id1;
if (buffer[0x12] & VBLK_FLAG_VOLU_SIZE) {
r_size2 = ldm_relative(buffer, buflen, 0x52, r_id2);
if (r_size2 < 0) {
ldm_error("r_size2 %d < 0", r_size2);
return false;
}
} else
r_size2 = r_id2;
if (buffer[0x12] & VBLK_FLAG_VOLU_DRIVE) {
r_drive = ldm_relative(buffer, buflen, 0x52, r_size2);
if (r_drive < 0) {
ldm_error("r_drive %d < 0", r_drive);
return false;
}
} else
r_drive = r_size2;
len = r_drive;
if (len < 0) {
ldm_error("len %d < 0", len);
return false;
}
len += VBLK_SIZE_VOL5;
if (len > get_unaligned_be32(buffer + 0x14)) {
ldm_error("len %d > BE32(buffer + 0x14) %d", len,
get_unaligned_be32(buffer + 0x14));
return false;
}
volu = &vb->vblk.volu;
ldm_get_vstr(buffer + 0x18 + r_name, volu->volume_type,
sizeof(volu->volume_type));
memcpy(volu->volume_state, buffer + 0x18 + r_disable_drive_letter,
sizeof(volu->volume_state));
volu->size = ldm_get_vnum(buffer + 0x3D + r_child);
volu->partition_type = buffer[0x41 + r_size];
memcpy(volu->guid, buffer + 0x42 + r_size, sizeof(volu->guid));
if (buffer[0x12] & VBLK_FLAG_VOLU_DRIVE) {
ldm_get_vstr(buffer + 0x52 + r_size, volu->drive_hint,
sizeof(volu->drive_hint));
}
return true;
}
/**
* ldm_parse_vblk - Read a raw VBLK object into a vblk structure
* @buf: Block of data being worked on
* @len: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK object into a vblk structure. This function just reads the
* information common to all VBLK types, then delegates the rest of the work to
* helper functions: ldm_parse_*.
*
* Return: 'true' @vb contains a VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_vblk (const u8 *buf, int len, struct vblk *vb)
{
bool result = false;
int r_objid;
BUG_ON (!buf || !vb);
r_objid = ldm_relative (buf, len, 0x18, 0);
if (r_objid < 0) {
ldm_error ("VBLK header is corrupt.");
return false;
}
vb->flags = buf[0x12];
vb->type = buf[0x13];
vb->obj_id = ldm_get_vnum (buf + 0x18);
ldm_get_vstr (buf+0x18+r_objid, vb->name, sizeof (vb->name));
switch (vb->type) {
case VBLK_CMP3: result = ldm_parse_cmp3 (buf, len, vb); break;
case VBLK_DSK3: result = ldm_parse_dsk3 (buf, len, vb); break;
case VBLK_DSK4: result = ldm_parse_dsk4 (buf, len, vb); break;
case VBLK_DGR3: result = ldm_parse_dgr3 (buf, len, vb); break;
case VBLK_DGR4: result = ldm_parse_dgr4 (buf, len, vb); break;
case VBLK_PRT3: result = ldm_parse_prt3 (buf, len, vb); break;
case VBLK_VOL5: result = ldm_parse_vol5 (buf, len, vb); break;
}
if (result)
ldm_debug ("Parsed VBLK 0x%llx (type: 0x%02x) ok.",
(unsigned long long) vb->obj_id, vb->type);
else
ldm_error ("Failed to parse VBLK 0x%llx (type: 0x%02x).",
(unsigned long long) vb->obj_id, vb->type);
return result;
}
/**
* ldm_ldmdb_add - Adds a raw VBLK entry to the ldmdb database
* @data: Raw VBLK to add to the database
* @len: Size of the raw VBLK
* @ldb: Cache of the database structures
*
* The VBLKs are sorted into categories. Partitions are also sorted by offset.
*
* N.B. This function does not check the validity of the VBLKs.
*
* Return: 'true' The VBLK was added
* 'false' An error occurred
*/
static bool ldm_ldmdb_add (u8 *data, int len, struct ldmdb *ldb)
{
struct vblk *vb;
struct list_head *item;
BUG_ON (!data || !ldb);
vb = kmalloc (sizeof (*vb), GFP_KERNEL);
if (!vb) {
ldm_crit ("Out of memory.");
return false;
}
if (!ldm_parse_vblk (data, len, vb)) {
kfree(vb);
return false; /* Already logged */
}
/* Put vblk into the correct list. */
switch (vb->type) {
case VBLK_DGR3:
case VBLK_DGR4:
list_add (&vb->list, &ldb->v_dgrp);
break;
case VBLK_DSK3:
case VBLK_DSK4:
list_add (&vb->list, &ldb->v_disk);
break;
case VBLK_VOL5:
list_add (&vb->list, &ldb->v_volu);
break;
case VBLK_CMP3:
list_add (&vb->list, &ldb->v_comp);
break;
case VBLK_PRT3:
/* Sort by the partition's start sector. */
list_for_each (item, &ldb->v_part) {
struct vblk *v = list_entry (item, struct vblk, list);
if ((v->vblk.part.disk_id == vb->vblk.part.disk_id) &&
(v->vblk.part.start > vb->vblk.part.start)) {
list_add_tail (&vb->list, &v->list);
return true;
}
}
list_add_tail (&vb->list, &ldb->v_part);
break;
}
return true;
}
/**
* ldm_frag_add - Add a VBLK fragment to a list
* @data: Raw fragment to be added to the list
* @size: Size of the raw fragment
* @frags: Linked list of VBLK fragments
*
* Fragmented VBLKs may not be consecutive in the database, so they are placed
* in a list so they can be pieced together later.
*
* Return: 'true' Success, the VBLK was added to the list
* 'false' Error, a problem occurred
*/
static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags)
{
struct frag *f;
struct list_head *item;
int rec, num, group;
BUG_ON (!data || !frags);
if (size < 2 * VBLK_SIZE_HEAD) {
ldm_error("Value of size is to small.");
return false;
}
group = get_unaligned_be32(data + 0x08);
rec = get_unaligned_be16(data + 0x0C);
num = get_unaligned_be16(data + 0x0E);
if ((num < 1) || (num > 4)) {
ldm_error ("A VBLK claims to have %d parts.", num);
return false;
}
if (rec >= num) {
ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num);
return false;
}
list_for_each (item, frags) {
f = list_entry (item, struct frag, list);
if (f->group == group)
goto found;
}
f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL);
if (!f) {
ldm_crit ("Out of memory.");
return false;
}
f->group = group;
f->num = num;
f->rec = rec;
f->map = 0xFF << num;
list_add_tail (&f->list, frags);
found:
if (rec >= f->num) {
ldm_error("REC value (%d) exceeds NUM value (%d)", rec, f->num);
return false;
}
if (f->map & (1 << rec)) {
ldm_error ("Duplicate VBLK, part %d.", rec);
f->map &= 0x7F; /* Mark the group as broken */
return false;
}
f->map |= (1 << rec);
data += VBLK_SIZE_HEAD;
size -= VBLK_SIZE_HEAD;
memcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size);
return true;
}
/**
* ldm_frag_free - Free a linked list of VBLK fragments
* @list: Linked list of fragments
*
* Free a linked list of VBLK fragments
*
* Return: none
*/
static void ldm_frag_free (struct list_head *list)
{
struct list_head *item, *tmp;
BUG_ON (!list);
list_for_each_safe (item, tmp, list)
kfree (list_entry (item, struct frag, list));
}
/**
* ldm_frag_commit - Validate fragmented VBLKs and add them to the database
* @frags: Linked list of VBLK fragments
* @ldb: Cache of the database structures
*
* Now that all the fragmented VBLKs have been collected, they must be added to
* the database for later use.
*
* Return: 'true' All the fragments we added successfully
* 'false' One or more of the fragments we invalid
*/
static bool ldm_frag_commit (struct list_head *frags, struct ldmdb *ldb)
{
struct frag *f;
struct list_head *item;
BUG_ON (!frags || !ldb);
list_for_each (item, frags) {
f = list_entry (item, struct frag, list);
if (f->map != 0xFF) {
ldm_error ("VBLK group %d is incomplete (0x%02x).",
f->group, f->map);
return false;
}
if (!ldm_ldmdb_add (f->data, f->num*ldb->vm.vblk_size, ldb))
return false; /* Already logged */
}
return true;
}
/**
* ldm_get_vblks - Read the on-disk database of VBLKs into memory
* @state: Partition check state including device holding the LDM Database
* @base: Offset, into @state->bdev, of the database
* @ldb: Cache of the database structures
*
* To use the information from the VBLKs, they need to be read from the disk,
* unpacked and validated. We cache them in @ldb according to their type.
*
* Return: 'true' All the VBLKs were read successfully
* 'false' An error occurred
*/
static bool ldm_get_vblks(struct parsed_partitions *state, unsigned long base,
struct ldmdb *ldb)
{
int size, perbuf, skip, finish, s, v, recs;
u8 *data = NULL;
Sector sect;
bool result = false;
LIST_HEAD (frags);
BUG_ON(!state || !ldb);
size = ldb->vm.vblk_size;
perbuf = 512 / size;
skip = ldb->vm.vblk_offset >> 9; /* Bytes to sectors */
finish = (size * ldb->vm.last_vblk_seq) >> 9;
for (s = skip; s < finish; s++) { /* For each sector */
data = read_part_sector(state, base + OFF_VMDB + s, §);
if (!data) {
ldm_crit ("Disk read failed.");
goto out;
}
for (v = 0; v < perbuf; v++, data+=size) { /* For each vblk */
if (MAGIC_VBLK != get_unaligned_be32(data)) {
ldm_error ("Expected to find a VBLK.");
goto out;
}
recs = get_unaligned_be16(data + 0x0E); /* Number of records */
if (recs == 1) {
if (!ldm_ldmdb_add (data, size, ldb))
goto out; /* Already logged */
} else if (recs > 1) {
if (!ldm_frag_add (data, size, &frags))
goto out; /* Already logged */
}
/* else Record is not in use, ignore it. */
}
put_dev_sector (sect);
data = NULL;
}
result = ldm_frag_commit (&frags, ldb); /* Failures, already logged */
out:
if (data)
put_dev_sector (sect);
ldm_frag_free (&frags);
return result;
}
/**
* ldm_free_vblks - Free a linked list of vblk's
* @lh: Head of a linked list of struct vblk
*
* Free a list of vblk's and free the memory used to maintain the list.
*
* Return: none
*/
static void ldm_free_vblks (struct list_head *lh)
{
struct list_head *item, *tmp;
BUG_ON (!lh);
list_for_each_safe (item, tmp, lh)
kfree (list_entry (item, struct vblk, list));
}
/**
* ldm_partition - Find out whether a device is a dynamic disk and handle it
* @state: Partition check state including device holding the LDM Database
*
* This determines whether the device @bdev is a dynamic disk and if so creates
* the partitions necessary in the gendisk structure pointed to by @hd.
*
* We create a dummy device 1, which contains the LDM database, and then create
* each partition described by the LDM database in sequence as devices 2+. For
* example, if the device is hda, we would have: hda1: LDM database, hda2, hda3,
* and so on: the actual data containing partitions.
*
* Return: 1 Success, @state->bdev is a dynamic disk and we handled it
* 0 Success, @state->bdev is not a dynamic disk
* -1 An error occurred before enough information had been read
* Or @state->bdev is a dynamic disk, but it may be corrupted
*/
int ldm_partition(struct parsed_partitions *state)
{
struct ldmdb *ldb;
unsigned long base;
int result = -1;
BUG_ON(!state);
/* Look for signs of a Dynamic Disk */
if (!ldm_validate_partition_table(state))
return 0;
ldb = kmalloc (sizeof (*ldb), GFP_KERNEL);
if (!ldb) {
ldm_crit ("Out of memory.");
goto out;
}
/* Parse and check privheads. */
if (!ldm_validate_privheads(state, &ldb->ph))
goto out; /* Already logged */
/* All further references are relative to base (database start). */
base = ldb->ph.config_start;
/* Parse and check tocs and vmdb. */
if (!ldm_validate_tocblocks(state, base, ldb) ||
!ldm_validate_vmdb(state, base, ldb))
goto out; /* Already logged */
/* Initialize vblk lists in ldmdb struct */
INIT_LIST_HEAD (&ldb->v_dgrp);
INIT_LIST_HEAD (&ldb->v_disk);
INIT_LIST_HEAD (&ldb->v_volu);
INIT_LIST_HEAD (&ldb->v_comp);
INIT_LIST_HEAD (&ldb->v_part);
if (!ldm_get_vblks(state, base, ldb)) {
ldm_crit ("Failed to read the VBLKs from the database.");
goto cleanup;
}
/* Finally, create the data partition devices. */
if (ldm_create_data_partitions(state, ldb)) {
ldm_debug ("Parsed LDM database successfully.");
result = 1;
}
/* else Already logged */
cleanup:
ldm_free_vblks (&ldb->v_dgrp);
ldm_free_vblks (&ldb->v_disk);
ldm_free_vblks (&ldb->v_volu);
ldm_free_vblks (&ldb->v_comp);
ldm_free_vblks (&ldb->v_part);
out:
kfree (ldb);
return result;
}
| gpl-2.0 |
RobinSystems/linux-3.13 | fs/lockd/clnt4xdr.c | 2776 | 13424 | /*
* linux/fs/lockd/clnt4xdr.c
*
* XDR functions to encode/decode NLM version 4 RPC arguments and results.
*
* NLM client-side only.
*
* Copyright (C) 2010, Oracle. All rights reserved.
*/
#include <linux/types.h>
#include <linux/sunrpc/xdr.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/stats.h>
#include <linux/lockd/lockd.h>
#define NLMDBG_FACILITY NLMDBG_XDR
#if (NLMCLNT_OHSIZE > XDR_MAX_NETOBJ)
# error "NLM host name cannot be larger than XDR_MAX_NETOBJ!"
#endif
#if (NLMCLNT_OHSIZE > NLM_MAXSTRLEN)
# error "NLM host name cannot be larger than NLM's maximum string length!"
#endif
/*
* Declare the space requirements for NLM arguments and replies as
* number of 32bit-words
*/
#define NLM4_void_sz (0)
#define NLM4_cookie_sz (1+(NLM_MAXCOOKIELEN>>2))
#define NLM4_caller_sz (1+(NLMCLNT_OHSIZE>>2))
#define NLM4_owner_sz (1+(NLMCLNT_OHSIZE>>2))
#define NLM4_fhandle_sz (1+(NFS3_FHSIZE>>2))
#define NLM4_lock_sz (5+NLM4_caller_sz+NLM4_owner_sz+NLM4_fhandle_sz)
#define NLM4_holder_sz (6+NLM4_owner_sz)
#define NLM4_testargs_sz (NLM4_cookie_sz+1+NLM4_lock_sz)
#define NLM4_lockargs_sz (NLM4_cookie_sz+4+NLM4_lock_sz)
#define NLM4_cancargs_sz (NLM4_cookie_sz+2+NLM4_lock_sz)
#define NLM4_unlockargs_sz (NLM4_cookie_sz+NLM4_lock_sz)
#define NLM4_testres_sz (NLM4_cookie_sz+1+NLM4_holder_sz)
#define NLM4_res_sz (NLM4_cookie_sz+1)
#define NLM4_norep_sz (0)
static s64 loff_t_to_s64(loff_t offset)
{
s64 res;
if (offset >= NLM4_OFFSET_MAX)
res = NLM4_OFFSET_MAX;
else if (offset <= -NLM4_OFFSET_MAX)
res = -NLM4_OFFSET_MAX;
else
res = offset;
return res;
}
static void nlm4_compute_offsets(const struct nlm_lock *lock,
u64 *l_offset, u64 *l_len)
{
const struct file_lock *fl = &lock->fl;
*l_offset = loff_t_to_s64(fl->fl_start);
if (fl->fl_end == OFFSET_MAX)
*l_len = 0;
else
*l_len = loff_t_to_s64(fl->fl_end - fl->fl_start + 1);
}
/*
* Handle decode buffer overflows out-of-line.
*/
static void print_overflow_msg(const char *func, const struct xdr_stream *xdr)
{
dprintk("lockd: %s prematurely hit the end of our receive buffer. "
"Remaining buffer length is %tu words.\n",
func, xdr->end - xdr->p);
}
/*
* Encode/decode NLMv4 basic data types
*
* Basic NLMv4 data types are defined in Appendix II, section 6.1.4
* of RFC 1813: "NFS Version 3 Protocol Specification" and in Chapter
* 10 of X/Open's "Protocols for Interworking: XNFS, Version 3W".
*
* Not all basic data types have their own encoding and decoding
* functions. For run-time efficiency, some data types are encoded
* or decoded inline.
*/
static void encode_bool(struct xdr_stream *xdr, const int value)
{
__be32 *p;
p = xdr_reserve_space(xdr, 4);
*p = value ? xdr_one : xdr_zero;
}
static void encode_int32(struct xdr_stream *xdr, const s32 value)
{
__be32 *p;
p = xdr_reserve_space(xdr, 4);
*p = cpu_to_be32(value);
}
/*
* typedef opaque netobj<MAXNETOBJ_SZ>
*/
static void encode_netobj(struct xdr_stream *xdr,
const u8 *data, const unsigned int length)
{
__be32 *p;
p = xdr_reserve_space(xdr, 4 + length);
xdr_encode_opaque(p, data, length);
}
static int decode_netobj(struct xdr_stream *xdr,
struct xdr_netobj *obj)
{
u32 length;
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(p == NULL))
goto out_overflow;
length = be32_to_cpup(p++);
if (unlikely(length > XDR_MAX_NETOBJ))
goto out_size;
obj->len = length;
obj->data = (u8 *)p;
return 0;
out_size:
dprintk("NFS: returned netobj was too long: %u\n", length);
return -EIO;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
/*
* netobj cookie;
*/
static void encode_cookie(struct xdr_stream *xdr,
const struct nlm_cookie *cookie)
{
encode_netobj(xdr, (u8 *)&cookie->data, cookie->len);
}
static int decode_cookie(struct xdr_stream *xdr,
struct nlm_cookie *cookie)
{
u32 length;
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(p == NULL))
goto out_overflow;
length = be32_to_cpup(p++);
/* apparently HPUX can return empty cookies */
if (length == 0)
goto out_hpux;
if (length > NLM_MAXCOOKIELEN)
goto out_size;
p = xdr_inline_decode(xdr, length);
if (unlikely(p == NULL))
goto out_overflow;
cookie->len = length;
memcpy(cookie->data, p, length);
return 0;
out_hpux:
cookie->len = 4;
memset(cookie->data, 0, 4);
return 0;
out_size:
dprintk("NFS: returned cookie was too long: %u\n", length);
return -EIO;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
/*
* netobj fh;
*/
static void encode_fh(struct xdr_stream *xdr, const struct nfs_fh *fh)
{
encode_netobj(xdr, (u8 *)&fh->data, fh->size);
}
/*
* enum nlm4_stats {
* NLM4_GRANTED = 0,
* NLM4_DENIED = 1,
* NLM4_DENIED_NOLOCKS = 2,
* NLM4_BLOCKED = 3,
* NLM4_DENIED_GRACE_PERIOD = 4,
* NLM4_DEADLCK = 5,
* NLM4_ROFS = 6,
* NLM4_STALE_FH = 7,
* NLM4_FBIG = 8,
* NLM4_FAILED = 9
* };
*
* struct nlm4_stat {
* nlm4_stats stat;
* };
*
* NB: we don't swap bytes for the NLM status values. The upper
* layers deal directly with the status value in network byte
* order.
*/
static void encode_nlm4_stat(struct xdr_stream *xdr,
const __be32 stat)
{
__be32 *p;
BUG_ON(be32_to_cpu(stat) > NLM_FAILED);
p = xdr_reserve_space(xdr, 4);
*p = stat;
}
static int decode_nlm4_stat(struct xdr_stream *xdr, __be32 *stat)
{
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(p == NULL))
goto out_overflow;
if (unlikely(ntohl(*p) > ntohl(nlm4_failed)))
goto out_bad_xdr;
*stat = *p;
return 0;
out_bad_xdr:
dprintk("%s: server returned invalid nlm4_stats value: %u\n",
__func__, be32_to_cpup(p));
return -EIO;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
/*
* struct nlm4_holder {
* bool exclusive;
* int32 svid;
* netobj oh;
* uint64 l_offset;
* uint64 l_len;
* };
*/
static void encode_nlm4_holder(struct xdr_stream *xdr,
const struct nlm_res *result)
{
const struct nlm_lock *lock = &result->lock;
u64 l_offset, l_len;
__be32 *p;
encode_bool(xdr, lock->fl.fl_type == F_RDLCK);
encode_int32(xdr, lock->svid);
encode_netobj(xdr, lock->oh.data, lock->oh.len);
p = xdr_reserve_space(xdr, 4 + 4);
nlm4_compute_offsets(lock, &l_offset, &l_len);
p = xdr_encode_hyper(p, l_offset);
xdr_encode_hyper(p, l_len);
}
static int decode_nlm4_holder(struct xdr_stream *xdr, struct nlm_res *result)
{
struct nlm_lock *lock = &result->lock;
struct file_lock *fl = &lock->fl;
u64 l_offset, l_len;
u32 exclusive;
int error;
__be32 *p;
s32 end;
memset(lock, 0, sizeof(*lock));
locks_init_lock(fl);
p = xdr_inline_decode(xdr, 4 + 4);
if (unlikely(p == NULL))
goto out_overflow;
exclusive = be32_to_cpup(p++);
lock->svid = be32_to_cpup(p);
fl->fl_pid = (pid_t)lock->svid;
error = decode_netobj(xdr, &lock->oh);
if (unlikely(error))
goto out;
p = xdr_inline_decode(xdr, 8 + 8);
if (unlikely(p == NULL))
goto out_overflow;
fl->fl_flags = FL_POSIX;
fl->fl_type = exclusive != 0 ? F_WRLCK : F_RDLCK;
p = xdr_decode_hyper(p, &l_offset);
xdr_decode_hyper(p, &l_len);
end = l_offset + l_len - 1;
fl->fl_start = (loff_t)l_offset;
if (l_len == 0 || end < 0)
fl->fl_end = OFFSET_MAX;
else
fl->fl_end = (loff_t)end;
error = 0;
out:
return error;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
/*
* string caller_name<LM_MAXSTRLEN>;
*/
static void encode_caller_name(struct xdr_stream *xdr, const char *name)
{
/* NB: client-side does not set lock->len */
u32 length = strlen(name);
__be32 *p;
p = xdr_reserve_space(xdr, 4 + length);
xdr_encode_opaque(p, name, length);
}
/*
* struct nlm4_lock {
* string caller_name<LM_MAXSTRLEN>;
* netobj fh;
* netobj oh;
* int32 svid;
* uint64 l_offset;
* uint64 l_len;
* };
*/
static void encode_nlm4_lock(struct xdr_stream *xdr,
const struct nlm_lock *lock)
{
u64 l_offset, l_len;
__be32 *p;
encode_caller_name(xdr, lock->caller);
encode_fh(xdr, &lock->fh);
encode_netobj(xdr, lock->oh.data, lock->oh.len);
p = xdr_reserve_space(xdr, 4 + 8 + 8);
*p++ = cpu_to_be32(lock->svid);
nlm4_compute_offsets(lock, &l_offset, &l_len);
p = xdr_encode_hyper(p, l_offset);
xdr_encode_hyper(p, l_len);
}
/*
* NLMv4 XDR encode functions
*
* NLMv4 argument types are defined in Appendix II of RFC 1813:
* "NFS Version 3 Protocol Specification" and Chapter 10 of X/Open's
* "Protocols for Interworking: XNFS, Version 3W".
*/
/*
* struct nlm4_testargs {
* netobj cookie;
* bool exclusive;
* struct nlm4_lock alock;
* };
*/
static void nlm4_xdr_enc_testargs(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nlm_args *args)
{
const struct nlm_lock *lock = &args->lock;
encode_cookie(xdr, &args->cookie);
encode_bool(xdr, lock->fl.fl_type == F_WRLCK);
encode_nlm4_lock(xdr, lock);
}
/*
* struct nlm4_lockargs {
* netobj cookie;
* bool block;
* bool exclusive;
* struct nlm4_lock alock;
* bool reclaim;
* int state;
* };
*/
static void nlm4_xdr_enc_lockargs(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nlm_args *args)
{
const struct nlm_lock *lock = &args->lock;
encode_cookie(xdr, &args->cookie);
encode_bool(xdr, args->block);
encode_bool(xdr, lock->fl.fl_type == F_WRLCK);
encode_nlm4_lock(xdr, lock);
encode_bool(xdr, args->reclaim);
encode_int32(xdr, args->state);
}
/*
* struct nlm4_cancargs {
* netobj cookie;
* bool block;
* bool exclusive;
* struct nlm4_lock alock;
* };
*/
static void nlm4_xdr_enc_cancargs(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nlm_args *args)
{
const struct nlm_lock *lock = &args->lock;
encode_cookie(xdr, &args->cookie);
encode_bool(xdr, args->block);
encode_bool(xdr, lock->fl.fl_type == F_WRLCK);
encode_nlm4_lock(xdr, lock);
}
/*
* struct nlm4_unlockargs {
* netobj cookie;
* struct nlm4_lock alock;
* };
*/
static void nlm4_xdr_enc_unlockargs(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nlm_args *args)
{
const struct nlm_lock *lock = &args->lock;
encode_cookie(xdr, &args->cookie);
encode_nlm4_lock(xdr, lock);
}
/*
* struct nlm4_res {
* netobj cookie;
* nlm4_stat stat;
* };
*/
static void nlm4_xdr_enc_res(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nlm_res *result)
{
encode_cookie(xdr, &result->cookie);
encode_nlm4_stat(xdr, result->status);
}
/*
* union nlm4_testrply switch (nlm4_stats stat) {
* case NLM4_DENIED:
* struct nlm4_holder holder;
* default:
* void;
* };
*
* struct nlm4_testres {
* netobj cookie;
* nlm4_testrply test_stat;
* };
*/
static void nlm4_xdr_enc_testres(struct rpc_rqst *req,
struct xdr_stream *xdr,
const struct nlm_res *result)
{
encode_cookie(xdr, &result->cookie);
encode_nlm4_stat(xdr, result->status);
if (result->status == nlm_lck_denied)
encode_nlm4_holder(xdr, result);
}
/*
* NLMv4 XDR decode functions
*
* NLMv4 argument types are defined in Appendix II of RFC 1813:
* "NFS Version 3 Protocol Specification" and Chapter 10 of X/Open's
* "Protocols for Interworking: XNFS, Version 3W".
*/
/*
* union nlm4_testrply switch (nlm4_stats stat) {
* case NLM4_DENIED:
* struct nlm4_holder holder;
* default:
* void;
* };
*
* struct nlm4_testres {
* netobj cookie;
* nlm4_testrply test_stat;
* };
*/
static int decode_nlm4_testrply(struct xdr_stream *xdr,
struct nlm_res *result)
{
int error;
error = decode_nlm4_stat(xdr, &result->status);
if (unlikely(error))
goto out;
if (result->status == nlm_lck_denied)
error = decode_nlm4_holder(xdr, result);
out:
return error;
}
static int nlm4_xdr_dec_testres(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nlm_res *result)
{
int error;
error = decode_cookie(xdr, &result->cookie);
if (unlikely(error))
goto out;
error = decode_nlm4_testrply(xdr, result);
out:
return error;
}
/*
* struct nlm4_res {
* netobj cookie;
* nlm4_stat stat;
* };
*/
static int nlm4_xdr_dec_res(struct rpc_rqst *req,
struct xdr_stream *xdr,
struct nlm_res *result)
{
int error;
error = decode_cookie(xdr, &result->cookie);
if (unlikely(error))
goto out;
error = decode_nlm4_stat(xdr, &result->status);
out:
return error;
}
/*
* For NLM, a void procedure really returns nothing
*/
#define nlm4_xdr_dec_norep NULL
#define PROC(proc, argtype, restype) \
[NLMPROC_##proc] = { \
.p_proc = NLMPROC_##proc, \
.p_encode = (kxdreproc_t)nlm4_xdr_enc_##argtype, \
.p_decode = (kxdrdproc_t)nlm4_xdr_dec_##restype, \
.p_arglen = NLM4_##argtype##_sz, \
.p_replen = NLM4_##restype##_sz, \
.p_statidx = NLMPROC_##proc, \
.p_name = #proc, \
}
static struct rpc_procinfo nlm4_procedures[] = {
PROC(TEST, testargs, testres),
PROC(LOCK, lockargs, res),
PROC(CANCEL, cancargs, res),
PROC(UNLOCK, unlockargs, res),
PROC(GRANTED, testargs, res),
PROC(TEST_MSG, testargs, norep),
PROC(LOCK_MSG, lockargs, norep),
PROC(CANCEL_MSG, cancargs, norep),
PROC(UNLOCK_MSG, unlockargs, norep),
PROC(GRANTED_MSG, testargs, norep),
PROC(TEST_RES, testres, norep),
PROC(LOCK_RES, res, norep),
PROC(CANCEL_RES, res, norep),
PROC(UNLOCK_RES, res, norep),
PROC(GRANTED_RES, res, norep),
};
const struct rpc_version nlm_version4 = {
.number = 4,
.nrprocs = ARRAY_SIZE(nlm4_procedures),
.procs = nlm4_procedures,
};
| gpl-2.0 |
friedrich420/N4-AEL-KERNEL-LOLLIPOP | sound/oss/opl3.c | 2776 | 27752 | /*
* sound/oss/opl3.c
*
* A low level driver for Yamaha YM3812 and OPL-3 -chips
*
*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*
*
* Changes
* Thomas Sailer ioctl code reworked (vmalloc/vfree removed)
* Alan Cox modularisation, fixed sound_mem allocs.
* Christoph Hellwig Adapted to module_init/module_exit
* Arnaldo C. de Melo get rid of check_region, use request_region for
* OPL4, release it on exit, some cleanups.
*
* Status
* Believed to work. Badly needs rewriting a bit to support multiple
* OPL3 devices.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/delay.h>
/*
* Major improvements to the FM handling 30AUG92 by Rob Hooft,
* hooft@chem.ruu.nl
*/
#include "sound_config.h"
#include "opl3_hw.h"
#define MAX_VOICE 18
#define OFFS_4OP 11
struct voice_info
{
unsigned char keyon_byte;
long bender;
long bender_range;
unsigned long orig_freq;
unsigned long current_freq;
int volume;
int mode;
int panning; /* 0xffff means not set */
};
typedef struct opl_devinfo
{
int base;
int left_io, right_io;
int nr_voice;
int lv_map[MAX_VOICE];
struct voice_info voc[MAX_VOICE];
struct voice_alloc_info *v_alloc;
struct channel_info *chn_info;
struct sbi_instrument i_map[SBFM_MAXINSTR];
struct sbi_instrument *act_i[MAX_VOICE];
struct synth_info fm_info;
int busy;
int model;
unsigned char cmask;
int is_opl4;
} opl_devinfo;
static struct opl_devinfo *devc = NULL;
static int detected_model;
static int store_instr(int instr_no, struct sbi_instrument *instr);
static void freq_to_fnum(int freq, int *block, int *fnum);
static void opl3_command(int io_addr, unsigned int addr, unsigned int val);
static int opl3_kill_note(int dev, int voice, int note, int velocity);
static void enter_4op_mode(void)
{
int i;
static int v4op[MAX_VOICE] = {
0, 1, 2, 9, 10, 11, 6, 7, 8, 15, 16, 17
};
devc->cmask = 0x3f; /* Connect all possible 4 OP voice operators */
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, 0x3f);
for (i = 0; i < 3; i++)
pv_map[i].voice_mode = 4;
for (i = 3; i < 6; i++)
pv_map[i].voice_mode = 0;
for (i = 9; i < 12; i++)
pv_map[i].voice_mode = 4;
for (i = 12; i < 15; i++)
pv_map[i].voice_mode = 0;
for (i = 0; i < 12; i++)
devc->lv_map[i] = v4op[i];
devc->v_alloc->max_voice = devc->nr_voice = 12;
}
static int opl3_ioctl(int dev, unsigned int cmd, void __user * arg)
{
struct sbi_instrument ins;
switch (cmd) {
case SNDCTL_FM_LOAD_INSTR:
printk(KERN_WARNING "Warning: Obsolete ioctl(SNDCTL_FM_LOAD_INSTR) used. Fix the program.\n");
if (copy_from_user(&ins, arg, sizeof(ins)))
return -EFAULT;
if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) {
printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel);
return -EINVAL;
}
return store_instr(ins.channel, &ins);
case SNDCTL_SYNTH_INFO:
devc->fm_info.nr_voices = (devc->nr_voice == 12) ? 6 : devc->nr_voice;
if (copy_to_user(arg, &devc->fm_info, sizeof(devc->fm_info)))
return -EFAULT;
return 0;
case SNDCTL_SYNTH_MEMAVL:
return 0x7fffffff;
case SNDCTL_FM_4OP_ENABLE:
if (devc->model == 2)
enter_4op_mode();
return 0;
default:
return -EINVAL;
}
}
static int opl3_detect(int ioaddr)
{
/*
* This function returns 1 if the FM chip is present at the given I/O port
* The detection algorithm plays with the timer built in the FM chip and
* looks for a change in the status register.
*
* Note! The timers of the FM chip are not connected to AdLib (and compatible)
* boards.
*
* Note2! The chip is initialized if detected.
*/
unsigned char stat1, signature;
int i;
if (devc != NULL)
{
printk(KERN_ERR "opl3: Only one OPL3 supported.\n");
return 0;
}
devc = kzalloc(sizeof(*devc), GFP_KERNEL);
if (devc == NULL)
{
printk(KERN_ERR "opl3: Can't allocate memory for the device control "
"structure \n ");
return 0;
}
strcpy(devc->fm_info.name, "OPL2");
if (!request_region(ioaddr, 4, devc->fm_info.name)) {
printk(KERN_WARNING "opl3: I/O port 0x%x already in use\n", ioaddr);
goto cleanup_devc;
}
devc->base = ioaddr;
/* Reset timers 1 and 2 */
opl3_command(ioaddr, TIMER_CONTROL_REGISTER, TIMER1_MASK | TIMER2_MASK);
/* Reset the IRQ of the FM chip */
opl3_command(ioaddr, TIMER_CONTROL_REGISTER, IRQ_RESET);
signature = stat1 = inb(ioaddr); /* Status register */
if (signature != 0x00 && signature != 0x06 && signature != 0x02 &&
signature != 0x0f)
{
MDB(printk(KERN_INFO "OPL3 not detected %x\n", signature));
goto cleanup_region;
}
if (signature == 0x06) /* OPL2 */
{
detected_model = 2;
}
else if (signature == 0x00 || signature == 0x0f) /* OPL3 or OPL4 */
{
unsigned char tmp;
detected_model = 3;
/*
* Detect availability of OPL4 (_experimental_). Works probably
* only after a cold boot. In addition the OPL4 port
* of the chip may not be connected to the PC bus at all.
*/
opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, 0x00);
opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, OPL3_ENABLE | OPL4_ENABLE);
if ((tmp = inb(ioaddr)) == 0x02) /* Have a OPL4 */
{
detected_model = 4;
}
if (request_region(ioaddr - 8, 2, "OPL4")) /* OPL4 port was free */
{
int tmp;
outb((0x02), ioaddr - 8); /* Select OPL4 ID register */
udelay(10);
tmp = inb(ioaddr - 7); /* Read it */
udelay(10);
if (tmp == 0x20) /* OPL4 should return 0x20 here */
{
detected_model = 4;
outb((0xF8), ioaddr - 8); /* Select OPL4 FM mixer control */
udelay(10);
outb((0x1B), ioaddr - 7); /* Write value */
udelay(10);
}
else
{ /* release OPL4 port */
release_region(ioaddr - 8, 2);
detected_model = 3;
}
}
opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, 0);
}
for (i = 0; i < 9; i++)
opl3_command(ioaddr, KEYON_BLOCK + i, 0); /*
* Note off
*/
opl3_command(ioaddr, TEST_REGISTER, ENABLE_WAVE_SELECT);
opl3_command(ioaddr, PERCOSSION_REGISTER, 0x00); /*
* Melodic mode.
*/
return 1;
cleanup_region:
release_region(ioaddr, 4);
cleanup_devc:
kfree(devc);
devc = NULL;
return 0;
}
static int opl3_kill_note (int devno, int voice, int note, int velocity)
{
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return 0;
devc->v_alloc->map[voice] = 0;
map = &pv_map[devc->lv_map[voice]];
DEB(printk("Kill note %d\n", voice));
if (map->voice_mode == 0)
return 0;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, devc->voc[voice].keyon_byte & ~0x20);
devc->voc[voice].keyon_byte = 0;
devc->voc[voice].bender = 0;
devc->voc[voice].volume = 64;
devc->voc[voice].panning = 0xffff; /* Not set */
devc->voc[voice].bender_range = 200;
devc->voc[voice].orig_freq = 0;
devc->voc[voice].current_freq = 0;
devc->voc[voice].mode = 0;
return 0;
}
#define HIHAT 0
#define CYMBAL 1
#define TOMTOM 2
#define SNARE 3
#define BDRUM 4
#define UNDEFINED TOMTOM
#define DEFAULT TOMTOM
static int store_instr(int instr_no, struct sbi_instrument *instr)
{
if (instr->key != FM_PATCH && (instr->key != OPL3_PATCH || devc->model != 2))
printk(KERN_WARNING "FM warning: Invalid patch format field (key) 0x%x\n", instr->key);
memcpy((char *) &(devc->i_map[instr_no]), (char *) instr, sizeof(*instr));
return 0;
}
static int opl3_set_instr (int dev, int voice, int instr_no)
{
if (voice < 0 || voice >= devc->nr_voice)
return 0;
if (instr_no < 0 || instr_no >= SBFM_MAXINSTR)
instr_no = 0; /* Acoustic piano (usually) */
devc->act_i[voice] = &devc->i_map[instr_no];
return 0;
}
/*
* The next table looks magical, but it certainly is not. Its values have
* been calculated as table[i]=8*log(i/64)/log(2) with an obvious exception
* for i=0. This log-table converts a linear volume-scaling (0..127) to a
* logarithmic scaling as present in the FM-synthesizer chips. so : Volume
* 64 = 0 db = relative volume 0 and: Volume 32 = -6 db = relative
* volume -8 it was implemented as a table because it is only 128 bytes and
* it saves a lot of log() calculations. (RH)
*/
static char fm_volume_table[128] =
{
-64, -48, -40, -35, -32, -29, -27, -26,
-24, -23, -21, -20, -19, -18, -18, -17,
-16, -15, -15, -14, -13, -13, -12, -12,
-11, -11, -10, -10, -10, -9, -9, -8,
-8, -8, -7, -7, -7, -6, -6, -6,
-5, -5, -5, -5, -4, -4, -4, -4,
-3, -3, -3, -3, -2, -2, -2, -2,
-2, -1, -1, -1, -1, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1,
1, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 4,
4, 4, 4, 4, 4, 4, 4, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6,
6, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 8, 8, 8, 8, 8
};
static void calc_vol(unsigned char *regbyte, int volume, int main_vol)
{
int level = (~*regbyte & 0x3f);
if (main_vol > 127)
main_vol = 127;
volume = (volume * main_vol) / 127;
if (level)
level += fm_volume_table[volume];
if (level > 0x3f)
level = 0x3f;
if (level < 0)
level = 0;
*regbyte = (*regbyte & 0xc0) | (~level & 0x3f);
}
static void set_voice_volume(int voice, int volume, int main_vol)
{
unsigned char vol1, vol2, vol3, vol4;
struct sbi_instrument *instr;
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return;
map = &pv_map[devc->lv_map[voice]];
instr = devc->act_i[voice];
if (!instr)
instr = &devc->i_map[0];
if (instr->channel < 0)
return;
if (devc->voc[voice].mode == 0)
return;
if (devc->voc[voice].mode == 2)
{
vol1 = instr->operators[2];
vol2 = instr->operators[3];
if ((instr->operators[10] & 0x01))
{
calc_vol(&vol1, volume, main_vol);
calc_vol(&vol2, volume, main_vol);
}
else
{
calc_vol(&vol2, volume, main_vol);
}
opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], vol1);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], vol2);
}
else
{ /*
* 4 OP voice
*/
int connection;
vol1 = instr->operators[2];
vol2 = instr->operators[3];
vol3 = instr->operators[OFFS_4OP + 2];
vol4 = instr->operators[OFFS_4OP + 3];
/*
* The connection method for 4 OP devc->voc is defined by the rightmost
* bits at the offsets 10 and 10+OFFS_4OP
*/
connection = ((instr->operators[10] & 0x01) << 1) | (instr->operators[10 + OFFS_4OP] & 0x01);
switch (connection)
{
case 0:
calc_vol(&vol4, volume, main_vol);
break;
case 1:
calc_vol(&vol2, volume, main_vol);
calc_vol(&vol4, volume, main_vol);
break;
case 2:
calc_vol(&vol1, volume, main_vol);
calc_vol(&vol4, volume, main_vol);
break;
case 3:
calc_vol(&vol1, volume, main_vol);
calc_vol(&vol3, volume, main_vol);
calc_vol(&vol4, volume, main_vol);
break;
default:
;
}
opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], vol1);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], vol2);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[2], vol3);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[3], vol4);
}
}
static int opl3_start_note (int dev, int voice, int note, int volume)
{
unsigned char data, fpc;
int block, fnum, freq, voice_mode, pan;
struct sbi_instrument *instr;
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return 0;
map = &pv_map[devc->lv_map[voice]];
pan = devc->voc[voice].panning;
if (map->voice_mode == 0)
return 0;
if (note == 255) /*
* Just change the volume
*/
{
set_voice_volume(voice, volume, devc->voc[voice].volume);
return 0;
}
/*
* Kill previous note before playing
*/
opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], 0xff); /*
* Carrier
* volume to
* min
*/
opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], 0xff); /*
* Modulator
* volume to
*/
if (map->voice_mode == 4)
{
opl3_command(map->ioaddr, KSL_LEVEL + map->op[2], 0xff);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[3], 0xff);
}
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, 0x00); /*
* Note
* off
*/
instr = devc->act_i[voice];
if (!instr)
instr = &devc->i_map[0];
if (instr->channel < 0)
{
printk(KERN_WARNING "opl3: Initializing voice %d with undefined instrument\n", voice);
return 0;
}
if (map->voice_mode == 2 && instr->key == OPL3_PATCH)
return 0; /*
* Cannot play
*/
voice_mode = map->voice_mode;
if (voice_mode == 4)
{
int voice_shift;
voice_shift = (map->ioaddr == devc->left_io) ? 0 : 3;
voice_shift += map->voice_num;
if (instr->key != OPL3_PATCH) /*
* Just 2 OP patch
*/
{
voice_mode = 2;
devc->cmask &= ~(1 << voice_shift);
}
else
{
devc->cmask |= (1 << voice_shift);
}
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, devc->cmask);
}
/*
* Set Sound Characteristics
*/
opl3_command(map->ioaddr, AM_VIB + map->op[0], instr->operators[0]);
opl3_command(map->ioaddr, AM_VIB + map->op[1], instr->operators[1]);
/*
* Set Attack/Decay
*/
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[0], instr->operators[4]);
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[1], instr->operators[5]);
/*
* Set Sustain/Release
*/
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[0], instr->operators[6]);
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[1], instr->operators[7]);
/*
* Set Wave Select
*/
opl3_command(map->ioaddr, WAVE_SELECT + map->op[0], instr->operators[8]);
opl3_command(map->ioaddr, WAVE_SELECT + map->op[1], instr->operators[9]);
/*
* Set Feedback/Connection
*/
fpc = instr->operators[10];
if (pan != 0xffff)
{
fpc &= ~STEREO_BITS;
if (pan < -64)
fpc |= VOICE_TO_LEFT;
else
if (pan > 64)
fpc |= VOICE_TO_RIGHT;
else
fpc |= (VOICE_TO_LEFT | VOICE_TO_RIGHT);
}
if (!(fpc & 0x30))
fpc |= 0x30; /*
* Ensure that at least one chn is enabled
*/
opl3_command(map->ioaddr, FEEDBACK_CONNECTION + map->voice_num, fpc);
/*
* If the voice is a 4 OP one, initialize the operators 3 and 4 also
*/
if (voice_mode == 4)
{
/*
* Set Sound Characteristics
*/
opl3_command(map->ioaddr, AM_VIB + map->op[2], instr->operators[OFFS_4OP + 0]);
opl3_command(map->ioaddr, AM_VIB + map->op[3], instr->operators[OFFS_4OP + 1]);
/*
* Set Attack/Decay
*/
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[2], instr->operators[OFFS_4OP + 4]);
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[3], instr->operators[OFFS_4OP + 5]);
/*
* Set Sustain/Release
*/
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[2], instr->operators[OFFS_4OP + 6]);
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[3], instr->operators[OFFS_4OP + 7]);
/*
* Set Wave Select
*/
opl3_command(map->ioaddr, WAVE_SELECT + map->op[2], instr->operators[OFFS_4OP + 8]);
opl3_command(map->ioaddr, WAVE_SELECT + map->op[3], instr->operators[OFFS_4OP + 9]);
/*
* Set Feedback/Connection
*/
fpc = instr->operators[OFFS_4OP + 10];
if (!(fpc & 0x30))
fpc |= 0x30; /*
* Ensure that at least one chn is enabled
*/
opl3_command(map->ioaddr, FEEDBACK_CONNECTION + map->voice_num + 3, fpc);
}
devc->voc[voice].mode = voice_mode;
set_voice_volume(voice, volume, devc->voc[voice].volume);
freq = devc->voc[voice].orig_freq = note_to_freq(note) / 1000;
/*
* Since the pitch bender may have been set before playing the note, we
* have to calculate the bending now.
*/
freq = compute_finetune(devc->voc[voice].orig_freq, devc->voc[voice].bender, devc->voc[voice].bender_range, 0);
devc->voc[voice].current_freq = freq;
freq_to_fnum(freq, &block, &fnum);
/*
* Play note
*/
data = fnum & 0xff; /*
* Least significant bits of fnumber
*/
opl3_command(map->ioaddr, FNUM_LOW + map->voice_num, data);
data = 0x20 | ((block & 0x7) << 2) | ((fnum >> 8) & 0x3);
devc->voc[voice].keyon_byte = data;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, data);
if (voice_mode == 4)
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num + 3, data);
return 0;
}
static void freq_to_fnum (int freq, int *block, int *fnum)
{
int f, octave;
/*
* Converts the note frequency to block and fnum values for the FM chip
*/
/*
* First try to compute the block -value (octave) where the note belongs
*/
f = freq;
octave = 5;
if (f == 0)
octave = 0;
else if (f < 261)
{
while (f < 261)
{
octave--;
f <<= 1;
}
}
else if (f > 493)
{
while (f > 493)
{
octave++;
f >>= 1;
}
}
if (octave > 7)
octave = 7;
*fnum = freq * (1 << (20 - octave)) / 49716;
*block = octave;
}
static void opl3_command (int io_addr, unsigned int addr, unsigned int val)
{
int i;
/*
* The original 2-OP synth requires a quite long delay after writing to a
* register. The OPL-3 survives with just two INBs
*/
outb(((unsigned char) (addr & 0xff)), io_addr);
if (devc->model != 2)
udelay(10);
else
for (i = 0; i < 2; i++)
inb(io_addr);
outb(((unsigned char) (val & 0xff)), io_addr + 1);
if (devc->model != 2)
udelay(30);
else
for (i = 0; i < 2; i++)
inb(io_addr);
}
static void opl3_reset(int devno)
{
int i;
for (i = 0; i < 18; i++)
devc->lv_map[i] = i;
for (i = 0; i < devc->nr_voice; i++)
{
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[0], 0xff);
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[1], 0xff);
if (pv_map[devc->lv_map[i]].voice_mode == 4)
{
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[2], 0xff);
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[3], 0xff);
}
opl3_kill_note(devno, i, 0, 64);
}
if (devc->model == 2)
{
devc->v_alloc->max_voice = devc->nr_voice = 18;
for (i = 0; i < 18; i++)
pv_map[i].voice_mode = 2;
}
}
static int opl3_open(int dev, int mode)
{
int i;
if (devc->busy)
return -EBUSY;
devc->busy = 1;
devc->v_alloc->max_voice = devc->nr_voice = (devc->model == 2) ? 18 : 9;
devc->v_alloc->timestamp = 0;
for (i = 0; i < 18; i++)
{
devc->v_alloc->map[i] = 0;
devc->v_alloc->alloc_times[i] = 0;
}
devc->cmask = 0x00; /*
* Just 2 OP mode
*/
if (devc->model == 2)
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, devc->cmask);
return 0;
}
static void opl3_close(int dev)
{
devc->busy = 0;
devc->v_alloc->max_voice = devc->nr_voice = (devc->model == 2) ? 18 : 9;
devc->fm_info.nr_drums = 0;
devc->fm_info.perc_mode = 0;
opl3_reset(dev);
}
static void opl3_hw_control(int dev, unsigned char *event)
{
}
static int opl3_load_patch(int dev, int format, const char __user *addr,
int count, int pmgr_flag)
{
struct sbi_instrument ins;
if (count <sizeof(ins))
{
printk(KERN_WARNING "FM Error: Patch record too short\n");
return -EINVAL;
}
if (copy_from_user(&ins, addr, sizeof(ins)))
return -EFAULT;
if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR)
{
printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel);
return -EINVAL;
}
ins.key = format;
return store_instr(ins.channel, &ins);
}
static void opl3_panning(int dev, int voice, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
devc->voc[voice].panning = value;
}
static void opl3_volume_method(int dev, int mode)
{
}
#define SET_VIBRATO(cell) { \
tmp = instr->operators[(cell-1)+(((cell-1)/2)*OFFS_4OP)]; \
if (pressure > 110) \
tmp |= 0x40; /* Vibrato on */ \
opl3_command (map->ioaddr, AM_VIB + map->op[cell-1], tmp);}
static void opl3_aftertouch(int dev, int voice, int pressure)
{
int tmp;
struct sbi_instrument *instr;
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return;
map = &pv_map[devc->lv_map[voice]];
DEB(printk("Aftertouch %d\n", voice));
if (map->voice_mode == 0)
return;
/*
* Adjust the amount of vibrato depending the pressure
*/
instr = devc->act_i[voice];
if (!instr)
instr = &devc->i_map[0];
if (devc->voc[voice].mode == 4)
{
int connection = ((instr->operators[10] & 0x01) << 1) | (instr->operators[10 + OFFS_4OP] & 0x01);
switch (connection)
{
case 0:
SET_VIBRATO(4);
break;
case 1:
SET_VIBRATO(2);
SET_VIBRATO(4);
break;
case 2:
SET_VIBRATO(1);
SET_VIBRATO(4);
break;
case 3:
SET_VIBRATO(1);
SET_VIBRATO(3);
SET_VIBRATO(4);
break;
}
/*
* Not implemented yet
*/
}
else
{
SET_VIBRATO(1);
if ((instr->operators[10] & 0x01)) /*
* Additive synthesis
*/
SET_VIBRATO(2);
}
}
#undef SET_VIBRATO
static void bend_pitch(int dev, int voice, int value)
{
unsigned char data;
int block, fnum, freq;
struct physical_voice_info *map;
map = &pv_map[devc->lv_map[voice]];
if (map->voice_mode == 0)
return;
devc->voc[voice].bender = value;
if (!value)
return;
if (!(devc->voc[voice].keyon_byte & 0x20))
return; /*
* Not keyed on
*/
freq = compute_finetune(devc->voc[voice].orig_freq, devc->voc[voice].bender, devc->voc[voice].bender_range, 0);
devc->voc[voice].current_freq = freq;
freq_to_fnum(freq, &block, &fnum);
data = fnum & 0xff; /*
* Least significant bits of fnumber
*/
opl3_command(map->ioaddr, FNUM_LOW + map->voice_num, data);
data = 0x20 | ((block & 0x7) << 2) | ((fnum >> 8) & 0x3);
devc->voc[voice].keyon_byte = data;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, data);
}
static void opl3_controller (int dev, int voice, int ctrl_num, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
switch (ctrl_num)
{
case CTRL_PITCH_BENDER:
bend_pitch(dev, voice, value);
break;
case CTRL_PITCH_BENDER_RANGE:
devc->voc[voice].bender_range = value;
break;
case CTL_MAIN_VOLUME:
devc->voc[voice].volume = value / 128;
break;
case CTL_PAN:
devc->voc[voice].panning = (value * 2) - 128;
break;
}
}
static void opl3_bender(int dev, int voice, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
bend_pitch(dev, voice, value - 8192);
}
static int opl3_alloc_voice(int dev, int chn, int note, struct voice_alloc_info *alloc)
{
int i, p, best, first, avail, best_time = 0x7fffffff;
struct sbi_instrument *instr;
int is4op;
int instr_no;
if (chn < 0 || chn > 15)
instr_no = 0;
else
instr_no = devc->chn_info[chn].pgm_num;
instr = &devc->i_map[instr_no];
if (instr->channel < 0 || /* Instrument not loaded */
devc->nr_voice != 12) /* Not in 4 OP mode */
is4op = 0;
else if (devc->nr_voice == 12) /* 4 OP mode */
is4op = (instr->key == OPL3_PATCH);
else
is4op = 0;
if (is4op)
{
first = p = 0;
avail = 6;
}
else
{
if (devc->nr_voice == 12) /* 4 OP mode. Use the '2 OP only' operators first */
first = p = 6;
else
first = p = 0;
avail = devc->nr_voice;
}
/*
* Now try to find a free voice
*/
best = first;
for (i = 0; i < avail; i++)
{
if (alloc->map[p] == 0)
{
return p;
}
if (alloc->alloc_times[p] < best_time) /* Find oldest playing note */
{
best_time = alloc->alloc_times[p];
best = p;
}
p = (p + 1) % avail;
}
/*
* Insert some kind of priority mechanism here.
*/
if (best < 0)
best = 0;
if (best > devc->nr_voice)
best -= devc->nr_voice;
return best; /* All devc->voc in use. Select the first one. */
}
static void opl3_setup_voice(int dev, int voice, int chn)
{
struct channel_info *info;
if (voice < 0 || voice >= devc->nr_voice)
return;
if (chn < 0 || chn > 15)
return;
info = &synth_devs[dev]->chn_info[chn];
opl3_set_instr(dev, voice, info->pgm_num);
devc->voc[voice].bender = 0;
devc->voc[voice].bender_range = info->bender_range;
devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];
devc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;
}
static struct synth_operations opl3_operations =
{
.owner = THIS_MODULE,
.id = "OPL",
.info = NULL,
.midi_dev = 0,
.synth_type = SYNTH_TYPE_FM,
.synth_subtype = FM_TYPE_ADLIB,
.open = opl3_open,
.close = opl3_close,
.ioctl = opl3_ioctl,
.kill_note = opl3_kill_note,
.start_note = opl3_start_note,
.set_instr = opl3_set_instr,
.reset = opl3_reset,
.hw_control = opl3_hw_control,
.load_patch = opl3_load_patch,
.aftertouch = opl3_aftertouch,
.controller = opl3_controller,
.panning = opl3_panning,
.volume_method = opl3_volume_method,
.bender = opl3_bender,
.alloc_voice = opl3_alloc_voice,
.setup_voice = opl3_setup_voice
};
static int opl3_init(int ioaddr, struct module *owner)
{
int i;
int me;
if (devc == NULL)
{
printk(KERN_ERR "opl3: Device control structure not initialized.\n");
return -1;
}
if ((me = sound_alloc_synthdev()) == -1)
{
printk(KERN_WARNING "opl3: Too many synthesizers\n");
return -1;
}
devc->nr_voice = 9;
devc->fm_info.device = 0;
devc->fm_info.synth_type = SYNTH_TYPE_FM;
devc->fm_info.synth_subtype = FM_TYPE_ADLIB;
devc->fm_info.perc_mode = 0;
devc->fm_info.nr_voices = 9;
devc->fm_info.nr_drums = 0;
devc->fm_info.instr_bank_size = SBFM_MAXINSTR;
devc->fm_info.capabilities = 0;
devc->left_io = ioaddr;
devc->right_io = ioaddr + 2;
if (detected_model <= 2)
devc->model = 1;
else
{
devc->model = 2;
if (detected_model == 4)
devc->is_opl4 = 1;
}
opl3_operations.info = &devc->fm_info;
synth_devs[me] = &opl3_operations;
if (owner)
synth_devs[me]->owner = owner;
sequencer_init();
devc->v_alloc = &opl3_operations.alloc;
devc->chn_info = &opl3_operations.chn_info[0];
if (devc->model == 2)
{
if (devc->is_opl4)
strcpy(devc->fm_info.name, "Yamaha OPL4/OPL3 FM");
else
strcpy(devc->fm_info.name, "Yamaha OPL3");
devc->v_alloc->max_voice = devc->nr_voice = 18;
devc->fm_info.nr_drums = 0;
devc->fm_info.synth_subtype = FM_TYPE_OPL3;
devc->fm_info.capabilities |= SYNTH_CAP_OPL3;
for (i = 0; i < 18; i++)
{
if (pv_map[i].ioaddr == USE_LEFT)
pv_map[i].ioaddr = devc->left_io;
else
pv_map[i].ioaddr = devc->right_io;
}
opl3_command(devc->right_io, OPL3_MODE_REGISTER, OPL3_ENABLE);
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, 0x00);
}
else
{
strcpy(devc->fm_info.name, "Yamaha OPL2");
devc->v_alloc->max_voice = devc->nr_voice = 9;
devc->fm_info.nr_drums = 0;
for (i = 0; i < 18; i++)
pv_map[i].ioaddr = devc->left_io;
}
conf_printf2(devc->fm_info.name, ioaddr, 0, -1, -1);
for (i = 0; i < SBFM_MAXINSTR; i++)
devc->i_map[i].channel = -1;
return me;
}
static int me;
static int io = -1;
module_param(io, int, 0);
static int __init init_opl3 (void)
{
printk(KERN_INFO "YM3812 and OPL-3 driver Copyright (C) by Hannu Savolainen, Rob Hooft 1993-1996\n");
if (io != -1) /* User loading pure OPL3 module */
{
if (!opl3_detect(io))
{
return -ENODEV;
}
me = opl3_init(io, THIS_MODULE);
}
return 0;
}
static void __exit cleanup_opl3(void)
{
if (devc && io != -1)
{
if (devc->base) {
release_region(devc->base,4);
if (devc->is_opl4)
release_region(devc->base - 8, 2);
}
kfree(devc);
devc = NULL;
sound_unload_synthdev(me);
}
}
module_init(init_opl3);
module_exit(cleanup_opl3);
#ifndef MODULE
static int __init setup_opl3(char *str)
{
/* io */
int ints[2];
str = get_options(str, ARRAY_SIZE(ints), ints);
io = ints[1];
return 1;
}
__setup("opl3=", setup_opl3);
#endif
MODULE_LICENSE("GPL");
| gpl-2.0 |
AKKP/lge-kernel-star | drivers/staging/rtl8712/rtl8712_efuse.c | 3032 | 15382 | /*
* rtl8712_efuse.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>.
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL8712_EFUSE_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "rtl8712_efuse.h"
/* reserve 3 bytes for HW stop read */
static int efuse_available_max_size = EFUSE_MAX_SIZE - 3 /*0x1FD*/;
static void efuse_reg_ctrl(struct _adapter *padapter, u8 bPowerOn)
{
u8 tmpu8 = 0;
if (true == bPowerOn) {
/* -----------------e-fuse pwr & clk reg ctrl ---------------
* Enable LDOE25 Macro Block
*/
tmpu8 = r8712_read8(padapter, EFUSE_TEST + 3);
tmpu8 |= 0x80;
r8712_write8(padapter, EFUSE_TEST + 3, tmpu8);
msleep(20); /* for some platform , need some delay time */
/* Change Efuse Clock for write action to 40MHZ */
r8712_write8(padapter, EFUSE_CLK_CTRL, 0x03);
msleep(20); /* for some platform , need some delay time */
} else {
/* -----------------e-fuse pwr & clk reg ctrl -----------------
* Disable LDOE25 Macro Block
*/
tmpu8 = r8712_read8(padapter, EFUSE_TEST + 3);
tmpu8 &= 0x7F;
r8712_write8(padapter, EFUSE_TEST + 3, tmpu8);
/* Change Efuse Clock for write action to 500K */
r8712_write8(padapter, EFUSE_CLK_CTRL, 0x02);
}
}
/*
* Before write E-Fuse, this function must be called.
*/
u8 r8712_efuse_reg_init(struct _adapter *padapter)
{
return true;
}
void r8712_efuse_reg_uninit(struct _adapter *padapter)
{
efuse_reg_ctrl(padapter, false);
}
static u8 efuse_one_byte_read(struct _adapter *padapter, u16 addr, u8 *data)
{
u8 tmpidx = 0, bResult;
/* -----------------e-fuse reg ctrl --------------------------------- */
r8712_write8(padapter, EFUSE_CTRL+1, (u8)(addr&0xFF)); /* address */
r8712_write8(padapter, EFUSE_CTRL+2, ((u8)((addr>>8)&0x03)) |
(r8712_read8(padapter, EFUSE_CTRL+2)&0xFC));
r8712_write8(padapter, EFUSE_CTRL+3, 0x72); /* read cmd */
/* wait for complete */
while (!(0x80 & r8712_read8(padapter, EFUSE_CTRL+3)) && (tmpidx < 100))
tmpidx++;
if (tmpidx < 100) {
*data = r8712_read8(padapter, EFUSE_CTRL);
bResult = true;
} else {
*data = 0xff;
bResult = false;
}
return bResult;
}
static u8 efuse_one_byte_write(struct _adapter *padapter, u16 addr, u8 data)
{
u8 tmpidx = 0, bResult;
/* -----------------e-fuse reg ctrl -------------------------------- */
r8712_write8(padapter, EFUSE_CTRL+1, (u8)(addr&0xFF)); /* address */
r8712_write8(padapter, EFUSE_CTRL+2, ((u8)((addr>>8)&0x03)) |
(r8712_read8(padapter, EFUSE_CTRL+2)&0xFC));
r8712_write8(padapter, EFUSE_CTRL, data); /* data */
r8712_write8(padapter, EFUSE_CTRL+3, 0xF2); /* write cmd */
/* wait for complete */
while ((0x80 & r8712_read8(padapter, EFUSE_CTRL+3)) && (tmpidx < 100))
tmpidx++;
if (tmpidx < 100)
bResult = true;
else
bResult = false;
return bResult;
}
static u8 efuse_one_byte_rw(struct _adapter *padapter, u8 bRead, u16 addr,
u8 *data)
{
u8 tmpidx = 0, tmpv8 = 0, bResult;
/* -----------------e-fuse reg ctrl --------------------------------- */
r8712_write8(padapter, EFUSE_CTRL+1, (u8)(addr&0xFF)); /* address */
tmpv8 = ((u8)((addr >> 8) & 0x03)) |
(r8712_read8(padapter, EFUSE_CTRL + 2) & 0xFC);
r8712_write8(padapter, EFUSE_CTRL+2, tmpv8);
if (true == bRead) {
r8712_write8(padapter, EFUSE_CTRL+3, 0x72); /* read cmd */
while (!(0x80 & r8712_read8(padapter, EFUSE_CTRL+3)) &&
(tmpidx < 100))
tmpidx++;
if (tmpidx < 100) {
*data = r8712_read8(padapter, EFUSE_CTRL);
bResult = true;
} else {
*data = 0;
bResult = false;
}
} else {
r8712_write8(padapter, EFUSE_CTRL, *data); /* data */
r8712_write8(padapter, EFUSE_CTRL+3, 0xF2); /* write cmd */
while ((0x80 & r8712_read8(padapter, EFUSE_CTRL+3)) &&
(tmpidx < 100))
tmpidx++;
if (tmpidx < 100)
bResult = true;
else
bResult = false;
}
return bResult;
}
static u8 efuse_is_empty(struct _adapter *padapter, u8 *empty)
{
u8 value, ret = true;
/* read one byte to check if E-Fuse is empty */
if (efuse_one_byte_rw(padapter, true, 0, &value) == true) {
if (0xFF == value)
*empty = true;
else
*empty = false;
} else
ret = false;
return ret;
}
void r8712_efuse_change_max_size(struct _adapter *padapter)
{
u16 pre_pg_data_saddr = 0x1FB;
u16 i;
u16 pre_pg_data_size = 5;
u8 pre_pg_data[5];
for (i = 0; i < pre_pg_data_size; i++)
efuse_one_byte_read(padapter, pre_pg_data_saddr + i,
&pre_pg_data[i]);
if ((pre_pg_data[0] == 0x03) && (pre_pg_data[1] == 0x00) &&
(pre_pg_data[2] == 0x00) && (pre_pg_data[3] == 0x00) &&
(pre_pg_data[4] == 0x0C))
efuse_available_max_size -= pre_pg_data_size;
}
int r8712_efuse_get_max_size(struct _adapter *padapter)
{
return efuse_available_max_size;
}
static u8 calculate_word_cnts(const u8 word_en)
{
u8 word_cnts = 0;
u8 word_idx;
for (word_idx = 0; word_idx < PGPKG_MAX_WORDS; word_idx++)
if (!(word_en & BIT(word_idx)))
word_cnts++; /* 0 : write enable */
return word_cnts;
}
static void pgpacket_copy_data(const u8 word_en, const u8 *sourdata,
u8 *targetdata)
{
u8 tmpindex = 0;
u8 word_idx, byte_idx;
for (word_idx = 0; word_idx < PGPKG_MAX_WORDS; word_idx++) {
if (!(word_en&BIT(word_idx))) {
byte_idx = word_idx * 2;
targetdata[byte_idx] = sourdata[tmpindex++];
targetdata[byte_idx + 1] = sourdata[tmpindex++];
}
}
}
u16 r8712_efuse_get_current_size(struct _adapter *padapter)
{
int bContinual = true;
u16 efuse_addr = 0;
u8 hoffset = 0, hworden = 0;
u8 efuse_data, word_cnts = 0;
while (bContinual && efuse_one_byte_read(padapter, efuse_addr,
&efuse_data) && (efuse_addr < efuse_available_max_size)) {
if (efuse_data != 0xFF) {
hoffset = (efuse_data >> 4) & 0x0F;
hworden = efuse_data & 0x0F;
word_cnts = calculate_word_cnts(hworden);
/* read next header */
efuse_addr = efuse_addr + (word_cnts * 2) + 1;
} else
bContinual = false ;
}
return efuse_addr;
}
u8 r8712_efuse_pg_packet_read(struct _adapter *padapter, u8 offset, u8 *data)
{
u8 hoffset = 0, hworden = 0, word_cnts = 0;
u16 efuse_addr = 0;
u8 efuse_data;
u8 tmpidx = 0;
u8 tmpdata[PGPKT_DATA_SIZE];
u8 ret = true;
if (data == NULL)
return false;
if (offset > 0x0f)
return false;
memset(data, 0xFF, sizeof(u8)*PGPKT_DATA_SIZE);
while (efuse_addr < efuse_available_max_size) {
if (efuse_one_byte_read(padapter, efuse_addr, &efuse_data) ==
true) {
if (efuse_data == 0xFF)
break;
hoffset = (efuse_data >> 4) & 0x0F;
hworden = efuse_data & 0x0F;
word_cnts = calculate_word_cnts(hworden);
if (hoffset == offset) {
memset(tmpdata, 0xFF, PGPKT_DATA_SIZE);
for (tmpidx = 0; tmpidx < word_cnts * 2;
tmpidx++) {
if (efuse_one_byte_read(padapter,
efuse_addr+1+tmpidx, &efuse_data) ==
true) {
tmpdata[tmpidx] = efuse_data;
} else
ret = false;
}
pgpacket_copy_data(hworden, tmpdata, data);
}
efuse_addr += 1 + (word_cnts*2);
} else {
ret = false;
break;
}
}
return ret;
}
static u8 fix_header(struct _adapter *padapter, u8 header, u16 header_addr)
{
struct PGPKT_STRUCT pkt;
u8 offset, word_en, value;
u16 addr;
int i;
u8 ret = true;
pkt.offset = GET_EFUSE_OFFSET(header);
pkt.word_en = GET_EFUSE_WORD_EN(header);
addr = header_addr + 1 + calculate_word_cnts(pkt.word_en) * 2;
if (addr > efuse_available_max_size)
return false;
/* retrieve original data */
addr = 0;
while (addr < header_addr) {
if (efuse_one_byte_read(padapter, addr++, &value) == false) {
ret = false;
break;
}
offset = GET_EFUSE_OFFSET(value);
word_en = GET_EFUSE_WORD_EN(value);
if (pkt.offset != offset) {
addr += calculate_word_cnts(word_en)*2;
continue;
}
for (i = 0; i < PGPKG_MAX_WORDS; i++) {
if (BIT(i) & word_en)
continue;
if (!(BIT(i) & pkt.word_en)) {
if (efuse_one_byte_read(padapter, addr,
&value) == true)
pkt.data[i*2] = value;
else
return false;
if (efuse_one_byte_read(padapter, addr + 1,
&value) == true)
pkt.data[i*2 + 1] = value;
else
return false;
}
addr += 2;
}
}
if (addr != header_addr)
return false;
addr++;
/* fill original data */
for (i = 0; i < PGPKG_MAX_WORDS; i++) {
if (BIT(i) & pkt.word_en)
continue;
efuse_one_byte_write(padapter, addr, pkt.data[i*2]);
efuse_one_byte_write(padapter, addr+1, pkt.data[i*2 + 1]);
/* additional check */
if (efuse_one_byte_read(padapter, addr, &value) == false)
ret = false;
else if (pkt.data[i*2] != value) {
ret = false;
if (0xFF == value) /* write again */
efuse_one_byte_write(padapter, addr,
pkt.data[i * 2]);
}
if (efuse_one_byte_read(padapter, addr+1, &value) == false)
ret = false;
else if (pkt.data[i*2 + 1] != value) {
ret = false;
if (0xFF == value) /* write again */
efuse_one_byte_write(padapter, addr+1,
pkt.data[i*2 + 1]);
}
addr += 2;
}
return ret;
}
u8 r8712_efuse_pg_packet_write(struct _adapter *padapter, const u8 offset,
const u8 word_en, const u8 *data)
{
u8 pg_header = 0;
u16 efuse_addr = 0, curr_size = 0;
u8 efuse_data, target_word_cnts = 0;
static int repeat_times;
int sub_repeat;
u8 bResult = true;
/* check if E-Fuse Clock Enable and E-Fuse Clock is 40M */
efuse_data = r8712_read8(padapter, EFUSE_CLK_CTRL);
if (efuse_data != 0x03)
return false;
pg_header = MAKE_EFUSE_HEADER(offset, word_en);
target_word_cnts = calculate_word_cnts(word_en);
repeat_times = 0;
efuse_addr = 0;
while (efuse_addr < efuse_available_max_size) {
curr_size = r8712_efuse_get_current_size(padapter);
if ((curr_size + 1 + target_word_cnts * 2) >
efuse_available_max_size)
return false; /*target_word_cnts + pg header(1 byte)*/
efuse_addr = curr_size; /* current size is also the last addr*/
efuse_one_byte_write(padapter, efuse_addr, pg_header); /*hdr*/
sub_repeat = 0;
/* check if what we read is what we write */
while (efuse_one_byte_read(padapter, efuse_addr,
&efuse_data) == false) {
if (++sub_repeat > _REPEAT_THRESHOLD_) {
bResult = false; /* continue to blind write */
break; /* continue to blind write */
}
}
if ((sub_repeat > _REPEAT_THRESHOLD_) ||
(pg_header == efuse_data)) {
/* write header ok OR can't check header(creep) */
u8 i;
/* go to next address */
efuse_addr++;
for (i = 0; i < target_word_cnts*2; i++) {
efuse_one_byte_write(padapter,
efuse_addr + i,
*(data + i));
if (efuse_one_byte_read(padapter,
efuse_addr + i, &efuse_data) == false)
bResult = false;
else if (*(data+i) != efuse_data) /* fail */
bResult = false;
}
break;
} else { /* write header fail */
bResult = false;
if (0xFF == efuse_data)
return bResult; /* not thing damaged. */
/* call rescue procedure */
if (fix_header(padapter, efuse_data, efuse_addr) ==
false)
return false; /* rescue fail */
if (++repeat_times > _REPEAT_THRESHOLD_) /* fail */
break;
/* otherwise, take another risk... */
}
}
return bResult;
}
u8 r8712_efuse_access(struct _adapter *padapter, u8 bRead, u16 start_addr,
u16 cnts, u8 *data)
{
int i;
u8 res = true;
if (start_addr > EFUSE_MAX_SIZE)
return false;
if ((bRead == false) && ((start_addr + cnts) >
efuse_available_max_size))
return false;
if ((false == bRead) && (r8712_efuse_reg_init(padapter) == false))
return false;
/* -----------------e-fuse one byte read / write ---------------------*/
for (i = 0; i < cnts; i++) {
if ((start_addr + i) > EFUSE_MAX_SIZE) {
res = false;
break;
}
res = efuse_one_byte_rw(padapter, bRead, start_addr + i,
data + i);
if ((false == bRead) && (false == res))
break;
}
if (false == bRead)
r8712_efuse_reg_uninit(padapter);
return res;
}
u8 r8712_efuse_map_read(struct _adapter *padapter, u16 addr, u16 cnts, u8 *data)
{
u8 offset, ret = true;
u8 pktdata[PGPKT_DATA_SIZE];
int i, idx;
if ((addr + cnts) > EFUSE_MAP_MAX_SIZE)
return false;
if ((efuse_is_empty(padapter, &offset) == true) && (offset ==
true)) {
for (i = 0; i < cnts; i++)
data[i] = 0xFF;
return ret;
}
offset = (addr >> 3) & 0xF;
ret = r8712_efuse_pg_packet_read(padapter, offset, pktdata);
i = addr & 0x7; /* pktdata index */
idx = 0; /* data index */
do {
for (; i < PGPKT_DATA_SIZE; i++) {
data[idx++] = pktdata[i];
if (idx == cnts)
return ret;
}
offset++;
if (!r8712_efuse_pg_packet_read(padapter, offset, pktdata))
ret = false;
i = 0;
} while (1);
return ret;
}
u8 r8712_efuse_map_write(struct _adapter *padapter, u16 addr, u16 cnts,
u8 *data)
{
u8 offset, word_en, empty;
u8 pktdata[PGPKT_DATA_SIZE], newdata[PGPKT_DATA_SIZE];
int i, j, idx;
if ((addr + cnts) > EFUSE_MAP_MAX_SIZE)
return false;
/* check if E-Fuse Clock Enable and E-Fuse Clock is 40M */
empty = r8712_read8(padapter, EFUSE_CLK_CTRL);
if (empty != 0x03)
return false;
if (efuse_is_empty(padapter, &empty) == true) {
if (true == empty)
memset(pktdata, 0xFF, PGPKT_DATA_SIZE);
} else
return false;
offset = (addr >> 3) & 0xF;
if (empty == false)
if (!r8712_efuse_pg_packet_read(padapter, offset, pktdata))
return false;
word_en = 0xF;
memset(newdata, 0xFF, PGPKT_DATA_SIZE);
i = addr & 0x7; /* pktdata index */
j = 0; /* newdata index */
idx = 0; /* data index */
if (i & 0x1) {
/* odd start */
if (data[idx] != pktdata[i]) {
word_en &= ~BIT(i >> 1);
newdata[j++] = pktdata[i - 1];
newdata[j++] = data[idx];
}
i++;
idx++;
}
do {
for (; i < PGPKT_DATA_SIZE; i += 2) {
if ((cnts - idx) == 1) {
if (data[idx] != pktdata[i]) {
word_en &= ~BIT(i >> 1);
newdata[j++] = data[idx];
newdata[j++] = pktdata[1 + 1];
}
idx++;
break;
} else {
if ((data[idx] != pktdata[i]) || (data[idx+1] !=
pktdata[i+1])) {
word_en &= ~BIT(i >> 1);
newdata[j++] = data[idx];
newdata[j++] = data[idx + 1];
}
idx += 2;
}
if (idx == cnts)
break;
}
if (word_en != 0xF)
if (r8712_efuse_pg_packet_write(padapter, offset,
word_en, newdata) == false)
return false;
if (idx == cnts)
break;
offset++;
if (empty == false)
if (!r8712_efuse_pg_packet_read(padapter, offset,
pktdata))
return false;
i = 0;
j = 0;
word_en = 0xF;
memset(newdata, 0xFF, PGPKT_DATA_SIZE);
} while (1);
return true;
}
| gpl-2.0 |
zarboz/T6_Blackout_Edition | lib/checksum.c | 4568 | 4946 | /*
*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* IP/TCP/UDP checksumming routines
*
* Authors: Jorge Cwik, <jorge@laser.satlink.net>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Tom May, <ftom@netcom.com>
* Andreas Schwab, <schwab@issan.informatik.uni-dortmund.de>
* Lots of code moved from tcp.c and ip.c; see those files
* for more names.
*
* 03/02/96 Jes Sorensen, Andreas Schwab, Roman Hodek:
* Fixed some nasty bugs, causing some horrible crashes.
* A: At some points, the sum (%0) was used as
* length-counter instead of the length counter
* (%1). Thanks to Roman Hodek for pointing this out.
* B: GCC seems to mess up if one uses too many
* data-registers to hold input values and one tries to
* specify d0 and d1 as scratch registers. Letting gcc
* choose these registers itself solves the problem.
*
* 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.
*/
/* Revised by Kenneth Albanowski for m68knommu. Basic problem: unaligned access
kills, so most of the assembly has to go. */
#include <linux/export.h>
#include <net/checksum.h>
#include <asm/byteorder.h>
#ifndef do_csum
static inline unsigned short from32to16(unsigned int x)
{
/* add up 16-bit and 16-bit for 16+c bit */
x = (x & 0xffff) + (x >> 16);
/* add up carry.. */
x = (x & 0xffff) + (x >> 16);
return x;
}
static unsigned int do_csum(const unsigned char *buff, int len)
{
int odd;
unsigned int result = 0;
if (len <= 0)
goto out;
odd = 1 & (unsigned long) buff;
if (odd) {
#ifdef __LITTLE_ENDIAN
result += (*buff << 8);
#else
result = *buff;
#endif
len--;
buff++;
}
if (len >= 2) {
if (2 & (unsigned long) buff) {
result += *(unsigned short *) buff;
len -= 2;
buff += 2;
}
if (len >= 4) {
const unsigned char *end = buff + ((unsigned)len & ~3);
unsigned int carry = 0;
do {
unsigned int w = *(unsigned int *) buff;
buff += 4;
result += carry;
result += w;
carry = (w > result);
} while (buff < end);
result += carry;
result = (result & 0xffff) + (result >> 16);
}
if (len & 2) {
result += *(unsigned short *) buff;
buff += 2;
}
}
if (len & 1)
#ifdef __LITTLE_ENDIAN
result += *buff;
#else
result += (*buff << 8);
#endif
result = from32to16(result);
if (odd)
result = ((result >> 8) & 0xff) | ((result & 0xff) << 8);
out:
return result;
}
#endif
/*
* This is a version of ip_compute_csum() optimized for IP headers,
* which always checksum on 4 octet boundaries.
*/
__sum16 ip_fast_csum(const void *iph, unsigned int ihl)
{
return (__force __sum16)~do_csum(iph, ihl*4);
}
EXPORT_SYMBOL(ip_fast_csum);
/*
* computes the checksum of a memory block at buff, length len,
* and adds in "sum" (32-bit)
*
* returns a 32-bit number suitable for feeding into itself
* or csum_tcpudp_magic
*
* this function must be called with even lengths, except
* for the last fragment, which may be odd
*
* it's best to have buff aligned on a 32-bit boundary
*/
__wsum csum_partial(const void *buff, int len, __wsum wsum)
{
unsigned int sum = (__force unsigned int)wsum;
unsigned int result = do_csum(buff, len);
/* add in old sum, and carry.. */
result += sum;
if (sum > result)
result += 1;
return (__force __wsum)result;
}
EXPORT_SYMBOL(csum_partial);
/*
* this routine is used for miscellaneous IP-like checksums, mainly
* in icmp.c
*/
__sum16 ip_compute_csum(const void *buff, int len)
{
return (__force __sum16)~do_csum(buff, len);
}
EXPORT_SYMBOL(ip_compute_csum);
/*
* copy from fs while checksumming, otherwise like csum_partial
*/
__wsum
csum_partial_copy_from_user(const void __user *src, void *dst, int len,
__wsum sum, int *csum_err)
{
int missing;
missing = __copy_from_user(dst, src, len);
if (missing) {
memset(dst + len - missing, 0, missing);
*csum_err = -EFAULT;
} else
*csum_err = 0;
return csum_partial(dst, len, sum);
}
EXPORT_SYMBOL(csum_partial_copy_from_user);
/*
* copy from ds while checksumming, otherwise like csum_partial
*/
__wsum
csum_partial_copy(const void *src, void *dst, int len, __wsum sum)
{
memcpy(dst, src, len);
return csum_partial(dst, len, sum);
}
EXPORT_SYMBOL(csum_partial_copy);
#ifndef csum_tcpudp_nofold
__wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
unsigned short len,
unsigned short proto,
__wsum sum)
{
unsigned long long s = (__force u32)sum;
s += (__force u32)saddr;
s += (__force u32)daddr;
#ifdef __BIG_ENDIAN
s += proto + len;
#else
s += (proto + len) << 8;
#endif
s += (s >> 32);
return (__force __wsum)s;
}
EXPORT_SYMBOL(csum_tcpudp_nofold);
#endif
| gpl-2.0 |
GreatDevs/kernel_sony_msm8974 | drivers/usb/gadget/uvc_v4l2.c | 4824 | 8230 | /*
* uvc_v4l2.c -- USB Video Class Gadget driver
*
* Copyright (C) 2009-2010
* Laurent Pinchart (laurent.pinchart@ideasonboard.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/device.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-event.h>
#include <media/v4l2-ioctl.h>
#include "uvc.h"
#include "uvc_queue.h"
/* --------------------------------------------------------------------------
* Requests handling
*/
static int
uvc_send_response(struct uvc_device *uvc, struct uvc_request_data *data)
{
struct usb_composite_dev *cdev = uvc->func.config->cdev;
struct usb_request *req = uvc->control_req;
if (data->length < 0)
return usb_ep_set_halt(cdev->gadget->ep0);
req->length = min_t(unsigned int, uvc->event_length, data->length);
req->zero = data->length < uvc->event_length;
req->dma = DMA_ADDR_INVALID;
memcpy(req->buf, data->data, data->length);
return usb_ep_queue(cdev->gadget->ep0, req, GFP_KERNEL);
}
/* --------------------------------------------------------------------------
* V4L2
*/
struct uvc_format
{
u8 bpp;
u32 fcc;
};
static struct uvc_format uvc_formats[] = {
{ 16, V4L2_PIX_FMT_YUYV },
{ 0, V4L2_PIX_FMT_MJPEG },
};
static int
uvc_v4l2_get_format(struct uvc_video *video, struct v4l2_format *fmt)
{
fmt->fmt.pix.pixelformat = video->fcc;
fmt->fmt.pix.width = video->width;
fmt->fmt.pix.height = video->height;
fmt->fmt.pix.field = V4L2_FIELD_NONE;
fmt->fmt.pix.bytesperline = video->bpp * video->width / 8;
fmt->fmt.pix.sizeimage = video->imagesize;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
fmt->fmt.pix.priv = 0;
return 0;
}
static int
uvc_v4l2_set_format(struct uvc_video *video, struct v4l2_format *fmt)
{
struct uvc_format *format;
unsigned int imagesize;
unsigned int bpl;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(uvc_formats); ++i) {
format = &uvc_formats[i];
if (format->fcc == fmt->fmt.pix.pixelformat)
break;
}
if (i == ARRAY_SIZE(uvc_formats)) {
printk(KERN_INFO "Unsupported format 0x%08x.\n",
fmt->fmt.pix.pixelformat);
return -EINVAL;
}
bpl = format->bpp * fmt->fmt.pix.width / 8;
imagesize = bpl ? bpl * fmt->fmt.pix.height : fmt->fmt.pix.sizeimage;
video->fcc = format->fcc;
video->bpp = format->bpp;
video->width = fmt->fmt.pix.width;
video->height = fmt->fmt.pix.height;
video->imagesize = imagesize;
fmt->fmt.pix.field = V4L2_FIELD_NONE;
fmt->fmt.pix.bytesperline = bpl;
fmt->fmt.pix.sizeimage = imagesize;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
fmt->fmt.pix.priv = 0;
return 0;
}
static int
uvc_v4l2_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle;
handle = kzalloc(sizeof(*handle), GFP_KERNEL);
if (handle == NULL)
return -ENOMEM;
v4l2_fh_init(&handle->vfh, vdev);
v4l2_fh_add(&handle->vfh);
handle->device = &uvc->video;
file->private_data = &handle->vfh;
uvc_function_connect(uvc);
return 0;
}
static int
uvc_v4l2_release(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
struct uvc_video *video = handle->device;
uvc_function_disconnect(uvc);
uvc_video_enable(video, 0);
mutex_lock(&video->queue.mutex);
if (uvc_free_buffers(&video->queue) < 0)
printk(KERN_ERR "uvc_v4l2_release: Unable to free "
"buffers.\n");
mutex_unlock(&video->queue.mutex);
file->private_data = NULL;
v4l2_fh_del(&handle->vfh);
v4l2_fh_exit(&handle->vfh);
kfree(handle);
return 0;
}
static long
uvc_v4l2_do_ioctl(struct file *file, unsigned int cmd, void *arg)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
struct usb_composite_dev *cdev = uvc->func.config->cdev;
struct uvc_video *video = &uvc->video;
int ret = 0;
switch (cmd) {
/* Query capabilities */
case VIDIOC_QUERYCAP:
{
struct v4l2_capability *cap = arg;
memset(cap, 0, sizeof *cap);
strncpy(cap->driver, "g_uvc", sizeof(cap->driver));
strncpy(cap->card, cdev->gadget->name, sizeof(cap->card));
strncpy(cap->bus_info, dev_name(&cdev->gadget->dev),
sizeof cap->bus_info);
cap->version = DRIVER_VERSION_NUMBER;
cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
break;
}
/* Get & Set format */
case VIDIOC_G_FMT:
{
struct v4l2_format *fmt = arg;
if (fmt->type != video->queue.type)
return -EINVAL;
return uvc_v4l2_get_format(video, fmt);
}
case VIDIOC_S_FMT:
{
struct v4l2_format *fmt = arg;
if (fmt->type != video->queue.type)
return -EINVAL;
return uvc_v4l2_set_format(video, fmt);
}
/* Buffers & streaming */
case VIDIOC_REQBUFS:
{
struct v4l2_requestbuffers *rb = arg;
if (rb->type != video->queue.type ||
rb->memory != V4L2_MEMORY_MMAP)
return -EINVAL;
ret = uvc_alloc_buffers(&video->queue, rb->count,
video->imagesize);
if (ret < 0)
return ret;
rb->count = ret;
ret = 0;
break;
}
case VIDIOC_QUERYBUF:
{
struct v4l2_buffer *buf = arg;
if (buf->type != video->queue.type)
return -EINVAL;
return uvc_query_buffer(&video->queue, buf);
}
case VIDIOC_QBUF:
if ((ret = uvc_queue_buffer(&video->queue, arg)) < 0)
return ret;
return uvc_video_pump(video);
case VIDIOC_DQBUF:
return uvc_dequeue_buffer(&video->queue, arg,
file->f_flags & O_NONBLOCK);
case VIDIOC_STREAMON:
{
int *type = arg;
if (*type != video->queue.type)
return -EINVAL;
return uvc_video_enable(video, 1);
}
case VIDIOC_STREAMOFF:
{
int *type = arg;
if (*type != video->queue.type)
return -EINVAL;
return uvc_video_enable(video, 0);
}
/* Events */
case VIDIOC_DQEVENT:
{
struct v4l2_event *event = arg;
ret = v4l2_event_dequeue(&handle->vfh, event,
file->f_flags & O_NONBLOCK);
if (ret == 0 && event->type == UVC_EVENT_SETUP) {
struct uvc_event *uvc_event = (void *)&event->u.data;
/* Tell the complete callback to generate an event for
* the next request that will be enqueued by
* uvc_event_write.
*/
uvc->event_setup_out =
!(uvc_event->req.bRequestType & USB_DIR_IN);
uvc->event_length = uvc_event->req.wLength;
}
return ret;
}
case VIDIOC_SUBSCRIBE_EVENT:
{
struct v4l2_event_subscription *sub = arg;
if (sub->type < UVC_EVENT_FIRST || sub->type > UVC_EVENT_LAST)
return -EINVAL;
return v4l2_event_subscribe(&handle->vfh, arg, 2);
}
case VIDIOC_UNSUBSCRIBE_EVENT:
return v4l2_event_unsubscribe(&handle->vfh, arg);
case UVCIOC_SEND_RESPONSE:
ret = uvc_send_response(uvc, arg);
break;
default:
return -ENOIOCTLCMD;
}
return ret;
}
static long
uvc_v4l2_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
return video_usercopy(file, cmd, arg, uvc_v4l2_do_ioctl);
}
static int
uvc_v4l2_mmap(struct file *file, struct vm_area_struct *vma)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
return uvc_queue_mmap(&uvc->video.queue, vma);
}
static unsigned int
uvc_v4l2_poll(struct file *file, poll_table *wait)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
unsigned int mask = 0;
poll_wait(file, &handle->vfh.wait, wait);
if (v4l2_event_pending(&handle->vfh))
mask |= POLLPRI;
mask |= uvc_queue_poll(&uvc->video.queue, file, wait);
return mask;
}
static struct v4l2_file_operations uvc_v4l2_fops = {
.owner = THIS_MODULE,
.open = uvc_v4l2_open,
.release = uvc_v4l2_release,
.ioctl = uvc_v4l2_ioctl,
.mmap = uvc_v4l2_mmap,
.poll = uvc_v4l2_poll,
};
| gpl-2.0 |
nasty007/android_kernel_lge_mako | drivers/mfd/aat2870-core.c | 4824 | 12617 | /*
* linux/drivers/mfd/aat2870-core.c
*
* Copyright (c) 2011, NVIDIA Corporation.
* Author: Jin Park <jinyoungp@nvidia.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/module.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/i2c.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/mfd/core.h>
#include <linux/mfd/aat2870.h>
#include <linux/regulator/machine.h>
static struct aat2870_register aat2870_regs[AAT2870_REG_NUM] = {
/* readable, writeable, value */
{ 0, 1, 0x00 }, /* 0x00 AAT2870_BL_CH_EN */
{ 0, 1, 0x16 }, /* 0x01 AAT2870_BLM */
{ 0, 1, 0x16 }, /* 0x02 AAT2870_BLS */
{ 0, 1, 0x56 }, /* 0x03 AAT2870_BL1 */
{ 0, 1, 0x56 }, /* 0x04 AAT2870_BL2 */
{ 0, 1, 0x56 }, /* 0x05 AAT2870_BL3 */
{ 0, 1, 0x56 }, /* 0x06 AAT2870_BL4 */
{ 0, 1, 0x56 }, /* 0x07 AAT2870_BL5 */
{ 0, 1, 0x56 }, /* 0x08 AAT2870_BL6 */
{ 0, 1, 0x56 }, /* 0x09 AAT2870_BL7 */
{ 0, 1, 0x56 }, /* 0x0A AAT2870_BL8 */
{ 0, 1, 0x00 }, /* 0x0B AAT2870_FLR */
{ 0, 1, 0x03 }, /* 0x0C AAT2870_FM */
{ 0, 1, 0x03 }, /* 0x0D AAT2870_FS */
{ 0, 1, 0x10 }, /* 0x0E AAT2870_ALS_CFG0 */
{ 0, 1, 0x06 }, /* 0x0F AAT2870_ALS_CFG1 */
{ 0, 1, 0x00 }, /* 0x10 AAT2870_ALS_CFG2 */
{ 1, 0, 0x00 }, /* 0x11 AAT2870_AMB */
{ 0, 1, 0x00 }, /* 0x12 AAT2870_ALS0 */
{ 0, 1, 0x00 }, /* 0x13 AAT2870_ALS1 */
{ 0, 1, 0x00 }, /* 0x14 AAT2870_ALS2 */
{ 0, 1, 0x00 }, /* 0x15 AAT2870_ALS3 */
{ 0, 1, 0x00 }, /* 0x16 AAT2870_ALS4 */
{ 0, 1, 0x00 }, /* 0x17 AAT2870_ALS5 */
{ 0, 1, 0x00 }, /* 0x18 AAT2870_ALS6 */
{ 0, 1, 0x00 }, /* 0x19 AAT2870_ALS7 */
{ 0, 1, 0x00 }, /* 0x1A AAT2870_ALS8 */
{ 0, 1, 0x00 }, /* 0x1B AAT2870_ALS9 */
{ 0, 1, 0x00 }, /* 0x1C AAT2870_ALSA */
{ 0, 1, 0x00 }, /* 0x1D AAT2870_ALSB */
{ 0, 1, 0x00 }, /* 0x1E AAT2870_ALSC */
{ 0, 1, 0x00 }, /* 0x1F AAT2870_ALSD */
{ 0, 1, 0x00 }, /* 0x20 AAT2870_ALSE */
{ 0, 1, 0x00 }, /* 0x21 AAT2870_ALSF */
{ 0, 1, 0x00 }, /* 0x22 AAT2870_SUB_SET */
{ 0, 1, 0x00 }, /* 0x23 AAT2870_SUB_CTRL */
{ 0, 1, 0x00 }, /* 0x24 AAT2870_LDO_AB */
{ 0, 1, 0x00 }, /* 0x25 AAT2870_LDO_CD */
{ 0, 1, 0x00 }, /* 0x26 AAT2870_LDO_EN */
};
static struct mfd_cell aat2870_devs[] = {
{
.name = "aat2870-backlight",
.id = AAT2870_ID_BL,
.pdata_size = sizeof(struct aat2870_bl_platform_data),
},
{
.name = "aat2870-regulator",
.id = AAT2870_ID_LDOA,
.pdata_size = sizeof(struct regulator_init_data),
},
{
.name = "aat2870-regulator",
.id = AAT2870_ID_LDOB,
.pdata_size = sizeof(struct regulator_init_data),
},
{
.name = "aat2870-regulator",
.id = AAT2870_ID_LDOC,
.pdata_size = sizeof(struct regulator_init_data),
},
{
.name = "aat2870-regulator",
.id = AAT2870_ID_LDOD,
.pdata_size = sizeof(struct regulator_init_data),
},
};
static int __aat2870_read(struct aat2870_data *aat2870, u8 addr, u8 *val)
{
int ret;
if (addr >= AAT2870_REG_NUM) {
dev_err(aat2870->dev, "Invalid address, 0x%02x\n", addr);
return -EINVAL;
}
if (!aat2870->reg_cache[addr].readable) {
*val = aat2870->reg_cache[addr].value;
goto out;
}
ret = i2c_master_send(aat2870->client, &addr, 1);
if (ret < 0)
return ret;
if (ret != 1)
return -EIO;
ret = i2c_master_recv(aat2870->client, val, 1);
if (ret < 0)
return ret;
if (ret != 1)
return -EIO;
out:
dev_dbg(aat2870->dev, "read: addr=0x%02x, val=0x%02x\n", addr, *val);
return 0;
}
static int __aat2870_write(struct aat2870_data *aat2870, u8 addr, u8 val)
{
u8 msg[2];
int ret;
if (addr >= AAT2870_REG_NUM) {
dev_err(aat2870->dev, "Invalid address, 0x%02x\n", addr);
return -EINVAL;
}
if (!aat2870->reg_cache[addr].writeable) {
dev_err(aat2870->dev, "Address 0x%02x is not writeable\n",
addr);
return -EINVAL;
}
msg[0] = addr;
msg[1] = val;
ret = i2c_master_send(aat2870->client, msg, 2);
if (ret < 0)
return ret;
if (ret != 2)
return -EIO;
aat2870->reg_cache[addr].value = val;
dev_dbg(aat2870->dev, "write: addr=0x%02x, val=0x%02x\n", addr, val);
return 0;
}
static int aat2870_read(struct aat2870_data *aat2870, u8 addr, u8 *val)
{
int ret;
mutex_lock(&aat2870->io_lock);
ret = __aat2870_read(aat2870, addr, val);
mutex_unlock(&aat2870->io_lock);
return ret;
}
static int aat2870_write(struct aat2870_data *aat2870, u8 addr, u8 val)
{
int ret;
mutex_lock(&aat2870->io_lock);
ret = __aat2870_write(aat2870, addr, val);
mutex_unlock(&aat2870->io_lock);
return ret;
}
static int aat2870_update(struct aat2870_data *aat2870, u8 addr, u8 mask,
u8 val)
{
int change;
u8 old_val, new_val;
int ret;
mutex_lock(&aat2870->io_lock);
ret = __aat2870_read(aat2870, addr, &old_val);
if (ret)
goto out_unlock;
new_val = (old_val & ~mask) | (val & mask);
change = old_val != new_val;
if (change)
ret = __aat2870_write(aat2870, addr, new_val);
out_unlock:
mutex_unlock(&aat2870->io_lock);
return ret;
}
static inline void aat2870_enable(struct aat2870_data *aat2870)
{
if (aat2870->en_pin >= 0)
gpio_set_value(aat2870->en_pin, 1);
aat2870->is_enable = 1;
}
static inline void aat2870_disable(struct aat2870_data *aat2870)
{
if (aat2870->en_pin >= 0)
gpio_set_value(aat2870->en_pin, 0);
aat2870->is_enable = 0;
}
#ifdef CONFIG_DEBUG_FS
static ssize_t aat2870_dump_reg(struct aat2870_data *aat2870, char *buf)
{
u8 addr, val;
ssize_t count = 0;
int ret;
count += sprintf(buf, "aat2870 registers\n");
for (addr = 0; addr < AAT2870_REG_NUM; addr++) {
count += sprintf(buf + count, "0x%02x: ", addr);
if (count >= PAGE_SIZE - 1)
break;
ret = aat2870->read(aat2870, addr, &val);
if (ret == 0)
count += snprintf(buf + count, PAGE_SIZE - count,
"0x%02x", val);
else
count += snprintf(buf + count, PAGE_SIZE - count,
"<read fail: %d>", ret);
if (count >= PAGE_SIZE - 1)
break;
count += snprintf(buf + count, PAGE_SIZE - count, "\n");
if (count >= PAGE_SIZE - 1)
break;
}
/* Truncate count; min() would cause a warning */
if (count >= PAGE_SIZE)
count = PAGE_SIZE - 1;
return count;
}
static ssize_t aat2870_reg_read_file(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct aat2870_data *aat2870 = file->private_data;
char *buf;
ssize_t ret;
buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
ret = aat2870_dump_reg(aat2870, buf);
if (ret >= 0)
ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret);
kfree(buf);
return ret;
}
static ssize_t aat2870_reg_write_file(struct file *file,
const char __user *user_buf, size_t count,
loff_t *ppos)
{
struct aat2870_data *aat2870 = file->private_data;
char buf[32];
ssize_t buf_size;
char *start = buf;
unsigned long addr, val;
int ret;
buf_size = min(count, (sizeof(buf)-1));
if (copy_from_user(buf, user_buf, buf_size)) {
dev_err(aat2870->dev, "Failed to copy from user\n");
return -EFAULT;
}
buf[buf_size] = 0;
while (*start == ' ')
start++;
addr = simple_strtoul(start, &start, 16);
if (addr >= AAT2870_REG_NUM) {
dev_err(aat2870->dev, "Invalid address, 0x%lx\n", addr);
return -EINVAL;
}
while (*start == ' ')
start++;
if (strict_strtoul(start, 16, &val))
return -EINVAL;
ret = aat2870->write(aat2870, (u8)addr, (u8)val);
if (ret)
return ret;
return buf_size;
}
static const struct file_operations aat2870_reg_fops = {
.open = simple_open,
.read = aat2870_reg_read_file,
.write = aat2870_reg_write_file,
};
static void aat2870_init_debugfs(struct aat2870_data *aat2870)
{
aat2870->dentry_root = debugfs_create_dir("aat2870", NULL);
if (!aat2870->dentry_root) {
dev_warn(aat2870->dev,
"Failed to create debugfs root directory\n");
return;
}
aat2870->dentry_reg = debugfs_create_file("regs", 0644,
aat2870->dentry_root,
aat2870, &aat2870_reg_fops);
if (!aat2870->dentry_reg)
dev_warn(aat2870->dev,
"Failed to create debugfs register file\n");
}
static void aat2870_uninit_debugfs(struct aat2870_data *aat2870)
{
debugfs_remove_recursive(aat2870->dentry_root);
}
#else
static inline void aat2870_init_debugfs(struct aat2870_data *aat2870)
{
}
static inline void aat2870_uninit_debugfs(struct aat2870_data *aat2870)
{
}
#endif /* CONFIG_DEBUG_FS */
static int aat2870_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct aat2870_platform_data *pdata = client->dev.platform_data;
struct aat2870_data *aat2870;
int i, j;
int ret = 0;
aat2870 = kzalloc(sizeof(struct aat2870_data), GFP_KERNEL);
if (!aat2870) {
dev_err(&client->dev,
"Failed to allocate memory for aat2870\n");
ret = -ENOMEM;
goto out;
}
aat2870->dev = &client->dev;
dev_set_drvdata(aat2870->dev, aat2870);
aat2870->client = client;
i2c_set_clientdata(client, aat2870);
aat2870->reg_cache = aat2870_regs;
if (pdata->en_pin < 0)
aat2870->en_pin = -1;
else
aat2870->en_pin = pdata->en_pin;
aat2870->init = pdata->init;
aat2870->uninit = pdata->uninit;
aat2870->read = aat2870_read;
aat2870->write = aat2870_write;
aat2870->update = aat2870_update;
mutex_init(&aat2870->io_lock);
if (aat2870->init)
aat2870->init(aat2870);
if (aat2870->en_pin >= 0) {
ret = gpio_request_one(aat2870->en_pin, GPIOF_OUT_INIT_HIGH,
"aat2870-en");
if (ret < 0) {
dev_err(&client->dev,
"Failed to request GPIO %d\n", aat2870->en_pin);
goto out_kfree;
}
}
aat2870_enable(aat2870);
for (i = 0; i < pdata->num_subdevs; i++) {
for (j = 0; j < ARRAY_SIZE(aat2870_devs); j++) {
if ((pdata->subdevs[i].id == aat2870_devs[j].id) &&
!strcmp(pdata->subdevs[i].name,
aat2870_devs[j].name)) {
aat2870_devs[j].platform_data =
pdata->subdevs[i].platform_data;
break;
}
}
}
ret = mfd_add_devices(aat2870->dev, 0, aat2870_devs,
ARRAY_SIZE(aat2870_devs), NULL, 0);
if (ret != 0) {
dev_err(aat2870->dev, "Failed to add subdev: %d\n", ret);
goto out_disable;
}
aat2870_init_debugfs(aat2870);
return 0;
out_disable:
aat2870_disable(aat2870);
if (aat2870->en_pin >= 0)
gpio_free(aat2870->en_pin);
out_kfree:
kfree(aat2870);
out:
return ret;
}
static int aat2870_i2c_remove(struct i2c_client *client)
{
struct aat2870_data *aat2870 = i2c_get_clientdata(client);
aat2870_uninit_debugfs(aat2870);
mfd_remove_devices(aat2870->dev);
aat2870_disable(aat2870);
if (aat2870->en_pin >= 0)
gpio_free(aat2870->en_pin);
if (aat2870->uninit)
aat2870->uninit(aat2870);
kfree(aat2870);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int aat2870_i2c_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct aat2870_data *aat2870 = i2c_get_clientdata(client);
aat2870_disable(aat2870);
return 0;
}
static int aat2870_i2c_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct aat2870_data *aat2870 = i2c_get_clientdata(client);
struct aat2870_register *reg = NULL;
int i;
aat2870_enable(aat2870);
/* restore registers */
for (i = 0; i < AAT2870_REG_NUM; i++) {
reg = &aat2870->reg_cache[i];
if (reg->writeable)
aat2870->write(aat2870, i, reg->value);
}
return 0;
}
#endif /* CONFIG_PM_SLEEP */
static SIMPLE_DEV_PM_OPS(aat2870_pm_ops, aat2870_i2c_suspend,
aat2870_i2c_resume);
static const struct i2c_device_id aat2870_i2c_id_table[] = {
{ "aat2870", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, aat2870_i2c_id_table);
static struct i2c_driver aat2870_i2c_driver = {
.driver = {
.name = "aat2870",
.owner = THIS_MODULE,
.pm = &aat2870_pm_ops,
},
.probe = aat2870_i2c_probe,
.remove = aat2870_i2c_remove,
.id_table = aat2870_i2c_id_table,
};
static int __init aat2870_init(void)
{
return i2c_add_driver(&aat2870_i2c_driver);
}
subsys_initcall(aat2870_init);
static void __exit aat2870_exit(void)
{
i2c_del_driver(&aat2870_i2c_driver);
}
module_exit(aat2870_exit);
MODULE_DESCRIPTION("Core support for the AnalogicTech AAT2870");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jin Park <jinyoungp@nvidia.com>");
| gpl-2.0 |
XperianPro/cyanogen_modified_edition_aries | drivers/watchdog/txx9wdt.c | 5080 | 4891 | /*
* txx9wdt: A Hardware Watchdog Driver for TXx9 SoCs
*
* Copyright (C) 2007 Atsushi Nemoto <anemo@mba.ocn.ne.jp>
*
* 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/moduleparam.h>
#include <linux/types.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <asm/txx9tmr.h>
#define WD_TIMER_CCD 7 /* 1/256 */
#define WD_TIMER_CLK (clk_get_rate(txx9_imclk) / (2 << WD_TIMER_CCD))
#define WD_MAX_TIMEOUT ((0xffffffff >> (32 - TXX9_TIMER_BITS)) / WD_TIMER_CLK)
#define TIMER_MARGIN 60 /* Default is 60 seconds */
static unsigned int timeout = TIMER_MARGIN; /* in seconds */
module_param(timeout, uint, 0);
MODULE_PARM_DESC(timeout,
"Watchdog timeout in seconds. "
"(0<timeout<((2^" __MODULE_STRING(TXX9_TIMER_BITS) ")/(IMCLK/256)), "
"default=" __MODULE_STRING(TIMER_MARGIN) ")");
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started "
"(default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static struct txx9_tmr_reg __iomem *txx9wdt_reg;
static struct clk *txx9_imclk;
static DEFINE_SPINLOCK(txx9_lock);
static int txx9wdt_ping(struct watchdog_device *wdt_dev)
{
spin_lock(&txx9_lock);
__raw_writel(TXx9_TMWTMR_TWIE | TXx9_TMWTMR_TWC, &txx9wdt_reg->wtmr);
spin_unlock(&txx9_lock);
return 0;
}
static int txx9wdt_start(struct watchdog_device *wdt_dev)
{
spin_lock(&txx9_lock);
__raw_writel(WD_TIMER_CLK * wdt_dev->timeout, &txx9wdt_reg->cpra);
__raw_writel(WD_TIMER_CCD, &txx9wdt_reg->ccdr);
__raw_writel(0, &txx9wdt_reg->tisr); /* clear pending interrupt */
__raw_writel(TXx9_TMTCR_TCE | TXx9_TMTCR_CCDE | TXx9_TMTCR_TMODE_WDOG,
&txx9wdt_reg->tcr);
__raw_writel(TXx9_TMWTMR_TWIE | TXx9_TMWTMR_TWC, &txx9wdt_reg->wtmr);
spin_unlock(&txx9_lock);
return 0;
}
static int txx9wdt_stop(struct watchdog_device *wdt_dev)
{
spin_lock(&txx9_lock);
__raw_writel(TXx9_TMWTMR_WDIS, &txx9wdt_reg->wtmr);
__raw_writel(__raw_readl(&txx9wdt_reg->tcr) & ~TXx9_TMTCR_TCE,
&txx9wdt_reg->tcr);
spin_unlock(&txx9_lock);
return 0;
}
static int txx9wdt_set_timeout(struct watchdog_device *wdt_dev,
unsigned int new_timeout)
{
wdt_dev->timeout = new_timeout;
txx9wdt_stop(wdt_dev);
txx9wdt_start(wdt_dev);
return 0;
}
static const struct watchdog_info txx9wdt_info = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
.identity = "Hardware Watchdog for TXx9",
};
static const struct watchdog_ops txx9wdt_ops = {
.owner = THIS_MODULE,
.start = txx9wdt_start,
.stop = txx9wdt_stop,
.ping = txx9wdt_ping,
.set_timeout = txx9wdt_set_timeout,
};
static struct watchdog_device txx9wdt = {
.info = &txx9wdt_info,
.ops = &txx9wdt_ops,
};
static int __init txx9wdt_probe(struct platform_device *dev)
{
struct resource *res;
int ret;
txx9_imclk = clk_get(NULL, "imbus_clk");
if (IS_ERR(txx9_imclk)) {
ret = PTR_ERR(txx9_imclk);
txx9_imclk = NULL;
goto exit;
}
ret = clk_enable(txx9_imclk);
if (ret) {
clk_put(txx9_imclk);
txx9_imclk = NULL;
goto exit;
}
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
txx9wdt_reg = devm_request_and_ioremap(&dev->dev, res);
if (!txx9wdt_reg) {
ret = -EBUSY;
goto exit;
}
if (timeout < 1 || timeout > WD_MAX_TIMEOUT)
timeout = TIMER_MARGIN;
txx9wdt.timeout = timeout;
txx9wdt.min_timeout = 1;
txx9wdt.max_timeout = WD_MAX_TIMEOUT;
watchdog_set_nowayout(&txx9wdt, nowayout);
ret = watchdog_register_device(&txx9wdt);
if (ret)
goto exit;
pr_info("Hardware Watchdog Timer: timeout=%d sec (max %ld) (nowayout= %d)\n",
timeout, WD_MAX_TIMEOUT, nowayout);
return 0;
exit:
if (txx9_imclk) {
clk_disable(txx9_imclk);
clk_put(txx9_imclk);
}
return ret;
}
static int __exit txx9wdt_remove(struct platform_device *dev)
{
watchdog_unregister_device(&txx9wdt);
clk_disable(txx9_imclk);
clk_put(txx9_imclk);
return 0;
}
static void txx9wdt_shutdown(struct platform_device *dev)
{
txx9wdt_stop(&txx9wdt);
}
static struct platform_driver txx9wdt_driver = {
.remove = __exit_p(txx9wdt_remove),
.shutdown = txx9wdt_shutdown,
.driver = {
.name = "txx9wdt",
.owner = THIS_MODULE,
},
};
static int __init watchdog_init(void)
{
return platform_driver_probe(&txx9wdt_driver, txx9wdt_probe);
}
static void __exit watchdog_exit(void)
{
platform_driver_unregister(&txx9wdt_driver);
}
module_init(watchdog_init);
module_exit(watchdog_exit);
MODULE_DESCRIPTION("TXx9 Watchdog Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
MODULE_ALIAS("platform:txx9wdt");
| gpl-2.0 |
iamjy/beaglebone-kernel | net/wanrouter/wanproc.c | 5336 | 9318 | /*****************************************************************************
* wanproc.c WAN Router Module. /proc filesystem interface.
*
* This module is completely hardware-independent and provides
* access to the router using Linux /proc filesystem.
*
* Author: Gideon Hack
*
* Copyright: (c) 1995-1999 Sangoma Technologies 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.
* ============================================================================
* Jun 02, 1999 Gideon Hack Updates for Linux 2.2.X kernels.
* Jun 29, 1997 Alan Cox Merged with 1.0.3 vendor code
* Jan 29, 1997 Gene Kozin v1.0.1. Implemented /proc read routines
* Jan 30, 1997 Alan Cox Hacked around for 2.1
* Dec 13, 1996 Gene Kozin Initial version (based on Sangoma's WANPIPE)
*****************************************************************************/
#include <linux/init.h> /* __initfunc et al. */
#include <linux/stddef.h> /* offsetof(), etc. */
#include <linux/errno.h> /* return codes */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/wanrouter.h> /* WAN router API definitions */
#include <linux/seq_file.h>
#include <linux/mutex.h>
#include <net/net_namespace.h>
#include <asm/io.h>
#define PROC_STATS_FORMAT "%30s: %12lu\n"
/****** Defines and Macros **************************************************/
#define PROT_DECODE(prot) ((prot == WANCONFIG_FR) ? " FR" :\
(prot == WANCONFIG_X25) ? " X25" : \
(prot == WANCONFIG_PPP) ? " PPP" : \
(prot == WANCONFIG_CHDLC) ? " CHDLC": \
(prot == WANCONFIG_MPPP) ? " MPPP" : \
" Unknown" )
/****** Function Prototypes *************************************************/
#ifdef CONFIG_PROC_FS
/* Miscellaneous */
/*
* Structures for interfacing with the /proc filesystem.
* Router creates its own directory /proc/net/router with the following
* entries:
* config device configuration
* status global device statistics
* <device> entry for each WAN device
*/
/*
* Generic /proc/net/router/<file> file and inode operations
*/
/*
* /proc/net/router
*/
static DEFINE_MUTEX(config_mutex);
static struct proc_dir_entry *proc_router;
/* Strings */
/*
* Interface functions
*/
/****** Proc filesystem entry points ****************************************/
/*
* Iterator
*/
static void *r_start(struct seq_file *m, loff_t *pos)
{
struct wan_device *wandev;
loff_t l = *pos;
mutex_lock(&config_mutex);
if (!l--)
return SEQ_START_TOKEN;
for (wandev = wanrouter_router_devlist; l-- && wandev;
wandev = wandev->next)
;
return wandev;
}
static void *r_next(struct seq_file *m, void *v, loff_t *pos)
{
struct wan_device *wandev = v;
(*pos)++;
return (v == SEQ_START_TOKEN) ? wanrouter_router_devlist : wandev->next;
}
static void r_stop(struct seq_file *m, void *v)
{
mutex_unlock(&config_mutex);
}
static int config_show(struct seq_file *m, void *v)
{
struct wan_device *p = v;
if (v == SEQ_START_TOKEN) {
seq_puts(m, "Device name | port |IRQ|DMA| mem.addr |"
"mem.size|option1|option2|option3|option4\n");
return 0;
}
if (!p->state)
return 0;
seq_printf(m, "%-15s|0x%-4X|%3u|%3u| 0x%-8lX |0x%-6X|%7u|%7u|%7u|%7u\n",
p->name, p->ioport, p->irq, p->dma, p->maddr, p->msize,
p->hw_opt[0], p->hw_opt[1], p->hw_opt[2], p->hw_opt[3]);
return 0;
}
static int status_show(struct seq_file *m, void *v)
{
struct wan_device *p = v;
if (v == SEQ_START_TOKEN) {
seq_puts(m, "Device name |protocol|station|interface|"
"clocking|baud rate| MTU |ndev|link state\n");
return 0;
}
if (!p->state)
return 0;
seq_printf(m, "%-15s|%-8s| %-7s| %-9s|%-8s|%9u|%5u|%3u |",
p->name,
PROT_DECODE(p->config_id),
p->config_id == WANCONFIG_FR ?
(p->station ? "Node" : "CPE") :
(p->config_id == WANCONFIG_X25 ?
(p->station ? "DCE" : "DTE") :
("N/A")),
p->interface ? "V.35" : "RS-232",
p->clocking ? "internal" : "external",
p->bps,
p->mtu,
p->ndev);
switch (p->state) {
case WAN_UNCONFIGURED:
seq_printf(m, "%-12s\n", "unconfigured");
break;
case WAN_DISCONNECTED:
seq_printf(m, "%-12s\n", "disconnected");
break;
case WAN_CONNECTING:
seq_printf(m, "%-12s\n", "connecting");
break;
case WAN_CONNECTED:
seq_printf(m, "%-12s\n", "connected");
break;
default:
seq_printf(m, "%-12s\n", "invalid");
break;
}
return 0;
}
static const struct seq_operations config_op = {
.start = r_start,
.next = r_next,
.stop = r_stop,
.show = config_show,
};
static const struct seq_operations status_op = {
.start = r_start,
.next = r_next,
.stop = r_stop,
.show = status_show,
};
static int config_open(struct inode *inode, struct file *file)
{
return seq_open(file, &config_op);
}
static int status_open(struct inode *inode, struct file *file)
{
return seq_open(file, &status_op);
}
static const struct file_operations config_fops = {
.owner = THIS_MODULE,
.open = config_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static const struct file_operations status_fops = {
.owner = THIS_MODULE,
.open = status_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int wandev_show(struct seq_file *m, void *v)
{
struct wan_device *wandev = m->private;
if (wandev->magic != ROUTER_MAGIC)
return 0;
if (!wandev->state) {
seq_puts(m, "device is not configured!\n");
return 0;
}
/* Update device statistics */
if (wandev->update) {
int err = wandev->update(wandev);
if (err == -EAGAIN) {
seq_puts(m, "Device is busy!\n");
return 0;
}
if (err) {
seq_puts(m, "Device is not configured!\n");
return 0;
}
}
seq_printf(m, PROC_STATS_FORMAT,
"total packets received", wandev->stats.rx_packets);
seq_printf(m, PROC_STATS_FORMAT,
"total packets transmitted", wandev->stats.tx_packets);
seq_printf(m, PROC_STATS_FORMAT,
"total bytes received", wandev->stats.rx_bytes);
seq_printf(m, PROC_STATS_FORMAT,
"total bytes transmitted", wandev->stats.tx_bytes);
seq_printf(m, PROC_STATS_FORMAT,
"bad packets received", wandev->stats.rx_errors);
seq_printf(m, PROC_STATS_FORMAT,
"packet transmit problems", wandev->stats.tx_errors);
seq_printf(m, PROC_STATS_FORMAT,
"received frames dropped", wandev->stats.rx_dropped);
seq_printf(m, PROC_STATS_FORMAT,
"transmit frames dropped", wandev->stats.tx_dropped);
seq_printf(m, PROC_STATS_FORMAT,
"multicast packets received", wandev->stats.multicast);
seq_printf(m, PROC_STATS_FORMAT,
"transmit collisions", wandev->stats.collisions);
seq_printf(m, PROC_STATS_FORMAT,
"receive length errors", wandev->stats.rx_length_errors);
seq_printf(m, PROC_STATS_FORMAT,
"receiver overrun errors", wandev->stats.rx_over_errors);
seq_printf(m, PROC_STATS_FORMAT,
"CRC errors", wandev->stats.rx_crc_errors);
seq_printf(m, PROC_STATS_FORMAT,
"frame format errors (aborts)", wandev->stats.rx_frame_errors);
seq_printf(m, PROC_STATS_FORMAT,
"receiver fifo overrun", wandev->stats.rx_fifo_errors);
seq_printf(m, PROC_STATS_FORMAT,
"receiver missed packet", wandev->stats.rx_missed_errors);
seq_printf(m, PROC_STATS_FORMAT,
"aborted frames transmitted", wandev->stats.tx_aborted_errors);
return 0;
}
static int wandev_open(struct inode *inode, struct file *file)
{
return single_open(file, wandev_show, PDE(inode)->data);
}
static const struct file_operations wandev_fops = {
.owner = THIS_MODULE,
.open = wandev_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.unlocked_ioctl = wanrouter_ioctl,
};
/*
* Initialize router proc interface.
*/
int __init wanrouter_proc_init(void)
{
struct proc_dir_entry *p;
proc_router = proc_mkdir(ROUTER_NAME, init_net.proc_net);
if (!proc_router)
goto fail;
p = proc_create("config", S_IRUGO, proc_router, &config_fops);
if (!p)
goto fail_config;
p = proc_create("status", S_IRUGO, proc_router, &status_fops);
if (!p)
goto fail_stat;
return 0;
fail_stat:
remove_proc_entry("config", proc_router);
fail_config:
remove_proc_entry(ROUTER_NAME, init_net.proc_net);
fail:
return -ENOMEM;
}
/*
* Clean up router proc interface.
*/
void wanrouter_proc_cleanup(void)
{
remove_proc_entry("config", proc_router);
remove_proc_entry("status", proc_router);
remove_proc_entry(ROUTER_NAME, init_net.proc_net);
}
/*
* Add directory entry for WAN device.
*/
int wanrouter_proc_add(struct wan_device* wandev)
{
if (wandev->magic != ROUTER_MAGIC)
return -EINVAL;
wandev->dent = proc_create(wandev->name, S_IRUGO,
proc_router, &wandev_fops);
if (!wandev->dent)
return -ENOMEM;
wandev->dent->data = wandev;
return 0;
}
/*
* Delete directory entry for WAN device.
*/
int wanrouter_proc_delete(struct wan_device* wandev)
{
if (wandev->magic != ROUTER_MAGIC)
return -EINVAL;
remove_proc_entry(wandev->name, proc_router);
return 0;
}
#else
/*
* No /proc - output stubs
*/
int __init wanrouter_proc_init(void)
{
return 0;
}
void wanrouter_proc_cleanup(void)
{
}
int wanrouter_proc_add(struct wan_device *wandev)
{
return 0;
}
int wanrouter_proc_delete(struct wan_device *wandev)
{
return 0;
}
#endif
/*
* End
*/
| gpl-2.0 |
Clouded/linux-rt-rpi2 | drivers/isdn/mISDN/dsp_dtmf.c | 5592 | 7905 | /*
* DTMF decoder.
*
* Copyright by Andreas Eversberg (jolly@eversberg.eu)
* based on different decoders such as ISDN4Linux
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/mISDNif.h>
#include <linux/mISDNdsp.h>
#include "core.h"
#include "dsp.h"
#define NCOEFF 8 /* number of frequencies to be analyzed */
/* For DTMF recognition:
* 2 * cos(2 * PI * k / N) precalculated for all k
*/
static u64 cos2pik[NCOEFF] =
{
/* k << 15 (source: hfc-4s/8s documentation (www.colognechip.de)) */
55960, 53912, 51402, 48438, 38146, 32650, 26170, 18630
};
/* digit matrix */
static char dtmf_matrix[4][4] =
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
/* dtmf detection using goertzel algorithm
* init function
*/
void dsp_dtmf_goertzel_init(struct dsp *dsp)
{
dsp->dtmf.size = 0;
dsp->dtmf.lastwhat = '\0';
dsp->dtmf.lastdigit = '\0';
dsp->dtmf.count = 0;
}
/* check for hardware or software features
*/
void dsp_dtmf_hardware(struct dsp *dsp)
{
int hardware = 1;
if (!dsp->dtmf.enable)
return;
if (!dsp->features.hfc_dtmf)
hardware = 0;
/* check for volume change */
if (dsp->tx_volume) {
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s dsp %s cannot do hardware DTMF, "
"because tx_volume is changed\n",
__func__, dsp->name);
hardware = 0;
}
if (dsp->rx_volume) {
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s dsp %s cannot do hardware DTMF, "
"because rx_volume is changed\n",
__func__, dsp->name);
hardware = 0;
}
/* check if encryption is enabled */
if (dsp->bf_enable) {
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s dsp %s cannot do hardware DTMF, "
"because encryption is enabled\n",
__func__, dsp->name);
hardware = 0;
}
/* check if pipeline exists */
if (dsp->pipeline.inuse) {
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s dsp %s cannot do hardware DTMF, "
"because pipeline exists.\n",
__func__, dsp->name);
hardware = 0;
}
dsp->dtmf.hardware = hardware;
dsp->dtmf.software = !hardware;
}
/*************************************************************
* calculate the coefficients of the given sample and decode *
*************************************************************/
/* the given sample is decoded. if the sample is not long enough for a
* complete frame, the decoding is finished and continued with the next
* call of this function.
*
* the algorithm is very good for detection with a minimum of errors. i
* tested it allot. it even works with very short tones (40ms). the only
* disadvantage is, that it doesn't work good with different volumes of both
* tones. this will happen, if accoustically coupled dialers are used.
* it sometimes detects tones during speech, which is normal for decoders.
* use sequences to given commands during calls.
*
* dtmf - points to a structure of the current dtmf state
* spl and len - the sample
* fmt - 0 = alaw, 1 = ulaw, 2 = coefficients from HFC DTMF hw-decoder
*/
u8
*dsp_dtmf_goertzel_decode(struct dsp *dsp, u8 *data, int len, int fmt)
{
u8 what;
int size;
signed short *buf;
s32 sk, sk1, sk2;
int k, n, i;
s32 *hfccoeff;
s32 result[NCOEFF], tresh, treshl;
int lowgroup, highgroup;
s64 cos2pik_;
dsp->dtmf.digits[0] = '\0';
/* Note: The function will loop until the buffer has not enough samples
* left to decode a full frame.
*/
again:
/* convert samples */
size = dsp->dtmf.size;
buf = dsp->dtmf.buffer;
switch (fmt) {
case 0: /* alaw */
case 1: /* ulaw */
while (size < DSP_DTMF_NPOINTS && len) {
buf[size++] = dsp_audio_law_to_s32[*data++];
len--;
}
break;
case 2: /* HFC coefficients */
default:
if (len < 64) {
if (len > 0)
printk(KERN_ERR "%s: coefficients have invalid "
"size. (is=%d < must=%d)\n",
__func__, len, 64);
return dsp->dtmf.digits;
}
hfccoeff = (s32 *)data;
for (k = 0; k < NCOEFF; k++) {
sk2 = (*hfccoeff++) >> 4;
sk = (*hfccoeff++) >> 4;
if (sk > 32767 || sk < -32767 || sk2 > 32767
|| sk2 < -32767)
printk(KERN_WARNING
"DTMF-Detection overflow\n");
/* compute |X(k)|**2 */
result[k] =
(sk * sk) -
(((cos2pik[k] * sk) >> 15) * sk2) +
(sk2 * sk2);
}
data += 64;
len -= 64;
goto coefficients;
break;
}
dsp->dtmf.size = size;
if (size < DSP_DTMF_NPOINTS)
return dsp->dtmf.digits;
dsp->dtmf.size = 0;
/* now we have a full buffer of signed long samples - we do goertzel */
for (k = 0; k < NCOEFF; k++) {
sk = 0;
sk1 = 0;
sk2 = 0;
buf = dsp->dtmf.buffer;
cos2pik_ = cos2pik[k];
for (n = 0; n < DSP_DTMF_NPOINTS; n++) {
sk = ((cos2pik_ * sk1) >> 15) - sk2 + (*buf++);
sk2 = sk1;
sk1 = sk;
}
sk >>= 8;
sk2 >>= 8;
if (sk > 32767 || sk < -32767 || sk2 > 32767 || sk2 < -32767)
printk(KERN_WARNING "DTMF-Detection overflow\n");
/* compute |X(k)|**2 */
result[k] =
(sk * sk) -
(((cos2pik[k] * sk) >> 15) * sk2) +
(sk2 * sk2);
}
/* our (squared) coefficients have been calculated, we need to process
* them.
*/
coefficients:
tresh = 0;
for (i = 0; i < NCOEFF; i++) {
if (result[i] < 0)
result[i] = 0;
if (result[i] > dsp->dtmf.treshold) {
if (result[i] > tresh)
tresh = result[i];
}
}
if (tresh == 0) {
what = 0;
goto storedigit;
}
if (dsp_debug & DEBUG_DSP_DTMFCOEFF) {
s32 tresh_100 = tresh/100;
if (tresh_100 == 0) {
tresh_100 = 1;
printk(KERN_DEBUG
"tresh(%d) too small set tresh/100 to 1\n",
tresh);
}
printk(KERN_DEBUG "a %3d %3d %3d %3d %3d %3d %3d %3d"
" tr:%3d r %3d %3d %3d %3d %3d %3d %3d %3d\n",
result[0] / 10000, result[1] / 10000, result[2] / 10000,
result[3] / 10000, result[4] / 10000, result[5] / 10000,
result[6] / 10000, result[7] / 10000, tresh / 10000,
result[0] / (tresh_100), result[1] / (tresh_100),
result[2] / (tresh_100), result[3] / (tresh_100),
result[4] / (tresh_100), result[5] / (tresh_100),
result[6] / (tresh_100), result[7] / (tresh_100));
}
/* calc digit (lowgroup/highgroup) */
lowgroup = -1;
highgroup = -1;
treshl = tresh >> 3; /* tones which are not on, must be below 9 dB */
tresh = tresh >> 2; /* touchtones must match within 6 dB */
for (i = 0; i < NCOEFF; i++) {
if (result[i] < treshl)
continue; /* ignore */
if (result[i] < tresh) {
lowgroup = -1;
highgroup = -1;
break; /* noise in between */
}
/* good level found. This is allowed only one time per group */
if (i < NCOEFF / 2) {
/* lowgroup */
if (lowgroup >= 0) {
/* Bad. Another tone found. */
lowgroup = -1;
break;
} else
lowgroup = i;
} else {
/* higroup */
if (highgroup >= 0) {
/* Bad. Another tone found. */
highgroup = -1;
break;
} else
highgroup = i - (NCOEFF / 2);
}
}
/* get digit or null */
what = 0;
if (lowgroup >= 0 && highgroup >= 0)
what = dtmf_matrix[lowgroup][highgroup];
storedigit:
if (what && (dsp_debug & DEBUG_DSP_DTMF))
printk(KERN_DEBUG "DTMF what: %c\n", what);
if (dsp->dtmf.lastwhat != what)
dsp->dtmf.count = 0;
/* the tone (or no tone) must remain 3 times without change */
if (dsp->dtmf.count == 2) {
if (dsp->dtmf.lastdigit != what) {
dsp->dtmf.lastdigit = what;
if (what) {
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "DTMF digit: %c\n",
what);
if ((strlen(dsp->dtmf.digits) + 1)
< sizeof(dsp->dtmf.digits)) {
dsp->dtmf.digits[strlen(
dsp->dtmf.digits) + 1] = '\0';
dsp->dtmf.digits[strlen(
dsp->dtmf.digits)] = what;
}
}
}
} else
dsp->dtmf.count++;
dsp->dtmf.lastwhat = what;
goto again;
}
| gpl-2.0 |
auras76/MM_6.0_32.1.A.1.185 | drivers/watchdog/it8712f_wdt.c | 7384 | 10237 | /*
* IT8712F "Smart Guardian" Watchdog support
*
* Copyright (c) 2006-2007 Jorge Boncompte - DTI2 <jorge@dti2.net>
*
* Based on info and code taken from:
*
* drivers/char/watchdog/scx200_wdt.c
* drivers/hwmon/it87.c
* IT8712F EC-LPC I/O Preliminary Specification 0.8.2
* IT8712F EC-LPC I/O Preliminary Specification 0.9.3
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* The author(s) of this software shall not be held liable for damages
* of any nature resulting due to the use of this software. This
* software is provided AS-IS with no warranties.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/fs.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/ioport.h>
#define DEBUG
#define NAME "it8712f_wdt"
MODULE_AUTHOR("Jorge Boncompte - DTI2 <jorge@dti2.net>");
MODULE_DESCRIPTION("IT8712F Watchdog Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
static int max_units = 255;
static int margin = 60; /* in seconds */
module_param(margin, int, 0);
MODULE_PARM_DESC(margin, "Watchdog margin in seconds");
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Disable watchdog shutdown on close");
static unsigned long wdt_open;
static unsigned expect_close;
static unsigned char revision;
/* Dog Food address - We use the game port address */
static unsigned short address;
#define REG 0x2e /* The register to read/write */
#define VAL 0x2f /* The value to read/write */
#define LDN 0x07 /* Register: Logical device select */
#define DEVID 0x20 /* Register: Device ID */
#define DEVREV 0x22 /* Register: Device Revision */
#define ACT_REG 0x30 /* LDN Register: Activation */
#define BASE_REG 0x60 /* LDN Register: Base address */
#define IT8712F_DEVID 0x8712
#define LDN_GPIO 0x07 /* GPIO and Watch Dog Timer */
#define LDN_GAME 0x09 /* Game Port */
#define WDT_CONTROL 0x71 /* WDT Register: Control */
#define WDT_CONFIG 0x72 /* WDT Register: Configuration */
#define WDT_TIMEOUT 0x73 /* WDT Register: Timeout Value */
#define WDT_RESET_GAME 0x10 /* Reset timer on read or write to game port */
#define WDT_RESET_KBD 0x20 /* Reset timer on keyboard interrupt */
#define WDT_RESET_MOUSE 0x40 /* Reset timer on mouse interrupt */
#define WDT_RESET_CIR 0x80 /* Reset timer on consumer IR interrupt */
#define WDT_UNIT_SEC 0x80 /* If 0 in MINUTES */
#define WDT_OUT_PWROK 0x10 /* Pulse PWROK on timeout */
#define WDT_OUT_KRST 0x40 /* Pulse reset on timeout */
static int wdt_control_reg = WDT_RESET_GAME;
module_param(wdt_control_reg, int, 0);
MODULE_PARM_DESC(wdt_control_reg, "Value to write to watchdog control "
"register. The default WDT_RESET_GAME resets the timer on "
"game port reads that this driver generates. You can also "
"use KBD, MOUSE or CIR if you have some external way to "
"generate those interrupts.");
static int superio_inb(int reg)
{
outb(reg, REG);
return inb(VAL);
}
static void superio_outb(int val, int reg)
{
outb(reg, REG);
outb(val, VAL);
}
static int superio_inw(int reg)
{
int val;
outb(reg++, REG);
val = inb(VAL) << 8;
outb(reg, REG);
val |= inb(VAL);
return val;
}
static inline void superio_select(int ldn)
{
outb(LDN, REG);
outb(ldn, VAL);
}
static inline int superio_enter(void)
{
/*
* Try to reserve REG and REG + 1 for exclusive access.
*/
if (!request_muxed_region(REG, 2, NAME))
return -EBUSY;
outb(0x87, REG);
outb(0x01, REG);
outb(0x55, REG);
outb(0x55, REG);
return 0;
}
static inline void superio_exit(void)
{
outb(0x02, REG);
outb(0x02, VAL);
release_region(REG, 2);
}
static inline void it8712f_wdt_ping(void)
{
if (wdt_control_reg & WDT_RESET_GAME)
inb(address);
}
static void it8712f_wdt_update_margin(void)
{
int config = WDT_OUT_KRST | WDT_OUT_PWROK;
int units = margin;
/* Switch to minutes precision if the configured margin
* value does not fit within the register width.
*/
if (units <= max_units) {
config |= WDT_UNIT_SEC; /* else UNIT is MINUTES */
pr_info("timer margin %d seconds\n", units);
} else {
units /= 60;
pr_info("timer margin %d minutes\n", units);
}
superio_outb(config, WDT_CONFIG);
if (revision >= 0x08)
superio_outb(units >> 8, WDT_TIMEOUT + 1);
superio_outb(units, WDT_TIMEOUT);
}
static int it8712f_wdt_get_status(void)
{
if (superio_inb(WDT_CONTROL) & 0x01)
return WDIOF_CARDRESET;
else
return 0;
}
static int it8712f_wdt_enable(void)
{
int ret = superio_enter();
if (ret)
return ret;
pr_debug("enabling watchdog timer\n");
superio_select(LDN_GPIO);
superio_outb(wdt_control_reg, WDT_CONTROL);
it8712f_wdt_update_margin();
superio_exit();
it8712f_wdt_ping();
return 0;
}
static int it8712f_wdt_disable(void)
{
int ret = superio_enter();
if (ret)
return ret;
pr_debug("disabling watchdog timer\n");
superio_select(LDN_GPIO);
superio_outb(0, WDT_CONFIG);
superio_outb(0, WDT_CONTROL);
if (revision >= 0x08)
superio_outb(0, WDT_TIMEOUT + 1);
superio_outb(0, WDT_TIMEOUT);
superio_exit();
return 0;
}
static int it8712f_wdt_notify(struct notifier_block *this,
unsigned long code, void *unused)
{
if (code == SYS_HALT || code == SYS_POWER_OFF)
if (!nowayout)
it8712f_wdt_disable();
return NOTIFY_DONE;
}
static struct notifier_block it8712f_wdt_notifier = {
.notifier_call = it8712f_wdt_notify,
};
static ssize_t it8712f_wdt_write(struct file *file, const char __user *data,
size_t len, loff_t *ppos)
{
/* check for a magic close character */
if (len) {
size_t i;
it8712f_wdt_ping();
expect_close = 0;
for (i = 0; i < len; ++i) {
char c;
if (get_user(c, data + i))
return -EFAULT;
if (c == 'V')
expect_close = 42;
}
}
return len;
}
static long it8712f_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = argp;
static const struct watchdog_info ident = {
.identity = "IT8712F Watchdog",
.firmware_version = 1,
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING |
WDIOF_MAGICCLOSE,
};
int value;
int ret;
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &ident, sizeof(ident)))
return -EFAULT;
return 0;
case WDIOC_GETSTATUS:
ret = superio_enter();
if (ret)
return ret;
superio_select(LDN_GPIO);
value = it8712f_wdt_get_status();
superio_exit();
return put_user(value, p);
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_KEEPALIVE:
it8712f_wdt_ping();
return 0;
case WDIOC_SETTIMEOUT:
if (get_user(value, p))
return -EFAULT;
if (value < 1)
return -EINVAL;
if (value > (max_units * 60))
return -EINVAL;
margin = value;
ret = superio_enter();
if (ret)
return ret;
superio_select(LDN_GPIO);
it8712f_wdt_update_margin();
superio_exit();
it8712f_wdt_ping();
/* Fall through */
case WDIOC_GETTIMEOUT:
if (put_user(margin, p))
return -EFAULT;
return 0;
default:
return -ENOTTY;
}
}
static int it8712f_wdt_open(struct inode *inode, struct file *file)
{
int ret;
/* only allow one at a time */
if (test_and_set_bit(0, &wdt_open))
return -EBUSY;
ret = it8712f_wdt_enable();
if (ret)
return ret;
return nonseekable_open(inode, file);
}
static int it8712f_wdt_release(struct inode *inode, struct file *file)
{
if (expect_close != 42) {
pr_warn("watchdog device closed unexpectedly, will not disable the watchdog timer\n");
} else if (!nowayout) {
if (it8712f_wdt_disable())
pr_warn("Watchdog disable failed\n");
}
expect_close = 0;
clear_bit(0, &wdt_open);
return 0;
}
static const struct file_operations it8712f_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = it8712f_wdt_write,
.unlocked_ioctl = it8712f_wdt_ioctl,
.open = it8712f_wdt_open,
.release = it8712f_wdt_release,
};
static struct miscdevice it8712f_wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &it8712f_wdt_fops,
};
static int __init it8712f_wdt_find(unsigned short *address)
{
int err = -ENODEV;
int chip_type;
int ret = superio_enter();
if (ret)
return ret;
chip_type = superio_inw(DEVID);
if (chip_type != IT8712F_DEVID)
goto exit;
superio_select(LDN_GAME);
superio_outb(1, ACT_REG);
if (!(superio_inb(ACT_REG) & 0x01)) {
pr_err("Device not activated, skipping\n");
goto exit;
}
*address = superio_inw(BASE_REG);
if (*address == 0) {
pr_err("Base address not set, skipping\n");
goto exit;
}
err = 0;
revision = superio_inb(DEVREV) & 0x0f;
/* Later revisions have 16-bit values per datasheet 0.9.1 */
if (revision >= 0x08)
max_units = 65535;
if (margin > (max_units * 60))
margin = (max_units * 60);
pr_info("Found IT%04xF chip revision %d - using DogFood address 0x%x\n",
chip_type, revision, *address);
exit:
superio_exit();
return err;
}
static int __init it8712f_wdt_init(void)
{
int err = 0;
if (it8712f_wdt_find(&address))
return -ENODEV;
if (!request_region(address, 1, "IT8712F Watchdog")) {
pr_warn("watchdog I/O region busy\n");
return -EBUSY;
}
err = it8712f_wdt_disable();
if (err) {
pr_err("unable to disable watchdog timer\n");
goto out;
}
err = register_reboot_notifier(&it8712f_wdt_notifier);
if (err) {
pr_err("unable to register reboot notifier\n");
goto out;
}
err = misc_register(&it8712f_wdt_miscdev);
if (err) {
pr_err("cannot register miscdev on minor=%d (err=%d)\n",
WATCHDOG_MINOR, err);
goto reboot_out;
}
return 0;
reboot_out:
unregister_reboot_notifier(&it8712f_wdt_notifier);
out:
release_region(address, 1);
return err;
}
static void __exit it8712f_wdt_exit(void)
{
misc_deregister(&it8712f_wdt_miscdev);
unregister_reboot_notifier(&it8712f_wdt_notifier);
release_region(address, 1);
}
module_init(it8712f_wdt_init);
module_exit(it8712f_wdt_exit);
| gpl-2.0 |
thederekjay/SGH-I727_NA | arch/um/sys-ppc/miscthings.c | 9432 | 1044 | #include "linux/threads.h"
#include "linux/stddef.h" // for NULL
#include "linux/elf.h" // for AT_NULL
/* The following function nicked from arch/ppc/kernel/process.c and
* adapted slightly */
/*
* XXX ld.so expects the auxiliary table to start on
* a 16-byte boundary, so we have to find it and
* move it up. :-(
*/
void shove_aux_table(unsigned long sp)
{
int argc;
char *p;
unsigned long e;
unsigned long aux_start, offset;
argc = *(int *)sp;
sp += sizeof(int) + (argc + 1) * sizeof(char *);
/* skip over the environment pointers */
do {
p = *(char **)sp;
sp += sizeof(char *);
} while (p != NULL);
aux_start = sp;
/* skip to the end of the auxiliary table */
do {
e = *(unsigned long *)sp;
sp += 2 * sizeof(unsigned long);
} while (e != AT_NULL);
offset = ((aux_start + 15) & ~15) - aux_start;
if (offset != 0) {
do {
sp -= sizeof(unsigned long);
e = *(unsigned long *)sp;
*(unsigned long *)(sp + offset) = e;
} while (sp > aux_start);
}
}
/* END stuff taken from arch/ppc/kernel/process.c */
| gpl-2.0 |
drewx2/Find5-Kernel-Source | drivers/usb/host/whci/wusb.c | 12504 | 5554 | /*
* Wireless Host Controller (WHC) WUSB operations.
*
* Copyright (C) 2007 Cambridge Silicon Radio Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/uwb/umc.h>
#include "../../wusbcore/wusbhc.h"
#include "whcd.h"
static int whc_update_di(struct whc *whc, int idx)
{
int offset = idx / 32;
u32 bit = 1 << (idx % 32);
le_writel(bit, whc->base + WUSBDIBUPDATED + offset);
return whci_wait_for(&whc->umc->dev,
whc->base + WUSBDIBUPDATED + offset, bit, 0,
100, "DI update");
}
/*
* WHCI starts MMCs based on there being a valid GTK so these need
* only start/stop the asynchronous and periodic schedules and send a
* channel stop command.
*/
int whc_wusbhc_start(struct wusbhc *wusbhc)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
asl_start(whc);
pzl_start(whc);
return 0;
}
void whc_wusbhc_stop(struct wusbhc *wusbhc, int delay)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
u32 stop_time, now_time;
int ret;
pzl_stop(whc);
asl_stop(whc);
now_time = le_readl(whc->base + WUSBTIME) & WUSBTIME_CHANNEL_TIME_MASK;
stop_time = (now_time + ((delay * 8) << 7)) & 0x00ffffff;
ret = whc_do_gencmd(whc, WUSBGENCMDSTS_CHAN_STOP, stop_time, NULL, 0);
if (ret == 0)
msleep(delay);
}
int whc_mmcie_add(struct wusbhc *wusbhc, u8 interval, u8 repeat_cnt,
u8 handle, struct wuie_hdr *wuie)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
u32 params;
params = (interval << 24)
| (repeat_cnt << 16)
| (wuie->bLength << 8)
| handle;
return whc_do_gencmd(whc, WUSBGENCMDSTS_MMCIE_ADD, params, wuie, wuie->bLength);
}
int whc_mmcie_rm(struct wusbhc *wusbhc, u8 handle)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
u32 params;
params = handle;
return whc_do_gencmd(whc, WUSBGENCMDSTS_MMCIE_RM, params, NULL, 0);
}
int whc_bwa_set(struct wusbhc *wusbhc, s8 stream_index, const struct uwb_mas_bm *mas_bm)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
if (stream_index >= 0)
whc_write_wusbcmd(whc, WUSBCMD_WUSBSI_MASK, WUSBCMD_WUSBSI(stream_index));
return whc_do_gencmd(whc, WUSBGENCMDSTS_SET_MAS, 0, (void *)mas_bm, sizeof(*mas_bm));
}
int whc_dev_info_set(struct wusbhc *wusbhc, struct wusb_dev *wusb_dev)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
int idx = wusb_dev->port_idx;
struct di_buf_entry *di = &whc->di_buf[idx];
int ret;
mutex_lock(&whc->mutex);
uwb_mas_bm_copy_le(di->availability_info, &wusb_dev->availability);
di->addr_sec_info &= ~(WHC_DI_DISABLE | WHC_DI_DEV_ADDR_MASK);
di->addr_sec_info |= WHC_DI_DEV_ADDR(wusb_dev->addr);
ret = whc_update_di(whc, idx);
mutex_unlock(&whc->mutex);
return ret;
}
/*
* Set the number of Device Notification Time Slots (DNTS) and enable
* device notifications.
*/
int whc_set_num_dnts(struct wusbhc *wusbhc, u8 interval, u8 slots)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
u32 dntsctrl;
dntsctrl = WUSBDNTSCTRL_ACTIVE
| WUSBDNTSCTRL_INTERVAL(interval)
| WUSBDNTSCTRL_SLOTS(slots);
le_writel(dntsctrl, whc->base + WUSBDNTSCTRL);
return 0;
}
static int whc_set_key(struct whc *whc, u8 key_index, uint32_t tkid,
const void *key, size_t key_size, bool is_gtk)
{
uint32_t setkeycmd;
uint32_t seckey[4];
int i;
int ret;
memcpy(seckey, key, key_size);
setkeycmd = WUSBSETSECKEYCMD_SET | WUSBSETSECKEYCMD_IDX(key_index);
if (is_gtk)
setkeycmd |= WUSBSETSECKEYCMD_GTK;
le_writel(tkid, whc->base + WUSBTKID);
for (i = 0; i < 4; i++)
le_writel(seckey[i], whc->base + WUSBSECKEY + 4*i);
le_writel(setkeycmd, whc->base + WUSBSETSECKEYCMD);
ret = whci_wait_for(&whc->umc->dev, whc->base + WUSBSETSECKEYCMD,
WUSBSETSECKEYCMD_SET, 0, 100, "set key");
return ret;
}
/**
* whc_set_ptk - set the PTK to use for a device.
*
* The index into the key table for this PTK is the same as the
* device's port index.
*/
int whc_set_ptk(struct wusbhc *wusbhc, u8 port_idx, u32 tkid,
const void *ptk, size_t key_size)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
struct di_buf_entry *di = &whc->di_buf[port_idx];
int ret;
mutex_lock(&whc->mutex);
if (ptk) {
ret = whc_set_key(whc, port_idx, tkid, ptk, key_size, false);
if (ret)
goto out;
di->addr_sec_info &= ~WHC_DI_KEY_IDX_MASK;
di->addr_sec_info |= WHC_DI_SECURE | WHC_DI_KEY_IDX(port_idx);
} else
di->addr_sec_info &= ~WHC_DI_SECURE;
ret = whc_update_di(whc, port_idx);
out:
mutex_unlock(&whc->mutex);
return ret;
}
/**
* whc_set_gtk - set the GTK for subsequent broadcast packets
*
* The GTK is stored in the last entry in the key table (the previous
* N_DEVICES entries are for the per-device PTKs).
*/
int whc_set_gtk(struct wusbhc *wusbhc, u32 tkid,
const void *gtk, size_t key_size)
{
struct whc *whc = wusbhc_to_whc(wusbhc);
int ret;
mutex_lock(&whc->mutex);
ret = whc_set_key(whc, whc->n_devices, tkid, gtk, key_size, true);
mutex_unlock(&whc->mutex);
return ret;
}
int whc_set_cluster_id(struct whc *whc, u8 bcid)
{
whc_write_wusbcmd(whc, WUSBCMD_BCID_MASK, WUSBCMD_BCID(bcid));
return 0;
}
| gpl-2.0 |
groeck/linux | fs/freevxfs/vxfs_immed.c | 13528 | 3556 | /*
* Copyright (c) 2000-2001 Christoph Hellwig.
* 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,
* without modification.
* 2. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL").
*
* 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.
*/
/*
* Veritas filesystem driver - support for 'immed' inodes.
*/
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/namei.h>
#include "vxfs.h"
#include "vxfs_extern.h"
#include "vxfs_inode.h"
static void * vxfs_immed_follow_link(struct dentry *, struct nameidata *);
static int vxfs_immed_readpage(struct file *, struct page *);
/*
* Inode operations for immed symlinks.
*
* Unliked all other operations we do not go through the pagecache,
* but do all work directly on the inode.
*/
const struct inode_operations vxfs_immed_symlink_iops = {
.readlink = generic_readlink,
.follow_link = vxfs_immed_follow_link,
};
/*
* Address space operations for immed files and directories.
*/
const struct address_space_operations vxfs_immed_aops = {
.readpage = vxfs_immed_readpage,
};
/**
* vxfs_immed_follow_link - follow immed symlink
* @dp: dentry for the link
* @np: pathname lookup data for the current path walk
*
* Description:
* vxfs_immed_follow_link restarts the pathname lookup with
* the data obtained from @dp.
*
* Returns:
* Zero on success, else a negative error code.
*/
static void *
vxfs_immed_follow_link(struct dentry *dp, struct nameidata *np)
{
struct vxfs_inode_info *vip = VXFS_INO(dp->d_inode);
nd_set_link(np, vip->vii_immed.vi_immed);
return NULL;
}
/**
* vxfs_immed_readpage - read part of an immed inode into pagecache
* @file: file context (unused)
* @page: page frame to fill in.
*
* Description:
* vxfs_immed_readpage reads a part of the immed area of the
* file that hosts @pp into the pagecache.
*
* Returns:
* Zero on success, else a negative error code.
*
* Locking status:
* @page is locked and will be unlocked.
*/
static int
vxfs_immed_readpage(struct file *fp, struct page *pp)
{
struct vxfs_inode_info *vip = VXFS_INO(pp->mapping->host);
u_int64_t offset = (u_int64_t)pp->index << PAGE_CACHE_SHIFT;
caddr_t kaddr;
kaddr = kmap(pp);
memcpy(kaddr, vip->vii_immed.vi_immed + offset, PAGE_CACHE_SIZE);
kunmap(pp);
flush_dcache_page(pp);
SetPageUptodate(pp);
unlock_page(pp);
return 0;
}
| gpl-2.0 |
olicmoon/linux | tools/lib/api/fs/debugfs.c | 217 | 3108 | #define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/vfs.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <linux/kernel.h>
#include "debugfs.h"
#include "tracefs.h"
#ifndef DEBUGFS_DEFAULT_PATH
#define DEBUGFS_DEFAULT_PATH "/sys/kernel/debug"
#endif
char debugfs_mountpoint[PATH_MAX + 1] = DEBUGFS_DEFAULT_PATH;
static const char * const debugfs_known_mountpoints[] = {
DEBUGFS_DEFAULT_PATH,
"/debug",
0,
};
static bool debugfs_found;
bool debugfs_configured(void)
{
return debugfs_find_mountpoint() != NULL;
}
/* find the path to the mounted debugfs */
const char *debugfs_find_mountpoint(void)
{
const char *ret;
if (debugfs_found)
return (const char *)debugfs_mountpoint;
ret = find_mountpoint("debugfs", (long) DEBUGFS_MAGIC,
debugfs_mountpoint, PATH_MAX + 1,
debugfs_known_mountpoints);
if (ret)
debugfs_found = true;
return ret;
}
/* mount the debugfs somewhere if it's not mounted */
char *debugfs_mount(const char *mountpoint)
{
/* see if it's already mounted */
if (debugfs_find_mountpoint())
goto out;
/* if not mounted and no argument */
if (mountpoint == NULL) {
/* see if environment variable set */
mountpoint = getenv(PERF_DEBUGFS_ENVIRONMENT);
/* if no environment variable, use default */
if (mountpoint == NULL)
mountpoint = DEBUGFS_DEFAULT_PATH;
}
if (mount(NULL, mountpoint, "debugfs", 0, NULL) < 0)
return NULL;
/* save the mountpoint */
debugfs_found = true;
strncpy(debugfs_mountpoint, mountpoint, sizeof(debugfs_mountpoint));
out:
return debugfs_mountpoint;
}
int debugfs__strerror_open(int err, char *buf, size_t size, const char *filename)
{
char sbuf[128];
switch (err) {
case ENOENT:
if (debugfs_found) {
snprintf(buf, size,
"Error:\tFile %s/%s not found.\n"
"Hint:\tPerhaps this kernel misses some CONFIG_ setting to enable this feature?.\n",
debugfs_mountpoint, filename);
break;
}
snprintf(buf, size, "%s",
"Error:\tUnable to find debugfs\n"
"Hint:\tWas your kernel compiled with debugfs support?\n"
"Hint:\tIs the debugfs filesystem mounted?\n"
"Hint:\tTry 'sudo mount -t debugfs nodev /sys/kernel/debug'");
break;
case EACCES: {
const char *mountpoint = debugfs_mountpoint;
if (!access(debugfs_mountpoint, R_OK) && strncmp(filename, "tracing/", 8) == 0) {
const char *tracefs_mntpoint = tracefs_find_mountpoint();
if (tracefs_mntpoint)
mountpoint = tracefs_mntpoint;
}
snprintf(buf, size,
"Error:\tNo permissions to read %s/%s\n"
"Hint:\tTry 'sudo mount -o remount,mode=755 %s'\n",
debugfs_mountpoint, filename, mountpoint);
}
break;
default:
snprintf(buf, size, "%s", strerror_r(err, sbuf, sizeof(sbuf)));
break;
}
return 0;
}
int debugfs__strerror_open_tp(int err, char *buf, size_t size, const char *sys, const char *name)
{
char path[PATH_MAX];
snprintf(path, PATH_MAX, "tracing/events/%s/%s", sys, name ?: "*");
return debugfs__strerror_open(err, buf, size, path);
}
| gpl-2.0 |
iamroot12D/linux | drivers/usb/host/xhci-plat.c | 217 | 7304 | /*
* xhci-plat.c - xHCI host controller driver platform Bus Glue.
*
* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com
* Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de>
*
* A lot of code borrowed from the Linux xHCI driver.
*
* 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/clk.h>
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/usb/phy.h>
#include <linux/slab.h>
#include <linux/usb/xhci_pdriver.h>
#include "xhci.h"
#include "xhci-mvebu.h"
#include "xhci-rcar.h"
static struct hc_driver __read_mostly xhci_plat_hc_driver;
static void xhci_plat_quirks(struct device *dev, struct xhci_hcd *xhci)
{
/*
* As of now platform drivers don't provide MSI support so we ensure
* here that the generic code does not try to make a pci_dev from our
* dev struct in order to setup MSI
*/
xhci->quirks |= XHCI_PLAT;
}
/* called during probe() after chip reset completes */
static int xhci_plat_setup(struct usb_hcd *hcd)
{
struct device_node *of_node = hcd->self.controller->of_node;
int ret;
if (of_device_is_compatible(of_node, "renesas,xhci-r8a7790") ||
of_device_is_compatible(of_node, "renesas,xhci-r8a7791")) {
ret = xhci_rcar_init_quirk(hcd);
if (ret)
return ret;
}
return xhci_gen_setup(hcd, xhci_plat_quirks);
}
static int xhci_plat_start(struct usb_hcd *hcd)
{
struct device_node *of_node = hcd->self.controller->of_node;
if (of_device_is_compatible(of_node, "renesas,xhci-r8a7790") ||
of_device_is_compatible(of_node, "renesas,xhci-r8a7791"))
xhci_rcar_start(hcd);
return xhci_run(hcd);
}
static int xhci_plat_probe(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct usb_xhci_pdata *pdata = dev_get_platdata(&pdev->dev);
const struct hc_driver *driver;
struct xhci_hcd *xhci;
struct resource *res;
struct usb_hcd *hcd;
struct clk *clk;
int ret;
int irq;
if (usb_disabled())
return -ENODEV;
driver = &xhci_plat_hc_driver;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return -ENODEV;
/* Initialize dma_mask and coherent_dma_mask to 32-bits */
ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
if (ret)
return ret;
if (!pdev->dev.dma_mask)
pdev->dev.dma_mask = &pdev->dev.coherent_dma_mask;
else
dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
hcd = usb_create_hcd(driver, &pdev->dev, dev_name(&pdev->dev));
if (!hcd)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
hcd->regs = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(hcd->regs)) {
ret = PTR_ERR(hcd->regs);
goto put_hcd;
}
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
/*
* Not all platforms have a clk so it is not an error if the
* clock does not exists.
*/
clk = devm_clk_get(&pdev->dev, NULL);
if (!IS_ERR(clk)) {
ret = clk_prepare_enable(clk);
if (ret)
goto put_hcd;
}
if (of_device_is_compatible(pdev->dev.of_node,
"marvell,armada-375-xhci") ||
of_device_is_compatible(pdev->dev.of_node,
"marvell,armada-380-xhci")) {
ret = xhci_mvebu_mbus_init_quirk(pdev);
if (ret)
goto disable_clk;
}
ret = usb_add_hcd(hcd, irq, IRQF_SHARED);
if (ret)
goto disable_clk;
device_wakeup_enable(hcd->self.controller);
/* USB 2.0 roothub is stored in the platform_device now. */
hcd = platform_get_drvdata(pdev);
xhci = hcd_to_xhci(hcd);
xhci->clk = clk;
xhci->shared_hcd = usb_create_shared_hcd(driver, &pdev->dev,
dev_name(&pdev->dev), hcd);
if (!xhci->shared_hcd) {
ret = -ENOMEM;
goto dealloc_usb2_hcd;
}
if ((node && of_property_read_bool(node, "usb3-lpm-capable")) ||
(pdata && pdata->usb3_lpm_capable))
xhci->quirks |= XHCI_LPM_SUPPORT;
/*
* Set the xHCI pointer before xhci_plat_setup() (aka hcd_driver.reset)
* is called by usb_add_hcd().
*/
*((struct xhci_hcd **) xhci->shared_hcd->hcd_priv) = xhci;
if (HCC_MAX_PSA(xhci->hcc_params) >= 4)
xhci->shared_hcd->can_do_streams = 1;
hcd->usb_phy = devm_usb_get_phy_by_phandle(&pdev->dev, "usb-phy", 0);
if (IS_ERR(hcd->usb_phy)) {
ret = PTR_ERR(hcd->usb_phy);
if (ret == -EPROBE_DEFER)
goto put_usb3_hcd;
hcd->usb_phy = NULL;
} else {
ret = usb_phy_init(hcd->usb_phy);
if (ret)
goto put_usb3_hcd;
}
ret = usb_add_hcd(xhci->shared_hcd, irq, IRQF_SHARED);
if (ret)
goto disable_usb_phy;
return 0;
disable_usb_phy:
usb_phy_shutdown(hcd->usb_phy);
put_usb3_hcd:
usb_put_hcd(xhci->shared_hcd);
dealloc_usb2_hcd:
usb_remove_hcd(hcd);
disable_clk:
if (!IS_ERR(clk))
clk_disable_unprepare(clk);
put_hcd:
usb_put_hcd(hcd);
return ret;
}
static int xhci_plat_remove(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
struct clk *clk = xhci->clk;
usb_remove_hcd(xhci->shared_hcd);
usb_phy_shutdown(hcd->usb_phy);
usb_put_hcd(xhci->shared_hcd);
usb_remove_hcd(hcd);
if (!IS_ERR(clk))
clk_disable_unprepare(clk);
usb_put_hcd(hcd);
kfree(xhci);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int xhci_plat_suspend(struct device *dev)
{
struct usb_hcd *hcd = dev_get_drvdata(dev);
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
/*
* xhci_suspend() needs `do_wakeup` to know whether host is allowed
* to do wakeup during suspend. Since xhci_plat_suspend is currently
* only designed for system suspend, device_may_wakeup() is enough
* to dertermine whether host is allowed to do wakeup. Need to
* reconsider this when xhci_plat_suspend enlarges its scope, e.g.,
* also applies to runtime suspend.
*/
return xhci_suspend(xhci, device_may_wakeup(dev));
}
static int xhci_plat_resume(struct device *dev)
{
struct usb_hcd *hcd = dev_get_drvdata(dev);
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
return xhci_resume(xhci, 0);
}
static const struct dev_pm_ops xhci_plat_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(xhci_plat_suspend, xhci_plat_resume)
};
#define DEV_PM_OPS (&xhci_plat_pm_ops)
#else
#define DEV_PM_OPS NULL
#endif /* CONFIG_PM */
#ifdef CONFIG_OF
static const struct of_device_id usb_xhci_of_match[] = {
{ .compatible = "generic-xhci" },
{ .compatible = "xhci-platform" },
{ .compatible = "marvell,armada-375-xhci"},
{ .compatible = "marvell,armada-380-xhci"},
{ .compatible = "renesas,xhci-r8a7790"},
{ .compatible = "renesas,xhci-r8a7791"},
{ },
};
MODULE_DEVICE_TABLE(of, usb_xhci_of_match);
#endif
static struct platform_driver usb_xhci_driver = {
.probe = xhci_plat_probe,
.remove = xhci_plat_remove,
.driver = {
.name = "xhci-hcd",
.pm = DEV_PM_OPS,
.of_match_table = of_match_ptr(usb_xhci_of_match),
},
};
MODULE_ALIAS("platform:xhci-hcd");
static int __init xhci_plat_init(void)
{
xhci_init_driver(&xhci_plat_hc_driver, xhci_plat_setup);
xhci_plat_hc_driver.start = xhci_plat_start;
return platform_driver_register(&usb_xhci_driver);
}
module_init(xhci_plat_init);
static void __exit xhci_plat_exit(void)
{
platform_driver_unregister(&usb_xhci_driver);
}
module_exit(xhci_plat_exit);
MODULE_DESCRIPTION("xHCI Platform Host Controller Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
guylamar2006/android_kernel_samsung_smdk4412 | drivers/hwmon/hwmon.c | 473 | 11380 | /*
hwmon.c - part of lm_sensors, Linux kernel modules for hardware monitoring
This file defines the sysfs class "hwmon", for use by sensors drivers.
Copyright (C) 2005 Mark M. Hoffman <mhoffman@lightlink.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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/kdev_t.h>
#include <linux/idr.h>
#include <linux/hwmon.h>
#include <linux/gfp.h>
#include <linux/spinlock.h>
#include <linux/pci.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#define HWMON_ID_PREFIX "hwmon"
#define HWMON_ID_FORMAT HWMON_ID_PREFIX "%d"
static struct class *hwmon_class;
static DEFINE_IDR(hwmon_idr);
static DEFINE_SPINLOCK(idr_lock);
struct hwmon_property {
struct list_head node;
const struct attribute *attr;
struct hwmon_property_head *head;
};
struct hwmon_property_head {
struct mutex lock;
struct list_head head;
};
/**
* hwmon_device_register - register w/ hwmon
* @dev: the device to register
*
* hwmon_device_unregister() must be called when the device is no
* longer needed.
*
* Returns the pointer to the new device.
*/
struct device *hwmon_device_register(struct device *dev)
{
struct device *hwdev;
int id, err;
struct hwmon_property_head *data;
again:
if (unlikely(idr_pre_get(&hwmon_idr, GFP_KERNEL) == 0))
return ERR_PTR(-ENOMEM);
spin_lock(&idr_lock);
err = idr_get_new(&hwmon_idr, NULL, &id);
spin_unlock(&idr_lock);
if (unlikely(err == -EAGAIN))
goto again;
else if (unlikely(err))
return ERR_PTR(err);
id = id & MAX_ID_MASK;
hwdev = device_create(hwmon_class, dev, MKDEV(0, 0), NULL,
HWMON_ID_FORMAT, id);
if (IS_ERR(hwdev)) {
spin_lock(&idr_lock);
idr_remove(&hwmon_idr, id);
spin_unlock(&idr_lock);
goto out;
}
data = kzalloc(sizeof(struct hwmon_property_head), GFP_KERNEL);
if (data == NULL)
return ERR_PTR(-ENOMEM);
INIT_LIST_HEAD(&data->head);
mutex_init(&data->lock);
dev_set_drvdata(hwdev, data);
out:
return hwdev;
}
static inline void _hwmon_free_prop(struct hwmon_property *prop)
{
list_del(&prop->node);
prop->attr = NULL;
prop->head = NULL;
kfree(prop);
}
/**
* hwmon_unregister_all_properties - removes every property registered
*
* @hwmon: the class device to unregister sysfs properties.
*/
void hwmon_unregister_all_properties(struct device *hwmon)
{
struct hwmon_property_head *data = dev_get_drvdata(hwmon);
struct hwmon_property *pos, *tmp;
mutex_lock(&data->lock);
list_for_each_entry_safe(pos, tmp, &data->head, node) {
_hwmon_free_prop(pos);
}
mutex_unlock(&data->lock);
}
/**
* hwmon_device_unregister - removes the previously registered class device
*
* @dev: the class device to destroy
*/
void hwmon_device_unregister(struct device *dev)
{
int id;
struct hwmon_property_head *data = dev_get_drvdata(dev);
hwmon_unregister_all_properties(dev);
mutex_destroy(&data->lock);
kfree(data);
if (likely(sscanf(dev_name(dev), HWMON_ID_FORMAT, &id) == 1)) {
device_unregister(dev);
spin_lock(&idr_lock);
idr_remove(&hwmon_idr, id);
spin_unlock(&idr_lock);
} else
dev_dbg(dev->parent,
"hwmon_device_unregister() failed: bad class ID!\n");
}
/**
* hwmon_register_property - register one sysfs entry for hwmon framework
*
* @hwmon: the class device
* @attr: a sysfs entry to be registered.
*/
struct hwmon_property *hwmon_register_property(struct device *hwmon,
const struct device_attribute *attr)
{
struct hwmon_property_head *data = dev_get_drvdata(hwmon);
struct hwmon_property *entry;
entry = kzalloc(sizeof(struct hwmon_property), GFP_KERNEL);
if (!entry)
return ERR_PTR(-ENOMEM);
mutex_lock(&data->lock);
entry->head = data;
entry->attr = &attr->attr;
list_add_tail(&entry->node, &data->head);
mutex_unlock(&data->lock);
return entry;
}
/**
* hwmon_unregister_property - unregister the sysfs entry registered to hwmon
*
* @hwmon: the class device
* @prop: hwmon_property entry to be unregistered
*
* Note that hwmon_device_unregister automatically unregister every property.
*/
int hwmon_unregister_property(struct device *hwmon,
struct hwmon_property *prop)
{
struct hwmon_property_head *data = dev_get_drvdata(hwmon);
struct hwmon_property *pos, *tmp;
int err = -EINVAL;
if (prop == NULL)
return -EINVAL;
if (!prop->attr || !prop->node.next || !prop->node.prev)
return -EINVAL;
mutex_lock(&data->lock);
list_for_each_entry_safe(pos, tmp, &data->head, node) {
if (prop == pos) {
_hwmon_free_prop(pos);
err = 0;
break;
}
}
mutex_unlock(&data->lock);
return err;
}
/**
* hwmon_register_properties - register a group of sysfs attributes
*
* @hwmon: hwmon class device to register sysfs entries.
* @attrs: a sysfs attribute group to be registered.
*/
int hwmon_register_properties(struct device *hwmon,
const struct attribute_group *attrs)
{
int i = 0, j, err = 0;
struct attribute **_attrs;
struct hwmon_property *prop;
struct hwmon_property_head *data = dev_get_drvdata(hwmon);
if (!attrs)
return -EINVAL;
_attrs = attrs->attrs;
if (!_attrs)
return -EINVAL;
mutex_lock(&data->lock);
while (_attrs[i]) {
prop = kzalloc(sizeof(struct hwmon_property), GFP_KERNEL);
if (!prop) {
err = -ENOMEM;
break;
}
prop->head = data;
prop->attr = _attrs[i];
list_add_tail(&prop->node, &data->head);
i++;
}
if (err && i > 0) {
struct hwmon_property *pos, *tmp;
/* nodes are added to tail. remove from head */
j = 0;
list_for_each_entry_safe(pos, tmp, &data->head, node) {
if (pos->attr == _attrs[j]) {
_hwmon_free_prop(pos);
j++;
if (j >= i)
break;
}
}
}
mutex_unlock(&data->lock);
return err;
}
/**
* hwmon_unregister_properties - unregister a group of attributes registered
*
* @hwmon: hwmon class device to register sysfs entries.
* @attrs: a sysfs attribute group to be unregistered.
*
* Note that hwmon_device_unregister automatically unregister every property.
*/
int hwmon_unregister_properties(struct device *hwmon,
const struct attribute_group *attrs)
{
struct hwmon_property_head *data = dev_get_drvdata(hwmon);
struct attribute **_attrs;
struct hwmon_property *pos, *tmp;
int i = 0;
if (!attrs)
return -EINVAL;
_attrs = attrs->attrs;
if (!_attrs)
return -EINVAL;
mutex_lock(&data->lock);
/*
* Assuming that hwmon_register_properties was used, try to
* remove in the inserted order first.
*/
list_for_each_entry_safe(pos, tmp, &data->head, node) {
if (_attrs[i] == NULL)
break;
if (pos->attr == _attrs[i]) {
_hwmon_free_prop(pos);
i++;
}
}
/* If it wasn't inserted in the order of attrs */
while (_attrs[i]) {
list_for_each_entry_safe(pos, tmp, &data->head, node) {
if (pos->attr == _attrs[i]) {
_hwmon_free_prop(pos);
break;
}
}
i++;
}
mutex_unlock(&data->lock);
return 0;
}
/**
* hwmon_get_property - get hwmon property based on an LMSENSOR sysfs name.
*
* @hwmon - hwmon class device
* @name - LMSENSOR sysfs name (e.g., "temp1_input")
*/
struct hwmon_property *hwmon_get_property(struct device *hwmon,
const char *name)
{
struct hwmon_property_head *data = dev_get_drvdata(hwmon);
struct hwmon_property *pos;
mutex_lock(&data->lock);
list_for_each_entry(pos, &data->head, node) {
if (!strcmp(name, pos->attr->name))
goto out;
}
pos = ERR_PTR(-EINVAL);
out:
mutex_unlock(&data->lock);
return pos;
}
/**
* hwmon_get_value - get the sysfs entry value of the hwmon device.
*
* @hwmon - hwmon class device
* @prop - hwmon property (use hwmon_get_property() to get one)
* @value - integer value from prop.
*/
int hwmon_get_value(struct device *hwmon, struct hwmon_property *prop,
int *value)
{
int err = -EINVAL;
struct device_attribute *devattr;
char buf[13]; /* 32b int max string length = 12 */
if (!prop || !prop->attr || !prop->head)
return -EINVAL;
mutex_lock(&prop->head->lock);
devattr = container_of(prop->attr, struct device_attribute, attr);
if (!devattr->show)
goto out;
err = devattr->show(hwmon->parent, devattr, buf);
if (strnlen(buf, 13) >= 13) {
err = -EINVAL;
goto out;
}
err = sscanf(buf, "%d", value);
if (err >= 0)
err = 0;
out:
mutex_unlock(&prop->head->lock);
return err;
}
EXPORT_SYMBOL_GPL(hwmon_get_value);
/**
* hwmon_set_value - set the sysfs entry value of the hwmon device.
*
* @hwmon - hwmon class device
* @prop - hwmon property (use hwmon_get_property() to get one)
* @value - integer value to set prop
*/
int hwmon_set_value(struct device *hwmon, struct hwmon_property *prop,
int value)
{
int err = -EINVAL, count;
struct device_attribute *devattr;
char buf[13]; /* 32b int max string length = 12 */
if (!prop || !prop->attr || !prop->head)
return -EINVAL;
mutex_lock(&prop->head->lock);
devattr = container_of(prop->attr, struct device_attribute, attr);
if (!devattr->store)
goto out;
count = snprintf(buf, 13, "%d\n", value);
err = devattr->store(hwmon->parent, devattr, buf, count);
out:
mutex_unlock(&prop->head->lock);
return err;
}
EXPORT_SYMBOL_GPL(hwmon_set_value);
static int hwmon_dev_match(struct device *dev, void *data)
{
if (dev->class == hwmon_class)
return 1;
return 0;
}
/**
* hwmon_find_device - find the hwmon device of the given device
*
* @dev - a parent device of a hwmon class device
*/
struct device *hwmon_find_device(struct device *dev)
{
return device_find_child(dev, NULL, hwmon_dev_match);
}
static int hwmon_parent_name_match(struct device *dev, void *data)
{
char *devname = data;
if (!strcmp(dev_name(dev->parent), devname))
return 1;
return 0;
}
/**
* hwmon_find_device_name - find the hwmon device with device name
*
* @name - device name of the parent device of a hwmon class device
*/
struct device *hwmon_find_device_name(char *devname)
{
return class_find_device(hwmon_class, NULL, devname,
hwmon_parent_name_match);
}
static void __init hwmon_pci_quirks(void)
{
#if defined CONFIG_X86 && defined CONFIG_PCI
struct pci_dev *sb;
u16 base;
u8 enable;
/* Open access to 0x295-0x296 on MSI MS-7031 */
sb = pci_get_device(PCI_VENDOR_ID_ATI, 0x436c, NULL);
if (sb &&
(sb->subsystem_vendor == 0x1462 && /* MSI */
sb->subsystem_device == 0x0031)) { /* MS-7031 */
pci_read_config_byte(sb, 0x48, &enable);
pci_read_config_word(sb, 0x64, &base);
if (base == 0 && !(enable & BIT(2))) {
dev_info(&sb->dev,
"Opening wide generic port at 0x295\n");
pci_write_config_word(sb, 0x64, 0x295);
pci_write_config_byte(sb, 0x48, enable | BIT(2));
}
}
#endif
}
static int __init hwmon_init(void)
{
hwmon_pci_quirks();
hwmon_class = class_create(THIS_MODULE, "hwmon");
if (IS_ERR(hwmon_class)) {
pr_err("couldn't create sysfs class\n");
return PTR_ERR(hwmon_class);
}
return 0;
}
static void __exit hwmon_exit(void)
{
class_destroy(hwmon_class);
}
subsys_initcall(hwmon_init);
module_exit(hwmon_exit);
EXPORT_SYMBOL_GPL(hwmon_device_register);
EXPORT_SYMBOL_GPL(hwmon_device_unregister);
MODULE_AUTHOR("Mark M. Hoffman <mhoffman@lightlink.com>");
MODULE_DESCRIPTION("hardware monitoring sysfs/class support");
MODULE_LICENSE("GPL");
| gpl-2.0 |
FlorinPetriuc/linux-1-moved-to-OpenChannelSSD-linux-nba_target | drivers/scsi/eata_pio.c | 985 | 26673 | /************************************************************
* *
* Linux EATA SCSI PIO driver *
* *
* based on the CAM document CAM/89-004 rev. 2.0c, *
* DPT's driver kit, some internal documents and source, *
* and several other Linux scsi drivers and kernel docs. *
* *
* The driver currently: *
* -supports all EATA-PIO boards *
* -only supports DASD devices *
* *
* (c)1993-96 Michael Neuffer, Alfred Arnold *
* neuffer@goofy.zdv.uni-mainz.de *
* a.arnold@kfa-juelich.de *
* *
* Updated 2002 by Alan Cox <alan@lxorguk.ukuu.org.uk> for *
* Linux 2.5.x and the newer locking and error handling *
* *
* 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 kernel; if not, write to *
* the Free Software Foundation, Inc., 675 Mass Ave, *
* Cambridge, MA 02139, USA. *
* *
* For the avoidance of doubt the "preferred form" of this *
* code is one which is in an open non patent encumbered *
* format. Where cryptographic key signing forms part of *
* the process of creating an executable the information *
* including keys needed to generate an equivalently *
* functional executable are deemed to be part of the *
* source code are deemed to be part of the source code. *
* *
************************************************************
* last change: 2002/11/02 OS: Linux 2.5.45 *
************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/pci.h>
#include <linux/proc_fs.h>
#include <linux/interrupt.h>
#include <linux/blkdev.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include "eata_generic.h"
#include "eata_pio.h"
static unsigned int ISAbases[MAXISA] = {
0x1F0, 0x170, 0x330, 0x230
};
static unsigned int ISAirqs[MAXISA] = {
14, 12, 15, 11
};
static unsigned char EISAbases[] = {
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1
};
static unsigned int registered_HBAs;
static struct Scsi_Host *last_HBA;
static struct Scsi_Host *first_HBA;
static unsigned char reg_IRQ[16];
static unsigned char reg_IRQL[16];
static unsigned long int_counter;
static unsigned long queue_counter;
static struct scsi_host_template driver_template;
static int eata_pio_show_info(struct seq_file *m, struct Scsi_Host *shost)
{
seq_printf(m, "EATA (Extended Attachment) PIO driver version: "
"%d.%d%s\n",VER_MAJOR, VER_MINOR, VER_SUB);
seq_printf(m, "queued commands: %10ld\n"
"processed interrupts:%10ld\n", queue_counter, int_counter);
seq_printf(m, "\nscsi%-2d: HBA %.10s\n",
shost->host_no, SD(shost)->name);
seq_printf(m, "Firmware revision: v%s\n",
SD(shost)->revision);
seq_puts(m, "IO: PIO\n");
seq_printf(m, "Base IO : %#.4x\n", (u32) shost->base);
seq_printf(m, "Host Bus: %s\n",
(SD(shost)->bustype == 'P')?"PCI ":
(SD(shost)->bustype == 'E')?"EISA":"ISA ");
return 0;
}
static int eata_pio_release(struct Scsi_Host *sh)
{
hostdata *hd = SD(sh);
if (sh->irq && reg_IRQ[sh->irq] == 1)
free_irq(sh->irq, NULL);
else
reg_IRQ[sh->irq]--;
if (SD(sh)->channel == 0) {
if (sh->io_port && sh->n_io_port)
release_region(sh->io_port, sh->n_io_port);
}
/* At this point the PCI reference can go */
if (hd->pdev)
pci_dev_put(hd->pdev);
return 1;
}
static void IncStat(struct scsi_pointer *SCp, unsigned int Increment)
{
SCp->ptr += Increment;
if ((SCp->this_residual -= Increment) == 0) {
if ((--SCp->buffers_residual) == 0)
SCp->Status = 0;
else {
SCp->buffer++;
SCp->ptr = sg_virt(SCp->buffer);
SCp->this_residual = SCp->buffer->length;
}
}
}
static irqreturn_t eata_pio_int_handler(int irq, void *dev_id);
static irqreturn_t do_eata_pio_int_handler(int irq, void *dev_id)
{
unsigned long flags;
struct Scsi_Host *dev = dev_id;
irqreturn_t ret;
spin_lock_irqsave(dev->host_lock, flags);
ret = eata_pio_int_handler(irq, dev_id);
spin_unlock_irqrestore(dev->host_lock, flags);
return ret;
}
static irqreturn_t eata_pio_int_handler(int irq, void *dev_id)
{
unsigned int eata_stat = 0xfffff;
struct scsi_cmnd *cmd;
hostdata *hd;
struct eata_ccb *cp;
unsigned long base;
unsigned int x, z;
struct Scsi_Host *sh;
unsigned short zwickel = 0;
unsigned char stat, odd;
irqreturn_t ret = IRQ_NONE;
for (x = 1, sh = first_HBA; x <= registered_HBAs; x++, sh = SD(sh)->prev)
{
if (sh->irq != irq)
continue;
if (inb(sh->base + HA_RSTATUS) & HA_SBUSY)
continue;
int_counter++;
ret = IRQ_HANDLED;
hd = SD(sh);
cp = &hd->ccb[0];
cmd = cp->cmd;
base = cmd->device->host->base;
do {
stat = inb(base + HA_RSTATUS);
if (stat & HA_SDRQ) {
if (cp->DataIn) {
z = 256;
odd = 0;
while ((cmd->SCp.Status) && ((z > 0) || (odd))) {
if (odd) {
*(cmd->SCp.ptr) = zwickel >> 8;
IncStat(&cmd->SCp, 1);
odd = 0;
}
x = min_t(unsigned int, z, cmd->SCp.this_residual / 2);
insw(base + HA_RDATA, cmd->SCp.ptr, x);
z -= x;
IncStat(&cmd->SCp, 2 * x);
if ((z > 0) && (cmd->SCp.this_residual == 1)) {
zwickel = inw(base + HA_RDATA);
*(cmd->SCp.ptr) = zwickel & 0xff;
IncStat(&cmd->SCp, 1);
z--;
odd = 1;
}
}
while (z > 0) {
zwickel = inw(base + HA_RDATA);
z--;
}
} else { /* cp->DataOut */
odd = 0;
z = 256;
while ((cmd->SCp.Status) && ((z > 0) || (odd))) {
if (odd) {
zwickel += *(cmd->SCp.ptr) << 8;
IncStat(&cmd->SCp, 1);
outw(zwickel, base + HA_RDATA);
z--;
odd = 0;
}
x = min_t(unsigned int, z, cmd->SCp.this_residual / 2);
outsw(base + HA_RDATA, cmd->SCp.ptr, x);
z -= x;
IncStat(&cmd->SCp, 2 * x);
if ((z > 0) && (cmd->SCp.this_residual == 1)) {
zwickel = *(cmd->SCp.ptr);
zwickel &= 0xff;
IncStat(&cmd->SCp, 1);
odd = 1;
}
}
while (z > 0 || odd) {
outw(zwickel, base + HA_RDATA);
z--;
odd = 0;
}
}
}
}
while ((stat & HA_SDRQ) || ((stat & HA_SMORE) && hd->moresupport));
/* terminate handler if HBA goes busy again, i.e. transfers
* more data */
if (stat & HA_SBUSY)
break;
/* OK, this is quite stupid, but I haven't found any correct
* way to get HBA&SCSI status so far */
if (!(inb(base + HA_RSTATUS) & HA_SERROR)) {
cmd->result = (DID_OK << 16);
hd->devflags |= (1 << cp->cp_id);
} else if (hd->devflags & (1 << cp->cp_id))
cmd->result = (DID_OK << 16) + 0x02;
else
cmd->result = (DID_NO_CONNECT << 16);
if (cp->status == LOCKED) {
cp->status = FREE;
eata_stat = inb(base + HA_RSTATUS);
printk(KERN_CRIT "eata_pio: int_handler, freeing locked " "queueslot\n");
return ret;
}
#if DBG_INTR2
if (stat != 0x50)
printk(KERN_DEBUG "stat: %#.2x, result: %#.8x\n", stat, cmd->result);
#endif
cp->status = FREE; /* now we can release the slot */
cmd->scsi_done(cmd);
}
return ret;
}
static inline unsigned int eata_pio_send_command(unsigned long base, unsigned char command)
{
unsigned int loop = 50;
while (inb(base + HA_RSTATUS) & HA_SBUSY)
if (--loop == 0)
return 1;
/* Enable interrupts for HBA. It is not the best way to do it at this
* place, but I hope that it doesn't interfere with the IDE driver
* initialization this way */
outb(HA_CTRL_8HEADS, base + HA_CTRLREG);
outb(command, base + HA_WCOMMAND);
return 0;
}
static int eata_pio_queue_lck(struct scsi_cmnd *cmd,
void (*done)(struct scsi_cmnd *))
{
unsigned int x, y;
unsigned long base;
hostdata *hd;
struct Scsi_Host *sh;
struct eata_ccb *cp;
queue_counter++;
hd = HD(cmd);
sh = cmd->device->host;
base = sh->base;
/* use only slot 0, as 2001 can handle only one cmd at a time */
y = x = 0;
if (hd->ccb[y].status != FREE) {
DBG(DBG_QUEUE, printk(KERN_EMERG "can_queue %d, x %d, y %d\n", sh->can_queue, x, y));
#if DEBUG_EATA
panic(KERN_EMERG "eata_pio: run out of queue slots cmdno:%ld " "intrno: %ld\n", queue_counter, int_counter);
#else
panic(KERN_EMERG "eata_pio: run out of queue slots....\n");
#endif
}
cp = &hd->ccb[y];
memset(cp, 0, sizeof(struct eata_ccb));
cp->status = USED; /* claim free slot */
DBG(DBG_QUEUE, scmd_printk(KERN_DEBUG, cmd,
"eata_pio_queue 0x%p, y %d\n", cmd, y));
cmd->scsi_done = (void *) done;
if (cmd->sc_data_direction == DMA_TO_DEVICE)
cp->DataOut = 1; /* Output mode */
else
cp->DataIn = 0; /* Input mode */
cp->Interpret = (cmd->device->id == hd->hostid);
cp->cp_datalen = cpu_to_be32(scsi_bufflen(cmd));
cp->Auto_Req_Sen = 0;
cp->cp_reqDMA = 0;
cp->reqlen = 0;
cp->cp_id = cmd->device->id;
cp->cp_lun = cmd->device->lun;
cp->cp_dispri = 0;
cp->cp_identify = 1;
memcpy(cp->cp_cdb, cmd->cmnd, COMMAND_SIZE(*cmd->cmnd));
cp->cp_statDMA = 0;
cp->cp_viraddr = cp;
cp->cmd = cmd;
cmd->host_scribble = (char *) &hd->ccb[y];
if (!scsi_bufflen(cmd)) {
cmd->SCp.buffers_residual = 1;
cmd->SCp.ptr = NULL;
cmd->SCp.this_residual = 0;
cmd->SCp.buffer = NULL;
} else {
cmd->SCp.buffer = scsi_sglist(cmd);
cmd->SCp.buffers_residual = scsi_sg_count(cmd);
cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
cmd->SCp.this_residual = cmd->SCp.buffer->length;
}
cmd->SCp.Status = (cmd->SCp.this_residual != 0); /* TRUE as long as bytes
* are to transfer */
if (eata_pio_send_command(base, EATA_CMD_PIO_SEND_CP)) {
cmd->result = DID_BUS_BUSY << 16;
scmd_printk(KERN_NOTICE, cmd,
"eata_pio_queue pid 0x%p, HBA busy, "
"returning DID_BUS_BUSY, done.\n", cmd);
done(cmd);
cp->status = FREE;
return 0;
}
/* FIXME: timeout */
while (!(inb(base + HA_RSTATUS) & HA_SDRQ))
cpu_relax();
outsw(base + HA_RDATA, cp, hd->cplen);
outb(EATA_CMD_PIO_TRUNC, base + HA_WCOMMAND);
for (x = 0; x < hd->cppadlen; x++)
outw(0, base + HA_RDATA);
DBG(DBG_QUEUE, scmd_printk(KERN_DEBUG, cmd,
"Queued base %#.4lx cmd: 0x%p "
"slot %d irq %d\n", sh->base, cmd, y, sh->irq));
return 0;
}
static DEF_SCSI_QCMD(eata_pio_queue)
static int eata_pio_abort(struct scsi_cmnd *cmd)
{
unsigned int loop = 100;
DBG(DBG_ABNORM, scmd_printk(KERN_WARNING, cmd,
"eata_pio_abort called pid: 0x%p\n", cmd));
while (inb(cmd->device->host->base + HA_RAUXSTAT) & HA_ABUSY)
if (--loop == 0) {
printk(KERN_WARNING "eata_pio: abort, timeout error.\n");
return FAILED;
}
if (CD(cmd)->status == FREE) {
DBG(DBG_ABNORM, printk(KERN_WARNING "Returning: SCSI_ABORT_NOT_RUNNING\n"));
return FAILED;
}
if (CD(cmd)->status == USED) {
DBG(DBG_ABNORM, printk(KERN_WARNING "Returning: SCSI_ABORT_BUSY\n"));
/* We want to sleep a bit more here */
return FAILED; /* SNOOZE */
}
if (CD(cmd)->status == RESET) {
printk(KERN_WARNING "eata_pio: abort, command reset error.\n");
return FAILED;
}
if (CD(cmd)->status == LOCKED) {
DBG(DBG_ABNORM, printk(KERN_WARNING "eata_pio: abort, queue slot " "locked.\n"));
return FAILED;
}
panic("eata_pio: abort: invalid slot status\n");
}
static int eata_pio_host_reset(struct scsi_cmnd *cmd)
{
unsigned int x, limit = 0;
unsigned char success = 0;
struct scsi_cmnd *sp;
struct Scsi_Host *host = cmd->device->host;
DBG(DBG_ABNORM, scmd_printk(KERN_WARNING, cmd,
"eata_pio_reset called\n"));
spin_lock_irq(host->host_lock);
if (HD(cmd)->state == RESET) {
printk(KERN_WARNING "eata_pio_reset: exit, already in reset.\n");
spin_unlock_irq(host->host_lock);
return FAILED;
}
/* force all slots to be free */
for (x = 0; x < cmd->device->host->can_queue; x++) {
if (HD(cmd)->ccb[x].status == FREE)
continue;
sp = HD(cmd)->ccb[x].cmd;
HD(cmd)->ccb[x].status = RESET;
printk(KERN_WARNING "eata_pio_reset: slot %d in reset.\n", x);
if (sp == NULL)
panic("eata_pio_reset: slot %d, sp==NULL.\n", x);
}
/* hard reset the HBA */
outb(EATA_CMD_RESET, cmd->device->host->base + HA_WCOMMAND);
DBG(DBG_ABNORM, printk(KERN_WARNING "eata_pio_reset: board reset done.\n"));
HD(cmd)->state = RESET;
spin_unlock_irq(host->host_lock);
msleep(3000);
spin_lock_irq(host->host_lock);
DBG(DBG_ABNORM, printk(KERN_WARNING "eata_pio_reset: interrupts disabled, " "loops %d.\n", limit));
for (x = 0; x < cmd->device->host->can_queue; x++) {
/* Skip slots already set free by interrupt */
if (HD(cmd)->ccb[x].status != RESET)
continue;
sp = HD(cmd)->ccb[x].cmd;
sp->result = DID_RESET << 16;
/* This mailbox is terminated */
printk(KERN_WARNING "eata_pio_reset: reset ccb %d.\n", x);
HD(cmd)->ccb[x].status = FREE;
sp->scsi_done(sp);
}
HD(cmd)->state = 0;
spin_unlock_irq(host->host_lock);
if (success) { /* hmmm... */
DBG(DBG_ABNORM, printk(KERN_WARNING "eata_pio_reset: exit, success.\n"));
return SUCCESS;
} else {
DBG(DBG_ABNORM, printk(KERN_WARNING "eata_pio_reset: exit, wakeup.\n"));
return FAILED;
}
}
static char *get_pio_board_data(unsigned long base, unsigned int irq, unsigned int id, unsigned long cplen, unsigned short cppadlen)
{
struct eata_ccb cp;
static char buff[256];
int z;
memset(&cp, 0, sizeof(struct eata_ccb));
memset(buff, 0, sizeof(buff));
cp.DataIn = 1;
cp.Interpret = 1; /* Interpret command */
cp.cp_datalen = cpu_to_be32(254);
cp.cp_dataDMA = cpu_to_be32(0);
cp.cp_id = id;
cp.cp_lun = 0;
cp.cp_cdb[0] = INQUIRY;
cp.cp_cdb[1] = 0;
cp.cp_cdb[2] = 0;
cp.cp_cdb[3] = 0;
cp.cp_cdb[4] = 254;
cp.cp_cdb[5] = 0;
if (eata_pio_send_command(base, EATA_CMD_PIO_SEND_CP))
return NULL;
while (!(inb(base + HA_RSTATUS) & HA_SDRQ))
cpu_relax();
outsw(base + HA_RDATA, &cp, cplen);
outb(EATA_CMD_PIO_TRUNC, base + HA_WCOMMAND);
for (z = 0; z < cppadlen; z++)
outw(0, base + HA_RDATA);
while (inb(base + HA_RSTATUS) & HA_SBUSY)
cpu_relax();
if (inb(base + HA_RSTATUS) & HA_SERROR)
return NULL;
else if (!(inb(base + HA_RSTATUS) & HA_SDRQ))
return NULL;
else {
insw(base + HA_RDATA, &buff, 127);
while (inb(base + HA_RSTATUS) & HA_SDRQ)
inw(base + HA_RDATA);
return buff;
}
}
static int get_pio_conf_PIO(unsigned long base, struct get_conf *buf)
{
unsigned long loop = HZ / 2;
int z;
unsigned short *p;
if (!request_region(base, 9, "eata_pio"))
return 0;
memset(buf, 0, sizeof(struct get_conf));
while (inb(base + HA_RSTATUS) & HA_SBUSY)
if (--loop == 0)
goto fail;
DBG(DBG_PIO && DBG_PROBE, printk(KERN_DEBUG "Issuing PIO READ CONFIG to HBA at %#lx\n", base));
eata_pio_send_command(base, EATA_CMD_PIO_READ_CONFIG);
loop = 50;
for (p = (unsigned short *) buf; (long) p <= ((long) buf + (sizeof(struct get_conf) / 2)); p++) {
while (!(inb(base + HA_RSTATUS) & HA_SDRQ))
if (--loop == 0)
goto fail;
loop = 50;
*p = inw(base + HA_RDATA);
}
if (inb(base + HA_RSTATUS) & HA_SERROR) {
DBG(DBG_PROBE, printk("eata_dma: get_conf_PIO, error during "
"transfer for HBA at %lx\n", base));
goto fail;
}
if (cpu_to_be32(EATA_SIGNATURE) != buf->signature)
goto fail;
DBG(DBG_PIO && DBG_PROBE, printk(KERN_NOTICE "EATA Controller found "
"at %#4lx EATA Level: %x\n",
base, (unsigned int) (buf->version)));
while (inb(base + HA_RSTATUS) & HA_SDRQ)
inw(base + HA_RDATA);
if (!ALLOW_DMA_BOARDS) {
for (z = 0; z < MAXISA; z++)
if (base == ISAbases[z]) {
buf->IRQ = ISAirqs[z];
break;
}
}
return 1;
fail:
release_region(base, 9);
return 0;
}
static void print_pio_config(struct get_conf *gc)
{
printk("Please check values: (read config data)\n");
printk("LEN: %d ver:%d OCS:%d TAR:%d TRNXFR:%d MORES:%d\n", be32_to_cpu(gc->len), gc->version, gc->OCS_enabled, gc->TAR_support, gc->TRNXFR, gc->MORE_support);
printk("HAAV:%d SCSIID0:%d ID1:%d ID2:%d QUEUE:%d SG:%d SEC:%d\n", gc->HAA_valid, gc->scsi_id[3], gc->scsi_id[2], gc->scsi_id[1], be16_to_cpu(gc->queuesiz), be16_to_cpu(gc->SGsiz), gc->SECOND);
printk("IRQ:%d IRQT:%d FORCADR:%d MCH:%d RIDQ:%d\n", gc->IRQ, gc->IRQ_TR, gc->FORCADR, gc->MAX_CHAN, gc->ID_qest);
}
static unsigned int print_selftest(unsigned int base)
{
unsigned char buffer[512];
#ifdef VERBOSE_SETUP
int z;
#endif
printk("eata_pio: executing controller self test & setup...\n");
while (inb(base + HA_RSTATUS) & HA_SBUSY);
outb(EATA_CMD_PIO_SETUPTEST, base + HA_WCOMMAND);
do {
while (inb(base + HA_RSTATUS) & HA_SBUSY)
/* nothing */ ;
if (inb(base + HA_RSTATUS) & HA_SDRQ) {
insw(base + HA_RDATA, &buffer, 256);
#ifdef VERBOSE_SETUP
/* no beeps please... */
for (z = 0; z < 511 && buffer[z]; z++)
if (buffer[z] != 7)
printk("%c", buffer[z]);
#endif
}
} while (inb(base + HA_RSTATUS) & (HA_SBUSY | HA_SDRQ));
return (!(inb(base + HA_RSTATUS) & HA_SERROR));
}
static int register_pio_HBA(long base, struct get_conf *gc, struct pci_dev *pdev)
{
unsigned long size = 0;
char *buff;
unsigned long cplen;
unsigned short cppadlen;
struct Scsi_Host *sh;
hostdata *hd;
DBG(DBG_REGISTER, print_pio_config(gc));
if (gc->DMA_support) {
printk("HBA at %#.4lx supports DMA. Please use EATA-DMA driver.\n", base);
if (!ALLOW_DMA_BOARDS)
return 0;
}
if ((buff = get_pio_board_data(base, gc->IRQ, gc->scsi_id[3], cplen = (cpu_to_be32(gc->cplen) + 1) / 2, cppadlen = (cpu_to_be16(gc->cppadlen) + 1) / 2)) == NULL) {
printk("HBA at %#lx didn't react on INQUIRY. Sorry.\n", base);
return 0;
}
if (!print_selftest(base) && !ALLOW_DMA_BOARDS) {
printk("HBA at %#lx failed while performing self test & setup.\n", base);
return 0;
}
size = sizeof(hostdata) + (sizeof(struct eata_ccb) * be16_to_cpu(gc->queuesiz));
sh = scsi_register(&driver_template, size);
if (sh == NULL)
return 0;
if (!reg_IRQ[gc->IRQ]) { /* Interrupt already registered ? */
if (!request_irq(gc->IRQ, do_eata_pio_int_handler, 0, "EATA-PIO", sh)) {
reg_IRQ[gc->IRQ]++;
if (!gc->IRQ_TR)
reg_IRQL[gc->IRQ] = 1; /* IRQ is edge triggered */
} else {
printk("Couldn't allocate IRQ %d, Sorry.\n", gc->IRQ);
return 0;
}
} else { /* More than one HBA on this IRQ */
if (reg_IRQL[gc->IRQ]) {
printk("Can't support more than one HBA on this IRQ,\n" " if the IRQ is edge triggered. Sorry.\n");
return 0;
} else
reg_IRQ[gc->IRQ]++;
}
hd = SD(sh);
memset(hd->ccb, 0, (sizeof(struct eata_ccb) * be16_to_cpu(gc->queuesiz)));
memset(hd->reads, 0, sizeof(hd->reads));
strlcpy(SD(sh)->vendor, &buff[8], sizeof(SD(sh)->vendor));
strlcpy(SD(sh)->name, &buff[16], sizeof(SD(sh)->name));
SD(sh)->revision[0] = buff[32];
SD(sh)->revision[1] = buff[33];
SD(sh)->revision[2] = buff[34];
SD(sh)->revision[3] = '.';
SD(sh)->revision[4] = buff[35];
SD(sh)->revision[5] = 0;
switch (be32_to_cpu(gc->len)) {
case 0x1c:
SD(sh)->EATA_revision = 'a';
break;
case 0x1e:
SD(sh)->EATA_revision = 'b';
break;
case 0x22:
SD(sh)->EATA_revision = 'c';
break;
case 0x24:
SD(sh)->EATA_revision = 'z';
default:
SD(sh)->EATA_revision = '?';
}
if (be32_to_cpu(gc->len) >= 0x22) {
if (gc->is_PCI)
hd->bustype = IS_PCI;
else if (gc->is_EISA)
hd->bustype = IS_EISA;
else
hd->bustype = IS_ISA;
} else {
if (buff[21] == '4')
hd->bustype = IS_PCI;
else if (buff[21] == '2')
hd->bustype = IS_EISA;
else
hd->bustype = IS_ISA;
}
SD(sh)->cplen = cplen;
SD(sh)->cppadlen = cppadlen;
SD(sh)->hostid = gc->scsi_id[3];
SD(sh)->devflags = 1 << gc->scsi_id[3];
SD(sh)->moresupport = gc->MORE_support;
sh->unique_id = base;
sh->base = base;
sh->io_port = base;
sh->n_io_port = 9;
sh->irq = gc->IRQ;
sh->dma_channel = PIO;
sh->this_id = gc->scsi_id[3];
sh->can_queue = 1;
sh->cmd_per_lun = 1;
sh->sg_tablesize = SG_ALL;
hd->channel = 0;
hd->pdev = pci_dev_get(pdev); /* Keep a PCI reference */
sh->max_id = 8;
sh->max_lun = 8;
if (gc->SECOND)
hd->primary = 0;
else
hd->primary = 1;
hd->next = NULL; /* build a linked list of all HBAs */
hd->prev = last_HBA;
if (hd->prev != NULL)
SD(hd->prev)->next = sh;
last_HBA = sh;
if (first_HBA == NULL)
first_HBA = sh;
registered_HBAs++;
return (1);
}
static void find_pio_ISA(struct get_conf *buf)
{
int i;
for (i = 0; i < MAXISA; i++) {
if (!ISAbases[i])
continue;
if (!get_pio_conf_PIO(ISAbases[i], buf))
continue;
if (!register_pio_HBA(ISAbases[i], buf, NULL))
release_region(ISAbases[i], 9);
else
ISAbases[i] = 0;
}
return;
}
static void find_pio_EISA(struct get_conf *buf)
{
u32 base;
int i;
#ifdef CHECKPAL
u8 pal1, pal2, pal3;
#endif
for (i = 0; i < MAXEISA; i++) {
if (EISAbases[i]) { /* Still a possibility ? */
base = 0x1c88 + (i * 0x1000);
#ifdef CHECKPAL
pal1 = inb((u16) base - 8);
pal2 = inb((u16) base - 7);
pal3 = inb((u16) base - 6);
if (((pal1 == 0x12) && (pal2 == 0x14)) || ((pal1 == 0x38) && (pal2 == 0xa3) && (pal3 == 0x82)) || ((pal1 == 0x06) && (pal2 == 0x94) && (pal3 == 0x24))) {
DBG(DBG_PROBE, printk(KERN_NOTICE "EISA EATA id tags found: " "%x %x %x \n", (int) pal1, (int) pal2, (int) pal3));
#endif
if (get_pio_conf_PIO(base, buf)) {
DBG(DBG_PROBE && DBG_EISA, print_pio_config(buf));
if (buf->IRQ) {
if (!register_pio_HBA(base, buf, NULL))
release_region(base, 9);
} else {
printk(KERN_NOTICE "eata_dma: No valid IRQ. HBA " "removed from list\n");
release_region(base, 9);
}
}
/* Nothing found here so we take it from the list */
EISAbases[i] = 0;
#ifdef CHECKPAL
}
#endif
}
}
return;
}
static void find_pio_PCI(struct get_conf *buf)
{
#ifndef CONFIG_PCI
printk("eata_dma: kernel PCI support not enabled. Skipping scan for PCI HBAs.\n");
#else
struct pci_dev *dev = NULL;
unsigned long base, x;
while ((dev = pci_get_device(PCI_VENDOR_ID_DPT, PCI_DEVICE_ID_DPT, dev)) != NULL) {
DBG(DBG_PROBE && DBG_PCI, printk("eata_pio: find_PCI, HBA at %s\n", pci_name(dev)));
if (pci_enable_device(dev))
continue;
pci_set_master(dev);
base = pci_resource_flags(dev, 0);
if (base & IORESOURCE_MEM) {
printk("eata_pio: invalid base address of device %s\n", pci_name(dev));
continue;
}
base = pci_resource_start(dev, 0);
/* EISA tag there ? */
if ((inb(base) == 0x12) && (inb(base + 1) == 0x14))
continue; /* Jep, it's forced, so move on */
base += 0x10; /* Now, THIS is the real address */
if (base != 0x1f8) {
/* We didn't find it in the primary search */
if (get_pio_conf_PIO(base, buf)) {
if (buf->FORCADR) { /* If the address is forced */
release_region(base, 9);
continue; /* we'll find it later */
}
/* OK. We made it till here, so we can go now
* and register it. We only have to check and
* eventually remove it from the EISA and ISA list
*/
if (!register_pio_HBA(base, buf, dev)) {
release_region(base, 9);
continue;
}
if (base < 0x1000) {
for (x = 0; x < MAXISA; ++x) {
if (ISAbases[x] == base) {
ISAbases[x] = 0;
break;
}
}
} else if ((base & 0x0fff) == 0x0c88) {
x = (base >> 12) & 0x0f;
EISAbases[x] = 0;
}
}
#ifdef CHECK_BLINK
else if (check_blink_state(base)) {
printk("eata_pio: HBA is in BLINK state.\n" "Consult your HBAs manual to correct this.\n");
}
#endif
}
}
#endif /* #ifndef CONFIG_PCI */
}
static int eata_pio_detect(struct scsi_host_template *tpnt)
{
struct Scsi_Host *HBA_ptr;
struct get_conf gc;
int i;
find_pio_PCI(&gc);
find_pio_EISA(&gc);
find_pio_ISA(&gc);
for (i = 0; i < MAXIRQ; i++)
if (reg_IRQ[i])
request_irq(i, do_eata_pio_int_handler, 0, "EATA-PIO", NULL);
HBA_ptr = first_HBA;
if (registered_HBAs != 0) {
printk("EATA (Extended Attachment) PIO driver version: %d.%d%s\n"
"(c) 1993-95 Michael Neuffer, neuffer@goofy.zdv.uni-mainz.de\n" " Alfred Arnold, a.arnold@kfa-juelich.de\n" "This release only supports DASD devices (harddisks)\n", VER_MAJOR, VER_MINOR, VER_SUB);
printk("Registered HBAs:\n");
printk("HBA no. Boardtype: Revis: EATA: Bus: BaseIO: IRQ: Ch: ID: Pr:" " QS: SG: CPL:\n");
for (i = 1; i <= registered_HBAs; i++) {
printk("scsi%-2d: %.10s v%s 2.0%c %s %#.4lx %2d %d %d %c"
" %2d %2d %2d\n",
HBA_ptr->host_no, SD(HBA_ptr)->name, SD(HBA_ptr)->revision,
SD(HBA_ptr)->EATA_revision, (SD(HBA_ptr)->bustype == 'P') ?
"PCI " : (SD(HBA_ptr)->bustype == 'E') ? "EISA" : "ISA ",
HBA_ptr->base, HBA_ptr->irq, SD(HBA_ptr)->channel, HBA_ptr->this_id,
SD(HBA_ptr)->primary ? 'Y' : 'N', HBA_ptr->can_queue,
HBA_ptr->sg_tablesize, HBA_ptr->cmd_per_lun);
HBA_ptr = SD(HBA_ptr)->next;
}
}
return (registered_HBAs);
}
static struct scsi_host_template driver_template = {
.proc_name = "eata_pio",
.name = "EATA (Extended Attachment) PIO driver",
.show_info = eata_pio_show_info,
.detect = eata_pio_detect,
.release = eata_pio_release,
.queuecommand = eata_pio_queue,
.eh_abort_handler = eata_pio_abort,
.eh_host_reset_handler = eata_pio_host_reset,
.use_clustering = ENABLE_CLUSTERING,
};
MODULE_AUTHOR("Michael Neuffer, Alfred Arnold");
MODULE_DESCRIPTION("EATA SCSI PIO driver");
MODULE_LICENSE("GPL");
#include "scsi_module.c"
| gpl-2.0 |
mlehtima/android_kernel_semc_msm7x30 | sound/soc/msm/qdsp6v2/msm-pcm-voice-v2.c | 1241 | 13631 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <asm/dma.h>
#include "msm-pcm-voice-v2.h"
#include "q6voice.h"
static struct msm_voice voice_info[VOICE_SESSION_INDEX_MAX];
static struct snd_pcm_hardware msm_pcm_hardware = {
.info = SNDRV_PCM_INFO_INTERLEAVED,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000,
.rate_min = 8000,
.rate_max = 16000,
.channels_min = 1,
.channels_max = 1,
.buffer_bytes_max = 4096 * 2,
.period_bytes_min = 4096,
.period_bytes_max = 4096,
.periods_min = 2,
.periods_max = 2,
.fifo_size = 0,
};
static int is_volte(struct msm_voice *pvolte)
{
if (pvolte == &voice_info[VOLTE_SESSION_INDEX])
return true;
else
return false;
}
static int msm_pcm_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *prtd = runtime->private_data;
pr_debug("%s\n", __func__);
if (!prtd->playback_start)
prtd->playback_start = 1;
return 0;
}
static int msm_pcm_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *prtd = runtime->private_data;
pr_debug("%s\n", __func__);
if (!prtd->capture_start)
prtd->capture_start = 1;
return 0;
}
static int msm_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *voice;
if (!strncmp("VoLTE", substream->pcm->id, 5)) {
voice = &voice_info[VOLTE_SESSION_INDEX];
pr_debug("%s: Open VoLTE Substream Id=%s\n",
__func__, substream->pcm->id);
} else {
voice = &voice_info[VOICE_SESSION_INDEX];
pr_debug("%s: Open VOICE Substream Id=%s\n",
__func__, substream->pcm->id);
}
mutex_lock(&voice->lock);
runtime->hw = msm_pcm_hardware;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
voice->playback_substream = substream;
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
voice->capture_substream = substream;
voice->instance++;
pr_debug("%s: Instance = %d, Stream ID = %s\n",
__func__ , voice->instance, substream->pcm->id);
runtime->private_data = voice;
mutex_unlock(&voice->lock);
return 0;
}
static int msm_pcm_playback_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *prtd = runtime->private_data;
pr_debug("%s\n", __func__);
if (prtd->playback_start)
prtd->playback_start = 0;
prtd->playback_substream = NULL;
return 0;
}
static int msm_pcm_capture_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *prtd = runtime->private_data;
pr_debug("%s\n", __func__);
if (prtd->capture_start)
prtd->capture_start = 0;
prtd->capture_substream = NULL;
return 0;
}
static int msm_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *prtd = runtime->private_data;
uint16_t session_id = 0;
int ret = 0;
mutex_lock(&prtd->lock);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_close(substream);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_close(substream);
prtd->instance--;
if (!prtd->playback_start && !prtd->capture_start) {
pr_debug("end voice call\n");
if (is_volte(prtd))
session_id = voc_get_session_id(VOLTE_SESSION_NAME);
else
session_id = voc_get_session_id(VOICE_SESSION_NAME);
voc_end_voice_call(session_id);
}
mutex_unlock(&prtd->lock);
return ret;
}
static int msm_pcm_prepare(struct snd_pcm_substream *substream)
{
int ret = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_voice *prtd = runtime->private_data;
uint16_t session_id = 0;
mutex_lock(&prtd->lock);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_prepare(substream);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_prepare(substream);
if (prtd->playback_start && prtd->capture_start) {
if (is_volte(prtd))
session_id = voc_get_session_id(VOLTE_SESSION_NAME);
else
session_id = voc_get_session_id(VOICE_SESSION_NAME);
voc_start_voice_call(session_id);
}
mutex_unlock(&prtd->lock);
return ret;
}
static int msm_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_debug("%s: Voice\n", __func__);
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
return 0;
}
static int msm_voice_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int msm_voice_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int volume = ucontrol->value.integer.value[0];
pr_debug("%s: volume: %d\n", __func__, volume);
voc_set_rx_vol_index(voc_get_session_id(VOICE_SESSION_NAME),
RX_PATH, volume);
return 0;
}
static int msm_volte_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int msm_volte_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int volume = ucontrol->value.integer.value[0];
pr_debug("%s: volume: %d\n", __func__, volume);
voc_set_rx_vol_index(voc_get_session_id(VOLTE_SESSION_NAME),
RX_PATH, volume);
return 0;
}
static int msm_voice_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int msm_voice_mute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int mute = ucontrol->value.integer.value[0];
pr_debug("%s: mute=%d\n", __func__, mute);
voc_set_tx_mute(voc_get_session_id(VOICE_SESSION_NAME), TX_PATH, mute);
return 0;
}
static int msm_volte_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int msm_volte_mute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int mute = ucontrol->value.integer.value[0];
pr_debug("%s: mute=%d\n", __func__, mute);
voc_set_tx_mute(voc_get_session_id(VOLTE_SESSION_NAME), TX_PATH, mute);
return 0;
}
static int msm_voice_rx_device_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_rx_device_mute(voc_get_session_id(VOICE_SESSION_NAME));
return 0;
}
static int msm_voice_rx_device_mute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int mute = ucontrol->value.integer.value[0];
pr_debug("%s: mute=%d\n", __func__, mute);
voc_set_rx_device_mute(voc_get_session_id(VOICE_SESSION_NAME), mute);
return 0;
}
static int msm_volte_rx_device_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_rx_device_mute(voc_get_session_id(VOLTE_SESSION_NAME));
return 0;
}
static int msm_volte_rx_device_mute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int mute = ucontrol->value.integer.value[0];
pr_debug("%s: mute=%d\n", __func__, mute);
voc_set_rx_device_mute(voc_get_session_id(VOLTE_SESSION_NAME), mute);
return 0;
}
static const char const *tty_mode[] = {"OFF", "HCO", "VCO", "FULL"};
static const struct soc_enum msm_tty_mode_enum[] = {
SOC_ENUM_SINGLE_EXT(4, tty_mode),
};
static int msm_voice_tty_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_tty_mode(voc_get_session_id(VOICE_SESSION_NAME));
return 0;
}
static int msm_voice_tty_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int tty_mode = ucontrol->value.integer.value[0];
pr_debug("%s: tty_mode=%d\n", __func__, tty_mode);
voc_set_tty_mode(voc_get_session_id(VOICE_SESSION_NAME), tty_mode);
return 0;
}
static int msm_voice_widevoice_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int wv_enable = ucontrol->value.integer.value[0];
pr_debug("%s: wv enable=%d\n", __func__, wv_enable);
voc_set_widevoice_enable(voc_get_session_id(VOICE_SESSION_NAME),
wv_enable);
return 0;
}
static int msm_voice_widevoice_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_widevoice_enable(voc_get_session_id(VOICE_SESSION_NAME));
return 0;
}
static int msm_voice_slowtalk_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int st_enable = ucontrol->value.integer.value[0];
pr_debug("%s: st enable=%d\n", __func__, st_enable);
voc_set_pp_enable(voc_get_session_id(VOICE_SESSION_NAME),
MODULE_ID_VOICE_MODULE_ST, st_enable);
return 0;
}
static int msm_voice_slowtalk_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_pp_enable(voc_get_session_id(VOICE_SESSION_NAME),
MODULE_ID_VOICE_MODULE_ST);
return 0;
}
static int msm_voice_fens_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int fens_enable = ucontrol->value.integer.value[0];
pr_debug("%s: fens enable=%d\n", __func__, fens_enable);
voc_set_pp_enable(voc_get_session_id(VOICE_SESSION_NAME),
MODULE_ID_VOICE_MODULE_FENS, fens_enable);
return 0;
}
static int msm_voice_fens_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] =
voc_get_pp_enable(voc_get_session_id(VOICE_SESSION_NAME),
MODULE_ID_VOICE_MODULE_FENS);
return 0;
}
static struct snd_kcontrol_new msm_voice_controls[] = {
SOC_SINGLE_EXT("Voice Rx Device Mute", SND_SOC_NOPM, 0, 1, 0,
msm_voice_rx_device_mute_get,
msm_voice_rx_device_mute_put),
SOC_SINGLE_EXT("Voice Tx Mute", SND_SOC_NOPM, 0, 1, 0,
msm_voice_mute_get, msm_voice_mute_put),
SOC_SINGLE_EXT("Voice Rx Volume", SND_SOC_NOPM, 0, 5, 0,
msm_voice_volume_get, msm_voice_volume_put),
SOC_ENUM_EXT("TTY Mode", msm_tty_mode_enum[0], msm_voice_tty_mode_get,
msm_voice_tty_mode_put),
SOC_SINGLE_EXT("Widevoice Enable", SND_SOC_NOPM, 0, 1, 0,
msm_voice_widevoice_get, msm_voice_widevoice_put),
SOC_SINGLE_EXT("Slowtalk Enable", SND_SOC_NOPM, 0, 1, 0,
msm_voice_slowtalk_get, msm_voice_slowtalk_put),
SOC_SINGLE_EXT("FENS Enable", SND_SOC_NOPM, 0, 1, 0,
msm_voice_fens_get, msm_voice_fens_put),
SOC_SINGLE_EXT("VoLTE Rx Device Mute", SND_SOC_NOPM, 0, 1, 0,
msm_volte_rx_device_mute_get,
msm_volte_rx_device_mute_put),
SOC_SINGLE_EXT("VoLTE Tx Mute", SND_SOC_NOPM, 0, 1, 0,
msm_volte_mute_get, msm_volte_mute_put),
SOC_SINGLE_EXT("VoLTE Rx Volume", SND_SOC_NOPM, 0, 5, 0,
msm_volte_volume_get, msm_volte_volume_put),
};
static struct snd_pcm_ops msm_pcm_ops = {
.open = msm_pcm_open,
.hw_params = msm_pcm_hw_params,
.close = msm_pcm_close,
.prepare = msm_pcm_prepare,
};
static int msm_asoc_pcm_new(struct snd_soc_pcm_runtime *rtd)
{
struct snd_card *card = rtd->card->snd_card;
int ret = 0;
if (!card->dev->coherent_dma_mask)
card->dev->coherent_dma_mask = DMA_BIT_MASK(32);
return ret;
}
static int msm_pcm_voice_probe(struct snd_soc_platform *platform)
{
snd_soc_add_platform_controls(platform, msm_voice_controls,
ARRAY_SIZE(msm_voice_controls));
return 0;
}
static struct snd_soc_platform_driver msm_soc_platform = {
.ops = &msm_pcm_ops,
.pcm_new = msm_asoc_pcm_new,
.probe = msm_pcm_voice_probe,
};
static __devinit int msm_pcm_probe(struct platform_device *pdev)
{
pr_debug("%s: dev name %s\n", __func__, dev_name(&pdev->dev));
return snd_soc_register_platform(&pdev->dev,
&msm_soc_platform);
}
static int msm_pcm_remove(struct platform_device *pdev)
{
snd_soc_unregister_platform(&pdev->dev);
return 0;
}
static struct platform_driver msm_pcm_driver = {
.driver = {
.name = "msm-pcm-voice",
.owner = THIS_MODULE,
},
.probe = msm_pcm_probe,
.remove = __devexit_p(msm_pcm_remove),
};
static int __init msm_soc_platform_init(void)
{
memset(&voice_info, 0, sizeof(voice_info));
mutex_init(&voice_info[VOICE_SESSION_INDEX].lock);
mutex_init(&voice_info[VOLTE_SESSION_INDEX].lock);
return platform_driver_register(&msm_pcm_driver);
}
module_init(msm_soc_platform_init);
static void __exit msm_soc_platform_exit(void)
{
platform_driver_unregister(&msm_pcm_driver);
}
module_exit(msm_soc_platform_exit);
MODULE_DESCRIPTION("Voice PCM module platform driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Dees-Troy/android_kernel_samsung_coreprimelte | arch/mips/math-emu/cp1emu.c | 1753 | 52602 | /*
* cp1emu.c: a MIPS coprocessor 1 (fpu) instruction emulator
*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* Kevin D. Kissell, kevink@mips.com and Carsten Langgaard, carstenl@mips.com
* Copyright (C) 2000 MIPS Technologies, Inc.
*
* This program is free software; you can distribute 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 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.
*
* A complete emulator for MIPS coprocessor 1 instructions. This is
* required for #float(switch) or #float(trap), where it catches all
* COP1 instructions via the "CoProcessor Unusable" exception.
*
* More surprisingly it is also required for #float(ieee), to help out
* the hardware fpu at the boundaries of the IEEE-754 representation
* (denormalised values, infinities, underflow, etc). It is made
* quite nasty because emulation of some non-COP1 instructions is
* required, e.g. in branch delay slots.
*
* Note if you know that you won't have an fpu, then you'll get much
* better performance by compiling with -msoft-float!
*/
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/perf_event.h>
#include <asm/inst.h>
#include <asm/bootinfo.h>
#include <asm/processor.h>
#include <asm/ptrace.h>
#include <asm/signal.h>
#include <asm/mipsregs.h>
#include <asm/fpu_emulator.h>
#include <asm/fpu.h>
#include <asm/uaccess.h>
#include <asm/branch.h>
#include "ieee754.h"
/* Strap kernel emulator for full MIPS IV emulation */
#ifdef __mips
#undef __mips
#endif
#define __mips 4
/* Function which emulates a floating point instruction. */
static int fpu_emu(struct pt_regs *, struct mips_fpu_struct *,
mips_instruction);
#if __mips >= 4 && __mips != 32
static int fpux_emu(struct pt_regs *,
struct mips_fpu_struct *, mips_instruction, void *__user *);
#endif
/* Further private data for which no space exists in mips_fpu_struct */
#ifdef CONFIG_DEBUG_FS
DEFINE_PER_CPU(struct mips_fpu_emulator_stats, fpuemustats);
#endif
/* Control registers */
#define FPCREG_RID 0 /* $0 = revision id */
#define FPCREG_CSR 31 /* $31 = csr */
/* Determine rounding mode from the RM bits of the FCSR */
#define modeindex(v) ((v) & FPU_CSR_RM)
/* microMIPS bitfields */
#define MM_POOL32A_MINOR_MASK 0x3f
#define MM_POOL32A_MINOR_SHIFT 0x6
#define MM_MIPS32_COND_FC 0x30
/* Convert Mips rounding mode (0..3) to IEEE library modes. */
static const unsigned char ieee_rm[4] = {
[FPU_CSR_RN] = IEEE754_RN,
[FPU_CSR_RZ] = IEEE754_RZ,
[FPU_CSR_RU] = IEEE754_RU,
[FPU_CSR_RD] = IEEE754_RD,
};
/* Convert IEEE library modes to Mips rounding mode (0..3). */
static const unsigned char mips_rm[4] = {
[IEEE754_RN] = FPU_CSR_RN,
[IEEE754_RZ] = FPU_CSR_RZ,
[IEEE754_RD] = FPU_CSR_RD,
[IEEE754_RU] = FPU_CSR_RU,
};
#if __mips >= 4
/* convert condition code register number to csr bit */
static const unsigned int fpucondbit[8] = {
FPU_CSR_COND0,
FPU_CSR_COND1,
FPU_CSR_COND2,
FPU_CSR_COND3,
FPU_CSR_COND4,
FPU_CSR_COND5,
FPU_CSR_COND6,
FPU_CSR_COND7
};
#endif
/* (microMIPS) Convert 16-bit register encoding to 32-bit register encoding. */
static const unsigned int reg16to32map[8] = {16, 17, 2, 3, 4, 5, 6, 7};
/* (microMIPS) Convert certain microMIPS instructions to MIPS32 format. */
static const int sd_format[] = {16, 17, 0, 0, 0, 0, 0, 0};
static const int sdps_format[] = {16, 17, 22, 0, 0, 0, 0, 0};
static const int dwl_format[] = {17, 20, 21, 0, 0, 0, 0, 0};
static const int swl_format[] = {16, 20, 21, 0, 0, 0, 0, 0};
/*
* This functions translates a 32-bit microMIPS instruction
* into a 32-bit MIPS32 instruction. Returns 0 on success
* and SIGILL otherwise.
*/
static int microMIPS32_to_MIPS32(union mips_instruction *insn_ptr)
{
union mips_instruction insn = *insn_ptr;
union mips_instruction mips32_insn = insn;
int func, fmt, op;
switch (insn.mm_i_format.opcode) {
case mm_ldc132_op:
mips32_insn.mm_i_format.opcode = ldc1_op;
mips32_insn.mm_i_format.rt = insn.mm_i_format.rs;
mips32_insn.mm_i_format.rs = insn.mm_i_format.rt;
break;
case mm_lwc132_op:
mips32_insn.mm_i_format.opcode = lwc1_op;
mips32_insn.mm_i_format.rt = insn.mm_i_format.rs;
mips32_insn.mm_i_format.rs = insn.mm_i_format.rt;
break;
case mm_sdc132_op:
mips32_insn.mm_i_format.opcode = sdc1_op;
mips32_insn.mm_i_format.rt = insn.mm_i_format.rs;
mips32_insn.mm_i_format.rs = insn.mm_i_format.rt;
break;
case mm_swc132_op:
mips32_insn.mm_i_format.opcode = swc1_op;
mips32_insn.mm_i_format.rt = insn.mm_i_format.rs;
mips32_insn.mm_i_format.rs = insn.mm_i_format.rt;
break;
case mm_pool32i_op:
/* NOTE: offset is << by 1 if in microMIPS mode. */
if ((insn.mm_i_format.rt == mm_bc1f_op) ||
(insn.mm_i_format.rt == mm_bc1t_op)) {
mips32_insn.fb_format.opcode = cop1_op;
mips32_insn.fb_format.bc = bc_op;
mips32_insn.fb_format.flag =
(insn.mm_i_format.rt == mm_bc1t_op) ? 1 : 0;
} else
return SIGILL;
break;
case mm_pool32f_op:
switch (insn.mm_fp0_format.func) {
case mm_32f_01_op:
case mm_32f_11_op:
case mm_32f_02_op:
case mm_32f_12_op:
case mm_32f_41_op:
case mm_32f_51_op:
case mm_32f_42_op:
case mm_32f_52_op:
op = insn.mm_fp0_format.func;
if (op == mm_32f_01_op)
func = madd_s_op;
else if (op == mm_32f_11_op)
func = madd_d_op;
else if (op == mm_32f_02_op)
func = nmadd_s_op;
else if (op == mm_32f_12_op)
func = nmadd_d_op;
else if (op == mm_32f_41_op)
func = msub_s_op;
else if (op == mm_32f_51_op)
func = msub_d_op;
else if (op == mm_32f_42_op)
func = nmsub_s_op;
else
func = nmsub_d_op;
mips32_insn.fp6_format.opcode = cop1x_op;
mips32_insn.fp6_format.fr = insn.mm_fp6_format.fr;
mips32_insn.fp6_format.ft = insn.mm_fp6_format.ft;
mips32_insn.fp6_format.fs = insn.mm_fp6_format.fs;
mips32_insn.fp6_format.fd = insn.mm_fp6_format.fd;
mips32_insn.fp6_format.func = func;
break;
case mm_32f_10_op:
func = -1; /* Invalid */
op = insn.mm_fp5_format.op & 0x7;
if (op == mm_ldxc1_op)
func = ldxc1_op;
else if (op == mm_sdxc1_op)
func = sdxc1_op;
else if (op == mm_lwxc1_op)
func = lwxc1_op;
else if (op == mm_swxc1_op)
func = swxc1_op;
if (func != -1) {
mips32_insn.r_format.opcode = cop1x_op;
mips32_insn.r_format.rs =
insn.mm_fp5_format.base;
mips32_insn.r_format.rt =
insn.mm_fp5_format.index;
mips32_insn.r_format.rd = 0;
mips32_insn.r_format.re = insn.mm_fp5_format.fd;
mips32_insn.r_format.func = func;
} else
return SIGILL;
break;
case mm_32f_40_op:
op = -1; /* Invalid */
if (insn.mm_fp2_format.op == mm_fmovt_op)
op = 1;
else if (insn.mm_fp2_format.op == mm_fmovf_op)
op = 0;
if (op != -1) {
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sdps_format[insn.mm_fp2_format.fmt];
mips32_insn.fp0_format.ft =
(insn.mm_fp2_format.cc<<2) + op;
mips32_insn.fp0_format.fs =
insn.mm_fp2_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp2_format.fd;
mips32_insn.fp0_format.func = fmovc_op;
} else
return SIGILL;
break;
case mm_32f_60_op:
func = -1; /* Invalid */
if (insn.mm_fp0_format.op == mm_fadd_op)
func = fadd_op;
else if (insn.mm_fp0_format.op == mm_fsub_op)
func = fsub_op;
else if (insn.mm_fp0_format.op == mm_fmul_op)
func = fmul_op;
else if (insn.mm_fp0_format.op == mm_fdiv_op)
func = fdiv_op;
if (func != -1) {
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sdps_format[insn.mm_fp0_format.fmt];
mips32_insn.fp0_format.ft =
insn.mm_fp0_format.ft;
mips32_insn.fp0_format.fs =
insn.mm_fp0_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp0_format.fd;
mips32_insn.fp0_format.func = func;
} else
return SIGILL;
break;
case mm_32f_70_op:
func = -1; /* Invalid */
if (insn.mm_fp0_format.op == mm_fmovn_op)
func = fmovn_op;
else if (insn.mm_fp0_format.op == mm_fmovz_op)
func = fmovz_op;
if (func != -1) {
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sdps_format[insn.mm_fp0_format.fmt];
mips32_insn.fp0_format.ft =
insn.mm_fp0_format.ft;
mips32_insn.fp0_format.fs =
insn.mm_fp0_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp0_format.fd;
mips32_insn.fp0_format.func = func;
} else
return SIGILL;
break;
case mm_32f_73_op: /* POOL32FXF */
switch (insn.mm_fp1_format.op) {
case mm_movf0_op:
case mm_movf1_op:
case mm_movt0_op:
case mm_movt1_op:
if ((insn.mm_fp1_format.op & 0x7f) ==
mm_movf0_op)
op = 0;
else
op = 1;
mips32_insn.r_format.opcode = spec_op;
mips32_insn.r_format.rs = insn.mm_fp4_format.fs;
mips32_insn.r_format.rt =
(insn.mm_fp4_format.cc << 2) + op;
mips32_insn.r_format.rd = insn.mm_fp4_format.rt;
mips32_insn.r_format.re = 0;
mips32_insn.r_format.func = movc_op;
break;
case mm_fcvtd0_op:
case mm_fcvtd1_op:
case mm_fcvts0_op:
case mm_fcvts1_op:
if ((insn.mm_fp1_format.op & 0x7f) ==
mm_fcvtd0_op) {
func = fcvtd_op;
fmt = swl_format[insn.mm_fp3_format.fmt];
} else {
func = fcvts_op;
fmt = dwl_format[insn.mm_fp3_format.fmt];
}
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt = fmt;
mips32_insn.fp0_format.ft = 0;
mips32_insn.fp0_format.fs =
insn.mm_fp3_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp3_format.rt;
mips32_insn.fp0_format.func = func;
break;
case mm_fmov0_op:
case mm_fmov1_op:
case mm_fabs0_op:
case mm_fabs1_op:
case mm_fneg0_op:
case mm_fneg1_op:
if ((insn.mm_fp1_format.op & 0x7f) ==
mm_fmov0_op)
func = fmov_op;
else if ((insn.mm_fp1_format.op & 0x7f) ==
mm_fabs0_op)
func = fabs_op;
else
func = fneg_op;
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sdps_format[insn.mm_fp3_format.fmt];
mips32_insn.fp0_format.ft = 0;
mips32_insn.fp0_format.fs =
insn.mm_fp3_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp3_format.rt;
mips32_insn.fp0_format.func = func;
break;
case mm_ffloorl_op:
case mm_ffloorw_op:
case mm_fceill_op:
case mm_fceilw_op:
case mm_ftruncl_op:
case mm_ftruncw_op:
case mm_froundl_op:
case mm_froundw_op:
case mm_fcvtl_op:
case mm_fcvtw_op:
if (insn.mm_fp1_format.op == mm_ffloorl_op)
func = ffloorl_op;
else if (insn.mm_fp1_format.op == mm_ffloorw_op)
func = ffloor_op;
else if (insn.mm_fp1_format.op == mm_fceill_op)
func = fceill_op;
else if (insn.mm_fp1_format.op == mm_fceilw_op)
func = fceil_op;
else if (insn.mm_fp1_format.op == mm_ftruncl_op)
func = ftruncl_op;
else if (insn.mm_fp1_format.op == mm_ftruncw_op)
func = ftrunc_op;
else if (insn.mm_fp1_format.op == mm_froundl_op)
func = froundl_op;
else if (insn.mm_fp1_format.op == mm_froundw_op)
func = fround_op;
else if (insn.mm_fp1_format.op == mm_fcvtl_op)
func = fcvtl_op;
else
func = fcvtw_op;
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sd_format[insn.mm_fp1_format.fmt];
mips32_insn.fp0_format.ft = 0;
mips32_insn.fp0_format.fs =
insn.mm_fp1_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp1_format.rt;
mips32_insn.fp0_format.func = func;
break;
case mm_frsqrt_op:
case mm_fsqrt_op:
case mm_frecip_op:
if (insn.mm_fp1_format.op == mm_frsqrt_op)
func = frsqrt_op;
else if (insn.mm_fp1_format.op == mm_fsqrt_op)
func = fsqrt_op;
else
func = frecip_op;
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sdps_format[insn.mm_fp1_format.fmt];
mips32_insn.fp0_format.ft = 0;
mips32_insn.fp0_format.fs =
insn.mm_fp1_format.fs;
mips32_insn.fp0_format.fd =
insn.mm_fp1_format.rt;
mips32_insn.fp0_format.func = func;
break;
case mm_mfc1_op:
case mm_mtc1_op:
case mm_cfc1_op:
case mm_ctc1_op:
if (insn.mm_fp1_format.op == mm_mfc1_op)
op = mfc_op;
else if (insn.mm_fp1_format.op == mm_mtc1_op)
op = mtc_op;
else if (insn.mm_fp1_format.op == mm_cfc1_op)
op = cfc_op;
else
op = ctc_op;
mips32_insn.fp1_format.opcode = cop1_op;
mips32_insn.fp1_format.op = op;
mips32_insn.fp1_format.rt =
insn.mm_fp1_format.rt;
mips32_insn.fp1_format.fs =
insn.mm_fp1_format.fs;
mips32_insn.fp1_format.fd = 0;
mips32_insn.fp1_format.func = 0;
break;
default:
return SIGILL;
break;
}
break;
case mm_32f_74_op: /* c.cond.fmt */
mips32_insn.fp0_format.opcode = cop1_op;
mips32_insn.fp0_format.fmt =
sdps_format[insn.mm_fp4_format.fmt];
mips32_insn.fp0_format.ft = insn.mm_fp4_format.rt;
mips32_insn.fp0_format.fs = insn.mm_fp4_format.fs;
mips32_insn.fp0_format.fd = insn.mm_fp4_format.cc << 2;
mips32_insn.fp0_format.func =
insn.mm_fp4_format.cond | MM_MIPS32_COND_FC;
break;
default:
return SIGILL;
break;
}
break;
default:
return SIGILL;
break;
}
*insn_ptr = mips32_insn;
return 0;
}
int mm_isBranchInstr(struct pt_regs *regs, struct mm_decoded_insn dec_insn,
unsigned long *contpc)
{
union mips_instruction insn = (union mips_instruction)dec_insn.insn;
int bc_false = 0;
unsigned int fcr31;
unsigned int bit;
switch (insn.mm_i_format.opcode) {
case mm_pool32a_op:
if ((insn.mm_i_format.simmediate & MM_POOL32A_MINOR_MASK) ==
mm_pool32axf_op) {
switch (insn.mm_i_format.simmediate >>
MM_POOL32A_MINOR_SHIFT) {
case mm_jalr_op:
case mm_jalrhb_op:
case mm_jalrs_op:
case mm_jalrshb_op:
if (insn.mm_i_format.rt != 0) /* Not mm_jr */
regs->regs[insn.mm_i_format.rt] =
regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
*contpc = regs->regs[insn.mm_i_format.rs];
return 1;
break;
}
}
break;
case mm_pool32i_op:
switch (insn.mm_i_format.rt) {
case mm_bltzals_op:
case mm_bltzal_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
/* Fall through */
case mm_bltz_op:
if ((long)regs->regs[insn.mm_i_format.rs] < 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case mm_bgezals_op:
case mm_bgezal_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
/* Fall through */
case mm_bgez_op:
if ((long)regs->regs[insn.mm_i_format.rs] >= 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case mm_blez_op:
if ((long)regs->regs[insn.mm_i_format.rs] <= 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case mm_bgtz_op:
if ((long)regs->regs[insn.mm_i_format.rs] <= 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case mm_bc2f_op:
case mm_bc1f_op:
bc_false = 1;
/* Fall through */
case mm_bc2t_op:
case mm_bc1t_op:
preempt_disable();
if (is_fpu_owner())
asm volatile("cfc1\t%0,$31" : "=r" (fcr31));
else
fcr31 = current->thread.fpu.fcr31;
preempt_enable();
if (bc_false)
fcr31 = ~fcr31;
bit = (insn.mm_i_format.rs >> 2);
bit += (bit != 0);
bit += 23;
if (fcr31 & (1 << bit))
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
return 1;
break;
}
break;
case mm_pool16c_op:
switch (insn.mm_i_format.rt) {
case mm_jalr16_op:
case mm_jalrs16_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
/* Fall through */
case mm_jr16_op:
*contpc = regs->regs[insn.mm_i_format.rs];
return 1;
break;
}
break;
case mm_beqz16_op:
if ((long)regs->regs[reg16to32map[insn.mm_b1_format.rs]] == 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_b1_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
return 1;
break;
case mm_bnez16_op:
if ((long)regs->regs[reg16to32map[insn.mm_b1_format.rs]] != 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_b1_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
return 1;
break;
case mm_b16_op:
*contpc = regs->cp0_epc + dec_insn.pc_inc +
(insn.mm_b0_format.simmediate << 1);
return 1;
break;
case mm_beq32_op:
if (regs->regs[insn.mm_i_format.rs] ==
regs->regs[insn.mm_i_format.rt])
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case mm_bne32_op:
if (regs->regs[insn.mm_i_format.rs] !=
regs->regs[insn.mm_i_format.rt])
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.mm_i_format.simmediate << 1);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
return 1;
break;
case mm_jalx32_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
*contpc = regs->cp0_epc + dec_insn.pc_inc;
*contpc >>= 28;
*contpc <<= 28;
*contpc |= (insn.j_format.target << 2);
return 1;
break;
case mm_jals32_op:
case mm_jal32_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc + dec_insn.next_pc_inc;
/* Fall through */
case mm_j32_op:
*contpc = regs->cp0_epc + dec_insn.pc_inc;
*contpc >>= 27;
*contpc <<= 27;
*contpc |= (insn.j_format.target << 1);
set_isa16_mode(*contpc);
return 1;
break;
}
return 0;
}
/*
* Redundant with logic already in kernel/branch.c,
* embedded in compute_return_epc. At some point,
* a single subroutine should be used across both
* modules.
*/
static int isBranchInstr(struct pt_regs *regs, struct mm_decoded_insn dec_insn,
unsigned long *contpc)
{
union mips_instruction insn = (union mips_instruction)dec_insn.insn;
unsigned int fcr31;
unsigned int bit = 0;
switch (insn.i_format.opcode) {
case spec_op:
switch (insn.r_format.func) {
case jalr_op:
regs->regs[insn.r_format.rd] =
regs->cp0_epc + dec_insn.pc_inc +
dec_insn.next_pc_inc;
/* Fall through */
case jr_op:
*contpc = regs->regs[insn.r_format.rs];
return 1;
break;
}
break;
case bcond_op:
switch (insn.i_format.rt) {
case bltzal_op:
case bltzall_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
/* Fall through */
case bltz_op:
case bltzl_op:
if ((long)regs->regs[insn.i_format.rs] < 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case bgezal_op:
case bgezall_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
/* Fall through */
case bgez_op:
case bgezl_op:
if ((long)regs->regs[insn.i_format.rs] >= 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
}
break;
case jalx_op:
set_isa16_mode(bit);
case jal_op:
regs->regs[31] = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
/* Fall through */
case j_op:
*contpc = regs->cp0_epc + dec_insn.pc_inc;
*contpc >>= 28;
*contpc <<= 28;
*contpc |= (insn.j_format.target << 2);
/* Set microMIPS mode bit: XOR for jalx. */
*contpc ^= bit;
return 1;
break;
case beq_op:
case beql_op:
if (regs->regs[insn.i_format.rs] ==
regs->regs[insn.i_format.rt])
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case bne_op:
case bnel_op:
if (regs->regs[insn.i_format.rs] !=
regs->regs[insn.i_format.rt])
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case blez_op:
case blezl_op:
if ((long)regs->regs[insn.i_format.rs] <= 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case bgtz_op:
case bgtzl_op:
if ((long)regs->regs[insn.i_format.rs] > 0)
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case cop0_op:
case cop1_op:
case cop2_op:
case cop1x_op:
if (insn.i_format.rs == bc_op) {
preempt_disable();
if (is_fpu_owner())
asm volatile("cfc1\t%0,$31" : "=r" (fcr31));
else
fcr31 = current->thread.fpu.fcr31;
preempt_enable();
bit = (insn.i_format.rt >> 2);
bit += (bit != 0);
bit += 23;
switch (insn.i_format.rt & 3) {
case 0: /* bc1f */
case 2: /* bc1fl */
if (~fcr31 & (1 << bit))
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
case 1: /* bc1t */
case 3: /* bc1tl */
if (fcr31 & (1 << bit))
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
(insn.i_format.simmediate << 2);
else
*contpc = regs->cp0_epc +
dec_insn.pc_inc +
dec_insn.next_pc_inc;
return 1;
break;
}
}
break;
}
return 0;
}
/*
* In the Linux kernel, we support selection of FPR format on the
* basis of the Status.FR bit. If an FPU is not present, the FR bit
* is hardwired to zero, which would imply a 32-bit FPU even for
* 64-bit CPUs so we rather look at TIF_32BIT_REGS.
* FPU emu is slow and bulky and optimizing this function offers fairly
* sizeable benefits so we try to be clever and make this function return
* a constant whenever possible, that is on 64-bit kernels without O32
* compatibility enabled and on 32-bit kernels.
*/
static inline int cop1_64bit(struct pt_regs *xcp)
{
#if defined(CONFIG_64BIT) && !defined(CONFIG_MIPS32_O32)
return 1;
#elif defined(CONFIG_64BIT) && defined(CONFIG_MIPS32_O32)
return !test_thread_flag(TIF_32BIT_REGS);
#else
return 0;
#endif
}
#define SIFROMREG(si, x) ((si) = cop1_64bit(xcp) || !(x & 1) ? \
(int)ctx->fpr[x] : (int)(ctx->fpr[x & ~1] >> 32))
#define SITOREG(si, x) (ctx->fpr[x & ~(cop1_64bit(xcp) == 0)] = \
cop1_64bit(xcp) || !(x & 1) ? \
ctx->fpr[x & ~1] >> 32 << 32 | (u32)(si) : \
ctx->fpr[x & ~1] << 32 >> 32 | (u64)(si) << 32)
#define DIFROMREG(di, x) ((di) = ctx->fpr[x & ~(cop1_64bit(xcp) == 0)])
#define DITOREG(di, x) (ctx->fpr[x & ~(cop1_64bit(xcp) == 0)] = (di))
#define SPFROMREG(sp, x) SIFROMREG((sp).bits, x)
#define SPTOREG(sp, x) SITOREG((sp).bits, x)
#define DPFROMREG(dp, x) DIFROMREG((dp).bits, x)
#define DPTOREG(dp, x) DITOREG((dp).bits, x)
/*
* Emulate the single floating point instruction pointed at by EPC.
* Two instructions if the instruction is in a branch delay slot.
*/
static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
struct mm_decoded_insn dec_insn, void *__user *fault_addr)
{
mips_instruction ir;
unsigned long contpc = xcp->cp0_epc + dec_insn.pc_inc;
unsigned int cond;
int pc_inc;
/* XXX NEC Vr54xx bug workaround */
if (xcp->cp0_cause & CAUSEF_BD) {
if (dec_insn.micro_mips_mode) {
if (!mm_isBranchInstr(xcp, dec_insn, &contpc))
xcp->cp0_cause &= ~CAUSEF_BD;
} else {
if (!isBranchInstr(xcp, dec_insn, &contpc))
xcp->cp0_cause &= ~CAUSEF_BD;
}
}
if (xcp->cp0_cause & CAUSEF_BD) {
/*
* The instruction to be emulated is in a branch delay slot
* which means that we have to emulate the branch instruction
* BEFORE we do the cop1 instruction.
*
* This branch could be a COP1 branch, but in that case we
* would have had a trap for that instruction, and would not
* come through this route.
*
* Linux MIPS branch emulator operates on context, updating the
* cp0_epc.
*/
ir = dec_insn.next_insn; /* process delay slot instr */
pc_inc = dec_insn.next_pc_inc;
} else {
ir = dec_insn.insn; /* process current instr */
pc_inc = dec_insn.pc_inc;
}
/*
* Since microMIPS FPU instructios are a subset of MIPS32 FPU
* instructions, we want to convert microMIPS FPU instructions
* into MIPS32 instructions so that we could reuse all of the
* FPU emulation code.
*
* NOTE: We cannot do this for branch instructions since they
* are not a subset. Example: Cannot emulate a 16-bit
* aligned target address with a MIPS32 instruction.
*/
if (dec_insn.micro_mips_mode) {
/*
* If next instruction is a 16-bit instruction, then it
* it cannot be a FPU instruction. This could happen
* since we can be called for non-FPU instructions.
*/
if ((pc_inc == 2) ||
(microMIPS32_to_MIPS32((union mips_instruction *)&ir)
== SIGILL))
return SIGILL;
}
emul:
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, xcp, 0);
MIPS_FPU_EMU_INC_STATS(emulated);
switch (MIPSInst_OPCODE(ir)) {
case ldc1_op:{
u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u64 val;
MIPS_FPU_EMU_INC_STATS(loads);
if (!access_ok(VERIFY_READ, va, sizeof(u64))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
DITOREG(val, MIPSInst_RT(ir));
break;
}
case sdc1_op:{
u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u64 val;
MIPS_FPU_EMU_INC_STATS(stores);
DIFROMREG(val, MIPSInst_RT(ir));
if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
break;
}
case lwc1_op:{
u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u32 val;
MIPS_FPU_EMU_INC_STATS(loads);
if (!access_ok(VERIFY_READ, va, sizeof(u32))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
SITOREG(val, MIPSInst_RT(ir));
break;
}
case swc1_op:{
u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u32 val;
MIPS_FPU_EMU_INC_STATS(stores);
SIFROMREG(val, MIPSInst_RT(ir));
if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
break;
}
case cop1_op:
switch (MIPSInst_RS(ir)) {
#if defined(__mips64)
case dmfc_op:
/* copregister fs -> gpr[rt] */
if (MIPSInst_RT(ir) != 0) {
DIFROMREG(xcp->regs[MIPSInst_RT(ir)],
MIPSInst_RD(ir));
}
break;
case dmtc_op:
/* copregister fs <- rt */
DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir));
break;
#endif
case mfc_op:
/* copregister rd -> gpr[rt] */
if (MIPSInst_RT(ir) != 0) {
SIFROMREG(xcp->regs[MIPSInst_RT(ir)],
MIPSInst_RD(ir));
}
break;
case mtc_op:
/* copregister rd <- rt */
SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir));
break;
case cfc_op:{
/* cop control register rd -> gpr[rt] */
u32 value;
if (MIPSInst_RD(ir) == FPCREG_CSR) {
value = ctx->fcr31;
value = (value & ~FPU_CSR_RM) |
mips_rm[modeindex(value)];
#ifdef CSRTRACE
printk("%p gpr[%d]<-csr=%08x\n",
(void *) (xcp->cp0_epc),
MIPSInst_RT(ir), value);
#endif
}
else if (MIPSInst_RD(ir) == FPCREG_RID)
value = 0;
else
value = 0;
if (MIPSInst_RT(ir))
xcp->regs[MIPSInst_RT(ir)] = value;
break;
}
case ctc_op:{
/* copregister rd <- rt */
u32 value;
if (MIPSInst_RT(ir) == 0)
value = 0;
else
value = xcp->regs[MIPSInst_RT(ir)];
/* we only have one writable control reg
*/
if (MIPSInst_RD(ir) == FPCREG_CSR) {
#ifdef CSRTRACE
printk("%p gpr[%d]->csr=%08x\n",
(void *) (xcp->cp0_epc),
MIPSInst_RT(ir), value);
#endif
/*
* Don't write reserved bits,
* and convert to ieee library modes
*/
ctx->fcr31 = (value &
~(FPU_CSR_RSVD | FPU_CSR_RM)) |
ieee_rm[modeindex(value)];
}
if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) {
return SIGFPE;
}
break;
}
case bc_op:{
int likely = 0;
if (xcp->cp0_cause & CAUSEF_BD)
return SIGILL;
#if __mips >= 4
cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2];
#else
cond = ctx->fcr31 & FPU_CSR_COND;
#endif
switch (MIPSInst_RT(ir) & 3) {
case bcfl_op:
likely = 1;
case bcf_op:
cond = !cond;
break;
case bctl_op:
likely = 1;
case bct_op:
break;
default:
/* thats an illegal instruction */
return SIGILL;
}
xcp->cp0_cause |= CAUSEF_BD;
if (cond) {
/* branch taken: emulate dslot
* instruction
*/
xcp->cp0_epc += dec_insn.pc_inc;
contpc = MIPSInst_SIMM(ir);
ir = dec_insn.next_insn;
if (dec_insn.micro_mips_mode) {
contpc = (xcp->cp0_epc + (contpc << 1));
/* If 16-bit instruction, not FPU. */
if ((dec_insn.next_pc_inc == 2) ||
(microMIPS32_to_MIPS32((union mips_instruction *)&ir) == SIGILL)) {
/*
* Since this instruction will
* be put on the stack with
* 32-bit words, get around
* this problem by putting a
* NOP16 as the second one.
*/
if (dec_insn.next_pc_inc == 2)
ir = (ir & (~0xffff)) | MM_NOP16;
/*
* Single step the non-CP1
* instruction in the dslot.
*/
return mips_dsemul(xcp, ir, contpc);
}
} else
contpc = (xcp->cp0_epc + (contpc << 2));
switch (MIPSInst_OPCODE(ir)) {
case lwc1_op:
case swc1_op:
#if (__mips >= 2 || defined(__mips64))
case ldc1_op:
case sdc1_op:
#endif
case cop1_op:
#if __mips >= 4 && __mips != 32
case cop1x_op:
#endif
/* its one of ours */
goto emul;
#if __mips >= 4
case spec_op:
if (MIPSInst_FUNC(ir) == movc_op)
goto emul;
break;
#endif
}
/*
* Single step the non-cp1
* instruction in the dslot
*/
return mips_dsemul(xcp, ir, contpc);
}
else {
/* branch not taken */
if (likely) {
/*
* branch likely nullifies
* dslot if not taken
*/
xcp->cp0_epc += dec_insn.pc_inc;
contpc += dec_insn.pc_inc;
/*
* else continue & execute
* dslot as normal insn
*/
}
}
break;
}
default:
if (!(MIPSInst_RS(ir) & 0x10))
return SIGILL;
{
int sig;
/* a real fpu computation instruction */
if ((sig = fpu_emu(xcp, ctx, ir)))
return sig;
}
}
break;
#if __mips >= 4 && __mips != 32
case cop1x_op:{
int sig = fpux_emu(xcp, ctx, ir, fault_addr);
if (sig)
return sig;
break;
}
#endif
#if __mips >= 4
case spec_op:
if (MIPSInst_FUNC(ir) != movc_op)
return SIGILL;
cond = fpucondbit[MIPSInst_RT(ir) >> 2];
if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0))
xcp->regs[MIPSInst_RD(ir)] =
xcp->regs[MIPSInst_RS(ir)];
break;
#endif
default:
return SIGILL;
}
/* we did it !! */
xcp->cp0_epc = contpc;
xcp->cp0_cause &= ~CAUSEF_BD;
return 0;
}
/*
* Conversion table from MIPS compare ops 48-63
* cond = ieee754dp_cmp(x,y,IEEE754_UN,sig);
*/
static const unsigned char cmptab[8] = {
0, /* cmp_0 (sig) cmp_sf */
IEEE754_CUN, /* cmp_un (sig) cmp_ngle */
IEEE754_CEQ, /* cmp_eq (sig) cmp_seq */
IEEE754_CEQ | IEEE754_CUN, /* cmp_ueq (sig) cmp_ngl */
IEEE754_CLT, /* cmp_olt (sig) cmp_lt */
IEEE754_CLT | IEEE754_CUN, /* cmp_ult (sig) cmp_nge */
IEEE754_CLT | IEEE754_CEQ, /* cmp_ole (sig) cmp_le */
IEEE754_CLT | IEEE754_CEQ | IEEE754_CUN, /* cmp_ule (sig) cmp_ngt */
};
#if __mips >= 4 && __mips != 32
/*
* Additional MIPS4 instructions
*/
#define DEF3OP(name, p, f1, f2, f3) \
static ieee754##p fpemu_##p##_##name(ieee754##p r, ieee754##p s, \
ieee754##p t) \
{ \
struct _ieee754_csr ieee754_csr_save; \
s = f1(s, t); \
ieee754_csr_save = ieee754_csr; \
s = f2(s, r); \
ieee754_csr_save.cx |= ieee754_csr.cx; \
ieee754_csr_save.sx |= ieee754_csr.sx; \
s = f3(s); \
ieee754_csr.cx |= ieee754_csr_save.cx; \
ieee754_csr.sx |= ieee754_csr_save.sx; \
return s; \
}
static ieee754dp fpemu_dp_recip(ieee754dp d)
{
return ieee754dp_div(ieee754dp_one(0), d);
}
static ieee754dp fpemu_dp_rsqrt(ieee754dp d)
{
return ieee754dp_div(ieee754dp_one(0), ieee754dp_sqrt(d));
}
static ieee754sp fpemu_sp_recip(ieee754sp s)
{
return ieee754sp_div(ieee754sp_one(0), s);
}
static ieee754sp fpemu_sp_rsqrt(ieee754sp s)
{
return ieee754sp_div(ieee754sp_one(0), ieee754sp_sqrt(s));
}
DEF3OP(madd, sp, ieee754sp_mul, ieee754sp_add, );
DEF3OP(msub, sp, ieee754sp_mul, ieee754sp_sub, );
DEF3OP(nmadd, sp, ieee754sp_mul, ieee754sp_add, ieee754sp_neg);
DEF3OP(nmsub, sp, ieee754sp_mul, ieee754sp_sub, ieee754sp_neg);
DEF3OP(madd, dp, ieee754dp_mul, ieee754dp_add, );
DEF3OP(msub, dp, ieee754dp_mul, ieee754dp_sub, );
DEF3OP(nmadd, dp, ieee754dp_mul, ieee754dp_add, ieee754dp_neg);
DEF3OP(nmsub, dp, ieee754dp_mul, ieee754dp_sub, ieee754dp_neg);
static int fpux_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
mips_instruction ir, void *__user *fault_addr)
{
unsigned rcsr = 0; /* resulting csr */
MIPS_FPU_EMU_INC_STATS(cp1xops);
switch (MIPSInst_FMA_FFMT(ir)) {
case s_fmt:{ /* 0 */
ieee754sp(*handler) (ieee754sp, ieee754sp, ieee754sp);
ieee754sp fd, fr, fs, ft;
u32 __user *va;
u32 val;
switch (MIPSInst_FUNC(ir)) {
case lwxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(loads);
if (!access_ok(VERIFY_READ, va, sizeof(u32))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
SITOREG(val, MIPSInst_FD(ir));
break;
case swxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(stores);
SIFROMREG(val, MIPSInst_FS(ir));
if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
break;
case madd_s_op:
handler = fpemu_sp_madd;
goto scoptop;
case msub_s_op:
handler = fpemu_sp_msub;
goto scoptop;
case nmadd_s_op:
handler = fpemu_sp_nmadd;
goto scoptop;
case nmsub_s_op:
handler = fpemu_sp_nmsub;
goto scoptop;
scoptop:
SPFROMREG(fr, MIPSInst_FR(ir));
SPFROMREG(fs, MIPSInst_FS(ir));
SPFROMREG(ft, MIPSInst_FT(ir));
fd = (*handler) (fr, fs, ft);
SPTOREG(fd, MIPSInst_FD(ir));
copcsr:
if (ieee754_cxtest(IEEE754_INEXACT))
rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S;
if (ieee754_cxtest(IEEE754_UNDERFLOW))
rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S;
if (ieee754_cxtest(IEEE754_OVERFLOW))
rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S;
if (ieee754_cxtest(IEEE754_INVALID_OPERATION))
rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S;
ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr;
if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) {
/*printk ("SIGFPE: fpu csr = %08x\n",
ctx->fcr31); */
return SIGFPE;
}
break;
default:
return SIGILL;
}
break;
}
case d_fmt:{ /* 1 */
ieee754dp(*handler) (ieee754dp, ieee754dp, ieee754dp);
ieee754dp fd, fr, fs, ft;
u64 __user *va;
u64 val;
switch (MIPSInst_FUNC(ir)) {
case ldxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(loads);
if (!access_ok(VERIFY_READ, va, sizeof(u64))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
DITOREG(val, MIPSInst_FD(ir));
break;
case sdxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(stores);
DIFROMREG(val, MIPSInst_FS(ir));
if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGBUS;
}
if (__put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
*fault_addr = va;
return SIGSEGV;
}
break;
case madd_d_op:
handler = fpemu_dp_madd;
goto dcoptop;
case msub_d_op:
handler = fpemu_dp_msub;
goto dcoptop;
case nmadd_d_op:
handler = fpemu_dp_nmadd;
goto dcoptop;
case nmsub_d_op:
handler = fpemu_dp_nmsub;
goto dcoptop;
dcoptop:
DPFROMREG(fr, MIPSInst_FR(ir));
DPFROMREG(fs, MIPSInst_FS(ir));
DPFROMREG(ft, MIPSInst_FT(ir));
fd = (*handler) (fr, fs, ft);
DPTOREG(fd, MIPSInst_FD(ir));
goto copcsr;
default:
return SIGILL;
}
break;
}
case 0x7: /* 7 */
if (MIPSInst_FUNC(ir) != pfetch_op) {
return SIGILL;
}
/* ignore prefx operation */
break;
default:
return SIGILL;
}
return 0;
}
#endif
/*
* Emulate a single COP1 arithmetic instruction.
*/
static int fpu_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
mips_instruction ir)
{
int rfmt; /* resulting format */
unsigned rcsr = 0; /* resulting csr */
unsigned cond;
union {
ieee754dp d;
ieee754sp s;
int w;
#ifdef __mips64
s64 l;
#endif
} rv; /* resulting value */
MIPS_FPU_EMU_INC_STATS(cp1ops);
switch (rfmt = (MIPSInst_FFMT(ir) & 0xf)) {
case s_fmt:{ /* 0 */
union {
ieee754sp(*b) (ieee754sp, ieee754sp);
ieee754sp(*u) (ieee754sp);
} handler;
switch (MIPSInst_FUNC(ir)) {
/* binary ops */
case fadd_op:
handler.b = ieee754sp_add;
goto scopbop;
case fsub_op:
handler.b = ieee754sp_sub;
goto scopbop;
case fmul_op:
handler.b = ieee754sp_mul;
goto scopbop;
case fdiv_op:
handler.b = ieee754sp_div;
goto scopbop;
/* unary ops */
#if __mips >= 2 || defined(__mips64)
case fsqrt_op:
handler.u = ieee754sp_sqrt;
goto scopuop;
#endif
#if __mips >= 4 && __mips != 32
case frsqrt_op:
handler.u = fpemu_sp_rsqrt;
goto scopuop;
case frecip_op:
handler.u = fpemu_sp_recip;
goto scopuop;
#endif
#if __mips >= 4
case fmovc_op:
cond = fpucondbit[MIPSInst_FT(ir) >> 2];
if (((ctx->fcr31 & cond) != 0) !=
((MIPSInst_FT(ir) & 1) != 0))
return 0;
SPFROMREG(rv.s, MIPSInst_FS(ir));
break;
case fmovz_op:
if (xcp->regs[MIPSInst_FT(ir)] != 0)
return 0;
SPFROMREG(rv.s, MIPSInst_FS(ir));
break;
case fmovn_op:
if (xcp->regs[MIPSInst_FT(ir)] == 0)
return 0;
SPFROMREG(rv.s, MIPSInst_FS(ir));
break;
#endif
case fabs_op:
handler.u = ieee754sp_abs;
goto scopuop;
case fneg_op:
handler.u = ieee754sp_neg;
goto scopuop;
case fmov_op:
/* an easy one */
SPFROMREG(rv.s, MIPSInst_FS(ir));
goto copcsr;
/* binary op on handler */
scopbop:
{
ieee754sp fs, ft;
SPFROMREG(fs, MIPSInst_FS(ir));
SPFROMREG(ft, MIPSInst_FT(ir));
rv.s = (*handler.b) (fs, ft);
goto copcsr;
}
scopuop:
{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.s = (*handler.u) (fs);
goto copcsr;
}
copcsr:
if (ieee754_cxtest(IEEE754_INEXACT))
rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S;
if (ieee754_cxtest(IEEE754_UNDERFLOW))
rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S;
if (ieee754_cxtest(IEEE754_OVERFLOW))
rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S;
if (ieee754_cxtest(IEEE754_ZERO_DIVIDE))
rcsr |= FPU_CSR_DIV_X | FPU_CSR_DIV_S;
if (ieee754_cxtest(IEEE754_INVALID_OPERATION))
rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S;
break;
/* unary conv ops */
case fcvts_op:
return SIGILL; /* not defined */
case fcvtd_op:{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.d = ieee754dp_fsp(fs);
rfmt = d_fmt;
goto copcsr;
}
case fcvtw_op:{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.w = ieee754sp_tint(fs);
rfmt = w_fmt;
goto copcsr;
}
#if __mips >= 2 || defined(__mips64)
case fround_op:
case ftrunc_op:
case fceil_op:
case ffloor_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.w = ieee754sp_tint(fs);
ieee754_csr.rm = oldrm;
rfmt = w_fmt;
goto copcsr;
}
#endif /* __mips >= 2 */
#if defined(__mips64)
case fcvtl_op:{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.l = ieee754sp_tlong(fs);
rfmt = l_fmt;
goto copcsr;
}
case froundl_op:
case ftruncl_op:
case fceill_op:
case ffloorl_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.l = ieee754sp_tlong(fs);
ieee754_csr.rm = oldrm;
rfmt = l_fmt;
goto copcsr;
}
#endif /* defined(__mips64) */
default:
if (MIPSInst_FUNC(ir) >= fcmp_op) {
unsigned cmpop = MIPSInst_FUNC(ir) - fcmp_op;
ieee754sp fs, ft;
SPFROMREG(fs, MIPSInst_FS(ir));
SPFROMREG(ft, MIPSInst_FT(ir));
rv.w = ieee754sp_cmp(fs, ft,
cmptab[cmpop & 0x7], cmpop & 0x8);
rfmt = -1;
if ((cmpop & 0x8) && ieee754_cxtest
(IEEE754_INVALID_OPERATION))
rcsr = FPU_CSR_INV_X | FPU_CSR_INV_S;
else
goto copcsr;
}
else {
return SIGILL;
}
break;
}
break;
}
case d_fmt:{
union {
ieee754dp(*b) (ieee754dp, ieee754dp);
ieee754dp(*u) (ieee754dp);
} handler;
switch (MIPSInst_FUNC(ir)) {
/* binary ops */
case fadd_op:
handler.b = ieee754dp_add;
goto dcopbop;
case fsub_op:
handler.b = ieee754dp_sub;
goto dcopbop;
case fmul_op:
handler.b = ieee754dp_mul;
goto dcopbop;
case fdiv_op:
handler.b = ieee754dp_div;
goto dcopbop;
/* unary ops */
#if __mips >= 2 || defined(__mips64)
case fsqrt_op:
handler.u = ieee754dp_sqrt;
goto dcopuop;
#endif
#if __mips >= 4 && __mips != 32
case frsqrt_op:
handler.u = fpemu_dp_rsqrt;
goto dcopuop;
case frecip_op:
handler.u = fpemu_dp_recip;
goto dcopuop;
#endif
#if __mips >= 4
case fmovc_op:
cond = fpucondbit[MIPSInst_FT(ir) >> 2];
if (((ctx->fcr31 & cond) != 0) !=
((MIPSInst_FT(ir) & 1) != 0))
return 0;
DPFROMREG(rv.d, MIPSInst_FS(ir));
break;
case fmovz_op:
if (xcp->regs[MIPSInst_FT(ir)] != 0)
return 0;
DPFROMREG(rv.d, MIPSInst_FS(ir));
break;
case fmovn_op:
if (xcp->regs[MIPSInst_FT(ir)] == 0)
return 0;
DPFROMREG(rv.d, MIPSInst_FS(ir));
break;
#endif
case fabs_op:
handler.u = ieee754dp_abs;
goto dcopuop;
case fneg_op:
handler.u = ieee754dp_neg;
goto dcopuop;
case fmov_op:
/* an easy one */
DPFROMREG(rv.d, MIPSInst_FS(ir));
goto copcsr;
/* binary op on handler */
dcopbop:{
ieee754dp fs, ft;
DPFROMREG(fs, MIPSInst_FS(ir));
DPFROMREG(ft, MIPSInst_FT(ir));
rv.d = (*handler.b) (fs, ft);
goto copcsr;
}
dcopuop:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.d = (*handler.u) (fs);
goto copcsr;
}
/* unary conv ops */
case fcvts_op:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.s = ieee754sp_fdp(fs);
rfmt = s_fmt;
goto copcsr;
}
case fcvtd_op:
return SIGILL; /* not defined */
case fcvtw_op:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.w = ieee754dp_tint(fs); /* wrong */
rfmt = w_fmt;
goto copcsr;
}
#if __mips >= 2 || defined(__mips64)
case fround_op:
case ftrunc_op:
case fceil_op:
case ffloor_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.w = ieee754dp_tint(fs);
ieee754_csr.rm = oldrm;
rfmt = w_fmt;
goto copcsr;
}
#endif
#if defined(__mips64)
case fcvtl_op:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.l = ieee754dp_tlong(fs);
rfmt = l_fmt;
goto copcsr;
}
case froundl_op:
case ftruncl_op:
case fceill_op:
case ffloorl_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.l = ieee754dp_tlong(fs);
ieee754_csr.rm = oldrm;
rfmt = l_fmt;
goto copcsr;
}
#endif /* __mips >= 3 */
default:
if (MIPSInst_FUNC(ir) >= fcmp_op) {
unsigned cmpop = MIPSInst_FUNC(ir) - fcmp_op;
ieee754dp fs, ft;
DPFROMREG(fs, MIPSInst_FS(ir));
DPFROMREG(ft, MIPSInst_FT(ir));
rv.w = ieee754dp_cmp(fs, ft,
cmptab[cmpop & 0x7], cmpop & 0x8);
rfmt = -1;
if ((cmpop & 0x8)
&&
ieee754_cxtest
(IEEE754_INVALID_OPERATION))
rcsr = FPU_CSR_INV_X | FPU_CSR_INV_S;
else
goto copcsr;
}
else {
return SIGILL;
}
break;
}
break;
}
case w_fmt:{
ieee754sp fs;
switch (MIPSInst_FUNC(ir)) {
case fcvts_op:
/* convert word to single precision real */
SPFROMREG(fs, MIPSInst_FS(ir));
rv.s = ieee754sp_fint(fs.bits);
rfmt = s_fmt;
goto copcsr;
case fcvtd_op:
/* convert word to double precision real */
SPFROMREG(fs, MIPSInst_FS(ir));
rv.d = ieee754dp_fint(fs.bits);
rfmt = d_fmt;
goto copcsr;
default:
return SIGILL;
}
break;
}
#if defined(__mips64)
case l_fmt:{
switch (MIPSInst_FUNC(ir)) {
case fcvts_op:
/* convert long to single precision real */
rv.s = ieee754sp_flong(ctx->fpr[MIPSInst_FS(ir)]);
rfmt = s_fmt;
goto copcsr;
case fcvtd_op:
/* convert long to double precision real */
rv.d = ieee754dp_flong(ctx->fpr[MIPSInst_FS(ir)]);
rfmt = d_fmt;
goto copcsr;
default:
return SIGILL;
}
break;
}
#endif
default:
return SIGILL;
}
/*
* Update the fpu CSR register for this operation.
* If an exception is required, generate a tidy SIGFPE exception,
* without updating the result register.
* Note: cause exception bits do not accumulate, they are rewritten
* for each op; only the flag/sticky bits accumulate.
*/
ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr;
if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) {
/*printk ("SIGFPE: fpu csr = %08x\n",ctx->fcr31); */
return SIGFPE;
}
/*
* Now we can safely write the result back to the register file.
*/
switch (rfmt) {
case -1:{
#if __mips >= 4
cond = fpucondbit[MIPSInst_FD(ir) >> 2];
#else
cond = FPU_CSR_COND;
#endif
if (rv.w)
ctx->fcr31 |= cond;
else
ctx->fcr31 &= ~cond;
break;
}
case d_fmt:
DPTOREG(rv.d, MIPSInst_FD(ir));
break;
case s_fmt:
SPTOREG(rv.s, MIPSInst_FD(ir));
break;
case w_fmt:
SITOREG(rv.w, MIPSInst_FD(ir));
break;
#if defined(__mips64)
case l_fmt:
DITOREG(rv.l, MIPSInst_FD(ir));
break;
#endif
default:
return SIGILL;
}
return 0;
}
int fpu_emulator_cop1Handler(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
int has_fpu, void *__user *fault_addr)
{
unsigned long oldepc, prevepc;
struct mm_decoded_insn dec_insn;
u16 instr[4];
u16 *instr_ptr;
int sig = 0;
oldepc = xcp->cp0_epc;
do {
prevepc = xcp->cp0_epc;
if (get_isa16_mode(prevepc) && cpu_has_mmips) {
/*
* Get next 2 microMIPS instructions and convert them
* into 32-bit instructions.
*/
if ((get_user(instr[0], (u16 __user *)msk_isa16_mode(xcp->cp0_epc))) ||
(get_user(instr[1], (u16 __user *)msk_isa16_mode(xcp->cp0_epc + 2))) ||
(get_user(instr[2], (u16 __user *)msk_isa16_mode(xcp->cp0_epc + 4))) ||
(get_user(instr[3], (u16 __user *)msk_isa16_mode(xcp->cp0_epc + 6)))) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
instr_ptr = instr;
/* Get first instruction. */
if (mm_insn_16bit(*instr_ptr)) {
/* Duplicate the half-word. */
dec_insn.insn = (*instr_ptr << 16) |
(*instr_ptr);
/* 16-bit instruction. */
dec_insn.pc_inc = 2;
instr_ptr += 1;
} else {
dec_insn.insn = (*instr_ptr << 16) |
*(instr_ptr+1);
/* 32-bit instruction. */
dec_insn.pc_inc = 4;
instr_ptr += 2;
}
/* Get second instruction. */
if (mm_insn_16bit(*instr_ptr)) {
/* Duplicate the half-word. */
dec_insn.next_insn = (*instr_ptr << 16) |
(*instr_ptr);
/* 16-bit instruction. */
dec_insn.next_pc_inc = 2;
} else {
dec_insn.next_insn = (*instr_ptr << 16) |
*(instr_ptr+1);
/* 32-bit instruction. */
dec_insn.next_pc_inc = 4;
}
dec_insn.micro_mips_mode = 1;
} else {
if ((get_user(dec_insn.insn,
(mips_instruction __user *) xcp->cp0_epc)) ||
(get_user(dec_insn.next_insn,
(mips_instruction __user *)(xcp->cp0_epc+4)))) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
dec_insn.pc_inc = 4;
dec_insn.next_pc_inc = 4;
dec_insn.micro_mips_mode = 0;
}
if ((dec_insn.insn == 0) ||
((dec_insn.pc_inc == 2) &&
((dec_insn.insn & 0xffff) == MM_NOP16)))
xcp->cp0_epc += dec_insn.pc_inc; /* Skip NOPs */
else {
/*
* The 'ieee754_csr' is an alias of
* ctx->fcr31. No need to copy ctx->fcr31 to
* ieee754_csr. But ieee754_csr.rm is ieee
* library modes. (not mips rounding mode)
*/
/* convert to ieee library modes */
ieee754_csr.rm = ieee_rm[ieee754_csr.rm];
sig = cop1Emulate(xcp, ctx, dec_insn, fault_addr);
/* revert to mips rounding mode */
ieee754_csr.rm = mips_rm[ieee754_csr.rm];
}
if (has_fpu)
break;
if (sig)
break;
cond_resched();
} while (xcp->cp0_epc > prevepc);
/* SIGILL indicates a non-fpu instruction */
if (sig == SIGILL && xcp->cp0_epc != oldepc)
/* but if epc has advanced, then ignore it */
sig = 0;
return sig;
}
#ifdef CONFIG_DEBUG_FS
static int fpuemu_stat_get(void *data, u64 *val)
{
int cpu;
unsigned long sum = 0;
for_each_online_cpu(cpu) {
struct mips_fpu_emulator_stats *ps;
local_t *pv;
ps = &per_cpu(fpuemustats, cpu);
pv = (void *)ps + (unsigned long)data;
sum += local_read(pv);
}
*val = sum;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_fpuemu_stat, fpuemu_stat_get, NULL, "%llu\n");
extern struct dentry *mips_debugfs_dir;
static int __init debugfs_fpuemu(void)
{
struct dentry *d, *dir;
if (!mips_debugfs_dir)
return -ENODEV;
dir = debugfs_create_dir("fpuemustats", mips_debugfs_dir);
if (!dir)
return -ENOMEM;
#define FPU_STAT_CREATE(M) \
do { \
d = debugfs_create_file(#M , S_IRUGO, dir, \
(void *)offsetof(struct mips_fpu_emulator_stats, M), \
&fops_fpuemu_stat); \
if (!d) \
return -ENOMEM; \
} while (0)
FPU_STAT_CREATE(emulated);
FPU_STAT_CREATE(loads);
FPU_STAT_CREATE(stores);
FPU_STAT_CREATE(cp1ops);
FPU_STAT_CREATE(cp1xops);
FPU_STAT_CREATE(errors);
return 0;
}
__initcall(debugfs_fpuemu);
#endif
| gpl-2.0 |
CaptainThrowback/kernel_htc_m8ql | arch/s390/hypfs/hypfs_dbfs.c | 2009 | 2473 | /*
* Hypervisor filesystem for Linux on s390 - debugfs interface
*
* Copyright IBM Corp. 2010
* Author(s): Michael Holzheu <holzheu@linux.vnet.ibm.com>
*/
#include <linux/slab.h>
#include "hypfs.h"
static struct dentry *dbfs_dir;
static struct hypfs_dbfs_data *hypfs_dbfs_data_alloc(struct hypfs_dbfs_file *f)
{
struct hypfs_dbfs_data *data;
data = kmalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return NULL;
kref_init(&data->kref);
data->dbfs_file = f;
return data;
}
static void hypfs_dbfs_data_free(struct kref *kref)
{
struct hypfs_dbfs_data *data;
data = container_of(kref, struct hypfs_dbfs_data, kref);
data->dbfs_file->data_free(data->buf_free_ptr);
kfree(data);
}
static void data_free_delayed(struct work_struct *work)
{
struct hypfs_dbfs_data *data;
struct hypfs_dbfs_file *df;
df = container_of(work, struct hypfs_dbfs_file, data_free_work.work);
mutex_lock(&df->lock);
data = df->data;
df->data = NULL;
mutex_unlock(&df->lock);
kref_put(&data->kref, hypfs_dbfs_data_free);
}
static ssize_t dbfs_read(struct file *file, char __user *buf,
size_t size, loff_t *ppos)
{
struct hypfs_dbfs_data *data;
struct hypfs_dbfs_file *df;
ssize_t rc;
if (*ppos != 0)
return 0;
df = file_inode(file)->i_private;
mutex_lock(&df->lock);
if (!df->data) {
data = hypfs_dbfs_data_alloc(df);
if (!data) {
mutex_unlock(&df->lock);
return -ENOMEM;
}
rc = df->data_create(&data->buf, &data->buf_free_ptr,
&data->size);
if (rc) {
mutex_unlock(&df->lock);
kfree(data);
return rc;
}
df->data = data;
schedule_delayed_work(&df->data_free_work, HZ);
}
data = df->data;
kref_get(&data->kref);
mutex_unlock(&df->lock);
rc = simple_read_from_buffer(buf, size, ppos, data->buf, data->size);
kref_put(&data->kref, hypfs_dbfs_data_free);
return rc;
}
static const struct file_operations dbfs_ops = {
.read = dbfs_read,
.llseek = no_llseek,
};
int hypfs_dbfs_create_file(struct hypfs_dbfs_file *df)
{
df->dentry = debugfs_create_file(df->name, 0400, dbfs_dir, df,
&dbfs_ops);
if (IS_ERR(df->dentry))
return PTR_ERR(df->dentry);
mutex_init(&df->lock);
INIT_DELAYED_WORK(&df->data_free_work, data_free_delayed);
return 0;
}
void hypfs_dbfs_remove_file(struct hypfs_dbfs_file *df)
{
debugfs_remove(df->dentry);
}
int hypfs_dbfs_init(void)
{
dbfs_dir = debugfs_create_dir("s390_hypfs", NULL);
return PTR_RET(dbfs_dir);
}
void hypfs_dbfs_exit(void)
{
debugfs_remove(dbfs_dir);
}
| gpl-2.0 |
HazyTeam/android_kernel_moto_shamu | drivers/input/touchscreen/penmount.c | 2521 | 7086 | /*
* Penmount serial touchscreen driver
*
* Copyright (c) 2006 Rick Koch <n1gp@hotmail.com>
* Copyright (c) 2011 John Sung <penmount.touch@gmail.com>
*
* Based on ELO driver (drivers/input/touchscreen/elo.c)
* Copyright (c) 2004 Vojtech Pavlik
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "PenMount serial touchscreen driver"
MODULE_AUTHOR("Rick Koch <n1gp@hotmail.com>");
MODULE_AUTHOR("John Sung <penmount.touch@gmail.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define PM_MAX_LENGTH 6
#define PM_MAX_MTSLOT 16
#define PM_3000_MTSLOT 2
#define PM_6250_MTSLOT 12
/*
* Multi-touch slot
*/
struct mt_slot {
unsigned short x, y;
bool active; /* is the touch valid? */
};
/*
* Per-touchscreen data.
*/
struct pm {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[PM_MAX_LENGTH];
char phys[32];
unsigned char packetsize;
unsigned char maxcontacts;
struct mt_slot slots[PM_MAX_MTSLOT];
void (*parse_packet)(struct pm *);
};
/*
* pm_mtevent() sends mt events and also emulates pointer movement
*/
static void pm_mtevent(struct pm *pm, struct input_dev *input)
{
int i;
for (i = 0; i < pm->maxcontacts; ++i) {
input_mt_slot(input, i);
input_mt_report_slot_state(input, MT_TOOL_FINGER,
pm->slots[i].active);
if (pm->slots[i].active) {
input_event(input, EV_ABS, ABS_MT_POSITION_X, pm->slots[i].x);
input_event(input, EV_ABS, ABS_MT_POSITION_Y, pm->slots[i].y);
}
}
input_mt_report_pointer_emulation(input, true);
input_sync(input);
}
/*
* pm_checkpacket() checks if data packet is valid
*/
static bool pm_checkpacket(unsigned char *packet)
{
int total = 0;
int i;
for (i = 0; i < 5; i++)
total += packet[i];
return packet[5] == (unsigned char)~(total & 0xff);
}
static void pm_parse_9000(struct pm *pm)
{
struct input_dev *dev = pm->dev;
if ((pm->data[0] & 0x80) && pm->packetsize == ++pm->idx) {
input_report_abs(dev, ABS_X, pm->data[1] * 128 + pm->data[2]);
input_report_abs(dev, ABS_Y, pm->data[3] * 128 + pm->data[4]);
input_report_key(dev, BTN_TOUCH, !!(pm->data[0] & 0x40));
input_sync(dev);
pm->idx = 0;
}
}
static void pm_parse_6000(struct pm *pm)
{
struct input_dev *dev = pm->dev;
if ((pm->data[0] & 0xbf) == 0x30 && pm->packetsize == ++pm->idx) {
if (pm_checkpacket(pm->data)) {
input_report_abs(dev, ABS_X,
pm->data[2] * 256 + pm->data[1]);
input_report_abs(dev, ABS_Y,
pm->data[4] * 256 + pm->data[3]);
input_report_key(dev, BTN_TOUCH, pm->data[0] & 0x40);
input_sync(dev);
}
pm->idx = 0;
}
}
static void pm_parse_3000(struct pm *pm)
{
struct input_dev *dev = pm->dev;
if ((pm->data[0] & 0xce) == 0x40 && pm->packetsize == ++pm->idx) {
if (pm_checkpacket(pm->data)) {
int slotnum = pm->data[0] & 0x0f;
pm->slots[slotnum].active = pm->data[0] & 0x30;
pm->slots[slotnum].x = pm->data[2] * 256 + pm->data[1];
pm->slots[slotnum].y = pm->data[4] * 256 + pm->data[3];
pm_mtevent(pm, dev);
}
pm->idx = 0;
}
}
static void pm_parse_6250(struct pm *pm)
{
struct input_dev *dev = pm->dev;
if ((pm->data[0] & 0xb0) == 0x30 && pm->packetsize == ++pm->idx) {
if (pm_checkpacket(pm->data)) {
int slotnum = pm->data[0] & 0x0f;
pm->slots[slotnum].active = pm->data[0] & 0x40;
pm->slots[slotnum].x = pm->data[2] * 256 + pm->data[1];
pm->slots[slotnum].y = pm->data[4] * 256 + pm->data[3];
pm_mtevent(pm, dev);
}
pm->idx = 0;
}
}
static irqreturn_t pm_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct pm *pm = serio_get_drvdata(serio);
pm->data[pm->idx] = data;
pm->parse_packet(pm);
return IRQ_HANDLED;
}
/*
* pm_disconnect() is the opposite of pm_connect()
*/
static void pm_disconnect(struct serio *serio)
{
struct pm *pm = serio_get_drvdata(serio);
serio_close(serio);
input_unregister_device(pm->dev);
kfree(pm);
serio_set_drvdata(serio, NULL);
}
/*
* pm_connect() is the routine that is called when someone adds a
* new serio device that supports PenMount protocol and registers it as
* an input device.
*/
static int pm_connect(struct serio *serio, struct serio_driver *drv)
{
struct pm *pm;
struct input_dev *input_dev;
int max_x, max_y;
int err;
pm = kzalloc(sizeof(struct pm), GFP_KERNEL);
input_dev = input_allocate_device();
if (!pm || !input_dev) {
err = -ENOMEM;
goto fail1;
}
pm->serio = serio;
pm->dev = input_dev;
snprintf(pm->phys, sizeof(pm->phys), "%s/input0", serio->phys);
pm->maxcontacts = 1;
input_dev->name = "PenMount Serial TouchScreen";
input_dev->phys = pm->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_PENMOUNT;
input_dev->id.product = 0;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
switch (serio->id.id) {
default:
case 0:
pm->packetsize = 5;
pm->parse_packet = pm_parse_9000;
input_dev->id.product = 0x9000;
max_x = max_y = 0x3ff;
break;
case 1:
pm->packetsize = 6;
pm->parse_packet = pm_parse_6000;
input_dev->id.product = 0x6000;
max_x = max_y = 0x3ff;
break;
case 2:
pm->packetsize = 6;
pm->parse_packet = pm_parse_3000;
input_dev->id.product = 0x3000;
max_x = max_y = 0x7ff;
pm->maxcontacts = PM_3000_MTSLOT;
break;
case 3:
pm->packetsize = 6;
pm->parse_packet = pm_parse_6250;
input_dev->id.product = 0x6250;
max_x = max_y = 0x3ff;
pm->maxcontacts = PM_6250_MTSLOT;
break;
}
input_set_abs_params(pm->dev, ABS_X, 0, max_x, 0, 0);
input_set_abs_params(pm->dev, ABS_Y, 0, max_y, 0, 0);
if (pm->maxcontacts > 1) {
input_mt_init_slots(pm->dev, pm->maxcontacts, 0);
input_set_abs_params(pm->dev,
ABS_MT_POSITION_X, 0, max_x, 0, 0);
input_set_abs_params(pm->dev,
ABS_MT_POSITION_Y, 0, max_y, 0, 0);
}
serio_set_drvdata(serio, pm);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(pm->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(pm);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id pm_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_PENMOUNT,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, pm_serio_ids);
static struct serio_driver pm_drv = {
.driver = {
.name = "serio-penmount",
},
.description = DRIVER_DESC,
.id_table = pm_serio_ids,
.interrupt = pm_interrupt,
.connect = pm_connect,
.disconnect = pm_disconnect,
};
module_serio_driver(pm_drv);
| gpl-2.0 |
Hybrid-Rom/kernel_lge_ls970 | drivers/net/ethernet/intel/igbvf/ethtool.c | 2777 | 13342 | /*******************************************************************************
Intel(R) 82576 Virtual Function Linux driver
Copyright(c) 2009 - 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.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
/* ethtool support for igbvf */
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include "igbvf.h"
#include <linux/if_vlan.h>
struct igbvf_stats {
char stat_string[ETH_GSTRING_LEN];
int sizeof_stat;
int stat_offset;
int base_stat_offset;
};
#define IGBVF_STAT(current, base) \
sizeof(((struct igbvf_adapter *)0)->current), \
offsetof(struct igbvf_adapter, current), \
offsetof(struct igbvf_adapter, base)
static const struct igbvf_stats igbvf_gstrings_stats[] = {
{ "rx_packets", IGBVF_STAT(stats.gprc, stats.base_gprc) },
{ "tx_packets", IGBVF_STAT(stats.gptc, stats.base_gptc) },
{ "rx_bytes", IGBVF_STAT(stats.gorc, stats.base_gorc) },
{ "tx_bytes", IGBVF_STAT(stats.gotc, stats.base_gotc) },
{ "multicast", IGBVF_STAT(stats.mprc, stats.base_mprc) },
{ "lbrx_bytes", IGBVF_STAT(stats.gorlbc, stats.base_gorlbc) },
{ "lbrx_packets", IGBVF_STAT(stats.gprlbc, stats.base_gprlbc) },
{ "tx_restart_queue", IGBVF_STAT(restart_queue, zero_base) },
{ "rx_long_byte_count", IGBVF_STAT(stats.gorc, stats.base_gorc) },
{ "rx_csum_offload_good", IGBVF_STAT(hw_csum_good, zero_base) },
{ "rx_csum_offload_errors", IGBVF_STAT(hw_csum_err, zero_base) },
{ "rx_header_split", IGBVF_STAT(rx_hdr_split, zero_base) },
{ "alloc_rx_buff_failed", IGBVF_STAT(alloc_rx_buff_failed, zero_base) },
};
#define IGBVF_GLOBAL_STATS_LEN ARRAY_SIZE(igbvf_gstrings_stats)
static const char igbvf_gstrings_test[][ETH_GSTRING_LEN] = {
"Link test (on/offline)"
};
#define IGBVF_TEST_LEN ARRAY_SIZE(igbvf_gstrings_test)
static int igbvf_get_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 status;
ecmd->supported = SUPPORTED_1000baseT_Full;
ecmd->advertising = ADVERTISED_1000baseT_Full;
ecmd->port = -1;
ecmd->transceiver = XCVR_DUMMY1;
status = er32(STATUS);
if (status & E1000_STATUS_LU) {
if (status & E1000_STATUS_SPEED_1000)
ethtool_cmd_speed_set(ecmd, SPEED_1000);
else if (status & E1000_STATUS_SPEED_100)
ethtool_cmd_speed_set(ecmd, SPEED_100);
else
ethtool_cmd_speed_set(ecmd, SPEED_10);
if (status & E1000_STATUS_FD)
ecmd->duplex = DUPLEX_FULL;
else
ecmd->duplex = DUPLEX_HALF;
} else {
ethtool_cmd_speed_set(ecmd, -1);
ecmd->duplex = -1;
}
ecmd->autoneg = AUTONEG_DISABLE;
return 0;
}
static int igbvf_set_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
return -EOPNOTSUPP;
}
static void igbvf_get_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
return;
}
static int igbvf_set_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
return -EOPNOTSUPP;
}
static u32 igbvf_get_msglevel(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
return adapter->msg_enable;
}
static void igbvf_set_msglevel(struct net_device *netdev, u32 data)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
adapter->msg_enable = data;
}
static int igbvf_get_regs_len(struct net_device *netdev)
{
#define IGBVF_REGS_LEN 8
return IGBVF_REGS_LEN * sizeof(u32);
}
static void igbvf_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *p)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 *regs_buff = p;
memset(p, 0, IGBVF_REGS_LEN * sizeof(u32));
regs->version = (1 << 24) | (adapter->pdev->revision << 16) |
adapter->pdev->device;
regs_buff[0] = er32(CTRL);
regs_buff[1] = er32(STATUS);
regs_buff[2] = er32(RDLEN(0));
regs_buff[3] = er32(RDH(0));
regs_buff[4] = er32(RDT(0));
regs_buff[5] = er32(TDLEN(0));
regs_buff[6] = er32(TDH(0));
regs_buff[7] = er32(TDT(0));
}
static int igbvf_get_eeprom_len(struct net_device *netdev)
{
return 0;
}
static int igbvf_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
return -EOPNOTSUPP;
}
static int igbvf_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
return -EOPNOTSUPP;
}
static void igbvf_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
strlcpy(drvinfo->driver, igbvf_driver_name, sizeof(drvinfo->driver));
strlcpy(drvinfo->version, igbvf_driver_version,
sizeof(drvinfo->version));
strlcpy(drvinfo->bus_info, pci_name(adapter->pdev),
sizeof(drvinfo->bus_info));
drvinfo->regdump_len = igbvf_get_regs_len(netdev);
drvinfo->eedump_len = igbvf_get_eeprom_len(netdev);
}
static void igbvf_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct igbvf_ring *tx_ring = adapter->tx_ring;
struct igbvf_ring *rx_ring = adapter->rx_ring;
ring->rx_max_pending = IGBVF_MAX_RXD;
ring->tx_max_pending = IGBVF_MAX_TXD;
ring->rx_pending = rx_ring->count;
ring->tx_pending = tx_ring->count;
}
static int igbvf_set_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct igbvf_ring *temp_ring;
int err = 0;
u32 new_rx_count, new_tx_count;
if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
return -EINVAL;
new_rx_count = max(ring->rx_pending, (u32)IGBVF_MIN_RXD);
new_rx_count = min(new_rx_count, (u32)IGBVF_MAX_RXD);
new_rx_count = ALIGN(new_rx_count, REQ_RX_DESCRIPTOR_MULTIPLE);
new_tx_count = max(ring->tx_pending, (u32)IGBVF_MIN_TXD);
new_tx_count = min(new_tx_count, (u32)IGBVF_MAX_TXD);
new_tx_count = ALIGN(new_tx_count, REQ_TX_DESCRIPTOR_MULTIPLE);
if ((new_tx_count == adapter->tx_ring->count) &&
(new_rx_count == adapter->rx_ring->count)) {
/* nothing to do */
return 0;
}
while (test_and_set_bit(__IGBVF_RESETTING, &adapter->state))
msleep(1);
if (!netif_running(adapter->netdev)) {
adapter->tx_ring->count = new_tx_count;
adapter->rx_ring->count = new_rx_count;
goto clear_reset;
}
temp_ring = vmalloc(sizeof(struct igbvf_ring));
if (!temp_ring) {
err = -ENOMEM;
goto clear_reset;
}
igbvf_down(adapter);
/*
* We can't just free everything and then setup again,
* because the ISRs in MSI-X mode get passed pointers
* to the tx and rx ring structs.
*/
if (new_tx_count != adapter->tx_ring->count) {
memcpy(temp_ring, adapter->tx_ring, sizeof(struct igbvf_ring));
temp_ring->count = new_tx_count;
err = igbvf_setup_tx_resources(adapter, temp_ring);
if (err)
goto err_setup;
igbvf_free_tx_resources(adapter->tx_ring);
memcpy(adapter->tx_ring, temp_ring, sizeof(struct igbvf_ring));
}
if (new_rx_count != adapter->rx_ring->count) {
memcpy(temp_ring, adapter->rx_ring, sizeof(struct igbvf_ring));
temp_ring->count = new_rx_count;
err = igbvf_setup_rx_resources(adapter, temp_ring);
if (err)
goto err_setup;
igbvf_free_rx_resources(adapter->rx_ring);
memcpy(adapter->rx_ring, temp_ring,sizeof(struct igbvf_ring));
}
err_setup:
igbvf_up(adapter);
vfree(temp_ring);
clear_reset:
clear_bit(__IGBVF_RESETTING, &adapter->state);
return err;
}
static int igbvf_link_test(struct igbvf_adapter *adapter, u64 *data)
{
struct e1000_hw *hw = &adapter->hw;
*data = 0;
hw->mac.ops.check_for_link(hw);
if (!(er32(STATUS) & E1000_STATUS_LU))
*data = 1;
return *data;
}
static void igbvf_diag_test(struct net_device *netdev,
struct ethtool_test *eth_test, u64 *data)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
set_bit(__IGBVF_TESTING, &adapter->state);
/*
* Link test performed before hardware reset so autoneg doesn't
* interfere with test result
*/
if (igbvf_link_test(adapter, &data[0]))
eth_test->flags |= ETH_TEST_FL_FAILED;
clear_bit(__IGBVF_TESTING, &adapter->state);
msleep_interruptible(4 * 1000);
}
static void igbvf_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
wol->supported = 0;
wol->wolopts = 0;
}
static int igbvf_set_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
return -EOPNOTSUPP;
}
static int igbvf_get_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ec)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (adapter->requested_itr <= 3)
ec->rx_coalesce_usecs = adapter->requested_itr;
else
ec->rx_coalesce_usecs = adapter->current_itr >> 2;
return 0;
}
static int igbvf_set_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ec)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if ((ec->rx_coalesce_usecs > IGBVF_MAX_ITR_USECS) ||
((ec->rx_coalesce_usecs > 3) &&
(ec->rx_coalesce_usecs < IGBVF_MIN_ITR_USECS)) ||
(ec->rx_coalesce_usecs == 2))
return -EINVAL;
/* convert to rate of irq's per second */
if (ec->rx_coalesce_usecs && ec->rx_coalesce_usecs <= 3) {
adapter->current_itr = IGBVF_START_ITR;
adapter->requested_itr = ec->rx_coalesce_usecs;
} else {
adapter->current_itr = ec->rx_coalesce_usecs << 2;
adapter->requested_itr = 1000000000 /
(adapter->current_itr * 256);
}
writel(adapter->current_itr,
hw->hw_addr + adapter->rx_ring->itr_register);
return 0;
}
static int igbvf_nway_reset(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev))
igbvf_reinit_locked(adapter);
return 0;
}
static void igbvf_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats,
u64 *data)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
int i;
igbvf_update_stats(adapter);
for (i = 0; i < IGBVF_GLOBAL_STATS_LEN; i++) {
char *p = (char *)adapter +
igbvf_gstrings_stats[i].stat_offset;
char *b = (char *)adapter +
igbvf_gstrings_stats[i].base_stat_offset;
data[i] = ((igbvf_gstrings_stats[i].sizeof_stat ==
sizeof(u64)) ? (*(u64 *)p - *(u64 *)b) :
(*(u32 *)p - *(u32 *)b));
}
}
static int igbvf_get_sset_count(struct net_device *dev, int stringset)
{
switch(stringset) {
case ETH_SS_TEST:
return IGBVF_TEST_LEN;
case ETH_SS_STATS:
return IGBVF_GLOBAL_STATS_LEN;
default:
return -EINVAL;
}
}
static void igbvf_get_strings(struct net_device *netdev, u32 stringset,
u8 *data)
{
u8 *p = data;
int i;
switch (stringset) {
case ETH_SS_TEST:
memcpy(data, *igbvf_gstrings_test, sizeof(igbvf_gstrings_test));
break;
case ETH_SS_STATS:
for (i = 0; i < IGBVF_GLOBAL_STATS_LEN; i++) {
memcpy(p, igbvf_gstrings_stats[i].stat_string,
ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
break;
}
}
static const struct ethtool_ops igbvf_ethtool_ops = {
.get_settings = igbvf_get_settings,
.set_settings = igbvf_set_settings,
.get_drvinfo = igbvf_get_drvinfo,
.get_regs_len = igbvf_get_regs_len,
.get_regs = igbvf_get_regs,
.get_wol = igbvf_get_wol,
.set_wol = igbvf_set_wol,
.get_msglevel = igbvf_get_msglevel,
.set_msglevel = igbvf_set_msglevel,
.nway_reset = igbvf_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = igbvf_get_eeprom_len,
.get_eeprom = igbvf_get_eeprom,
.set_eeprom = igbvf_set_eeprom,
.get_ringparam = igbvf_get_ringparam,
.set_ringparam = igbvf_set_ringparam,
.get_pauseparam = igbvf_get_pauseparam,
.set_pauseparam = igbvf_set_pauseparam,
.self_test = igbvf_diag_test,
.get_sset_count = igbvf_get_sset_count,
.get_strings = igbvf_get_strings,
.get_ethtool_stats = igbvf_get_ethtool_stats,
.get_coalesce = igbvf_get_coalesce,
.set_coalesce = igbvf_set_coalesce,
};
void igbvf_set_ethtool_ops(struct net_device *netdev)
{
SET_ETHTOOL_OPS(netdev, &igbvf_ethtool_ops);
}
| gpl-2.0 |
XPerience-AOSP-Lollipop/android_kernel_sony_lbmsm8960t | net/wireless/mlme.c | 4569 | 26084 | /*
* cfg80211 MLME SAP interface
*
* Copyright (c) 2009, Jouni Malinen <j@w1.fi>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/nl80211.h>
#include <linux/slab.h>
#include <linux/wireless.h>
#include <net/cfg80211.h>
#include <net/iw_handler.h>
#include "core.h"
#include "nl80211.h"
void cfg80211_send_rx_auth(struct net_device *dev, const u8 *buf, size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
wdev_lock(wdev);
nl80211_send_rx_auth(rdev, dev, buf, len, GFP_KERNEL);
cfg80211_sme_rx_auth(dev, buf, len);
wdev_unlock(wdev);
}
EXPORT_SYMBOL(cfg80211_send_rx_auth);
void cfg80211_send_rx_assoc(struct net_device *dev, struct cfg80211_bss *bss,
const u8 *buf, size_t len)
{
u16 status_code;
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)buf;
u8 *ie = mgmt->u.assoc_resp.variable;
int ieoffs = offsetof(struct ieee80211_mgmt, u.assoc_resp.variable);
wdev_lock(wdev);
status_code = le16_to_cpu(mgmt->u.assoc_resp.status_code);
/*
* This is a bit of a hack, we don't notify userspace of
* a (re-)association reply if we tried to send a reassoc
* and got a reject -- we only try again with an assoc
* frame instead of reassoc.
*/
if (status_code != WLAN_STATUS_SUCCESS && wdev->conn &&
cfg80211_sme_failed_reassoc(wdev)) {
cfg80211_put_bss(bss);
goto out;
}
nl80211_send_rx_assoc(rdev, dev, buf, len, GFP_KERNEL);
if (status_code != WLAN_STATUS_SUCCESS && wdev->conn) {
cfg80211_sme_failed_assoc(wdev);
/*
* do not call connect_result() now because the
* sme will schedule work that does it later.
*/
cfg80211_put_bss(bss);
goto out;
}
if (!wdev->conn && wdev->sme_state == CFG80211_SME_IDLE) {
/*
* This is for the userspace SME, the CONNECTING
* state will be changed to CONNECTED by
* __cfg80211_connect_result() below.
*/
wdev->sme_state = CFG80211_SME_CONNECTING;
}
/* this consumes the bss reference */
__cfg80211_connect_result(dev, mgmt->bssid, NULL, 0, ie, len - ieoffs,
status_code,
status_code == WLAN_STATUS_SUCCESS, bss);
out:
wdev_unlock(wdev);
}
EXPORT_SYMBOL(cfg80211_send_rx_assoc);
void __cfg80211_send_deauth(struct net_device *dev,
const u8 *buf, size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)buf;
const u8 *bssid = mgmt->bssid;
bool was_current = false;
ASSERT_WDEV_LOCK(wdev);
if (wdev->current_bss &&
memcmp(wdev->current_bss->pub.bssid, bssid, ETH_ALEN) == 0) {
cfg80211_unhold_bss(wdev->current_bss);
cfg80211_put_bss(&wdev->current_bss->pub);
wdev->current_bss = NULL;
was_current = true;
}
nl80211_send_deauth(rdev, dev, buf, len, GFP_KERNEL);
if (wdev->sme_state == CFG80211_SME_CONNECTED && was_current) {
u16 reason_code;
bool from_ap;
reason_code = le16_to_cpu(mgmt->u.deauth.reason_code);
from_ap = memcmp(mgmt->sa, dev->dev_addr, ETH_ALEN) != 0;
__cfg80211_disconnected(dev, NULL, 0, reason_code, from_ap);
} else if (wdev->sme_state == CFG80211_SME_CONNECTING) {
__cfg80211_connect_result(dev, mgmt->bssid, NULL, 0, NULL, 0,
WLAN_STATUS_UNSPECIFIED_FAILURE,
false, NULL);
}
}
EXPORT_SYMBOL(__cfg80211_send_deauth);
void cfg80211_send_deauth(struct net_device *dev, const u8 *buf, size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
wdev_lock(wdev);
__cfg80211_send_deauth(dev, buf, len);
wdev_unlock(wdev);
}
EXPORT_SYMBOL(cfg80211_send_deauth);
void __cfg80211_send_disassoc(struct net_device *dev,
const u8 *buf, size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)buf;
const u8 *bssid = mgmt->bssid;
u16 reason_code;
bool from_ap;
ASSERT_WDEV_LOCK(wdev);
nl80211_send_disassoc(rdev, dev, buf, len, GFP_KERNEL);
if (wdev->sme_state != CFG80211_SME_CONNECTED)
return;
if (wdev->current_bss &&
memcmp(wdev->current_bss->pub.bssid, bssid, ETH_ALEN) == 0) {
cfg80211_sme_disassoc(dev, wdev->current_bss);
cfg80211_unhold_bss(wdev->current_bss);
cfg80211_put_bss(&wdev->current_bss->pub);
wdev->current_bss = NULL;
} else
WARN_ON(1);
reason_code = le16_to_cpu(mgmt->u.disassoc.reason_code);
from_ap = memcmp(mgmt->sa, dev->dev_addr, ETH_ALEN) != 0;
__cfg80211_disconnected(dev, NULL, 0, reason_code, from_ap);
}
EXPORT_SYMBOL(__cfg80211_send_disassoc);
void cfg80211_send_disassoc(struct net_device *dev, const u8 *buf, size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
wdev_lock(wdev);
__cfg80211_send_disassoc(dev, buf, len);
wdev_unlock(wdev);
}
EXPORT_SYMBOL(cfg80211_send_disassoc);
void cfg80211_send_unprot_deauth(struct net_device *dev, const u8 *buf,
size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_send_unprot_deauth(rdev, dev, buf, len, GFP_ATOMIC);
}
EXPORT_SYMBOL(cfg80211_send_unprot_deauth);
void cfg80211_send_unprot_disassoc(struct net_device *dev, const u8 *buf,
size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_send_unprot_disassoc(rdev, dev, buf, len, GFP_ATOMIC);
}
EXPORT_SYMBOL(cfg80211_send_unprot_disassoc);
void cfg80211_send_auth_timeout(struct net_device *dev, const u8 *addr)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
wdev_lock(wdev);
nl80211_send_auth_timeout(rdev, dev, addr, GFP_KERNEL);
if (wdev->sme_state == CFG80211_SME_CONNECTING)
__cfg80211_connect_result(dev, addr, NULL, 0, NULL, 0,
WLAN_STATUS_UNSPECIFIED_FAILURE,
false, NULL);
wdev_unlock(wdev);
}
EXPORT_SYMBOL(cfg80211_send_auth_timeout);
void cfg80211_send_assoc_timeout(struct net_device *dev, const u8 *addr)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
wdev_lock(wdev);
nl80211_send_assoc_timeout(rdev, dev, addr, GFP_KERNEL);
if (wdev->sme_state == CFG80211_SME_CONNECTING)
__cfg80211_connect_result(dev, addr, NULL, 0, NULL, 0,
WLAN_STATUS_UNSPECIFIED_FAILURE,
false, NULL);
wdev_unlock(wdev);
}
EXPORT_SYMBOL(cfg80211_send_assoc_timeout);
void cfg80211_michael_mic_failure(struct net_device *dev, const u8 *addr,
enum nl80211_key_type key_type, int key_id,
const u8 *tsc, gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
#ifdef CONFIG_CFG80211_WEXT
union iwreq_data wrqu;
char *buf = kmalloc(128, gfp);
if (buf) {
sprintf(buf, "MLME-MICHAELMICFAILURE.indication("
"keyid=%d %scast addr=%pM)", key_id,
key_type == NL80211_KEYTYPE_GROUP ? "broad" : "uni",
addr);
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = strlen(buf);
wireless_send_event(dev, IWEVCUSTOM, &wrqu, buf);
kfree(buf);
}
#endif
nl80211_michael_mic_failure(rdev, dev, addr, key_type, key_id, tsc, gfp);
}
EXPORT_SYMBOL(cfg80211_michael_mic_failure);
/* some MLME handling for userspace SME */
int __cfg80211_mlme_auth(struct cfg80211_registered_device *rdev,
struct net_device *dev,
struct ieee80211_channel *chan,
enum nl80211_auth_type auth_type,
const u8 *bssid,
const u8 *ssid, int ssid_len,
const u8 *ie, int ie_len,
const u8 *key, int key_len, int key_idx)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_auth_request req;
int err;
ASSERT_WDEV_LOCK(wdev);
if (auth_type == NL80211_AUTHTYPE_SHARED_KEY)
if (!key || !key_len || key_idx < 0 || key_idx > 4)
return -EINVAL;
if (wdev->current_bss &&
memcmp(bssid, wdev->current_bss->pub.bssid, ETH_ALEN) == 0)
return -EALREADY;
memset(&req, 0, sizeof(req));
req.ie = ie;
req.ie_len = ie_len;
req.auth_type = auth_type;
req.bss = cfg80211_get_bss(&rdev->wiphy, chan, bssid, ssid, ssid_len,
WLAN_CAPABILITY_ESS, WLAN_CAPABILITY_ESS);
req.key = key;
req.key_len = key_len;
req.key_idx = key_idx;
if (!req.bss)
return -ENOENT;
err = rdev->ops->auth(&rdev->wiphy, dev, &req);
cfg80211_put_bss(req.bss);
return err;
}
int cfg80211_mlme_auth(struct cfg80211_registered_device *rdev,
struct net_device *dev, struct ieee80211_channel *chan,
enum nl80211_auth_type auth_type, const u8 *bssid,
const u8 *ssid, int ssid_len,
const u8 *ie, int ie_len,
const u8 *key, int key_len, int key_idx)
{
int err;
wdev_lock(dev->ieee80211_ptr);
err = __cfg80211_mlme_auth(rdev, dev, chan, auth_type, bssid,
ssid, ssid_len, ie, ie_len,
key, key_len, key_idx);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
/* Do a logical ht_capa &= ht_capa_mask. */
void cfg80211_oper_and_ht_capa(struct ieee80211_ht_cap *ht_capa,
const struct ieee80211_ht_cap *ht_capa_mask)
{
int i;
u8 *p1, *p2;
if (!ht_capa_mask) {
memset(ht_capa, 0, sizeof(*ht_capa));
return;
}
p1 = (u8*)(ht_capa);
p2 = (u8*)(ht_capa_mask);
for (i = 0; i<sizeof(*ht_capa); i++)
p1[i] &= p2[i];
}
int __cfg80211_mlme_assoc(struct cfg80211_registered_device *rdev,
struct net_device *dev,
struct ieee80211_channel *chan,
const u8 *bssid, const u8 *prev_bssid,
const u8 *ssid, int ssid_len,
const u8 *ie, int ie_len, bool use_mfp,
struct cfg80211_crypto_settings *crypt,
u32 assoc_flags, struct ieee80211_ht_cap *ht_capa,
struct ieee80211_ht_cap *ht_capa_mask)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_assoc_request req;
int err;
bool was_connected = false;
ASSERT_WDEV_LOCK(wdev);
memset(&req, 0, sizeof(req));
if (wdev->current_bss && prev_bssid &&
memcmp(wdev->current_bss->pub.bssid, prev_bssid, ETH_ALEN) == 0) {
/*
* Trying to reassociate: Allow this to proceed and let the old
* association to be dropped when the new one is completed.
*/
if (wdev->sme_state == CFG80211_SME_CONNECTED) {
was_connected = true;
wdev->sme_state = CFG80211_SME_CONNECTING;
}
} else if (wdev->current_bss)
return -EALREADY;
req.ie = ie;
req.ie_len = ie_len;
memcpy(&req.crypto, crypt, sizeof(req.crypto));
req.use_mfp = use_mfp;
req.prev_bssid = prev_bssid;
req.flags = assoc_flags;
if (ht_capa)
memcpy(&req.ht_capa, ht_capa, sizeof(req.ht_capa));
if (ht_capa_mask)
memcpy(&req.ht_capa_mask, ht_capa_mask,
sizeof(req.ht_capa_mask));
cfg80211_oper_and_ht_capa(&req.ht_capa_mask,
rdev->wiphy.ht_capa_mod_mask);
req.bss = cfg80211_get_bss(&rdev->wiphy, chan, bssid, ssid, ssid_len,
WLAN_CAPABILITY_ESS, WLAN_CAPABILITY_ESS);
if (!req.bss) {
if (was_connected)
wdev->sme_state = CFG80211_SME_CONNECTED;
return -ENOENT;
}
err = rdev->ops->assoc(&rdev->wiphy, dev, &req);
if (err) {
if (was_connected)
wdev->sme_state = CFG80211_SME_CONNECTED;
cfg80211_put_bss(req.bss);
}
return err;
}
int cfg80211_mlme_assoc(struct cfg80211_registered_device *rdev,
struct net_device *dev,
struct ieee80211_channel *chan,
const u8 *bssid, const u8 *prev_bssid,
const u8 *ssid, int ssid_len,
const u8 *ie, int ie_len, bool use_mfp,
struct cfg80211_crypto_settings *crypt,
u32 assoc_flags, struct ieee80211_ht_cap *ht_capa,
struct ieee80211_ht_cap *ht_capa_mask)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
wdev_lock(wdev);
err = __cfg80211_mlme_assoc(rdev, dev, chan, bssid, prev_bssid,
ssid, ssid_len, ie, ie_len, use_mfp, crypt,
assoc_flags, ht_capa, ht_capa_mask);
wdev_unlock(wdev);
return err;
}
int __cfg80211_mlme_deauth(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *bssid,
const u8 *ie, int ie_len, u16 reason,
bool local_state_change)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_deauth_request req = {
.bssid = bssid,
.reason_code = reason,
.ie = ie,
.ie_len = ie_len,
};
ASSERT_WDEV_LOCK(wdev);
if (local_state_change) {
if (wdev->current_bss &&
memcmp(wdev->current_bss->pub.bssid, bssid, ETH_ALEN) == 0) {
cfg80211_unhold_bss(wdev->current_bss);
cfg80211_put_bss(&wdev->current_bss->pub);
wdev->current_bss = NULL;
}
return 0;
}
return rdev->ops->deauth(&rdev->wiphy, dev, &req);
}
int cfg80211_mlme_deauth(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *bssid,
const u8 *ie, int ie_len, u16 reason,
bool local_state_change)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
wdev_lock(wdev);
err = __cfg80211_mlme_deauth(rdev, dev, bssid, ie, ie_len, reason,
local_state_change);
wdev_unlock(wdev);
return err;
}
static int __cfg80211_mlme_disassoc(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *bssid,
const u8 *ie, int ie_len, u16 reason,
bool local_state_change)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_disassoc_request req;
ASSERT_WDEV_LOCK(wdev);
if (wdev->sme_state != CFG80211_SME_CONNECTED)
return -ENOTCONN;
if (WARN_ON(!wdev->current_bss))
return -ENOTCONN;
memset(&req, 0, sizeof(req));
req.reason_code = reason;
req.local_state_change = local_state_change;
req.ie = ie;
req.ie_len = ie_len;
if (memcmp(wdev->current_bss->pub.bssid, bssid, ETH_ALEN) == 0)
req.bss = &wdev->current_bss->pub;
else
return -ENOTCONN;
return rdev->ops->disassoc(&rdev->wiphy, dev, &req);
}
int cfg80211_mlme_disassoc(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *bssid,
const u8 *ie, int ie_len, u16 reason,
bool local_state_change)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
wdev_lock(wdev);
err = __cfg80211_mlme_disassoc(rdev, dev, bssid, ie, ie_len, reason,
local_state_change);
wdev_unlock(wdev);
return err;
}
void cfg80211_mlme_down(struct cfg80211_registered_device *rdev,
struct net_device *dev)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_deauth_request req;
u8 bssid[ETH_ALEN];
ASSERT_WDEV_LOCK(wdev);
if (!rdev->ops->deauth)
return;
memset(&req, 0, sizeof(req));
req.reason_code = WLAN_REASON_DEAUTH_LEAVING;
req.ie = NULL;
req.ie_len = 0;
if (!wdev->current_bss)
return;
memcpy(bssid, wdev->current_bss->pub.bssid, ETH_ALEN);
req.bssid = bssid;
rdev->ops->deauth(&rdev->wiphy, dev, &req);
if (wdev->current_bss) {
cfg80211_unhold_bss(wdev->current_bss);
cfg80211_put_bss(&wdev->current_bss->pub);
wdev->current_bss = NULL;
}
}
void cfg80211_ready_on_channel(struct net_device *dev, u64 cookie,
struct ieee80211_channel *chan,
enum nl80211_channel_type channel_type,
unsigned int duration, gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_send_remain_on_channel(rdev, dev, cookie, chan, channel_type,
duration, gfp);
}
EXPORT_SYMBOL(cfg80211_ready_on_channel);
void cfg80211_remain_on_channel_expired(struct net_device *dev,
u64 cookie,
struct ieee80211_channel *chan,
enum nl80211_channel_type channel_type,
gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_send_remain_on_channel_cancel(rdev, dev, cookie, chan,
channel_type, gfp);
}
EXPORT_SYMBOL(cfg80211_remain_on_channel_expired);
void cfg80211_new_sta(struct net_device *dev, const u8 *mac_addr,
struct station_info *sinfo, gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_send_sta_event(rdev, dev, mac_addr, sinfo, gfp);
}
EXPORT_SYMBOL(cfg80211_new_sta);
void cfg80211_del_sta(struct net_device *dev, const u8 *mac_addr, gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_send_sta_del_event(rdev, dev, mac_addr, gfp);
}
EXPORT_SYMBOL(cfg80211_del_sta);
struct cfg80211_mgmt_registration {
struct list_head list;
u32 nlpid;
int match_len;
__le16 frame_type;
u8 match[];
};
int cfg80211_mlme_register_mgmt(struct wireless_dev *wdev, u32 snd_pid,
u16 frame_type, const u8 *match_data,
int match_len)
{
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct cfg80211_mgmt_registration *reg, *nreg;
int err = 0;
u16 mgmt_type;
if (!wdev->wiphy->mgmt_stypes)
return -EOPNOTSUPP;
if ((frame_type & IEEE80211_FCTL_FTYPE) != IEEE80211_FTYPE_MGMT)
return -EINVAL;
if (frame_type & ~(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE))
return -EINVAL;
mgmt_type = (frame_type & IEEE80211_FCTL_STYPE) >> 4;
if (!(wdev->wiphy->mgmt_stypes[wdev->iftype].rx & BIT(mgmt_type)))
return -EINVAL;
nreg = kzalloc(sizeof(*reg) + match_len, GFP_KERNEL);
if (!nreg)
return -ENOMEM;
spin_lock_bh(&wdev->mgmt_registrations_lock);
list_for_each_entry(reg, &wdev->mgmt_registrations, list) {
int mlen = min(match_len, reg->match_len);
if (frame_type != le16_to_cpu(reg->frame_type))
continue;
if (memcmp(reg->match, match_data, mlen) == 0) {
err = -EALREADY;
break;
}
}
if (err) {
kfree(nreg);
goto out;
}
memcpy(nreg->match, match_data, match_len);
nreg->match_len = match_len;
nreg->nlpid = snd_pid;
nreg->frame_type = cpu_to_le16(frame_type);
list_add(&nreg->list, &wdev->mgmt_registrations);
if (rdev->ops->mgmt_frame_register)
rdev->ops->mgmt_frame_register(wiphy, wdev->netdev,
frame_type, true);
out:
spin_unlock_bh(&wdev->mgmt_registrations_lock);
return err;
}
void cfg80211_mlme_unregister_socket(struct wireless_dev *wdev, u32 nlpid)
{
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct cfg80211_mgmt_registration *reg, *tmp;
spin_lock_bh(&wdev->mgmt_registrations_lock);
list_for_each_entry_safe(reg, tmp, &wdev->mgmt_registrations, list) {
if (reg->nlpid != nlpid)
continue;
if (rdev->ops->mgmt_frame_register) {
u16 frame_type = le16_to_cpu(reg->frame_type);
rdev->ops->mgmt_frame_register(wiphy, wdev->netdev,
frame_type, false);
}
list_del(®->list);
kfree(reg);
}
spin_unlock_bh(&wdev->mgmt_registrations_lock);
if (nlpid == wdev->ap_unexpected_nlpid)
wdev->ap_unexpected_nlpid = 0;
}
void cfg80211_mlme_purge_registrations(struct wireless_dev *wdev)
{
struct cfg80211_mgmt_registration *reg, *tmp;
spin_lock_bh(&wdev->mgmt_registrations_lock);
list_for_each_entry_safe(reg, tmp, &wdev->mgmt_registrations, list) {
list_del(®->list);
kfree(reg);
}
spin_unlock_bh(&wdev->mgmt_registrations_lock);
}
int cfg80211_mlme_mgmt_tx(struct cfg80211_registered_device *rdev,
struct net_device *dev,
struct ieee80211_channel *chan, bool offchan,
enum nl80211_channel_type channel_type,
bool channel_type_valid, unsigned int wait,
const u8 *buf, size_t len, bool no_cck,
bool dont_wait_for_ack, u64 *cookie)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
const struct ieee80211_mgmt *mgmt;
u16 stype;
if (!wdev->wiphy->mgmt_stypes)
return -EOPNOTSUPP;
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
if (len < 24 + 1)
return -EINVAL;
mgmt = (const struct ieee80211_mgmt *) buf;
if (!ieee80211_is_mgmt(mgmt->frame_control))
return -EINVAL;
stype = le16_to_cpu(mgmt->frame_control) & IEEE80211_FCTL_STYPE;
if (!(wdev->wiphy->mgmt_stypes[wdev->iftype].tx & BIT(stype >> 4)))
return -EINVAL;
if (ieee80211_is_action(mgmt->frame_control) &&
mgmt->u.action.category != WLAN_CATEGORY_PUBLIC) {
int err = 0;
wdev_lock(wdev);
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_P2P_CLIENT:
if (!wdev->current_bss) {
err = -ENOTCONN;
break;
}
if (memcmp(wdev->current_bss->pub.bssid,
mgmt->bssid, ETH_ALEN)) {
err = -ENOTCONN;
break;
}
/*
* check for IBSS DA must be done by driver as
* cfg80211 doesn't track the stations
*/
if (wdev->iftype == NL80211_IFTYPE_ADHOC)
break;
/* for station, check that DA is the AP */
if (memcmp(wdev->current_bss->pub.bssid,
mgmt->da, ETH_ALEN)) {
err = -ENOTCONN;
break;
}
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_AP_VLAN:
if (memcmp(mgmt->bssid, dev->dev_addr, ETH_ALEN))
err = -EINVAL;
break;
case NL80211_IFTYPE_MESH_POINT:
if (memcmp(mgmt->sa, mgmt->bssid, ETH_ALEN)) {
err = -EINVAL;
break;
}
/*
* check for mesh DA must be done by driver as
* cfg80211 doesn't track the stations
*/
break;
default:
err = -EOPNOTSUPP;
break;
}
wdev_unlock(wdev);
if (err)
return err;
}
if (memcmp(mgmt->sa, dev->dev_addr, ETH_ALEN) != 0)
return -EINVAL;
/* Transmit the Action frame as requested by user space */
return rdev->ops->mgmt_tx(&rdev->wiphy, dev, chan, offchan,
channel_type, channel_type_valid,
wait, buf, len, no_cck, dont_wait_for_ack,
cookie);
}
bool cfg80211_rx_mgmt(struct net_device *dev, int freq, int sig_mbm,
const u8 *buf, size_t len, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct cfg80211_mgmt_registration *reg;
const struct ieee80211_txrx_stypes *stypes =
&wiphy->mgmt_stypes[wdev->iftype];
struct ieee80211_mgmt *mgmt = (void *)buf;
const u8 *data;
int data_len;
bool result = false;
__le16 ftype = mgmt->frame_control &
cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE);
u16 stype;
stype = (le16_to_cpu(mgmt->frame_control) & IEEE80211_FCTL_STYPE) >> 4;
if (!(stypes->rx & BIT(stype)))
return false;
data = buf + ieee80211_hdrlen(mgmt->frame_control);
data_len = len - ieee80211_hdrlen(mgmt->frame_control);
spin_lock_bh(&wdev->mgmt_registrations_lock);
list_for_each_entry(reg, &wdev->mgmt_registrations, list) {
if (reg->frame_type != ftype)
continue;
if (reg->match_len > data_len)
continue;
if (memcmp(reg->match, data, reg->match_len))
continue;
/* found match! */
/* Indicate the received Action frame to user space */
if (nl80211_send_mgmt(rdev, dev, reg->nlpid,
freq, sig_mbm,
buf, len, gfp))
continue;
result = true;
break;
}
spin_unlock_bh(&wdev->mgmt_registrations_lock);
return result;
}
EXPORT_SYMBOL(cfg80211_rx_mgmt);
void cfg80211_mgmt_tx_status(struct net_device *dev, u64 cookie,
const u8 *buf, size_t len, bool ack, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
/* Indicate TX status of the Action frame to user space */
nl80211_send_mgmt_tx_status(rdev, dev, cookie, buf, len, ack, gfp);
}
EXPORT_SYMBOL(cfg80211_mgmt_tx_status);
void cfg80211_cqm_rssi_notify(struct net_device *dev,
enum nl80211_cqm_rssi_threshold_event rssi_event,
gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
/* Indicate roaming trigger event to user space */
nl80211_send_cqm_rssi_notify(rdev, dev, rssi_event, gfp);
}
EXPORT_SYMBOL(cfg80211_cqm_rssi_notify);
void cfg80211_cqm_pktloss_notify(struct net_device *dev,
const u8 *peer, u32 num_packets, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
/* Indicate roaming trigger event to user space */
nl80211_send_cqm_pktloss_notify(rdev, dev, peer, num_packets, gfp);
}
EXPORT_SYMBOL(cfg80211_cqm_pktloss_notify);
void cfg80211_gtk_rekey_notify(struct net_device *dev, const u8 *bssid,
const u8 *replay_ctr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_gtk_rekey_notify(rdev, dev, bssid, replay_ctr, gfp);
}
EXPORT_SYMBOL(cfg80211_gtk_rekey_notify);
void cfg80211_pmksa_candidate_notify(struct net_device *dev, int index,
const u8 *bssid, bool preauth, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
nl80211_pmksa_candidate_notify(rdev, dev, index, bssid, preauth, gfp);
}
EXPORT_SYMBOL(cfg80211_pmksa_candidate_notify);
bool cfg80211_rx_spurious_frame(struct net_device *dev,
const u8 *addr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO))
return false;
return nl80211_unexpected_frame(dev, addr, gfp);
}
EXPORT_SYMBOL(cfg80211_rx_spurious_frame);
bool cfg80211_rx_unexpected_4addr_frame(struct net_device *dev,
const u8 *addr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO &&
wdev->iftype != NL80211_IFTYPE_AP_VLAN))
return false;
return nl80211_unexpected_4addr_frame(dev, addr, gfp);
}
EXPORT_SYMBOL(cfg80211_rx_unexpected_4addr_frame);
| gpl-2.0 |
shinkumara/sprout_shinkumara_kernel | arch/arm/mach-s5p64x0/mach-smdk6450.c | 4825 | 7275 | /* linux/arch/arm/mach-s5p64x0/mach-smdk6450.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.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/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <linux/gpio.h>
#include <linux/pwm_backlight.h>
#include <linux/fb.h>
#include <linux/mmc/host.h>
#include <video/platform_lcd.h>
#include <asm/hardware/vic.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <mach/i2c.h>
#include <mach/regs-gpio.h>
#include <plat/regs-serial.h>
#include <plat/gpio-cfg.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/iic.h>
#include <plat/pll.h>
#include <plat/adc.h>
#include <plat/ts.h>
#include <plat/s5p-time.h>
#include <plat/backlight.h>
#include <plat/fb.h>
#include <plat/regs-fb.h>
#include <plat/sdhci.h>
#include "common.h"
#define SMDK6450_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define SMDK6450_ULCON_DEFAULT S3C2410_LCON_CS8
#define SMDK6450_UFCON_DEFAULT (S3C2410_UFCON_FIFOMODE | \
S3C2440_UFCON_TXTRIG16 | \
S3C2410_UFCON_RXTRIG8)
static struct s3c2410_uartcfg smdk6450_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = SMDK6450_UCON_DEFAULT,
.ulcon = SMDK6450_ULCON_DEFAULT,
.ufcon = SMDK6450_UFCON_DEFAULT,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = SMDK6450_UCON_DEFAULT,
.ulcon = SMDK6450_ULCON_DEFAULT,
.ufcon = SMDK6450_UFCON_DEFAULT,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = SMDK6450_UCON_DEFAULT,
.ulcon = SMDK6450_ULCON_DEFAULT,
.ufcon = SMDK6450_UFCON_DEFAULT,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = SMDK6450_UCON_DEFAULT,
.ulcon = SMDK6450_ULCON_DEFAULT,
.ufcon = SMDK6450_UFCON_DEFAULT,
},
#if CONFIG_SERIAL_SAMSUNG_UARTS > 4
[4] = {
.hwport = 4,
.flags = 0,
.ucon = SMDK6450_UCON_DEFAULT,
.ulcon = SMDK6450_ULCON_DEFAULT,
.ufcon = SMDK6450_UFCON_DEFAULT,
},
#endif
#if CONFIG_SERIAL_SAMSUNG_UARTS > 5
[5] = {
.hwport = 5,
.flags = 0,
.ucon = SMDK6450_UCON_DEFAULT,
.ulcon = SMDK6450_ULCON_DEFAULT,
.ufcon = SMDK6450_UFCON_DEFAULT,
},
#endif
};
/* Frame Buffer */
static struct s3c_fb_pd_win smdk6450_fb_win0 = {
.win_mode = {
.left_margin = 8,
.right_margin = 13,
.upper_margin = 7,
.lower_margin = 5,
.hsync_len = 3,
.vsync_len = 1,
.xres = 800,
.yres = 480,
},
.max_bpp = 32,
.default_bpp = 24,
};
static struct s3c_fb_platdata smdk6450_lcd_pdata __initdata = {
.win[0] = &smdk6450_fb_win0,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC,
.setup_gpio = s5p64x0_fb_gpio_setup_24bpp,
};
/* LCD power controller */
static void smdk6450_lte480_reset_power(struct plat_lcd_data *pd,
unsigned int power)
{
int err;
if (power) {
err = gpio_request(S5P6450_GPN(5), "GPN");
if (err) {
printk(KERN_ERR "failed to request GPN for lcd reset\n");
return;
}
gpio_direction_output(S5P6450_GPN(5), 1);
gpio_set_value(S5P6450_GPN(5), 0);
gpio_set_value(S5P6450_GPN(5), 1);
gpio_free(S5P6450_GPN(5));
}
}
static struct plat_lcd_data smdk6450_lcd_power_data = {
.set_power = smdk6450_lte480_reset_power,
};
static struct platform_device smdk6450_lcd_lte480wv = {
.name = "platform-lcd",
.dev.parent = &s3c_device_fb.dev,
.dev.platform_data = &smdk6450_lcd_power_data,
};
static struct platform_device *smdk6450_devices[] __initdata = {
&s3c_device_adc,
&s3c_device_rtc,
&s3c_device_i2c0,
&s3c_device_i2c1,
&s3c_device_ts,
&s3c_device_wdt,
&samsung_asoc_dma,
&s5p6450_device_iis0,
&s3c_device_fb,
&smdk6450_lcd_lte480wv,
&s3c_device_hsmmc0,
&s3c_device_hsmmc1,
&s3c_device_hsmmc2,
/* s5p6450_device_spi0 will be added */
};
static struct s3c_sdhci_platdata smdk6450_hsmmc0_pdata __initdata = {
.cd_type = S3C_SDHCI_CD_NONE,
};
static struct s3c_sdhci_platdata smdk6450_hsmmc1_pdata __initdata = {
.cd_type = S3C_SDHCI_CD_NONE,
#if defined(CONFIG_S5P64X0_SD_CH1_8BIT)
.max_width = 8,
.host_caps = MMC_CAP_8_BIT_DATA,
#endif
};
static struct s3c_sdhci_platdata smdk6450_hsmmc2_pdata __initdata = {
.cd_type = S3C_SDHCI_CD_NONE,
};
static struct s3c2410_platform_i2c s5p6450_i2c0_data __initdata = {
.flags = 0,
.slave_addr = 0x10,
.frequency = 100*1000,
.sda_delay = 100,
.cfg_gpio = s5p6450_i2c0_cfg_gpio,
};
static struct s3c2410_platform_i2c s5p6450_i2c1_data __initdata = {
.flags = 0,
.bus_num = 1,
.slave_addr = 0x10,
.frequency = 100*1000,
.sda_delay = 100,
.cfg_gpio = s5p6450_i2c1_cfg_gpio,
};
static struct i2c_board_info smdk6450_i2c_devs0[] __initdata = {
{ I2C_BOARD_INFO("wm8580", 0x1b), },
{ I2C_BOARD_INFO("24c08", 0x50), }, /* Samsung KS24C080C EEPROM */
};
static struct i2c_board_info smdk6450_i2c_devs1[] __initdata = {
{ I2C_BOARD_INFO("24c128", 0x57), },/* Samsung S524AD0XD1 EEPROM */
};
/* LCD Backlight data */
static struct samsung_bl_gpio_info smdk6450_bl_gpio_info = {
.no = S5P6450_GPF(15),
.func = S3C_GPIO_SFN(2),
};
static struct platform_pwm_backlight_data smdk6450_bl_data = {
.pwm_id = 1,
};
static void __init smdk6450_map_io(void)
{
s5p64x0_init_io(NULL, 0);
s3c24xx_init_clocks(19200000);
s3c24xx_init_uarts(smdk6450_uartcfgs, ARRAY_SIZE(smdk6450_uartcfgs));
s5p_set_timer_source(S5P_PWM3, S5P_PWM4);
}
static void s5p6450_set_lcd_interface(void)
{
unsigned int cfg;
/* select TFT LCD type (RGB I/F) */
cfg = __raw_readl(S5P64X0_SPCON0);
cfg &= ~S5P64X0_SPCON0_LCD_SEL_MASK;
cfg |= S5P64X0_SPCON0_LCD_SEL_RGB;
__raw_writel(cfg, S5P64X0_SPCON0);
}
static void __init smdk6450_machine_init(void)
{
s3c24xx_ts_set_platdata(NULL);
s3c_i2c0_set_platdata(&s5p6450_i2c0_data);
s3c_i2c1_set_platdata(&s5p6450_i2c1_data);
i2c_register_board_info(0, smdk6450_i2c_devs0,
ARRAY_SIZE(smdk6450_i2c_devs0));
i2c_register_board_info(1, smdk6450_i2c_devs1,
ARRAY_SIZE(smdk6450_i2c_devs1));
samsung_bl_set(&smdk6450_bl_gpio_info, &smdk6450_bl_data);
s5p6450_set_lcd_interface();
s3c_fb_set_platdata(&smdk6450_lcd_pdata);
s3c_sdhci0_set_platdata(&smdk6450_hsmmc0_pdata);
s3c_sdhci1_set_platdata(&smdk6450_hsmmc1_pdata);
s3c_sdhci2_set_platdata(&smdk6450_hsmmc2_pdata);
platform_add_devices(smdk6450_devices, ARRAY_SIZE(smdk6450_devices));
}
MACHINE_START(SMDK6450, "SMDK6450")
/* Maintainer: Kukjin Kim <kgene.kim@samsung.com> */
.atag_offset = 0x100,
.init_irq = s5p6450_init_irq,
.handle_irq = vic_handle_irq,
.map_io = smdk6450_map_io,
.init_machine = smdk6450_machine_init,
.timer = &s5p_timer,
.restart = s5p64x0_restart,
MACHINE_END
| gpl-2.0 |
jeboo/kernel_JB_i337_ATT_MF3 | arch/sh/kernel/cpu/sh3/serial-sh7720.c | 5081 | 1083 | #include <linux/serial_sci.h>
#include <linux/serial_core.h>
#include <linux/io.h>
#include <cpu/serial.h>
#include <asm/gpio.h>
static void sh7720_sci_init_pins(struct uart_port *port, unsigned int cflag)
{
unsigned short data;
if (cflag & CRTSCTS) {
/* enable RTS/CTS */
if (port->mapbase == 0xa4430000) { /* SCIF0 */
/* Clear PTCR bit 9-2; enable all scif pins but sck */
data = __raw_readw(PORT_PTCR);
__raw_writew((data & 0xfc03), PORT_PTCR);
} else if (port->mapbase == 0xa4438000) { /* SCIF1 */
/* Clear PVCR bit 9-2 */
data = __raw_readw(PORT_PVCR);
__raw_writew((data & 0xfc03), PORT_PVCR);
}
} else {
if (port->mapbase == 0xa4430000) { /* SCIF0 */
/* Clear PTCR bit 5-2; enable only tx and rx */
data = __raw_readw(PORT_PTCR);
__raw_writew((data & 0xffc3), PORT_PTCR);
} else if (port->mapbase == 0xa4438000) { /* SCIF1 */
/* Clear PVCR bit 5-2 */
data = __raw_readw(PORT_PVCR);
__raw_writew((data & 0xffc3), PORT_PVCR);
}
}
}
struct plat_sci_port_ops sh7720_sci_port_ops = {
.init_pins = sh7720_sci_init_pins,
};
| gpl-2.0 |
jmaurice/android_kernel_samsung_jfltedcm_old | drivers/watchdog/wafer5823wdt.c | 7385 | 7294 | /*
* ICP Wafer 5823 Single Board Computer WDT driver
* http://www.icpamerica.com/wafer_5823.php
* May also work on other similar models
*
* (c) Copyright 2002 Justin Cormack <justin@street-vision.com>
*
* Release 0.02
*
* Based on advantechwdt.c which is based on wdt.c.
* Original copyright messages:
*
* (c) Copyright 1996-1997 Alan Cox <alan@lxorguk.ukuu.org.uk>,
* 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.
*
* Neither Alan Cox nor CymruNet Ltd. admit liability nor provide
* warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* (c) Copyright 1995 Alan Cox <alan@lxorguk.ukuu.org.uk>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#define WATCHDOG_NAME "Wafer 5823 WDT"
#define PFX WATCHDOG_NAME ": "
#define WD_TIMO 60 /* 60 sec default timeout */
static unsigned long wafwdt_is_open;
static char expect_close;
static DEFINE_SPINLOCK(wafwdt_lock);
/*
* You must set these - there is no sane way to probe for this board.
*
* To enable, write the timeout value in seconds (1 to 255) to I/O
* port WDT_START, then read the port to start the watchdog. To pat
* the dog, read port WDT_STOP to stop the timer, then read WDT_START
* to restart it again.
*/
static int wdt_stop = 0x843;
static int wdt_start = 0x443;
static int timeout = WD_TIMO; /* in seconds */
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout,
"Watchdog timeout in seconds. 1 <= timeout <= 255, default="
__MODULE_STRING(WD_TIMO) ".");
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static void wafwdt_ping(void)
{
/* pat watchdog */
spin_lock(&wafwdt_lock);
inb_p(wdt_stop);
inb_p(wdt_start);
spin_unlock(&wafwdt_lock);
}
static void wafwdt_start(void)
{
/* start up watchdog */
outb_p(timeout, wdt_start);
inb_p(wdt_start);
}
static void wafwdt_stop(void)
{
/* stop watchdog */
inb_p(wdt_stop);
}
static ssize_t wafwdt_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
/* See if we got the magic character 'V' and reload the timer */
if (count) {
if (!nowayout) {
size_t i;
/* In case it was set long ago */
expect_close = 0;
/* scan to see whether or not we got the magic
character */
for (i = 0; i != count; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V')
expect_close = 42;
}
}
/* Well, anyhow someone wrote to us, we should
return that favour */
wafwdt_ping();
}
return count;
}
static long wafwdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int new_timeout;
void __user *argp = (void __user *)arg;
int __user *p = argp;
static const struct watchdog_info ident = {
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT |
WDIOF_MAGICCLOSE,
.firmware_version = 1,
.identity = "Wafer 5823 WDT",
};
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &ident, sizeof(ident)))
return -EFAULT;
break;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_SETOPTIONS:
{
int options, retval = -EINVAL;
if (get_user(options, p))
return -EFAULT;
if (options & WDIOS_DISABLECARD) {
wafwdt_stop();
retval = 0;
}
if (options & WDIOS_ENABLECARD) {
wafwdt_start();
retval = 0;
}
return retval;
}
case WDIOC_KEEPALIVE:
wafwdt_ping();
break;
case WDIOC_SETTIMEOUT:
if (get_user(new_timeout, p))
return -EFAULT;
if ((new_timeout < 1) || (new_timeout > 255))
return -EINVAL;
timeout = new_timeout;
wafwdt_stop();
wafwdt_start();
/* Fall */
case WDIOC_GETTIMEOUT:
return put_user(timeout, p);
default:
return -ENOTTY;
}
return 0;
}
static int wafwdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &wafwdt_is_open))
return -EBUSY;
/*
* Activate
*/
wafwdt_start();
return nonseekable_open(inode, file);
}
static int wafwdt_close(struct inode *inode, struct file *file)
{
if (expect_close == 42)
wafwdt_stop();
else {
pr_crit("WDT device closed unexpectedly. WDT will not stop!\n");
wafwdt_ping();
}
clear_bit(0, &wafwdt_is_open);
expect_close = 0;
return 0;
}
/*
* Notifier for system down
*/
static int wafwdt_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if (code == SYS_DOWN || code == SYS_HALT)
wafwdt_stop();
return NOTIFY_DONE;
}
/*
* Kernel Interfaces
*/
static const struct file_operations wafwdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = wafwdt_write,
.unlocked_ioctl = wafwdt_ioctl,
.open = wafwdt_open,
.release = wafwdt_close,
};
static struct miscdevice wafwdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wafwdt_fops,
};
/*
* The WDT needs to learn about soft shutdowns in order to
* turn the timebomb registers off.
*/
static struct notifier_block wafwdt_notifier = {
.notifier_call = wafwdt_notify_sys,
};
static int __init wafwdt_init(void)
{
int ret;
pr_info("WDT driver for Wafer 5823 single board computer initialising\n");
if (timeout < 1 || timeout > 255) {
timeout = WD_TIMO;
pr_info("timeout value must be 1 <= x <= 255, using %d\n",
timeout);
}
if (wdt_stop != wdt_start) {
if (!request_region(wdt_stop, 1, "Wafer 5823 WDT")) {
pr_err("I/O address 0x%04x already in use\n", wdt_stop);
ret = -EIO;
goto error;
}
}
if (!request_region(wdt_start, 1, "Wafer 5823 WDT")) {
pr_err("I/O address 0x%04x already in use\n", wdt_start);
ret = -EIO;
goto error2;
}
ret = register_reboot_notifier(&wafwdt_notifier);
if (ret != 0) {
pr_err("cannot register reboot notifier (err=%d)\n", ret);
goto error3;
}
ret = misc_register(&wafwdt_miscdev);
if (ret != 0) {
pr_err("cannot register miscdev on minor=%d (err=%d)\n",
WATCHDOG_MINOR, ret);
goto error4;
}
pr_info("initialized. timeout=%d sec (nowayout=%d)\n",
timeout, nowayout);
return ret;
error4:
unregister_reboot_notifier(&wafwdt_notifier);
error3:
release_region(wdt_start, 1);
error2:
if (wdt_stop != wdt_start)
release_region(wdt_stop, 1);
error:
return ret;
}
static void __exit wafwdt_exit(void)
{
misc_deregister(&wafwdt_miscdev);
unregister_reboot_notifier(&wafwdt_notifier);
if (wdt_stop != wdt_start)
release_region(wdt_stop, 1);
release_region(wdt_start, 1);
}
module_init(wafwdt_init);
module_exit(wafwdt_exit);
MODULE_AUTHOR("Justin Cormack");
MODULE_DESCRIPTION("ICP Wafer 5823 Single Board Computer WDT driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
/* end of wafer5823wdt.c */
| gpl-2.0 |
charles1018/kernel_msm | drivers/infiniband/hw/mlx4/mr.c | 8153 | 8616 | /*
* Copyright (c) 2007 Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2007, 2008 Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/slab.h>
#include "mlx4_ib.h"
static u32 convert_access(int acc)
{
return (acc & IB_ACCESS_REMOTE_ATOMIC ? MLX4_PERM_ATOMIC : 0) |
(acc & IB_ACCESS_REMOTE_WRITE ? MLX4_PERM_REMOTE_WRITE : 0) |
(acc & IB_ACCESS_REMOTE_READ ? MLX4_PERM_REMOTE_READ : 0) |
(acc & IB_ACCESS_LOCAL_WRITE ? MLX4_PERM_LOCAL_WRITE : 0) |
MLX4_PERM_LOCAL_READ;
}
struct ib_mr *mlx4_ib_get_dma_mr(struct ib_pd *pd, int acc)
{
struct mlx4_ib_mr *mr;
int err;
mr = kmalloc(sizeof *mr, GFP_KERNEL);
if (!mr)
return ERR_PTR(-ENOMEM);
err = mlx4_mr_alloc(to_mdev(pd->device)->dev, to_mpd(pd)->pdn, 0,
~0ull, convert_access(acc), 0, 0, &mr->mmr);
if (err)
goto err_free;
err = mlx4_mr_enable(to_mdev(pd->device)->dev, &mr->mmr);
if (err)
goto err_mr;
mr->ibmr.rkey = mr->ibmr.lkey = mr->mmr.key;
mr->umem = NULL;
return &mr->ibmr;
err_mr:
mlx4_mr_free(to_mdev(pd->device)->dev, &mr->mmr);
err_free:
kfree(mr);
return ERR_PTR(err);
}
int mlx4_ib_umem_write_mtt(struct mlx4_ib_dev *dev, struct mlx4_mtt *mtt,
struct ib_umem *umem)
{
u64 *pages;
struct ib_umem_chunk *chunk;
int i, j, k;
int n;
int len;
int err = 0;
pages = (u64 *) __get_free_page(GFP_KERNEL);
if (!pages)
return -ENOMEM;
i = n = 0;
list_for_each_entry(chunk, &umem->chunk_list, list)
for (j = 0; j < chunk->nmap; ++j) {
len = sg_dma_len(&chunk->page_list[j]) >> mtt->page_shift;
for (k = 0; k < len; ++k) {
pages[i++] = sg_dma_address(&chunk->page_list[j]) +
umem->page_size * k;
/*
* Be friendly to mlx4_write_mtt() and
* pass it chunks of appropriate size.
*/
if (i == PAGE_SIZE / sizeof (u64)) {
err = mlx4_write_mtt(dev->dev, mtt, n,
i, pages);
if (err)
goto out;
n += i;
i = 0;
}
}
}
if (i)
err = mlx4_write_mtt(dev->dev, mtt, n, i, pages);
out:
free_page((unsigned long) pages);
return err;
}
struct ib_mr *mlx4_ib_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
u64 virt_addr, int access_flags,
struct ib_udata *udata)
{
struct mlx4_ib_dev *dev = to_mdev(pd->device);
struct mlx4_ib_mr *mr;
int shift;
int err;
int n;
mr = kmalloc(sizeof *mr, GFP_KERNEL);
if (!mr)
return ERR_PTR(-ENOMEM);
mr->umem = ib_umem_get(pd->uobject->context, start, length,
access_flags, 0);
if (IS_ERR(mr->umem)) {
err = PTR_ERR(mr->umem);
goto err_free;
}
n = ib_umem_page_count(mr->umem);
shift = ilog2(mr->umem->page_size);
err = mlx4_mr_alloc(dev->dev, to_mpd(pd)->pdn, virt_addr, length,
convert_access(access_flags), n, shift, &mr->mmr);
if (err)
goto err_umem;
err = mlx4_ib_umem_write_mtt(dev, &mr->mmr.mtt, mr->umem);
if (err)
goto err_mr;
err = mlx4_mr_enable(dev->dev, &mr->mmr);
if (err)
goto err_mr;
mr->ibmr.rkey = mr->ibmr.lkey = mr->mmr.key;
return &mr->ibmr;
err_mr:
mlx4_mr_free(to_mdev(pd->device)->dev, &mr->mmr);
err_umem:
ib_umem_release(mr->umem);
err_free:
kfree(mr);
return ERR_PTR(err);
}
int mlx4_ib_dereg_mr(struct ib_mr *ibmr)
{
struct mlx4_ib_mr *mr = to_mmr(ibmr);
mlx4_mr_free(to_mdev(ibmr->device)->dev, &mr->mmr);
if (mr->umem)
ib_umem_release(mr->umem);
kfree(mr);
return 0;
}
struct ib_mr *mlx4_ib_alloc_fast_reg_mr(struct ib_pd *pd,
int max_page_list_len)
{
struct mlx4_ib_dev *dev = to_mdev(pd->device);
struct mlx4_ib_mr *mr;
int err;
mr = kmalloc(sizeof *mr, GFP_KERNEL);
if (!mr)
return ERR_PTR(-ENOMEM);
err = mlx4_mr_alloc(dev->dev, to_mpd(pd)->pdn, 0, 0, 0,
max_page_list_len, 0, &mr->mmr);
if (err)
goto err_free;
err = mlx4_mr_enable(dev->dev, &mr->mmr);
if (err)
goto err_mr;
mr->ibmr.rkey = mr->ibmr.lkey = mr->mmr.key;
mr->umem = NULL;
return &mr->ibmr;
err_mr:
mlx4_mr_free(dev->dev, &mr->mmr);
err_free:
kfree(mr);
return ERR_PTR(err);
}
struct ib_fast_reg_page_list *mlx4_ib_alloc_fast_reg_page_list(struct ib_device *ibdev,
int page_list_len)
{
struct mlx4_ib_dev *dev = to_mdev(ibdev);
struct mlx4_ib_fast_reg_page_list *mfrpl;
int size = page_list_len * sizeof (u64);
if (page_list_len > MLX4_MAX_FAST_REG_PAGES)
return ERR_PTR(-EINVAL);
mfrpl = kmalloc(sizeof *mfrpl, GFP_KERNEL);
if (!mfrpl)
return ERR_PTR(-ENOMEM);
mfrpl->ibfrpl.page_list = kmalloc(size, GFP_KERNEL);
if (!mfrpl->ibfrpl.page_list)
goto err_free;
mfrpl->mapped_page_list = dma_alloc_coherent(&dev->dev->pdev->dev,
size, &mfrpl->map,
GFP_KERNEL);
if (!mfrpl->mapped_page_list)
goto err_free;
WARN_ON(mfrpl->map & 0x3f);
return &mfrpl->ibfrpl;
err_free:
kfree(mfrpl->ibfrpl.page_list);
kfree(mfrpl);
return ERR_PTR(-ENOMEM);
}
void mlx4_ib_free_fast_reg_page_list(struct ib_fast_reg_page_list *page_list)
{
struct mlx4_ib_dev *dev = to_mdev(page_list->device);
struct mlx4_ib_fast_reg_page_list *mfrpl = to_mfrpl(page_list);
int size = page_list->max_page_list_len * sizeof (u64);
dma_free_coherent(&dev->dev->pdev->dev, size, mfrpl->mapped_page_list,
mfrpl->map);
kfree(mfrpl->ibfrpl.page_list);
kfree(mfrpl);
}
struct ib_fmr *mlx4_ib_fmr_alloc(struct ib_pd *pd, int acc,
struct ib_fmr_attr *fmr_attr)
{
struct mlx4_ib_dev *dev = to_mdev(pd->device);
struct mlx4_ib_fmr *fmr;
int err = -ENOMEM;
fmr = kmalloc(sizeof *fmr, GFP_KERNEL);
if (!fmr)
return ERR_PTR(-ENOMEM);
err = mlx4_fmr_alloc(dev->dev, to_mpd(pd)->pdn, convert_access(acc),
fmr_attr->max_pages, fmr_attr->max_maps,
fmr_attr->page_shift, &fmr->mfmr);
if (err)
goto err_free;
err = mlx4_fmr_enable(to_mdev(pd->device)->dev, &fmr->mfmr);
if (err)
goto err_mr;
fmr->ibfmr.rkey = fmr->ibfmr.lkey = fmr->mfmr.mr.key;
return &fmr->ibfmr;
err_mr:
mlx4_mr_free(to_mdev(pd->device)->dev, &fmr->mfmr.mr);
err_free:
kfree(fmr);
return ERR_PTR(err);
}
int mlx4_ib_map_phys_fmr(struct ib_fmr *ibfmr, u64 *page_list,
int npages, u64 iova)
{
struct mlx4_ib_fmr *ifmr = to_mfmr(ibfmr);
struct mlx4_ib_dev *dev = to_mdev(ifmr->ibfmr.device);
return mlx4_map_phys_fmr(dev->dev, &ifmr->mfmr, page_list, npages, iova,
&ifmr->ibfmr.lkey, &ifmr->ibfmr.rkey);
}
int mlx4_ib_unmap_fmr(struct list_head *fmr_list)
{
struct ib_fmr *ibfmr;
int err;
struct mlx4_dev *mdev = NULL;
list_for_each_entry(ibfmr, fmr_list, list) {
if (mdev && to_mdev(ibfmr->device)->dev != mdev)
return -EINVAL;
mdev = to_mdev(ibfmr->device)->dev;
}
if (!mdev)
return 0;
list_for_each_entry(ibfmr, fmr_list, list) {
struct mlx4_ib_fmr *ifmr = to_mfmr(ibfmr);
mlx4_fmr_unmap(mdev, &ifmr->mfmr, &ifmr->ibfmr.lkey, &ifmr->ibfmr.rkey);
}
/*
* Make sure all MPT status updates are visible before issuing
* SYNC_TPT firmware command.
*/
wmb();
err = mlx4_SYNC_TPT(mdev);
if (err)
printk(KERN_WARNING "mlx4_ib: SYNC_TPT error %d when "
"unmapping FMRs\n", err);
return 0;
}
int mlx4_ib_fmr_dealloc(struct ib_fmr *ibfmr)
{
struct mlx4_ib_fmr *ifmr = to_mfmr(ibfmr);
struct mlx4_ib_dev *dev = to_mdev(ibfmr->device);
int err;
err = mlx4_fmr_free(dev->dev, &ifmr->mfmr);
if (!err)
kfree(ifmr);
return err;
}
| gpl-2.0 |
Suninus/Xiaomi_Kernel_OpenSource | arch/avr32/mach-at32ap/pm.c | 9945 | 5664 | /*
* AVR32 AP Power Management
*
* Copyright (C) 2008 Atmel Corporation
*
* 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/io.h>
#include <linux/suspend.h>
#include <linux/vmalloc.h>
#include <asm/cacheflush.h>
#include <asm/sysreg.h>
#include <mach/chip.h>
#include <mach/pm.h>
#include <mach/sram.h>
#include "sdramc.h"
#define SRAM_PAGE_FLAGS (SYSREG_BIT(TLBELO_D) | SYSREG_BF(SZ, 1) \
| SYSREG_BF(AP, 3) | SYSREG_BIT(G))
static unsigned long pm_sram_start;
static size_t pm_sram_size;
static struct vm_struct *pm_sram_area;
static void (*avr32_pm_enter_standby)(unsigned long sdramc_base);
static void (*avr32_pm_enter_str)(unsigned long sdramc_base);
/*
* Must be called with interrupts disabled. Exceptions will be masked
* on return (i.e. all exceptions will be "unrecoverable".)
*/
static void *avr32_pm_map_sram(void)
{
unsigned long vaddr;
unsigned long page_addr;
u32 tlbehi;
u32 mmucr;
vaddr = (unsigned long)pm_sram_area->addr;
page_addr = pm_sram_start & PAGE_MASK;
/*
* Mask exceptions and grab the first TLB entry. We won't be
* needing it while sleeping.
*/
asm volatile("ssrf %0" : : "i"(SYSREG_EM_OFFSET) : "memory");
mmucr = sysreg_read(MMUCR);
tlbehi = sysreg_read(TLBEHI);
sysreg_write(MMUCR, SYSREG_BFINS(DRP, 0, mmucr));
tlbehi = SYSREG_BF(ASID, SYSREG_BFEXT(ASID, tlbehi));
tlbehi |= vaddr & PAGE_MASK;
tlbehi |= SYSREG_BIT(TLBEHI_V);
sysreg_write(TLBELO, page_addr | SRAM_PAGE_FLAGS);
sysreg_write(TLBEHI, tlbehi);
__builtin_tlbw();
return (void *)(vaddr + pm_sram_start - page_addr);
}
/*
* Must be called with interrupts disabled. Exceptions will be
* unmasked on return.
*/
static void avr32_pm_unmap_sram(void)
{
u32 mmucr;
u32 tlbehi;
u32 tlbarlo;
/* Going to update TLB entry at index 0 */
mmucr = sysreg_read(MMUCR);
tlbehi = sysreg_read(TLBEHI);
sysreg_write(MMUCR, SYSREG_BFINS(DRP, 0, mmucr));
/* Clear the "valid" bit */
tlbehi = SYSREG_BF(ASID, SYSREG_BFEXT(ASID, tlbehi));
sysreg_write(TLBEHI, tlbehi);
/* Mark it as "not accessed" */
tlbarlo = sysreg_read(TLBARLO);
sysreg_write(TLBARLO, tlbarlo | 0x80000000U);
/* Update the TLB */
__builtin_tlbw();
/* Unmask exceptions */
asm volatile("csrf %0" : : "i"(SYSREG_EM_OFFSET) : "memory");
}
static int avr32_pm_valid_state(suspend_state_t state)
{
switch (state) {
case PM_SUSPEND_ON:
case PM_SUSPEND_STANDBY:
case PM_SUSPEND_MEM:
return 1;
default:
return 0;
}
}
static int avr32_pm_enter(suspend_state_t state)
{
u32 lpr_saved;
u32 evba_saved;
void *sram;
switch (state) {
case PM_SUSPEND_STANDBY:
sram = avr32_pm_map_sram();
/* Switch to in-sram exception handlers */
evba_saved = sysreg_read(EVBA);
sysreg_write(EVBA, (unsigned long)sram);
/*
* Save the LPR register so that we can re-enable
* SDRAM Low Power mode on resume.
*/
lpr_saved = sdramc_readl(LPR);
pr_debug("%s: Entering standby...\n", __func__);
avr32_pm_enter_standby(SDRAMC_BASE);
sdramc_writel(LPR, lpr_saved);
/* Switch back to regular exception handlers */
sysreg_write(EVBA, evba_saved);
avr32_pm_unmap_sram();
break;
case PM_SUSPEND_MEM:
sram = avr32_pm_map_sram();
/* Switch to in-sram exception handlers */
evba_saved = sysreg_read(EVBA);
sysreg_write(EVBA, (unsigned long)sram);
/*
* Save the LPR register so that we can re-enable
* SDRAM Low Power mode on resume.
*/
lpr_saved = sdramc_readl(LPR);
pr_debug("%s: Entering suspend-to-ram...\n", __func__);
avr32_pm_enter_str(SDRAMC_BASE);
sdramc_writel(LPR, lpr_saved);
/* Switch back to regular exception handlers */
sysreg_write(EVBA, evba_saved);
avr32_pm_unmap_sram();
break;
case PM_SUSPEND_ON:
pr_debug("%s: Entering idle...\n", __func__);
cpu_enter_idle();
break;
default:
pr_debug("%s: Invalid suspend state %d\n", __func__, state);
goto out;
}
pr_debug("%s: wakeup\n", __func__);
out:
return 0;
}
static const struct platform_suspend_ops avr32_pm_ops = {
.valid = avr32_pm_valid_state,
.enter = avr32_pm_enter,
};
static unsigned long avr32_pm_offset(void *symbol)
{
extern u8 pm_exception[];
return (unsigned long)symbol - (unsigned long)pm_exception;
}
static int __init avr32_pm_init(void)
{
extern u8 pm_exception[];
extern u8 pm_irq0[];
extern u8 pm_standby[];
extern u8 pm_suspend_to_ram[];
extern u8 pm_sram_end[];
void *dst;
/*
* To keep things simple, we depend on not needing more than a
* single page.
*/
pm_sram_size = avr32_pm_offset(pm_sram_end);
if (pm_sram_size > PAGE_SIZE)
goto err;
pm_sram_start = sram_alloc(pm_sram_size);
if (!pm_sram_start)
goto err_alloc_sram;
/* Grab a virtual area we can use later on. */
pm_sram_area = get_vm_area(pm_sram_size, VM_IOREMAP);
if (!pm_sram_area)
goto err_vm_area;
pm_sram_area->phys_addr = pm_sram_start;
local_irq_disable();
dst = avr32_pm_map_sram();
memcpy(dst, pm_exception, pm_sram_size);
flush_dcache_region(dst, pm_sram_size);
invalidate_icache_region(dst, pm_sram_size);
avr32_pm_unmap_sram();
local_irq_enable();
avr32_pm_enter_standby = dst + avr32_pm_offset(pm_standby);
avr32_pm_enter_str = dst + avr32_pm_offset(pm_suspend_to_ram);
intc_set_suspend_handler(avr32_pm_offset(pm_irq0));
suspend_set_ops(&avr32_pm_ops);
printk("AVR32 AP Power Management enabled\n");
return 0;
err_vm_area:
sram_free(pm_sram_start, pm_sram_size);
err_alloc_sram:
err:
pr_err("AVR32 Power Management initialization failed\n");
return -ENOMEM;
}
arch_initcall(avr32_pm_init);
| gpl-2.0 |
VanirAOSP/kernel_amlogic_mbx12122012 | arch/avr32/kernel/ocd.c | 13785 | 3885 | /*
* Copyright (C) 2007 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <asm/ocd.h>
static long ocd_count;
static spinlock_t ocd_lock;
/**
* ocd_enable - enable on-chip debugging
* @child: task to be debugged
*
* If @child is non-NULL, ocd_enable() first checks if debugging has
* already been enabled for @child, and if it has, does nothing.
*
* If @child is NULL (e.g. when debugging the kernel), or debugging
* has not already been enabled for it, ocd_enable() increments the
* reference count and enables the debugging hardware.
*/
void ocd_enable(struct task_struct *child)
{
u32 dc;
if (child)
pr_debug("ocd_enable: child=%s [%u]\n",
child->comm, child->pid);
else
pr_debug("ocd_enable (no child)\n");
if (!child || !test_and_set_tsk_thread_flag(child, TIF_DEBUG)) {
spin_lock(&ocd_lock);
ocd_count++;
dc = ocd_read(DC);
dc |= (1 << OCD_DC_MM_BIT) | (1 << OCD_DC_DBE_BIT);
ocd_write(DC, dc);
spin_unlock(&ocd_lock);
}
}
/**
* ocd_disable - disable on-chip debugging
* @child: task that was being debugged, but isn't anymore
*
* If @child is non-NULL, ocd_disable() checks if debugging is enabled
* for @child, and if it isn't, does nothing.
*
* If @child is NULL (e.g. when debugging the kernel), or debugging is
* enabled, ocd_disable() decrements the reference count, and if it
* reaches zero, disables the debugging hardware.
*/
void ocd_disable(struct task_struct *child)
{
u32 dc;
if (!child)
pr_debug("ocd_disable (no child)\n");
else if (test_tsk_thread_flag(child, TIF_DEBUG))
pr_debug("ocd_disable: child=%s [%u]\n",
child->comm, child->pid);
if (!child || test_and_clear_tsk_thread_flag(child, TIF_DEBUG)) {
spin_lock(&ocd_lock);
ocd_count--;
WARN_ON(ocd_count < 0);
if (ocd_count <= 0) {
dc = ocd_read(DC);
dc &= ~((1 << OCD_DC_MM_BIT) | (1 << OCD_DC_DBE_BIT));
ocd_write(DC, dc);
}
spin_unlock(&ocd_lock);
}
}
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/module.h>
static struct dentry *ocd_debugfs_root;
static struct dentry *ocd_debugfs_DC;
static struct dentry *ocd_debugfs_DS;
static struct dentry *ocd_debugfs_count;
static int ocd_DC_get(void *data, u64 *val)
{
*val = ocd_read(DC);
return 0;
}
static int ocd_DC_set(void *data, u64 val)
{
ocd_write(DC, val);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_DC, ocd_DC_get, ocd_DC_set, "0x%08llx\n");
static int ocd_DS_get(void *data, u64 *val)
{
*val = ocd_read(DS);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_DS, ocd_DS_get, NULL, "0x%08llx\n");
static int ocd_count_get(void *data, u64 *val)
{
*val = ocd_count;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_count, ocd_count_get, NULL, "%lld\n");
static void ocd_debugfs_init(void)
{
struct dentry *root;
root = debugfs_create_dir("ocd", NULL);
if (IS_ERR(root) || !root)
goto err_root;
ocd_debugfs_root = root;
ocd_debugfs_DC = debugfs_create_file("DC", S_IRUSR | S_IWUSR,
root, NULL, &fops_DC);
if (!ocd_debugfs_DC)
goto err_DC;
ocd_debugfs_DS = debugfs_create_file("DS", S_IRUSR, root,
NULL, &fops_DS);
if (!ocd_debugfs_DS)
goto err_DS;
ocd_debugfs_count = debugfs_create_file("count", S_IRUSR, root,
NULL, &fops_count);
if (!ocd_debugfs_count)
goto err_count;
return;
err_count:
debugfs_remove(ocd_debugfs_DS);
err_DS:
debugfs_remove(ocd_debugfs_DC);
err_DC:
debugfs_remove(ocd_debugfs_root);
err_root:
printk(KERN_WARNING "OCD: Failed to create debugfs entries\n");
}
#else
static inline void ocd_debugfs_init(void)
{
}
#endif
static int __init ocd_init(void)
{
spin_lock_init(&ocd_lock);
ocd_debugfs_init();
return 0;
}
arch_initcall(ocd_init);
| gpl-2.0 |
andip71/boeffla-kernel-samsung-s3 | drivers/net/wireless/ipsecdrvtl/bu.c | 218 | 20713 | /*
'src_pm_pgpNetPMConfig.c' Obfuscated by COBF (Version 1.06 2006-01-07 by BB) at Fri Oct 12 22:15:16 2012
*/
#include"cobf.h"
#ifdef _WIN32
#if defined( UNDER_CE) && defined( bb337) || ! defined( bb329)
#define bb355 1
#define bb332 1
#else
#define bb351 bb343
#define bb333 1
#define bb331 1
#endif
#define bb348 1
#include"uncobf.h"
#include<ndis.h>
#include"cobf.h"
#ifdef UNDER_CE
#include"uncobf.h"
#include<ndiswan.h>
#include"cobf.h"
#endif
#include"uncobf.h"
#include<stdio.h>
#include<basetsd.h>
#include"cobf.h"
bba bbs bbl bbf, *bb1;bba bbs bbe bbq, *bb93;bba bb135 bb124, *bb334;
bba bbs bbl bb40, *bb72;bba bbs bb135 bbk, *bb59;bba bbe bbu, *bb133;
bba bbh bbf*bb89;
#ifdef bb311
bba bbd bb60, *bb122;
#endif
#else
#include"uncobf.h"
#include<linux/module.h>
#include<linux/ctype.h>
#include<linux/time.h>
#include<linux/slab.h>
#include"cobf.h"
#ifndef bb116
#define bb116
#ifdef _WIN32
#include"uncobf.h"
#include<wtypes.h>
#include"cobf.h"
#else
#ifdef bb120
#include"uncobf.h"
#include<linux/types.h>
#include"cobf.h"
#else
#include"uncobf.h"
#include<stddef.h>
#include<sys/types.h>
#include"cobf.h"
#endif
#endif
#ifdef _WIN32
bba bb119 bb215;
#else
bba bbe bbu, *bb133, *bb246;
#define bb201 1
#define bb202 0
bba bb251 bb205, *bb240, *bb208;bba bbe bb285, *bb283, *bb262;bba bbs
bbq, *bb93, *bb270;bba bb6 bb238, *bb216;bba bbs bb6 bb263, *bb250;
bba bb6 bb111, *bb222;bba bbs bb6 bb63, *bb289;bba bb63 bb264, *bb207
;bba bb63 bb219, *bb254;bba bb111 bb119, *bb226;bba bb243 bb247;bba
bb279 bb124;bba bb230 bb83;bba bb118 bb112;bba bb118 bb253;
#ifdef bb211
bba bb282 bb40, *bb72;bba bb258 bbk, *bb59;bba bb232 bbd, *bb28;bba
bb256 bb56, *bb113;
#else
bba bb271 bb40, *bb72;bba bb229 bbk, *bb59;bba bb233 bbd, *bb28;bba
bb277 bb56, *bb113;
#endif
bba bb40 bbf, *bb1, *bb214;bba bbk bb237, *bb245, *bb224;bba bbk bb255
, *bb220, *bb248;bba bbd bb60, *bb122, *bb206;bba bb83 bb37, *bb274, *
bb252;bba bbd bb290, *bb275, *bb210;bba bb112 bb265, *bb291, *bb269;
bba bb56 bb227, *bb261, *bb223;
#define bb140 bbb
bba bbb*bb221, *bb77;bba bbh bbb*bb225;bba bbl bb287;bba bbl*bb276;
bba bbh bbl*bb82;
#if defined( bb120)
bba bbe bb115;
#endif
bba bb115 bb20;bba bb20*bb218;bba bbh bb20*bb187;
#if defined( bb213) || defined( bb266)
bba bb20 bb36;bba bb20 bb114;
#else
bba bbl bb36;bba bbs bbl bb114;
#endif
bba bbh bb36*bb257;bba bb36*bb244;bba bb60 bb212, *bb239;bba bbb*
bb106;bba bb106*bb241;
#define bb281( bb34) bbi bb34##__ { bbe bb228; }; bba bbi bb34##__ * \
bb34
bba bbi{bb37 bb188,bb242,bb231,bb260;}bb286, *bb234, *bb278;bba bbi{
bb37 bb8,bb193;}bb280, *bb235, *bb259;bba bbi{bb37 bb267,bb249;}bb236
, *bb217, *bb284;
#endif
bba bbh bbf*bb89;
#endif
bba bbf bb100;
#define IN
#define OUT
#ifdef _DEBUG
#define bb139( bbc) bb31( bbc)
#else
#define bb139( bbc) ( bbb)( bbc)
#endif
bba bbe bb161, *bb173;
#define bb209 0
#define bb314 1
#define bb298 2
#define bb324 3
#define bb346 4
bba bbe bb349;bba bbb*bb121;
#endif
#ifdef _WIN32
#ifndef UNDER_CE
#define bb30 bb344
#define bb43 bb335
bba bbs bb6 bb30;bba bb6 bb43;
#endif
#else
#endif
#ifdef _WIN32
bbb*bb128(bb30 bb47);bbb bb105(bbb* );bbb*bb137(bb30 bb159,bb30 bb47);
#else
#define bb128( bbc) bb146(1, bbc, bb142)
#define bb105( bbc) bb342( bbc)
#define bb137( bbc, bbn) bb146( bbc, bbn, bb142)
#endif
#ifdef _WIN32
#define bb31( bbc) bb358( bbc)
#else
#ifdef _DEBUG
bbe bb145(bbh bbl*bb95,bbh bbl*bb25,bbs bb272);
#define bb31( bbc) ( bbb)(( bbc) || ( bb145(# bbc, __FILE__, __LINE__ \
)))
#else
#define bb31( bbc) (( bbb)0)
#endif
#endif
bb43 bb301(bb43*bb320);
#ifndef _WIN32
bbe bb328(bbh bbl*bbg);bbe bb322(bbh bbl*bb19,...);
#endif
#ifdef _WIN32
bba bb353 bb96;
#define bb141( bbc) bb356( bbc)
#define bb144( bbc) bb345( bbc)
#define bb134( bbc) bb350( bbc)
#define bb132( bbc) bb339( bbc)
#else
bba bb347 bb96;
#define bb141( bbc) ( bbb)( * bbc = bb330( bbc))
#define bb144( bbc) (( bbb)0)
#define bb134( bbc) bb352( bbc)
#define bb132( bbc) bb354( bbc)
#endif
#define bb951 bb53(0x0800)
#define bb1138 bb53(0x0806)
#define bb937 bb53(0x01f4)
#define bb945 bb53(0x1194)
#define bb1131 bb53(0x4000)
#define bb1137 bb53(0x2000)
#define bb1107 bb53(0x1FFF)
#define bb1064( bb8) (( bb8) & bb53(0x2000 | 0x1FFF))
#define bb1022( bb8) ((( bb196( bb8)) & 0x1FFF) << 3)
#define bb979( bb8) ((( bb8) & bb53(0x1FFF)) == 0)
#define bb494( bb8) (( bb8) & bb53(0x2000))
#define bb987( bb8) (!( bb494( bb8)))
#pragma pack(push, 1)
bba bbi{bbf bb371[6 ];bbf bb1006[6 ];bbk bb373;}bb366, *bb376;bba bbi{
bbf bb446[6 ];bbk bb373;}bb1082, *bb1091;bba bbi{bbf bb938:4 ;bbf bb1088
:4 ;bbf bb1048;bbk bb361;bbk bb881;bbk bb567;bbf bb1002;bbf bb292;bbk
bb610;bbd bb310;bbd bb203;}bb326, *bb312;bba bbi{bbk bb1085;bbk bb1092
;bbf bb1047;bbf bb1039;bbk bb1057;bbf bb1074[6 ];bbd bb1035;bbf bb1090
[6 ];bbd bb1061;}bb1071, *bb1077;
#pragma pack(pop)
bba bbi{bbk bb288;bbk bb427;bbk bb1005;bbk bb319;}bb416, *bb341;bba
bbi{bbk bb288;bbk bb592;bbd bb549;bbd bb918;bbf bb92;bbf bb172;bbk
bb158;bbk bb319;bbk bb1019;}bb487, *bb318;bba bbi{bbf bb1075;bbf
bb1067;bbf bb1058;bbf bb1036;bbd bb1060;bbk bb1072;bbk bb372;bbd
bb1032;bbd bb1078;bbd bb1063;bbd bb1056;bbf bb1076[16 ];bbf bb1046[64 ]
;bbf bb25[128 ];bbf bb1033[64 ];}bb1080, *bb1086;bba bbi{bbd bb310;bbd
bb203;bbf bb910;bbf bb292;bbk bb919;}bb612, *bb569;
#if defined( _WIN32)
#define bb53( bbc) (((( bbc) & 0XFF00) >> 8) | ((( bbc) & 0X00FF) << \
8))
#define bb196( bbc) ( bb53( bbc))
#define bb445( bbc) (((( bbc) & 0XFF000000) >> 24) | ((( bbc) & \
0X00FF0000) >> 8) | ((( bbc) & 0X0000FF00) << 8) | ((( bbc) & \
0X000000FF) << 24))
#define bb499( bbc) ( bb445( bbc))
#endif
bbk bb921(bbh bbb*bb295);bbk bb886(bbh bbb*bb510,bbe bb22);bba bb83
bb4;bb9{bb98=0 ,bb364=-12000 ,bb357=-11999 ,bb375=-11998 ,bb671=-11997 ,
bb797=-11996 ,bb724=-11995 ,bb871=-11994 ,bb788=-11992 ,bb806=-11991 ,
bb668=-11990 ,bb712=-11989 ,bb833=-11988 ,bb637=-11987 ,bb672=-11986 ,
bb773=-11985 ,bb851=-11984 ,bb623=-11983 ,bb617=-11982 ,bb764=-11981 ,
bb903=-11980 ,bb791=-11979 ,bb722=-11978 ,bb843=-11977 ,bb583=-11976 ,
bb844=-11975 ,bb767=-11960 ,bb678=-11959 ,bb689=-11500 ,bb732=-11499 ,
bb856=-11498 ,bb798=-11497 ,bb879=-11496 ,bb869=-11495 ,bb828=-11494 ,
bb774=-11493 ,bb858=-11492 ,bb885=-11491 ,bb705=-11490 ,bb745=-11489 ,
bb702=-11488 ,bb892=-11487 ,bb872=-11486 ,bb706=-11485 ,bb645=-11484 ,
bb902=-11483 ,bb769=-11482 ,bb905=-11481 ,bb846=-11480 ,bb759=-11479 ,
bb644=-11478 ,bb717=-11477 ,bb657=-11476 ,bb631=-11475 ,bb864=-11474 ,
bb789=-11473 ,bb707=-11472 ,bb809=-11460 ,bb652=-11450 ,bb740=-11449 ,
bb710=-11448 ,bb733=-11447 ,bb790=-11446 ,bb635=-11445 ,bb887=-11444 ,
bb824=-11443 ,bb842=-11440 ,bb865=-11439 ,bb801=-11438 ,bb800=-11437 ,
bb673=-11436 ,bb688=-11435 ,bb620=-11420 ,bb531=-11419 ,bb571=-11418 ,
bb685=-11417 ,bb835=-11416 ,bb667=-11415 ,bb795=-11414 ,bb731=-11413 ,
bb633=-11412 ,bb823=-11411 ,bb674=-11410 ,bb636=-11409 ,bb708=-11408 ,
bb900=-11407 ,bb898=-11406 ,bb803=-11405 ,bb720=-11404 ,bb658=-11403 ,
bb761=-11402 ,bb634=-11401 ,bb679=-11400 ,bb878=-11399 ,bb754=-11398 ,
bb762=-11397 ,bb683=-11396 ,bb866=-11395 ,bb889=-11394 ,bb615=-11393 ,
bb894=-11392 ,bb692=-11391 ,bb784=-11390 ,bb727=-11389 ,bb711=-11388 ,
bb749=-11387 ,bb904=-11386 ,bb627=-11385 ,bb700=-11384 ,bb786=-11383 ,
bb648=-11382 ,bb814=-11381 ,bb736=-11380 ,bb785=-11379 ,bb669=-11378 ,
bb752=-11377 ,bb808=-11376 ,bb709=-11375 ,bb763=-11374 ,bb699=-11373 ,
bb897=-11372 ,bb862=-11371 ,bb802=-11370 ,bb777=-11369 ,bb841=-11368 ,
bb756=-11367 ,bb794=-11366 ,bb719=-11365 ,bb860=-11364 ,bb845=-11363 ,
bb388=-11350 ,bb883=bb388,bb714=-11349 ,bb834=-11348 ,bb836=-11347 ,bb643
=-11346 ,bb649=-11345 ,bb906=-11344 ,bb822=-11343 ,bb779=-11342 ,bb680=-
11341 ,bb770=-11340 ,bb901=-11339 ,bb398=-11338 ,bb663=-11337 ,bb687=bb398
,bb799=-11330 ,bb817=-11329 ,bb781=-11328 ,bb632=-11327 ,bb718=-11326 ,
bb650=-11325 ,bb821=-11324 ,bb698=-11320 ,bb819=-11319 ,bb859=-11318 ,
bb690=-11317 ,bb626=-11316 ,bb681=-11315 ,bb825=-11314 ,bb723=-11313 ,
bb641=-11312 ,bb642=-11300 ,bb741=-11299 ,bb796=-11298 ,bb703=-11297 ,
bb852=-11296 ,bb811=-11295 ,bb832=-11294 ,bb654=-11293 ,bb847=-11292 ,
bb882=-11291 ,bb618=-11290 ,bb804=-11289 ,bb857=-11288 ,bb849=-11287 ,
bb734=-11286 ,bb653=-11285 ,bb646=-11284 ,bb812=-11283 ,bb738=-11282 ,
bb704=-11281 ,bb661=-11280 ,bb713=-11279 ,bb701=-11250 ,bb850=-11249 ,
bb848=-11248 ,bb748=-11247 ,bb737=-11246 ,bb805=-11245 ,bb778=-11244 ,
bb755=-11243 ,bb621=-11242 ,bb839=-11240 ,bb651=-11239 ,bb729=-11238 ,
bb792=-11237 ,bb677=-11150 ,bb855=-11100 ,bb820=-11099 ,bb655=-11098 ,
bb744=-11097 ,bb782=-11096 ,bb793=-11095 ,bb768=-11094 ,bb628=-11093 ,
bb830=-11092 ,bb899=-11091 ,bb666=-11090 ,bb877=-11089 ,bb884=-11088 ,
bb853=-11087 ,bb638=-11086 ,bb780=-11085 ,bb783=-11050 ,bb751=-11049 ,
bb691=-10999 ,bb639=-10998 ,bb656=-10997 ,bb753=-10996 ,bb893=-10995 ,
bb682=-10994 ,bb694=-10993 ,bb840=-10992 ,bb771=-10991 ,bb735=-10990 ,
bb630=-10989 ,bb907=-10988 ,bb728=-10979 ,bb660=-10978 ,bb765=-10977 ,
bb873=-10976 ,bb695=-10975 ,bb826=-10974 ,};bba bbi bb455{bb1 bb74;bbd
bb127;bbd bb181;bbi bb455*bb94;}bbx;bb4 bb465(bbx*bb670,bbd bb909,bbx
*bb696,bbd bb895,bbd bb538);bb4 bb532(bbx*bbj,bbd bb92,bbh bbb*bb95,
bbd bb47);bb4 bb577(bbx*bbj,bbd bb92,bbb*bb131,bbd bb47);bbu bb827(
bbx*bbj,bbd bb92,bbh bbb*bb95,bbd bb47);bb4 bb595(bbx*bb85,bbf bb102,
bbx*bb58);bb4 bb686(bbx*bb85,bbu bb177,bbf*bb408);bb4 bb955(bbx*bb58,
bbf*bb389);bb4 bb941(bbh bbf*bb389,bbx*bb58);bb4 bb541(bbx*bb51,bbf
bb102,bbd*bb939);bb4 bb929(bbx*bb85,bbf bb102,bbf bb408,bbx*bb58);bbd
bb517(bbx*bb51);bbk bb534(bbx*bb51);bbb bb527(bbk bb151,bbx*bb51);bbb
bb536(bbx*bb51);bbb bb968(bbx*bb51,bbd*bb26);bbb bb999(bbx*bb51,bbd*
bb26);bbb bb1020(bbx*bb51,bbd bb26);bbb bb931(bbx*bb51,bbd bb26);bbb
bb983(bbx*bb51);bbu bb1013(bbf*bb51);bba bbi bb991*bb989;bba bbi
bb1026*bb1027;bba bbi bb993*bb1021;bba bbi bb1000*bb1010;bba bbi
bb1012*bb1023;bba bbi bb990*bb986;bba bb9{bb552=0 ,bb581=1 ,bb593=2 ,
bb813=3 ,bb585=4 ,bb570=5 ,bb575=6 ,bb562=7 ,bb579=9 ,}bb422;bba bb9{bb606=
0 ,bb992,bb598,bb1009,bb930,bb923,bb926,bb916,bb924,bb922,bb915,}bb519
;
#pragma pack(push, 8)
#ifdef _MSC_VER
#pragma warning (disable:4200)
#endif
bba bbf bb178[4 ];bba bb9{bb1651=0 ,bb1466=1 ,}bb1390;bba bb9{bb1527=0 ,
bb1718=1 ,bb1559=2 ,bb1437=3 ,bb1657=4 ,bb1495=5 ,bb1634=6 ,bb1514=7 ,bb1605
=8 ,bb1518=9 ,bb1677=10 ,bb1506=11 ,bb1694=12 ,bb1710=13 ,bb1716=14 ,bb1422=
15 ,bb1452=16 ,bb1393=17 ,bb1598=18 ,bb1688=19 ,bb1642=20 ,bb1491=21 ,bb1504
=22 ,bb1473=23 ,bb1601=24 ,bb1604=25 ,bb1449=26 ,bb1579=27 ,bb1373=28 ,
bb1612=29 ,bb1686=30 ,bb1630=16300 ,bb1429=16301 ,bb1727=16384 ,bb1535=
24576 ,bb1462=24577 ,bb1436=24578 ,bb1477=34793 ,bb1380=40500 ,}bb629;bba
bb9{bb1460=0 ,bb1523=1 ,bb1456=2 ,bb1424=3 ,bb1397=4 ,bb1386=5 ,bb1668=6 ,
bb1474=7 ,bb1528=8 ,bb1399=9 ,bb1443=21 ,bb1487=22 ,bb1488=23 ,bb1445=24 ,
bb1540=25 ,bb1508=26 ,bb1461=27 ,bb1382=28 ,bb1479=29 ,bb1489=80 ,}bb775;
bba bb9{bb1562=0 ,bb1697=1 ,bb1693=2 ,bb1483=3 ,bb1520=4 ,}bb1646;bba bb9{
bb1685=0 ,bb1347=1 ,bb1165=2 ,bb1225=3 ,bb1289=4 ,bb1049=61440 ,bb1329=
61441 ,bb1113=61443 ,bb1301=61444 ,}bb486;bba bb9{bb1700=0 ,bb1494=1 ,
bb1560=2 ,}bb1679;bba bb9{bb1388=0 ,bb1726,bb1438,bb1453,bb1565,bb1496,
bb1635,bb1464,bb1603,bb1492,bb1396,bb1728,}bb743;bba bb9{bb1507=0 ,
bb1361=2 ,bb1328=3 ,bb1375=4 ,bb1325=9 ,bb1297=12 ,bb1359=13 ,bb1310=14 ,
bb1348=249 ,}bb715;bba bb9{bb1357=0 ,bb1300=1 ,bb1285=2 ,bb1421=3 ,bb1633=
4 ,bb1356=5 ,bb1342=12 ,bb1320=13 ,bb1368=14 ,bb1286=61440 ,}bb481;bba bb9{
bb1293=1 ,bb1369=2 ,bb1338=3 ,bb1539=4 ,bb1600=5 ,bb1448=6 ,bb1427=7 ,bb1469
=8 ,bb1454=9 ,bb1538=10 ,bb1305=11 ,bb391=12 ,bb1339=13 ,bb390=240 ,bb1344=(
128 <<16 )|bb390,bb1343=(192 <<16 )|bb390,bb1331=(256 <<16 )|bb390,bb1303=(
128 <<16 )|bb391,bb1294=(192 <<16 )|bb391,bb1346=(256 <<16 )|bb391,}bb616;
bba bb9{bb1296=0 ,bb1501=1 ,bb1365=2 ,bb1330=3 ,bb1458=4 ,}bb890;bba bb9{
bb1434=0 ,bb1573=1 ,bb1222=2 ,bb604=3 ,bb1236=4 ,}bb716;bba bb9{bb1576=0 ,
bb1526=1 ,bb1406=2 ,bb1669=5 ,bb1706=7 ,}bb483;bba bb9{bb1425=0 ,bb1513=1 ,
bb1618=2 ,bb1711=3 ,bb1482=4 ,bb1690=5 ,bb1647=6 ,bb386=7 ,bb1543=65001 ,
bb396=240 ,bb1484=(128 <<16 )|bb396,bb1502=(192 <<16 )|bb396,bb1511=(256 <<
16 )|bb396,bb1542=(128 <<16 )|bb386,bb1556=(192 <<16 )|bb386,bb1614=(256 <<
16 )|bb386,}bb810;bba bb9{bb1717=0 ,bb1457=1 ,bb1662=2 ,bb1572=3 ,bb1472=4
,bb1529=5 ,bb1566=6 ,bb1644=65001 ,}bb625;bba bb9{bb1684=0 ,bb1524=1 ,
bb1661=2 ,bb1551=3 ,bb1654=4 ,bb1611=5 ,bb1553=64221 ,bb1617=64222 ,bb1658=
64223 ,bb1672=64224 ,bb1709=65001 ,bb1680=65002 ,bb1549=65003 ,bb1440=
65004 ,bb1722=65005 ,bb1486=65006 ,bb1510=65007 ,bb1476=65008 ,bb1708=
65009 ,bb1475=65010 ,}bb896;bba bb9{bb1698=0 ,bb1416=1 ,bb1431=2 ,}bb891;
bba bb9{bb1409=0 ,bb1638=1 ,bb1478=2 ,bb1682=3 ,}bb739;bba bb9{bb1590=0 ,
bb1418=1 ,bb1433=2 ,bb1648=3 ,bb1660=4 ,bb1641=5 ,bb1500=21 ,bb1569=6 ,
bb1615=7 ,bb1536=8 ,bb1378=1000 ,}bb490;bba bb9{bb1410=0 ,bb1561=1 ,bb1666
=2 ,}bb730;bba bb9{bb1665=0 ,bb1629=1 ,bb1715=2 ,bb1435=3 ,bb1471=4 ,}bb676
;bba bb9{bb1530=0 ,bb1673=1 ,bb1392=1001 ,bb1713=1002 ,}bb837;bba bb9{
bb1558=0 ,bb1134=1 ,bb1040=2 ,bb1051=3 ,bb1112=4 ,bb1126=5 ,bb1094=6 ,bb1695
=100 ,bb1581=101 ,}bb480;bba bbi bb394{bb616 bb154;bb481 bb580;bb486
bb57;}bb394;bba bbi bb400{bb715 bb1349;bb481 bb580;bb486 bb57;}bb400;
bba bbi bb392{bb890 bb1003;}bb392;bba bbi bb476{bb896 bb1606;bb625
bb414;bb810 bb154;bbu bb1485;bb483 bb647;}bb476;bba bbi bb485{bbu
bb599;bb394 bb308;bbu bb640;bb400 bb560;bbu bb772;bb392 bb607;bb483
bb647;}bb485;bba bbi bb450{bb178 bb957;bb178 bb1211;bb716 bb102;bb556
{bbi{bb400 bb45;bbf bb558[64 ];bbf bb551[64 ];}bb560;bbi{bb394 bb45;bbf
bb1218[32 ];bbf bb1229[32 ];bbf bb558[64 ];bbf bb551[64 ];bbf bb1199[16 ];
}bb308;bbi{bb392 bb45;}bb607;}bb317;}bb450;bba bbi{bbd bb818,bb589;
bbf bb1132:1 ;bbf bb1168:1 ;bbf bb102;bbk bb440;}bb185;bba bbi bb507{
bbd bb11;bb185 bbc[64 *2 ];}bb507;
#ifdef UNDER_CE
bba bb43 bb378;
#else
bba bb83 bb378;
#endif
bba bbi bb199{bbi bb199*bb1467, *bb1385;bbd bb26;bbd bb1114;bb185
bb914[64 ];bb480 bb504;bbd bb1299;bbk bb1062;bbd bb554;bbd bb675;bbd
bb816;bbf bb488;bbf bb1335;bbf bb1103;bbd bb1029;bbd bb1381;bb378
bb568;bbk bb1280;bb450 bb409[3 ];bb378 bb1568;bbf bb1503[40 ];bbd bb590
;bbd bb1577;}bb199;bba bbi bb399{bbi bb399*bb1723;bb185 bb475;}bb399;
bba bbi bb746{bbu bb473;bbu bb488;bbd bb26;bbd bb590;bbf bb1512;bbk
bb1592;bbf*bb1544;bbd bb1423;bbf*bb1583;bbd bb1714;bbf*bb1376;bbd
bb1412;bbu bb1645;bbu bb1570;bb399*bb131;bbu bb1470;bb676 bb1519;bbd
bb1593;bb891 bb1707;bb480 bb504;bbk bb1371;bbd bb1533;bb837 bb1403;
bbd bb1650;bbd bb1720;bb743 bb1417;bbf*bb1405;bbd bb1413;bb490 bb867;
bbd bb1656;bbd bb1623;bbd bb1408;bbd bb1699;bbd bb1493;bb476*bb1537;
bbd bb1610;bb485*bb1505;bbd bb1395;bbd bb1531;bbd bb1441;}bb746;bba
bbi bb684{bbu bb473;bbd bb26;bb185 bb475;}bb684;bba bbi bb665{bb199*
bb316;bbu bb1571;bbf*bb1701;bbd bb1667;}bb665;bba bbi bb876{bbd bb26;
bb185 bb475;bbf bb1432;bbf bb1447;}bb876;bba bbi bb829{bbu bb473;bbu
bb1119;bbd bb26;bbf*bb1625;bbd bb1541;}bb829;bba bbi bb662{bbd bb26;
bbk bb1702;bbk bb1729;bbd bb151;bbf*bb48;}bb662;bba bbi bb831{bbu
bb1586;bbd bb26;bbd bb554;bbd bb675;bbd bb816;}bb831;bba bbi bb868{
bb629 bb1490;bbd bb26;bb775 bb1323;bbu bb1555;}bb868;bba bbi bb622{
bbf bb1674;bbf bb1389;bbf bb1687;bbf bb1394;bbf bb1575;bbf bb1602;bbf
bb1584;bbf bb1459;bbf bb1374;bbf bb1521;bbf bb1411;bbf bb1627;bbf
bb1725;bbf bb1407;bbf bb1676;bbf bb1439;bbf bb1620;bbf bb1383;bbf
bb1450;bbf bb512;bbf bb1548;bbf bb1663;bbf bb1532;bbf bb1689;bbf
bb1415;bbf bb1430;bbf bb1414;}bb622;bba bbi bb742{bbu bb1637;bbd bb489
;bbd bb1621;bb739 bb1426;bbk bb1632;bbu bb1516;bbu bb1563;bbu bb1652;
bbu bb1451;bbu bb1631;bbu bb1659;bbu bb1398;bbl bb1624[128 ];bbl bb1670
[128 ];bbl bb1595[128 ];bbl bb1419[256 ];bbl bb1636[128 ];bbl bb1444[128 ]
;bbd bb1589;bbf bb1564[8 ];bbf bb1404[8 ];}bb742;bba bbi bb659{bbd bb26
;bbd bb1696;}bb659;bba bbi bb861{bbd bb26;bbu bb488;}bb861;bba bbi
bb747{bbu bb1522;bbd bb510;bbd bb1171;}bb747;bba bbi bb757{bbd bb26;
bb490 bb867;bb730 bb1599;bbf*bb1578;bbd bb1587;}bb757;bba bb9{bb1400=
0 ,bb1552,bb1671,bb1384,bb1613,bb1534,bb1594,bb1391,bb1525,bb1580,
bb1582,bb1692,bb1705,bb1653,bb1401,bb1585,bb1463,bb1402,bb1622,bb1640
,}bb664;bba bbi bb1649 bb815;bba bb4( *bb1550)(bb815*bb1567,bbb*
bb1588,bb664 bb321,bbb*bb74);
#pragma pack(pop)
#ifdef _WIN32
#ifdef UNDER_CE
#define bb468 bb1703 bb603("1:")
#else
#define bb468 bb603("\\\\.\\IPSecTL")
#endif
#else
#define bb614 "ipsecdrvtl"
#define bb468 "/dev/" bb614
#ifndef bb116
#define bb116
#ifdef _WIN32
#include"uncobf.h"
#include<wtypes.h>
#include"cobf.h"
#else
#ifdef bb120
#include"uncobf.h"
#include<linux/types.h>
#include"cobf.h"
#else
#include"uncobf.h"
#include<stddef.h>
#include<sys/types.h>
#include"cobf.h"
#endif
#endif
#ifdef _WIN32
bba bb119 bb215;
#else
bba bbe bbu, *bb133, *bb246;
#define bb201 1
#define bb202 0
bba bb251 bb205, *bb240, *bb208;bba bbe bb285, *bb283, *bb262;bba bbs
bbq, *bb93, *bb270;bba bb6 bb238, *bb216;bba bbs bb6 bb263, *bb250;
bba bb6 bb111, *bb222;bba bbs bb6 bb63, *bb289;bba bb63 bb264, *bb207
;bba bb63 bb219, *bb254;bba bb111 bb119, *bb226;bba bb243 bb247;bba
bb279 bb124;bba bb230 bb83;bba bb118 bb112;bba bb118 bb253;
#ifdef bb211
bba bb282 bb40, *bb72;bba bb258 bbk, *bb59;bba bb232 bbd, *bb28;bba
bb256 bb56, *bb113;
#else
bba bb271 bb40, *bb72;bba bb229 bbk, *bb59;bba bb233 bbd, *bb28;bba
bb277 bb56, *bb113;
#endif
bba bb40 bbf, *bb1, *bb214;bba bbk bb237, *bb245, *bb224;bba bbk bb255
, *bb220, *bb248;bba bbd bb60, *bb122, *bb206;bba bb83 bb37, *bb274, *
bb252;bba bbd bb290, *bb275, *bb210;bba bb112 bb265, *bb291, *bb269;
bba bb56 bb227, *bb261, *bb223;
#define bb140 bbb
bba bbb*bb221, *bb77;bba bbh bbb*bb225;bba bbl bb287;bba bbl*bb276;
bba bbh bbl*bb82;
#if defined( bb120)
bba bbe bb115;
#endif
bba bb115 bb20;bba bb20*bb218;bba bbh bb20*bb187;
#if defined( bb213) || defined( bb266)
bba bb20 bb36;bba bb20 bb114;
#else
bba bbl bb36;bba bbs bbl bb114;
#endif
bba bbh bb36*bb257;bba bb36*bb244;bba bb60 bb212, *bb239;bba bbb*
bb106;bba bb106*bb241;
#define bb281( bb34) bbi bb34##__ { bbe bb228; }; bba bbi bb34##__ * \
bb34
bba bbi{bb37 bb188,bb242,bb231,bb260;}bb286, *bb234, *bb278;bba bbi{
bb37 bb8,bb193;}bb280, *bb235, *bb259;bba bbi{bb37 bb267,bb249;}bb236
, *bb217, *bb284;
#endif
bba bbh bbf*bb89;
#endif
#include"uncobf.h"
#include<linux/ioctl.h>
#include"cobf.h"
bba bbi{bb1 bb1367;bbd bb1319;bb1 bb1240;bbd bb1144;bbd bb448;}bb1198
;
#define bb1364 1
#endif
#pragma pack(push, 8)
bb9{bb1355=3 ,bb1353,bb1354,bb1420,};bba bbi{bbf bb103[4 ];}bb1268;bba
bbi{bbf bb103[4 ];}bb1235;bba bbi{bbd bb948;bbd bb26;}bb1265;bba bbi{
bbd bb129;bbf bb1224[8 ];}bb402;bba bb9{bb1220=0 ,bb1232,bb1250,bb1262,
bb1731}bb1233;bba bbi{bbf bb1120;bbd bb1070;bbf bb1360;}bb474;
#pragma pack(pop)
#pragma pack(push, 8)
bb9{bb1135=-5000 ,bb1104=-4000 ,bb997=-4999 ,bb988=-4998 ,bb1011=-4997 ,
bb981=-4996 ,bb1141=-4995 ,bb1087=-4994 ,bb1096=-4993 ,bb1024=-4992 ,
bb1031=-4991 };bb4 bb1129(bb4 bb1133,bbd bb1116,bbl*bb1100);bba bbi{
bb199 bb180;bbd bb1194;bbd bb1084;bbd bb1370;bbd bb1081;bbd bb1239;
bbd bb1279;bbd bb1256;bbd bb1238;bbd bb1248;bbd bb1281;bbd bb1249;bbu
bb1221;bb43 bb568,bb1172,bb1170;bbf bb371[6 ];}bb160;bba bbi bb478{bbi
bb478*bb94;bbf bb102;bbk bb1275;bbk bb1276;bbk bb1271;bbk bb1274;}
bb430;bba bbi bb787{bbi bb787*bb94;bbi bb478*bb1095;bbd bb26;bbf bb371
[6 ];}bb411;bba bb9{bb1146=0 ,bb1730,bb1037,bb1017,bb1007}bb204;bba bbi
{bbd bb382;bbd bb448;bbd bb513;bb402*bb912;bb96 bb980;}bb302;bba bbi{
bb474*bb457;bb411*bb1142;bbd bb584;bb430*bb542;bb96 bb601;bbq bb1118;
bbq bb548;bb160*bb508;bbu bb1269;bbk bb1157;bbk bb1106;bb302 bb1041;}
bb32, *bb1607;
#pragma pack(pop)
bba bbi bb967 bb1334, *bb78;bba bbi bb838{bbi bb838*bb323;bb1 bb466;
bbq bb565;bbd bb26;bbk bb440;bbq bb92;bb1 bb315;bbq bb442;bb1 bb546;
bbq bb543;bb1 bb1498;bb100 bb1362;bbf bb1307[6 ];bb100 bb964;bb100
bb1140;bb100 bb521;bb100 bb533;}bb174, *bb87;bba bbi bb870{bbi bb870*
bb94;bb174*bb323;bbd bb26;bbk bb537;bbk bb1468;bbq bb1442;bbq bb1517;
bbk bb1428;}bb1455, *bb459;bbu bb1284(bb32* *bb1215);bbb bb1283(bb32*
bbj);bb204 bb1267(bb32*bb109,bb376 bb451,bb312 bb138,bb341 bb413,
bb318 bb200);bb204 bb1246(bb32*bb109,bb376 bb451,bb312 bb138,bb341
bb413,bb318 bb200);bb204 bb1254(bb32*bb109,bb174*bb48,bb78 bb76);
bb204 bb1234(bb32*bb109,bb174*bb48,bb78 bb76);bb4 bb1244(bb32*bb109,
bb174*bb48,bbd*bb103);bb4 bb1153(bb78 bb76,bb32*bb109,bb174*bb48,
bb160*bb316,bbu bb594,bbu bb947);bb4 bb1780(bb32*bbj,bb474*bb457);bbb
bb2029(bb32*bbj);bb4 bb1780(bb32*bbj,bb474*bb457){bbm(!bbj->bb457){
bbj->bb457=bb128(bb12( *bb457));bbm(!bbj->bb457)bb2 bb357;}bb81(bbj->
bb457,bb457,bb12( *bb457));bb2 bb98;}bbb bb2029(bb32*bbj){bbm(bbj->
bb457)bb105(bbj->bb457);bbj->bb457=bb91;}
| gpl-2.0 |
jackyxhb/linux | drivers/iio/gyro/st_gyro_core.c | 218 | 13082 | /*
* STMicroelectronics gyroscopes driver
*
* Copyright 2012-2013 STMicroelectronics Inc.
*
* Denis Ciocca <denis.ciocca@st.com>
*
* Licensed under the GPL-2.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/trigger.h>
#include <linux/iio/buffer.h>
#include <linux/iio/common/st_sensors.h>
#include "st_gyro.h"
#define ST_GYRO_NUMBER_DATA_CHANNELS 3
/* DEFAULT VALUE FOR SENSORS */
#define ST_GYRO_DEFAULT_OUT_X_L_ADDR 0x28
#define ST_GYRO_DEFAULT_OUT_Y_L_ADDR 0x2a
#define ST_GYRO_DEFAULT_OUT_Z_L_ADDR 0x2c
/* FULLSCALE */
#define ST_GYRO_FS_AVL_250DPS 250
#define ST_GYRO_FS_AVL_500DPS 500
#define ST_GYRO_FS_AVL_2000DPS 2000
/* CUSTOM VALUES FOR SENSOR 1 */
#define ST_GYRO_1_WAI_EXP 0xd3
#define ST_GYRO_1_ODR_ADDR 0x20
#define ST_GYRO_1_ODR_MASK 0xc0
#define ST_GYRO_1_ODR_AVL_100HZ_VAL 0x00
#define ST_GYRO_1_ODR_AVL_200HZ_VAL 0x01
#define ST_GYRO_1_ODR_AVL_400HZ_VAL 0x02
#define ST_GYRO_1_ODR_AVL_800HZ_VAL 0x03
#define ST_GYRO_1_PW_ADDR 0x20
#define ST_GYRO_1_PW_MASK 0x08
#define ST_GYRO_1_FS_ADDR 0x23
#define ST_GYRO_1_FS_MASK 0x30
#define ST_GYRO_1_FS_AVL_250_VAL 0x00
#define ST_GYRO_1_FS_AVL_500_VAL 0x01
#define ST_GYRO_1_FS_AVL_2000_VAL 0x02
#define ST_GYRO_1_FS_AVL_250_GAIN IIO_DEGREE_TO_RAD(8750)
#define ST_GYRO_1_FS_AVL_500_GAIN IIO_DEGREE_TO_RAD(17500)
#define ST_GYRO_1_FS_AVL_2000_GAIN IIO_DEGREE_TO_RAD(70000)
#define ST_GYRO_1_BDU_ADDR 0x23
#define ST_GYRO_1_BDU_MASK 0x80
#define ST_GYRO_1_DRDY_IRQ_ADDR 0x22
#define ST_GYRO_1_DRDY_IRQ_INT2_MASK 0x08
#define ST_GYRO_1_MULTIREAD_BIT true
/* CUSTOM VALUES FOR SENSOR 2 */
#define ST_GYRO_2_WAI_EXP 0xd4
#define ST_GYRO_2_ODR_ADDR 0x20
#define ST_GYRO_2_ODR_MASK 0xc0
#define ST_GYRO_2_ODR_AVL_95HZ_VAL 0x00
#define ST_GYRO_2_ODR_AVL_190HZ_VAL 0x01
#define ST_GYRO_2_ODR_AVL_380HZ_VAL 0x02
#define ST_GYRO_2_ODR_AVL_760HZ_VAL 0x03
#define ST_GYRO_2_PW_ADDR 0x20
#define ST_GYRO_2_PW_MASK 0x08
#define ST_GYRO_2_FS_ADDR 0x23
#define ST_GYRO_2_FS_MASK 0x30
#define ST_GYRO_2_FS_AVL_250_VAL 0x00
#define ST_GYRO_2_FS_AVL_500_VAL 0x01
#define ST_GYRO_2_FS_AVL_2000_VAL 0x02
#define ST_GYRO_2_FS_AVL_250_GAIN IIO_DEGREE_TO_RAD(8750)
#define ST_GYRO_2_FS_AVL_500_GAIN IIO_DEGREE_TO_RAD(17500)
#define ST_GYRO_2_FS_AVL_2000_GAIN IIO_DEGREE_TO_RAD(70000)
#define ST_GYRO_2_BDU_ADDR 0x23
#define ST_GYRO_2_BDU_MASK 0x80
#define ST_GYRO_2_DRDY_IRQ_ADDR 0x22
#define ST_GYRO_2_DRDY_IRQ_INT2_MASK 0x08
#define ST_GYRO_2_MULTIREAD_BIT true
/* CUSTOM VALUES FOR SENSOR 3 */
#define ST_GYRO_3_WAI_EXP 0xd7
#define ST_GYRO_3_ODR_ADDR 0x20
#define ST_GYRO_3_ODR_MASK 0xc0
#define ST_GYRO_3_ODR_AVL_95HZ_VAL 0x00
#define ST_GYRO_3_ODR_AVL_190HZ_VAL 0x01
#define ST_GYRO_3_ODR_AVL_380HZ_VAL 0x02
#define ST_GYRO_3_ODR_AVL_760HZ_VAL 0x03
#define ST_GYRO_3_PW_ADDR 0x20
#define ST_GYRO_3_PW_MASK 0x08
#define ST_GYRO_3_FS_ADDR 0x23
#define ST_GYRO_3_FS_MASK 0x30
#define ST_GYRO_3_FS_AVL_250_VAL 0x00
#define ST_GYRO_3_FS_AVL_500_VAL 0x01
#define ST_GYRO_3_FS_AVL_2000_VAL 0x02
#define ST_GYRO_3_FS_AVL_250_GAIN IIO_DEGREE_TO_RAD(8750)
#define ST_GYRO_3_FS_AVL_500_GAIN IIO_DEGREE_TO_RAD(17500)
#define ST_GYRO_3_FS_AVL_2000_GAIN IIO_DEGREE_TO_RAD(70000)
#define ST_GYRO_3_BDU_ADDR 0x23
#define ST_GYRO_3_BDU_MASK 0x80
#define ST_GYRO_3_DRDY_IRQ_ADDR 0x22
#define ST_GYRO_3_DRDY_IRQ_INT2_MASK 0x08
#define ST_GYRO_3_MULTIREAD_BIT true
static const struct iio_chan_spec st_gyro_16bit_channels[] = {
ST_SENSORS_LSM_CHANNELS(IIO_ANGL_VEL,
BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE),
ST_SENSORS_SCAN_X, 1, IIO_MOD_X, 's', IIO_LE, 16, 16,
ST_GYRO_DEFAULT_OUT_X_L_ADDR),
ST_SENSORS_LSM_CHANNELS(IIO_ANGL_VEL,
BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE),
ST_SENSORS_SCAN_Y, 1, IIO_MOD_Y, 's', IIO_LE, 16, 16,
ST_GYRO_DEFAULT_OUT_Y_L_ADDR),
ST_SENSORS_LSM_CHANNELS(IIO_ANGL_VEL,
BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE),
ST_SENSORS_SCAN_Z, 1, IIO_MOD_Z, 's', IIO_LE, 16, 16,
ST_GYRO_DEFAULT_OUT_Z_L_ADDR),
IIO_CHAN_SOFT_TIMESTAMP(3)
};
static const struct st_sensor_settings st_gyro_sensors_settings[] = {
{
.wai = ST_GYRO_1_WAI_EXP,
.wai_addr = ST_SENSORS_DEFAULT_WAI_ADDRESS,
.sensors_supported = {
[0] = L3G4200D_GYRO_DEV_NAME,
[1] = LSM330DL_GYRO_DEV_NAME,
},
.ch = (struct iio_chan_spec *)st_gyro_16bit_channels,
.odr = {
.addr = ST_GYRO_1_ODR_ADDR,
.mask = ST_GYRO_1_ODR_MASK,
.odr_avl = {
{ 100, ST_GYRO_1_ODR_AVL_100HZ_VAL, },
{ 200, ST_GYRO_1_ODR_AVL_200HZ_VAL, },
{ 400, ST_GYRO_1_ODR_AVL_400HZ_VAL, },
{ 800, ST_GYRO_1_ODR_AVL_800HZ_VAL, },
},
},
.pw = {
.addr = ST_GYRO_1_PW_ADDR,
.mask = ST_GYRO_1_PW_MASK,
.value_on = ST_SENSORS_DEFAULT_POWER_ON_VALUE,
.value_off = ST_SENSORS_DEFAULT_POWER_OFF_VALUE,
},
.enable_axis = {
.addr = ST_SENSORS_DEFAULT_AXIS_ADDR,
.mask = ST_SENSORS_DEFAULT_AXIS_MASK,
},
.fs = {
.addr = ST_GYRO_1_FS_ADDR,
.mask = ST_GYRO_1_FS_MASK,
.fs_avl = {
[0] = {
.num = ST_GYRO_FS_AVL_250DPS,
.value = ST_GYRO_1_FS_AVL_250_VAL,
.gain = ST_GYRO_1_FS_AVL_250_GAIN,
},
[1] = {
.num = ST_GYRO_FS_AVL_500DPS,
.value = ST_GYRO_1_FS_AVL_500_VAL,
.gain = ST_GYRO_1_FS_AVL_500_GAIN,
},
[2] = {
.num = ST_GYRO_FS_AVL_2000DPS,
.value = ST_GYRO_1_FS_AVL_2000_VAL,
.gain = ST_GYRO_1_FS_AVL_2000_GAIN,
},
},
},
.bdu = {
.addr = ST_GYRO_1_BDU_ADDR,
.mask = ST_GYRO_1_BDU_MASK,
},
.drdy_irq = {
.addr = ST_GYRO_1_DRDY_IRQ_ADDR,
.mask_int2 = ST_GYRO_1_DRDY_IRQ_INT2_MASK,
},
.multi_read_bit = ST_GYRO_1_MULTIREAD_BIT,
.bootime = 2,
},
{
.wai = ST_GYRO_2_WAI_EXP,
.wai_addr = ST_SENSORS_DEFAULT_WAI_ADDRESS,
.sensors_supported = {
[0] = L3GD20_GYRO_DEV_NAME,
[1] = LSM330D_GYRO_DEV_NAME,
[2] = LSM330DLC_GYRO_DEV_NAME,
[3] = L3G4IS_GYRO_DEV_NAME,
[4] = LSM330_GYRO_DEV_NAME,
},
.ch = (struct iio_chan_spec *)st_gyro_16bit_channels,
.odr = {
.addr = ST_GYRO_2_ODR_ADDR,
.mask = ST_GYRO_2_ODR_MASK,
.odr_avl = {
{ 95, ST_GYRO_2_ODR_AVL_95HZ_VAL, },
{ 190, ST_GYRO_2_ODR_AVL_190HZ_VAL, },
{ 380, ST_GYRO_2_ODR_AVL_380HZ_VAL, },
{ 760, ST_GYRO_2_ODR_AVL_760HZ_VAL, },
},
},
.pw = {
.addr = ST_GYRO_2_PW_ADDR,
.mask = ST_GYRO_2_PW_MASK,
.value_on = ST_SENSORS_DEFAULT_POWER_ON_VALUE,
.value_off = ST_SENSORS_DEFAULT_POWER_OFF_VALUE,
},
.enable_axis = {
.addr = ST_SENSORS_DEFAULT_AXIS_ADDR,
.mask = ST_SENSORS_DEFAULT_AXIS_MASK,
},
.fs = {
.addr = ST_GYRO_2_FS_ADDR,
.mask = ST_GYRO_2_FS_MASK,
.fs_avl = {
[0] = {
.num = ST_GYRO_FS_AVL_250DPS,
.value = ST_GYRO_2_FS_AVL_250_VAL,
.gain = ST_GYRO_2_FS_AVL_250_GAIN,
},
[1] = {
.num = ST_GYRO_FS_AVL_500DPS,
.value = ST_GYRO_2_FS_AVL_500_VAL,
.gain = ST_GYRO_2_FS_AVL_500_GAIN,
},
[2] = {
.num = ST_GYRO_FS_AVL_2000DPS,
.value = ST_GYRO_2_FS_AVL_2000_VAL,
.gain = ST_GYRO_2_FS_AVL_2000_GAIN,
},
},
},
.bdu = {
.addr = ST_GYRO_2_BDU_ADDR,
.mask = ST_GYRO_2_BDU_MASK,
},
.drdy_irq = {
.addr = ST_GYRO_2_DRDY_IRQ_ADDR,
.mask_int2 = ST_GYRO_2_DRDY_IRQ_INT2_MASK,
},
.multi_read_bit = ST_GYRO_2_MULTIREAD_BIT,
.bootime = 2,
},
{
.wai = ST_GYRO_3_WAI_EXP,
.wai_addr = ST_SENSORS_DEFAULT_WAI_ADDRESS,
.sensors_supported = {
[0] = L3GD20_GYRO_DEV_NAME,
},
.ch = (struct iio_chan_spec *)st_gyro_16bit_channels,
.odr = {
.addr = ST_GYRO_3_ODR_ADDR,
.mask = ST_GYRO_3_ODR_MASK,
.odr_avl = {
{ 95, ST_GYRO_3_ODR_AVL_95HZ_VAL, },
{ 190, ST_GYRO_3_ODR_AVL_190HZ_VAL, },
{ 380, ST_GYRO_3_ODR_AVL_380HZ_VAL, },
{ 760, ST_GYRO_3_ODR_AVL_760HZ_VAL, },
},
},
.pw = {
.addr = ST_GYRO_3_PW_ADDR,
.mask = ST_GYRO_3_PW_MASK,
.value_on = ST_SENSORS_DEFAULT_POWER_ON_VALUE,
.value_off = ST_SENSORS_DEFAULT_POWER_OFF_VALUE,
},
.enable_axis = {
.addr = ST_SENSORS_DEFAULT_AXIS_ADDR,
.mask = ST_SENSORS_DEFAULT_AXIS_MASK,
},
.fs = {
.addr = ST_GYRO_3_FS_ADDR,
.mask = ST_GYRO_3_FS_MASK,
.fs_avl = {
[0] = {
.num = ST_GYRO_FS_AVL_250DPS,
.value = ST_GYRO_3_FS_AVL_250_VAL,
.gain = ST_GYRO_3_FS_AVL_250_GAIN,
},
[1] = {
.num = ST_GYRO_FS_AVL_500DPS,
.value = ST_GYRO_3_FS_AVL_500_VAL,
.gain = ST_GYRO_3_FS_AVL_500_GAIN,
},
[2] = {
.num = ST_GYRO_FS_AVL_2000DPS,
.value = ST_GYRO_3_FS_AVL_2000_VAL,
.gain = ST_GYRO_3_FS_AVL_2000_GAIN,
},
},
},
.bdu = {
.addr = ST_GYRO_3_BDU_ADDR,
.mask = ST_GYRO_3_BDU_MASK,
},
.drdy_irq = {
.addr = ST_GYRO_3_DRDY_IRQ_ADDR,
.mask_int2 = ST_GYRO_3_DRDY_IRQ_INT2_MASK,
},
.multi_read_bit = ST_GYRO_3_MULTIREAD_BIT,
.bootime = 2,
},
};
static int st_gyro_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *ch, int *val,
int *val2, long mask)
{
int err;
struct st_sensor_data *gdata = iio_priv(indio_dev);
switch (mask) {
case IIO_CHAN_INFO_RAW:
err = st_sensors_read_info_raw(indio_dev, ch, val);
if (err < 0)
goto read_error;
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
*val = 0;
*val2 = gdata->current_fullscale->gain;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_CHAN_INFO_SAMP_FREQ:
*val = gdata->odr;
return IIO_VAL_INT;
default:
return -EINVAL;
}
read_error:
return err;
}
static int st_gyro_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int val, int val2, long mask)
{
int err;
switch (mask) {
case IIO_CHAN_INFO_SCALE:
err = st_sensors_set_fullscale_by_gain(indio_dev, val2);
break;
case IIO_CHAN_INFO_SAMP_FREQ:
if (val2)
return -EINVAL;
mutex_lock(&indio_dev->mlock);
err = st_sensors_set_odr(indio_dev, val);
mutex_unlock(&indio_dev->mlock);
return err;
default:
err = -EINVAL;
}
return err;
}
static ST_SENSORS_DEV_ATTR_SAMP_FREQ_AVAIL();
static ST_SENSORS_DEV_ATTR_SCALE_AVAIL(in_anglvel_scale_available);
static struct attribute *st_gyro_attributes[] = {
&iio_dev_attr_sampling_frequency_available.dev_attr.attr,
&iio_dev_attr_in_anglvel_scale_available.dev_attr.attr,
NULL,
};
static const struct attribute_group st_gyro_attribute_group = {
.attrs = st_gyro_attributes,
};
static const struct iio_info gyro_info = {
.driver_module = THIS_MODULE,
.attrs = &st_gyro_attribute_group,
.read_raw = &st_gyro_read_raw,
.write_raw = &st_gyro_write_raw,
};
#ifdef CONFIG_IIO_TRIGGER
static const struct iio_trigger_ops st_gyro_trigger_ops = {
.owner = THIS_MODULE,
.set_trigger_state = ST_GYRO_TRIGGER_SET_STATE,
};
#define ST_GYRO_TRIGGER_OPS (&st_gyro_trigger_ops)
#else
#define ST_GYRO_TRIGGER_OPS NULL
#endif
int st_gyro_common_probe(struct iio_dev *indio_dev)
{
struct st_sensor_data *gdata = iio_priv(indio_dev);
int irq = gdata->get_irq_data_ready(indio_dev);
int err;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->info = &gyro_info;
mutex_init(&gdata->tb.buf_lock);
st_sensors_power_enable(indio_dev);
err = st_sensors_check_device_support(indio_dev,
ARRAY_SIZE(st_gyro_sensors_settings),
st_gyro_sensors_settings);
if (err < 0)
return err;
gdata->num_data_channels = ST_GYRO_NUMBER_DATA_CHANNELS;
gdata->multiread_bit = gdata->sensor_settings->multi_read_bit;
indio_dev->channels = gdata->sensor_settings->ch;
indio_dev->num_channels = ST_SENSORS_NUMBER_ALL_CHANNELS;
gdata->current_fullscale = (struct st_sensor_fullscale_avl *)
&gdata->sensor_settings->fs.fs_avl[0];
gdata->odr = gdata->sensor_settings->odr.odr_avl[0].hz;
err = st_sensors_init_sensor(indio_dev,
(struct st_sensors_platform_data *)&gyro_pdata);
if (err < 0)
return err;
err = st_gyro_allocate_ring(indio_dev);
if (err < 0)
return err;
if (irq > 0) {
err = st_sensors_allocate_trigger(indio_dev,
ST_GYRO_TRIGGER_OPS);
if (err < 0)
goto st_gyro_probe_trigger_error;
}
err = iio_device_register(indio_dev);
if (err)
goto st_gyro_device_register_error;
dev_info(&indio_dev->dev, "registered gyroscope %s\n",
indio_dev->name);
return 0;
st_gyro_device_register_error:
if (irq > 0)
st_sensors_deallocate_trigger(indio_dev);
st_gyro_probe_trigger_error:
st_gyro_deallocate_ring(indio_dev);
return err;
}
EXPORT_SYMBOL(st_gyro_common_probe);
void st_gyro_common_remove(struct iio_dev *indio_dev)
{
struct st_sensor_data *gdata = iio_priv(indio_dev);
st_sensors_power_disable(indio_dev);
iio_device_unregister(indio_dev);
if (gdata->get_irq_data_ready(indio_dev) > 0)
st_sensors_deallocate_trigger(indio_dev);
st_gyro_deallocate_ring(indio_dev);
}
EXPORT_SYMBOL(st_gyro_common_remove);
MODULE_AUTHOR("Denis Ciocca <denis.ciocca@st.com>");
MODULE_DESCRIPTION("STMicroelectronics gyroscopes driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
HelllGuest/Qualcomm_MSM7227 | drivers/scsi/lpfc/lpfc_ct.c | 986 | 53065 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2004-2010 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* *
* 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. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
/*
* Fibre Channel SCSI LAN Device Driver CT support: FC Generic Services FC-GS
*/
#include <linux/blkdev.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/utsname.h>
#include <scsi/scsi.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include <scsi/fc/fc_fs.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_nl.h"
#include "lpfc_disc.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_version.h"
#include "lpfc_vport.h"
#include "lpfc_debugfs.h"
#define HBA_PORTSPEED_UNKNOWN 0 /* Unknown - transceiver
* incapable of reporting */
#define HBA_PORTSPEED_1GBIT 1 /* 1 GBit/sec */
#define HBA_PORTSPEED_2GBIT 2 /* 2 GBit/sec */
#define HBA_PORTSPEED_4GBIT 8 /* 4 GBit/sec */
#define HBA_PORTSPEED_8GBIT 16 /* 8 GBit/sec */
#define HBA_PORTSPEED_10GBIT 4 /* 10 GBit/sec */
#define HBA_PORTSPEED_NOT_NEGOTIATED 5 /* Speed not established */
#define FOURBYTES 4
static char *lpfc_release_version = LPFC_DRIVER_VERSION;
static void
lpfc_ct_ignore_hbq_buffer(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
struct lpfc_dmabuf *mp, uint32_t size)
{
if (!mp) {
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"0146 Ignoring unsolicited CT No HBQ "
"status = x%x\n",
piocbq->iocb.ulpStatus);
}
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"0145 Ignoring unsolicted CT HBQ Size:%d "
"status = x%x\n",
size, piocbq->iocb.ulpStatus);
}
static void
lpfc_ct_unsol_buffer(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
struct lpfc_dmabuf *mp, uint32_t size)
{
lpfc_ct_ignore_hbq_buffer(phba, piocbq, mp, size);
}
void
lpfc_ct_unsol_event(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
struct lpfc_iocbq *piocbq)
{
struct lpfc_dmabuf *mp = NULL;
IOCB_t *icmd = &piocbq->iocb;
int i;
struct lpfc_iocbq *iocbq;
dma_addr_t paddr;
uint32_t size;
struct list_head head;
struct lpfc_dmabuf *bdeBuf;
if (lpfc_bsg_ct_unsol_event(phba, pring, piocbq) == 0)
return;
if (unlikely(icmd->ulpStatus == IOSTAT_NEED_BUFFER)) {
lpfc_sli_hbqbuf_add_hbqs(phba, LPFC_ELS_HBQ);
} else if ((icmd->ulpStatus == IOSTAT_LOCAL_REJECT) &&
((icmd->un.ulpWord[4] & 0xff) == IOERR_RCV_BUFFER_WAITING)) {
/* Not enough posted buffers; Try posting more buffers */
phba->fc_stat.NoRcvBuf++;
if (!(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED))
lpfc_post_buffer(phba, pring, 2);
return;
}
/* If there are no BDEs associated with this IOCB,
* there is nothing to do.
*/
if (icmd->ulpBdeCount == 0)
return;
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
INIT_LIST_HEAD(&head);
list_add_tail(&head, &piocbq->list);
list_for_each_entry(iocbq, &head, list) {
icmd = &iocbq->iocb;
if (icmd->ulpBdeCount == 0)
continue;
bdeBuf = iocbq->context2;
iocbq->context2 = NULL;
size = icmd->un.cont64[0].tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, piocbq, bdeBuf, size);
lpfc_in_buf_free(phba, bdeBuf);
if (icmd->ulpBdeCount == 2) {
bdeBuf = iocbq->context3;
iocbq->context3 = NULL;
size = icmd->unsli3.rcvsli3.bde2.tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, piocbq, bdeBuf,
size);
lpfc_in_buf_free(phba, bdeBuf);
}
}
list_del(&head);
} else {
INIT_LIST_HEAD(&head);
list_add_tail(&head, &piocbq->list);
list_for_each_entry(iocbq, &head, list) {
icmd = &iocbq->iocb;
if (icmd->ulpBdeCount == 0)
lpfc_ct_unsol_buffer(phba, iocbq, NULL, 0);
for (i = 0; i < icmd->ulpBdeCount; i++) {
paddr = getPaddr(icmd->un.cont64[i].addrHigh,
icmd->un.cont64[i].addrLow);
mp = lpfc_sli_ringpostbuf_get(phba, pring,
paddr);
size = icmd->un.cont64[i].tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, iocbq, mp, size);
lpfc_in_buf_free(phba, mp);
}
lpfc_post_buffer(phba, pring, i);
}
list_del(&head);
}
}
/**
* lpfc_sli4_ct_abort_unsol_event - Default handle for sli4 unsol abort
* @phba: Pointer to HBA context object.
* @pring: Pointer to the driver internal I/O ring.
* @piocbq: Pointer to the IOCBQ.
*
* This function serves as the default handler for the sli4 unsolicited
* abort event. It shall be invoked when there is no application interface
* registered unsolicited abort handler. This handler does nothing but
* just simply releases the dma buffer used by the unsol abort event.
**/
void
lpfc_sli4_ct_abort_unsol_event(struct lpfc_hba *phba,
struct lpfc_sli_ring *pring,
struct lpfc_iocbq *piocbq)
{
IOCB_t *icmd = &piocbq->iocb;
struct lpfc_dmabuf *bdeBuf;
uint32_t size;
/* Forward abort event to any process registered to receive ct event */
if (lpfc_bsg_ct_unsol_event(phba, pring, piocbq) == 0)
return;
/* If there is no BDE associated with IOCB, there is nothing to do */
if (icmd->ulpBdeCount == 0)
return;
bdeBuf = piocbq->context2;
piocbq->context2 = NULL;
size = icmd->un.cont64[0].tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, piocbq, bdeBuf, size);
lpfc_in_buf_free(phba, bdeBuf);
}
static void
lpfc_free_ct_rsp(struct lpfc_hba *phba, struct lpfc_dmabuf *mlist)
{
struct lpfc_dmabuf *mlast, *next_mlast;
list_for_each_entry_safe(mlast, next_mlast, &mlist->list, list) {
lpfc_mbuf_free(phba, mlast->virt, mlast->phys);
list_del(&mlast->list);
kfree(mlast);
}
lpfc_mbuf_free(phba, mlist->virt, mlist->phys);
kfree(mlist);
return;
}
static struct lpfc_dmabuf *
lpfc_alloc_ct_rsp(struct lpfc_hba *phba, int cmdcode, struct ulp_bde64 *bpl,
uint32_t size, int *entries)
{
struct lpfc_dmabuf *mlist = NULL;
struct lpfc_dmabuf *mp;
int cnt, i = 0;
/* We get chunks of FCELSSIZE */
cnt = size > FCELSSIZE ? FCELSSIZE: size;
while (size) {
/* Allocate buffer for rsp payload */
mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!mp) {
if (mlist)
lpfc_free_ct_rsp(phba, mlist);
return NULL;
}
INIT_LIST_HEAD(&mp->list);
if (cmdcode == be16_to_cpu(SLI_CTNS_GID_FT) ||
cmdcode == be16_to_cpu(SLI_CTNS_GFF_ID))
mp->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &(mp->phys));
else
mp->virt = lpfc_mbuf_alloc(phba, 0, &(mp->phys));
if (!mp->virt) {
kfree(mp);
if (mlist)
lpfc_free_ct_rsp(phba, mlist);
return NULL;
}
/* Queue it to a linked list */
if (!mlist)
mlist = mp;
else
list_add_tail(&mp->list, &mlist->list);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
/* build buffer ptr list for IOCB */
bpl->addrLow = le32_to_cpu(putPaddrLow(mp->phys) );
bpl->addrHigh = le32_to_cpu(putPaddrHigh(mp->phys) );
bpl->tus.f.bdeSize = (uint16_t) cnt;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
bpl++;
i++;
size -= cnt;
}
*entries = i;
return mlist;
}
int
lpfc_ct_free_iocb(struct lpfc_hba *phba, struct lpfc_iocbq *ctiocb)
{
struct lpfc_dmabuf *buf_ptr;
if (ctiocb->context_un.ndlp) {
lpfc_nlp_put(ctiocb->context_un.ndlp);
ctiocb->context_un.ndlp = NULL;
}
if (ctiocb->context1) {
buf_ptr = (struct lpfc_dmabuf *) ctiocb->context1;
lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
kfree(buf_ptr);
ctiocb->context1 = NULL;
}
if (ctiocb->context2) {
lpfc_free_ct_rsp(phba, (struct lpfc_dmabuf *) ctiocb->context2);
ctiocb->context2 = NULL;
}
if (ctiocb->context3) {
buf_ptr = (struct lpfc_dmabuf *) ctiocb->context3;
lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
kfree(buf_ptr);
ctiocb->context1 = NULL;
}
lpfc_sli_release_iocbq(phba, ctiocb);
return 0;
}
static int
lpfc_gen_req(struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
struct lpfc_dmabuf *inp, struct lpfc_dmabuf *outp,
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *),
struct lpfc_nodelist *ndlp, uint32_t usr_flg, uint32_t num_entry,
uint32_t tmo, uint8_t retry)
{
struct lpfc_hba *phba = vport->phba;
IOCB_t *icmd;
struct lpfc_iocbq *geniocb;
int rc;
/* Allocate buffer for command iocb */
geniocb = lpfc_sli_get_iocbq(phba);
if (geniocb == NULL)
return 1;
icmd = &geniocb->iocb;
icmd->un.genreq64.bdl.ulpIoTag32 = 0;
icmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
icmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
icmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
icmd->un.genreq64.bdl.bdeSize = (num_entry * sizeof (struct ulp_bde64));
if (usr_flg)
geniocb->context3 = NULL;
else
geniocb->context3 = (uint8_t *) bmp;
/* Save for completion so we can release these resources */
geniocb->context1 = (uint8_t *) inp;
geniocb->context2 = (uint8_t *) outp;
geniocb->context_un.ndlp = lpfc_nlp_get(ndlp);
/* Fill in payload, bp points to frame payload */
icmd->ulpCommand = CMD_GEN_REQUEST64_CR;
/* Fill in rest of iocb */
icmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
icmd->un.genreq64.w5.hcsw.Dfctl = 0;
icmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
icmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
if (!tmo) {
/* FC spec states we need 3 * ratov for CT requests */
tmo = (3 * phba->fc_ratov);
}
icmd->ulpTimeout = tmo;
icmd->ulpBdeCount = 1;
icmd->ulpLe = 1;
icmd->ulpClass = CLASS3;
icmd->ulpContext = ndlp->nlp_rpi;
if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
/* For GEN_REQUEST64_CR, use the RPI */
icmd->ulpCt_h = 0;
icmd->ulpCt_l = 0;
}
/* Issue GEN REQ IOCB for NPORT <did> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
"0119 Issue GEN REQ IOCB to NPORT x%x "
"Data: x%x x%x\n",
ndlp->nlp_DID, icmd->ulpIoTag,
vport->port_state);
geniocb->iocb_cmpl = cmpl;
geniocb->drvrTimeout = icmd->ulpTimeout + LPFC_DRVR_TIMEOUT;
geniocb->vport = vport;
geniocb->retry = retry;
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, geniocb, 0);
if (rc == IOCB_ERROR) {
lpfc_sli_release_iocbq(phba, geniocb);
return 1;
}
return 0;
}
static int
lpfc_ct_cmd(struct lpfc_vport *vport, struct lpfc_dmabuf *inmp,
struct lpfc_dmabuf *bmp, struct lpfc_nodelist *ndlp,
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *),
uint32_t rsp_size, uint8_t retry)
{
struct lpfc_hba *phba = vport->phba;
struct ulp_bde64 *bpl = (struct ulp_bde64 *) bmp->virt;
struct lpfc_dmabuf *outmp;
int cnt = 0, status;
int cmdcode = ((struct lpfc_sli_ct_request *) inmp->virt)->
CommandResponse.bits.CmdRsp;
bpl++; /* Skip past ct request */
/* Put buffer(s) for ct rsp in bpl */
outmp = lpfc_alloc_ct_rsp(phba, cmdcode, bpl, rsp_size, &cnt);
if (!outmp)
return -ENOMEM;
/*
* Form the CT IOCB. The total number of BDEs in this IOCB
* is the single command plus response count from
* lpfc_alloc_ct_rsp.
*/
cnt += 1;
status = lpfc_gen_req(vport, bmp, inmp, outmp, cmpl, ndlp, 0,
cnt, 0, retry);
if (status) {
lpfc_free_ct_rsp(phba, outmp);
return -ENOMEM;
}
return 0;
}
struct lpfc_vport *
lpfc_find_vport_by_did(struct lpfc_hba *phba, uint32_t did) {
struct lpfc_vport *vport_curr;
unsigned long flags;
spin_lock_irqsave(&phba->hbalock, flags);
list_for_each_entry(vport_curr, &phba->port_list, listentry) {
if ((vport_curr->fc_myDID) && (vport_curr->fc_myDID == did)) {
spin_unlock_irqrestore(&phba->hbalock, flags);
return vport_curr;
}
}
spin_unlock_irqrestore(&phba->hbalock, flags);
return NULL;
}
static int
lpfc_ns_rsp(struct lpfc_vport *vport, struct lpfc_dmabuf *mp, uint32_t Size)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_sli_ct_request *Response =
(struct lpfc_sli_ct_request *) mp->virt;
struct lpfc_nodelist *ndlp = NULL;
struct lpfc_dmabuf *mlast, *next_mp;
uint32_t *ctptr = (uint32_t *) & Response->un.gid.PortType;
uint32_t Did, CTentry;
int Cnt;
struct list_head head;
lpfc_set_disctmo(vport);
vport->num_disc_nodes = 0;
vport->fc_ns_retry = 0;
list_add_tail(&head, &mp->list);
list_for_each_entry_safe(mp, next_mp, &head, list) {
mlast = mp;
Cnt = Size > FCELSSIZE ? FCELSSIZE : Size;
Size -= Cnt;
if (!ctptr) {
ctptr = (uint32_t *) mlast->virt;
} else
Cnt -= 16; /* subtract length of CT header */
/* Loop through entire NameServer list of DIDs */
while (Cnt >= sizeof (uint32_t)) {
/* Get next DID from NameServer List */
CTentry = *ctptr++;
Did = ((be32_to_cpu(CTentry)) & Mask_DID);
ndlp = NULL;
/*
* Check for rscn processing or not
* To conserve rpi's, filter out addresses for other
* vports on the same physical HBAs.
*/
if ((Did != vport->fc_myDID) &&
((lpfc_find_vport_by_did(phba, Did) == NULL) ||
vport->cfg_peer_port_login)) {
if ((vport->port_type != LPFC_NPIV_PORT) ||
(!(vport->ct_flags & FC_CT_RFF_ID)) ||
(!vport->cfg_restrict_login)) {
ndlp = lpfc_setup_disc_node(vport, Did);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Parse GID_FTrsp: "
"did:x%x flg:x%x x%x",
Did, ndlp->nlp_flag,
vport->fc_flag);
lpfc_printf_vlog(vport,
KERN_INFO,
LOG_DISCOVERY,
"0238 Process "
"x%x NameServer Rsp"
"Data: x%x x%x x%x\n",
Did, ndlp->nlp_flag,
vport->fc_flag,
vport->fc_rscn_id_cnt);
} else {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Skip1 GID_FTrsp: "
"did:x%x flg:x%x cnt:%d",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
lpfc_printf_vlog(vport,
KERN_INFO,
LOG_DISCOVERY,
"0239 Skip x%x "
"NameServer Rsp Data: "
"x%x x%x\n",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
}
} else {
if (!(vport->fc_flag & FC_RSCN_MODE) ||
(lpfc_rscn_payload_check(vport, Did))) {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Query GID_FTrsp: "
"did:x%x flg:x%x cnt:%d",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
/* This NPortID was previously
* a FCP target, * Don't even
* bother to send GFF_ID.
*/
ndlp = lpfc_findnode_did(vport,
Did);
if (ndlp &&
NLP_CHK_NODE_ACT(ndlp)
&& (ndlp->nlp_type &
NLP_FCP_TARGET))
lpfc_setup_disc_node
(vport, Did);
else if (lpfc_ns_cmd(vport,
SLI_CTNS_GFF_ID,
0, Did) == 0)
vport->num_disc_nodes++;
else
lpfc_setup_disc_node
(vport, Did);
}
else {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Skip2 GID_FTrsp: "
"did:x%x flg:x%x cnt:%d",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
lpfc_printf_vlog(vport,
KERN_INFO,
LOG_DISCOVERY,
"0245 Skip x%x "
"NameServer Rsp Data: "
"x%x x%x\n",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
}
}
}
if (CTentry & (be32_to_cpu(SLI_CT_LAST_ENTRY)))
goto nsout1;
Cnt -= sizeof (uint32_t);
}
ctptr = NULL;
}
nsout1:
list_del(&head);
return 0;
}
static void
lpfc_cmpl_ct_cmd_gid_ft(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
IOCB_t *irsp;
struct lpfc_dmabuf *bmp;
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
struct lpfc_nodelist *ndlp;
int rc;
/* First save ndlp, before we overwrite it */
ndlp = cmdiocb->context_un.ndlp;
/* we pass cmdiocb to state machine which needs rspiocb as well */
cmdiocb->context_un.rsp_iocb = rspiocb;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
bmp = (struct lpfc_dmabuf *) cmdiocb->context3;
irsp = &rspiocb->iocb;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT cmpl: status:x%x/x%x rtry:%d",
irsp->ulpStatus, irsp->un.ulpWord[4], vport->fc_ns_retry);
/* Don't bother processing response if vport is being torn down. */
if (vport->load_flag & FC_UNLOADING) {
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
goto out;
}
if (lpfc_els_chk_latt(vport)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0216 Link event during NS query\n");
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
goto out;
}
if (lpfc_error_lost_link(irsp)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0226 NS query failed due to link event\n");
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
goto out;
}
if (irsp->ulpStatus) {
/* Check for retry */
if (vport->fc_ns_retry < LPFC_MAX_NS_RETRY) {
if (irsp->ulpStatus != IOSTAT_LOCAL_REJECT ||
irsp->un.ulpWord[4] != IOERR_NO_RESOURCES)
vport->fc_ns_retry++;
/* CT command is being retried */
rc = lpfc_ns_cmd(vport, SLI_CTNS_GID_FT,
vport->fc_ns_retry, 0);
if (rc == 0)
goto out;
}
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0257 GID_FT Query error: 0x%x 0x%x\n",
irsp->ulpStatus, vport->fc_ns_retry);
} else {
/* Good status, continue checking */
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0208 NameServer Rsp Data: x%x\n",
vport->fc_flag);
lpfc_ns_rsp(vport, outp,
(uint32_t) (irsp->un.genreq64.bdl.bdeSize));
} else if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_RJT)) {
/* NameServer Rsp Error */
if ((CTrsp->ReasonCode == SLI_CT_UNABLE_TO_PERFORM_REQ)
&& (CTrsp->Explanation == SLI_CT_NO_FC4_TYPES)) {
lpfc_printf_vlog(vport, KERN_INFO,
LOG_DISCOVERY,
"0269 No NameServer Entries "
"Data: x%x x%x x%x x%x\n",
CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation,
vport->fc_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT no entry cmd:x%x rsn:x%x exp:x%x",
(uint32_t)CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation);
} else {
lpfc_printf_vlog(vport, KERN_INFO,
LOG_DISCOVERY,
"0240 NameServer Rsp Error "
"Data: x%x x%x x%x x%x\n",
CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation,
vport->fc_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT rsp err1 cmd:x%x rsn:x%x exp:x%x",
(uint32_t)CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation);
}
} else {
/* NameServer Rsp Error */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0241 NameServer Rsp Error "
"Data: x%x x%x x%x x%x\n",
CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation,
vport->fc_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT rsp err2 cmd:x%x rsn:x%x exp:x%x",
(uint32_t)CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation);
}
}
/* Link up / RSCN discovery */
if (vport->num_disc_nodes == 0) {
/*
* The driver has cycled through all Nports in the RSCN payload.
* Complete the handling by cleaning up and marking the
* current driver state.
*/
if (vport->port_state >= LPFC_DISC_AUTH) {
if (vport->fc_flag & FC_RSCN_MODE) {
lpfc_els_flush_rscn(vport);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_RSCN_MODE; /* RSCN still */
spin_unlock_irq(shost->host_lock);
}
else
lpfc_els_flush_rscn(vport);
}
lpfc_disc_start(vport);
}
out:
cmdiocb->context_un.ndlp = ndlp; /* Now restore ndlp for free */
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_gff_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_dmabuf *inp = (struct lpfc_dmabuf *) cmdiocb->context1;
struct lpfc_dmabuf *outp = (struct lpfc_dmabuf *) cmdiocb->context2;
struct lpfc_sli_ct_request *CTrsp;
int did, rc, retry;
uint8_t fbits;
struct lpfc_nodelist *ndlp;
did = ((struct lpfc_sli_ct_request *) inp->virt)->un.gff.PortId;
did = be32_to_cpu(did);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GFF_ID cmpl: status:x%x/x%x did:x%x",
irsp->ulpStatus, irsp->un.ulpWord[4], did);
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
/* Good status, continue checking */
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
fbits = CTrsp->un.gff_acc.fbits[FCP_TYPE_FEATURE_OFFSET];
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC)) {
if ((fbits & FC4_FEATURE_INIT) &&
!(fbits & FC4_FEATURE_TARGET)) {
lpfc_printf_vlog(vport, KERN_INFO,
LOG_DISCOVERY,
"0270 Skip x%x GFF "
"NameServer Rsp Data: (init) "
"x%x x%x\n", did, fbits,
vport->fc_rscn_id_cnt);
goto out;
}
}
}
else {
/* Check for retry */
if (cmdiocb->retry < LPFC_MAX_NS_RETRY) {
retry = 1;
if (irsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (irsp->un.ulpWord[4]) {
case IOERR_NO_RESOURCES:
/* We don't increment the retry
* count for this case.
*/
break;
case IOERR_LINK_DOWN:
case IOERR_SLI_ABORTED:
case IOERR_SLI_DOWN:
retry = 0;
break;
default:
cmdiocb->retry++;
}
}
else
cmdiocb->retry++;
if (retry) {
/* CT command is being retried */
rc = lpfc_ns_cmd(vport, SLI_CTNS_GFF_ID,
cmdiocb->retry, did);
if (rc == 0) {
/* success */
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
}
}
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0267 NameServer GFF Rsp "
"x%x Error (%d %d) Data: x%x x%x\n",
did, irsp->ulpStatus, irsp->un.ulpWord[4],
vport->fc_flag, vport->fc_rscn_id_cnt);
}
/* This is a target port, unregistered port, or the GFF_ID failed */
ndlp = lpfc_setup_disc_node(vport, did);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0242 Process x%x GFF "
"NameServer Rsp Data: x%x x%x x%x\n",
did, ndlp->nlp_flag, vport->fc_flag,
vport->fc_rscn_id_cnt);
} else {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0243 Skip x%x GFF "
"NameServer Rsp Data: x%x x%x\n", did,
vport->fc_flag, vport->fc_rscn_id_cnt);
}
out:
/* Link up / RSCN discovery */
if (vport->num_disc_nodes)
vport->num_disc_nodes--;
if (vport->num_disc_nodes == 0) {
/*
* The driver has cycled through all Nports in the RSCN payload.
* Complete the handling by cleaning up and marking the
* current driver state.
*/
if (vport->port_state >= LPFC_DISC_AUTH) {
if (vport->fc_flag & FC_RSCN_MODE) {
lpfc_els_flush_rscn(vport);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_RSCN_MODE; /* RSCN still */
spin_unlock_irq(shost->host_lock);
}
else
lpfc_els_flush_rscn(vport);
}
lpfc_disc_start(vport);
}
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
static void
lpfc_cmpl_ct(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
struct lpfc_dmabuf *inp;
struct lpfc_dmabuf *outp;
IOCB_t *irsp;
struct lpfc_sli_ct_request *CTrsp;
struct lpfc_nodelist *ndlp;
int cmdcode, rc;
uint8_t retry;
uint32_t latt;
/* First save ndlp, before we overwrite it */
ndlp = cmdiocb->context_un.ndlp;
/* we pass cmdiocb to state machine which needs rspiocb as well */
cmdiocb->context_un.rsp_iocb = rspiocb;
inp = (struct lpfc_dmabuf *) cmdiocb->context1;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
irsp = &rspiocb->iocb;
cmdcode = be16_to_cpu(((struct lpfc_sli_ct_request *) inp->virt)->
CommandResponse.bits.CmdRsp);
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
latt = lpfc_els_chk_latt(vport);
/* RFT request completes status <ulpStatus> CmdRsp <CmdRsp> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0209 CT Request completes, latt %d, "
"ulpStatus x%x CmdRsp x%x, Context x%x, Tag x%x\n",
latt, irsp->ulpStatus,
CTrsp->CommandResponse.bits.CmdRsp,
cmdiocb->iocb.ulpContext, cmdiocb->iocb.ulpIoTag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"CT cmd cmpl: status:x%x/x%x cmd:x%x",
irsp->ulpStatus, irsp->un.ulpWord[4], cmdcode);
if (irsp->ulpStatus) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0268 NS cmd %x Error (%d %d)\n",
cmdcode, irsp->ulpStatus, irsp->un.ulpWord[4]);
if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
((irsp->un.ulpWord[4] == IOERR_SLI_DOWN) ||
(irsp->un.ulpWord[4] == IOERR_SLI_ABORTED)))
goto out;
retry = cmdiocb->retry;
if (retry >= LPFC_MAX_NS_RETRY)
goto out;
retry++;
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0250 Retrying NS cmd %x\n", cmdcode);
rc = lpfc_ns_cmd(vport, cmdcode, retry, 0);
if (rc == 0)
goto out;
}
out:
cmdiocb->context_un.ndlp = ndlp; /* Now restore ndlp for free */
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rft_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RFT_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rnn_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RNN_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rspn_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RSPN_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rsnn_nn(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RSNN_NN;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_da_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
/* even if it fails we will act as though it succeeded. */
vport->ct_flags = 0;
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rff_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RFF_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
int
lpfc_vport_symbolic_port_name(struct lpfc_vport *vport, char *symbol,
size_t size)
{
int n;
uint8_t *wwn = vport->phba->wwpn;
n = snprintf(symbol, size,
"Emulex PPN-%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
wwn[0], wwn[1], wwn[2], wwn[3],
wwn[4], wwn[5], wwn[6], wwn[7]);
if (vport->port_type == LPFC_PHYSICAL_PORT)
return n;
if (n < size)
n += snprintf(symbol + n, size - n, " VPort-%d", vport->vpi);
if (n < size &&
strlen(vport->fc_vport->symbolic_name))
n += snprintf(symbol + n, size - n, " VName-%s",
vport->fc_vport->symbolic_name);
return n;
}
int
lpfc_vport_symbolic_node_name(struct lpfc_vport *vport, char *symbol,
size_t size)
{
char fwrev[16];
int n;
lpfc_decode_firmware_rev(vport->phba, fwrev, 0);
n = snprintf(symbol, size, "Emulex %s FV%s DV%s",
vport->phba->ModelName, fwrev, lpfc_release_version);
return n;
}
/*
* lpfc_ns_cmd
* Description:
* Issue Cmd to NameServer
* SLI_CTNS_GID_FT
* LI_CTNS_RFT_ID
*/
int
lpfc_ns_cmd(struct lpfc_vport *vport, int cmdcode,
uint8_t retry, uint32_t context)
{
struct lpfc_nodelist * ndlp;
struct lpfc_hba *phba = vport->phba;
struct lpfc_dmabuf *mp, *bmp;
struct lpfc_sli_ct_request *CtReq;
struct ulp_bde64 *bpl;
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *) = NULL;
uint32_t rsp_size = 1024;
size_t size;
int rc = 0;
ndlp = lpfc_findnode_did(vport, NameServer_DID);
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)
|| ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) {
rc=1;
goto ns_cmd_exit;
}
/* fill in BDEs for command */
/* Allocate buffer for command payload */
mp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!mp) {
rc=2;
goto ns_cmd_exit;
}
INIT_LIST_HEAD(&mp->list);
mp->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &(mp->phys));
if (!mp->virt) {
rc=3;
goto ns_cmd_free_mp;
}
/* Allocate buffer for Buffer ptr list */
bmp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc=4;
goto ns_cmd_free_mpvirt;
}
INIT_LIST_HEAD(&bmp->list);
bmp->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &(bmp->phys));
if (!bmp->virt) {
rc=5;
goto ns_cmd_free_bmp;
}
/* NameServer Req */
lpfc_printf_vlog(vport, KERN_INFO ,LOG_DISCOVERY,
"0236 NameServer Req Data: x%x x%x x%x\n",
cmdcode, vport->fc_flag, vport->fc_rscn_id_cnt);
bpl = (struct ulp_bde64 *) bmp->virt;
memset(bpl, 0, sizeof(struct ulp_bde64));
bpl->addrHigh = le32_to_cpu(putPaddrHigh(mp->phys) );
bpl->addrLow = le32_to_cpu(putPaddrLow(mp->phys) );
bpl->tus.f.bdeFlags = 0;
if (cmdcode == SLI_CTNS_GID_FT)
bpl->tus.f.bdeSize = GID_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_GFF_ID)
bpl->tus.f.bdeSize = GFF_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RFT_ID)
bpl->tus.f.bdeSize = RFT_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RNN_ID)
bpl->tus.f.bdeSize = RNN_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RSPN_ID)
bpl->tus.f.bdeSize = RSPN_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RSNN_NN)
bpl->tus.f.bdeSize = RSNN_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_DA_ID)
bpl->tus.f.bdeSize = DA_ID_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RFF_ID)
bpl->tus.f.bdeSize = RFF_REQUEST_SZ;
else
bpl->tus.f.bdeSize = 0;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
CtReq = (struct lpfc_sli_ct_request *) mp->virt;
memset(CtReq, 0, sizeof (struct lpfc_sli_ct_request));
CtReq->RevisionId.bits.Revision = SLI_CT_REVISION;
CtReq->RevisionId.bits.InId = 0;
CtReq->FsType = SLI_CT_DIRECTORY_SERVICE;
CtReq->FsSubType = SLI_CT_DIRECTORY_NAME_SERVER;
CtReq->CommandResponse.bits.Size = 0;
switch (cmdcode) {
case SLI_CTNS_GID_FT:
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_GID_FT);
CtReq->un.gid.Fc4Type = SLI_CTPT_FCP;
if (vport->port_state < LPFC_NS_QRY)
vport->port_state = LPFC_NS_QRY;
lpfc_set_disctmo(vport);
cmpl = lpfc_cmpl_ct_cmd_gid_ft;
rsp_size = FC_MAX_NS_RSP;
break;
case SLI_CTNS_GFF_ID:
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_GFF_ID);
CtReq->un.gff.PortId = cpu_to_be32(context);
cmpl = lpfc_cmpl_ct_cmd_gff_id;
break;
case SLI_CTNS_RFT_ID:
vport->ct_flags &= ~FC_CT_RFT_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RFT_ID);
CtReq->un.rft.PortId = cpu_to_be32(vport->fc_myDID);
CtReq->un.rft.fcpReg = 1;
cmpl = lpfc_cmpl_ct_cmd_rft_id;
break;
case SLI_CTNS_RNN_ID:
vport->ct_flags &= ~FC_CT_RNN_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RNN_ID);
CtReq->un.rnn.PortId = cpu_to_be32(vport->fc_myDID);
memcpy(CtReq->un.rnn.wwnn, &vport->fc_nodename,
sizeof (struct lpfc_name));
cmpl = lpfc_cmpl_ct_cmd_rnn_id;
break;
case SLI_CTNS_RSPN_ID:
vport->ct_flags &= ~FC_CT_RSPN_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RSPN_ID);
CtReq->un.rspn.PortId = cpu_to_be32(vport->fc_myDID);
size = sizeof(CtReq->un.rspn.symbname);
CtReq->un.rspn.len =
lpfc_vport_symbolic_port_name(vport,
CtReq->un.rspn.symbname, size);
cmpl = lpfc_cmpl_ct_cmd_rspn_id;
break;
case SLI_CTNS_RSNN_NN:
vport->ct_flags &= ~FC_CT_RSNN_NN;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RSNN_NN);
memcpy(CtReq->un.rsnn.wwnn, &vport->fc_nodename,
sizeof (struct lpfc_name));
size = sizeof(CtReq->un.rsnn.symbname);
CtReq->un.rsnn.len =
lpfc_vport_symbolic_node_name(vport,
CtReq->un.rsnn.symbname, size);
cmpl = lpfc_cmpl_ct_cmd_rsnn_nn;
break;
case SLI_CTNS_DA_ID:
/* Implement DA_ID Nameserver request */
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_DA_ID);
CtReq->un.da_id.port_id = cpu_to_be32(vport->fc_myDID);
cmpl = lpfc_cmpl_ct_cmd_da_id;
break;
case SLI_CTNS_RFF_ID:
vport->ct_flags &= ~FC_CT_RFF_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RFF_ID);
CtReq->un.rff.PortId = cpu_to_be32(vport->fc_myDID);
CtReq->un.rff.fbits = FC4_FEATURE_INIT;
CtReq->un.rff.type_code = FC_TYPE_FCP;
cmpl = lpfc_cmpl_ct_cmd_rff_id;
break;
}
/* The lpfc_ct_cmd/lpfc_get_req shall increment ndlp reference count
* to hold ndlp reference for the corresponding callback function.
*/
if (!lpfc_ct_cmd(vport, mp, bmp, ndlp, cmpl, rsp_size, retry)) {
/* On success, The cmpl function will free the buffers */
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"Issue CT cmd: cmd:x%x did:x%x",
cmdcode, ndlp->nlp_DID, 0);
return 0;
}
rc=6;
/* Decrement ndlp reference count to release ndlp reference held
* for the failed command's callback function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
ns_cmd_free_bmp:
kfree(bmp);
ns_cmd_free_mpvirt:
lpfc_mbuf_free(phba, mp->virt, mp->phys);
ns_cmd_free_mp:
kfree(mp);
ns_cmd_exit:
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0266 Issue NameServer Req x%x err %d Data: x%x x%x\n",
cmdcode, rc, vport->fc_flag, vport->fc_rscn_id_cnt);
return 1;
}
static void
lpfc_cmpl_ct_cmd_fdmi(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq * rspiocb)
{
struct lpfc_dmabuf *inp = cmdiocb->context1;
struct lpfc_dmabuf *outp = cmdiocb->context2;
struct lpfc_sli_ct_request *CTrsp = outp->virt;
struct lpfc_sli_ct_request *CTcmd = inp->virt;
struct lpfc_nodelist *ndlp;
uint16_t fdmi_cmd = CTcmd->CommandResponse.bits.CmdRsp;
uint16_t fdmi_rsp = CTrsp->CommandResponse.bits.CmdRsp;
struct lpfc_vport *vport = cmdiocb->vport;
IOCB_t *irsp = &rspiocb->iocb;
uint32_t latt;
latt = lpfc_els_chk_latt(vport);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"FDMI cmpl: status:x%x/x%x latt:%d",
irsp->ulpStatus, irsp->un.ulpWord[4], latt);
if (latt || irsp->ulpStatus) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0229 FDMI cmd %04x failed, latt = %d "
"ulpStatus: x%x, rid x%x\n",
be16_to_cpu(fdmi_cmd), latt, irsp->ulpStatus,
irsp->un.ulpWord[4]);
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
ndlp = lpfc_findnode_did(vport, FDMI_DID);
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
goto fail_out;
if (fdmi_rsp == be16_to_cpu(SLI_CT_RESPONSE_FS_RJT)) {
/* FDMI rsp failed */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0220 FDMI rsp failed Data: x%x\n",
be16_to_cpu(fdmi_cmd));
}
switch (be16_to_cpu(fdmi_cmd)) {
case SLI_MGMT_RHBA:
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_RPA);
break;
case SLI_MGMT_RPA:
break;
case SLI_MGMT_DHBA:
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_DPRT);
break;
case SLI_MGMT_DPRT:
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_RHBA);
break;
}
fail_out:
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
int
lpfc_fdmi_cmd(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp, int cmdcode)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_dmabuf *mp, *bmp;
struct lpfc_sli_ct_request *CtReq;
struct ulp_bde64 *bpl;
uint32_t size;
REG_HBA *rh;
PORT_ENTRY *pe;
REG_PORT_ATTRIBUTE *pab;
ATTRIBUTE_BLOCK *ab;
ATTRIBUTE_ENTRY *ae;
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *);
/* fill in BDEs for command */
/* Allocate buffer for command payload */
mp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!mp)
goto fdmi_cmd_exit;
mp->virt = lpfc_mbuf_alloc(phba, 0, &(mp->phys));
if (!mp->virt)
goto fdmi_cmd_free_mp;
/* Allocate buffer for Buffer ptr list */
bmp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp)
goto fdmi_cmd_free_mpvirt;
bmp->virt = lpfc_mbuf_alloc(phba, 0, &(bmp->phys));
if (!bmp->virt)
goto fdmi_cmd_free_bmp;
INIT_LIST_HEAD(&mp->list);
INIT_LIST_HEAD(&bmp->list);
/* FDMI request */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0218 FDMI Request Data: x%x x%x x%x\n",
vport->fc_flag, vport->port_state, cmdcode);
CtReq = (struct lpfc_sli_ct_request *) mp->virt;
memset(CtReq, 0, sizeof(struct lpfc_sli_ct_request));
CtReq->RevisionId.bits.Revision = SLI_CT_REVISION;
CtReq->RevisionId.bits.InId = 0;
CtReq->FsType = SLI_CT_MANAGEMENT_SERVICE;
CtReq->FsSubType = SLI_CT_FDMI_Subtypes;
size = 0;
switch (cmdcode) {
case SLI_MGMT_RHBA:
{
lpfc_vpd_t *vp = &phba->vpd;
uint32_t i, j, incr;
int len;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_MGMT_RHBA);
CtReq->CommandResponse.bits.Size = 0;
rh = (REG_HBA *) & CtReq->un.PortID;
memcpy(&rh->hi.PortName, &vport->fc_sparam.portName,
sizeof (struct lpfc_name));
/* One entry (port) per adapter */
rh->rpl.EntryCnt = be32_to_cpu(1);
memcpy(&rh->rpl.pe, &vport->fc_sparam.portName,
sizeof (struct lpfc_name));
/* point to the HBA attribute block */
size = 2 * sizeof (struct lpfc_name) + FOURBYTES;
ab = (ATTRIBUTE_BLOCK *) ((uint8_t *) rh + size);
ab->EntryCnt = 0;
/* Point to the beginning of the first HBA attribute
entry */
/* #1 HBA attribute entry */
size += FOURBYTES;
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(NODE_NAME);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES
+ sizeof (struct lpfc_name));
memcpy(&ae->un.NodeName, &vport->fc_sparam.nodeName,
sizeof (struct lpfc_name));
ab->EntryCnt++;
size += FOURBYTES + sizeof (struct lpfc_name);
/* #2 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MANUFACTURER);
strcpy(ae->un.Manufacturer, "Emulex Corporation");
len = strlen(ae->un.Manufacturer);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #3 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(SERIAL_NUMBER);
strcpy(ae->un.SerialNumber, phba->SerialNumber);
len = strlen(ae->un.SerialNumber);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #4 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MODEL);
strcpy(ae->un.Model, phba->ModelName);
len = strlen(ae->un.Model);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #5 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MODEL_DESCRIPTION);
strcpy(ae->un.ModelDescription, phba->ModelDesc);
len = strlen(ae->un.ModelDescription);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #6 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(HARDWARE_VERSION);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 8);
/* Convert JEDEC ID to ascii for hardware version */
incr = vp->rev.biuRev;
for (i = 0; i < 8; i++) {
j = (incr & 0xf);
if (j <= 9)
ae->un.HardwareVersion[7 - i] =
(char)((uint8_t) 0x30 +
(uint8_t) j);
else
ae->un.HardwareVersion[7 - i] =
(char)((uint8_t) 0x61 +
(uint8_t) (j - 10));
incr = (incr >> 4);
}
ab->EntryCnt++;
size += FOURBYTES + 8;
/* #7 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(DRIVER_VERSION);
strcpy(ae->un.DriverVersion, lpfc_release_version);
len = strlen(ae->un.DriverVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #8 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(OPTION_ROM_VERSION);
strcpy(ae->un.OptionROMVersion, phba->OptionROMVersion);
len = strlen(ae->un.OptionROMVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #9 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(FIRMWARE_VERSION);
lpfc_decode_firmware_rev(phba, ae->un.FirmwareVersion,
1);
len = strlen(ae->un.FirmwareVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #10 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(OS_NAME_VERSION);
sprintf(ae->un.OsNameVersion, "%s %s %s",
init_utsname()->sysname,
init_utsname()->release,
init_utsname()->version);
len = strlen(ae->un.OsNameVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #11 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MAX_CT_PAYLOAD_LEN);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
ae->un.MaxCTPayloadLen = (65 * 4096);
ab->EntryCnt++;
size += FOURBYTES + 4;
ab->EntryCnt = be32_to_cpu(ab->EntryCnt);
/* Total size */
size = GID_REQUEST_SZ - 4 + size;
}
break;
case SLI_MGMT_RPA:
{
lpfc_vpd_t *vp;
struct serv_parm *hsp;
int len;
vp = &phba->vpd;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_MGMT_RPA);
CtReq->CommandResponse.bits.Size = 0;
pab = (REG_PORT_ATTRIBUTE *) & CtReq->un.PortID;
size = sizeof (struct lpfc_name) + FOURBYTES;
memcpy((uint8_t *) & pab->PortName,
(uint8_t *) & vport->fc_sparam.portName,
sizeof (struct lpfc_name));
pab->ab.EntryCnt = 0;
/* #1 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(SUPPORTED_FC4_TYPES);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 32);
ae->un.SupportFC4Types[2] = 1;
ae->un.SupportFC4Types[7] = 1;
pab->ab.EntryCnt++;
size += FOURBYTES + 32;
/* #2 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(SUPPORTED_SPEED);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
ae->un.SupportSpeed = 0;
if (phba->lmt & LMT_10Gb)
ae->un.SupportSpeed = HBA_PORTSPEED_10GBIT;
if (phba->lmt & LMT_8Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_8GBIT;
if (phba->lmt & LMT_4Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_4GBIT;
if (phba->lmt & LMT_2Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_2GBIT;
if (phba->lmt & LMT_1Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_1GBIT;
pab->ab.EntryCnt++;
size += FOURBYTES + 4;
/* #3 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(PORT_SPEED);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
switch(phba->fc_linkspeed) {
case LA_1GHZ_LINK:
ae->un.PortSpeed = HBA_PORTSPEED_1GBIT;
break;
case LA_2GHZ_LINK:
ae->un.PortSpeed = HBA_PORTSPEED_2GBIT;
break;
case LA_4GHZ_LINK:
ae->un.PortSpeed = HBA_PORTSPEED_4GBIT;
break;
case LA_8GHZ_LINK:
ae->un.PortSpeed = HBA_PORTSPEED_8GBIT;
break;
case LA_10GHZ_LINK:
ae->un.PortSpeed = HBA_PORTSPEED_10GBIT;
break;
default:
ae->un.PortSpeed =
HBA_PORTSPEED_UNKNOWN;
break;
}
pab->ab.EntryCnt++;
size += FOURBYTES + 4;
/* #4 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(MAX_FRAME_SIZE);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
hsp = (struct serv_parm *) & vport->fc_sparam;
ae->un.MaxFrameSize =
(((uint32_t) hsp->cmn.
bbRcvSizeMsb) << 8) | (uint32_t) hsp->cmn.
bbRcvSizeLsb;
pab->ab.EntryCnt++;
size += FOURBYTES + 4;
/* #5 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(OS_DEVICE_NAME);
strcpy((char *)ae->un.OsDeviceName, LPFC_DRIVER_NAME);
len = strlen((char *)ae->un.OsDeviceName);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
pab->ab.EntryCnt++;
size += FOURBYTES + len;
if (vport->cfg_fdmi_on == 2) {
/* #6 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab +
size);
ae->ad.bits.AttrType = be16_to_cpu(HOST_NAME);
sprintf(ae->un.HostName, "%s",
init_utsname()->nodename);
len = strlen(ae->un.HostName);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen =
be16_to_cpu(FOURBYTES + len);
pab->ab.EntryCnt++;
size += FOURBYTES + len;
}
pab->ab.EntryCnt = be32_to_cpu(pab->ab.EntryCnt);
/* Total size */
size = GID_REQUEST_SZ - 4 + size;
}
break;
case SLI_MGMT_DHBA:
CtReq->CommandResponse.bits.CmdRsp = be16_to_cpu(SLI_MGMT_DHBA);
CtReq->CommandResponse.bits.Size = 0;
pe = (PORT_ENTRY *) & CtReq->un.PortID;
memcpy((uint8_t *) & pe->PortName,
(uint8_t *) & vport->fc_sparam.portName,
sizeof (struct lpfc_name));
size = GID_REQUEST_SZ - 4 + sizeof (struct lpfc_name);
break;
case SLI_MGMT_DPRT:
CtReq->CommandResponse.bits.CmdRsp = be16_to_cpu(SLI_MGMT_DPRT);
CtReq->CommandResponse.bits.Size = 0;
pe = (PORT_ENTRY *) & CtReq->un.PortID;
memcpy((uint8_t *) & pe->PortName,
(uint8_t *) & vport->fc_sparam.portName,
sizeof (struct lpfc_name));
size = GID_REQUEST_SZ - 4 + sizeof (struct lpfc_name);
break;
}
bpl = (struct ulp_bde64 *) bmp->virt;
bpl->addrHigh = le32_to_cpu(putPaddrHigh(mp->phys) );
bpl->addrLow = le32_to_cpu(putPaddrLow(mp->phys) );
bpl->tus.f.bdeFlags = 0;
bpl->tus.f.bdeSize = size;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
cmpl = lpfc_cmpl_ct_cmd_fdmi;
/* The lpfc_ct_cmd/lpfc_get_req shall increment ndlp reference count
* to hold ndlp reference for the corresponding callback function.
*/
if (!lpfc_ct_cmd(vport, mp, bmp, ndlp, cmpl, FC_MAX_NS_RSP, 0))
return 0;
/* Decrement ndlp reference count to release ndlp reference held
* for the failed command's callback function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
fdmi_cmd_free_bmp:
kfree(bmp);
fdmi_cmd_free_mpvirt:
lpfc_mbuf_free(phba, mp->virt, mp->phys);
fdmi_cmd_free_mp:
kfree(mp);
fdmi_cmd_exit:
/* Issue FDMI request failed */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0244 Issue FDMI request failed Data: x%x\n",
cmdcode);
return 1;
}
void
lpfc_fdmi_tmo(unsigned long ptr)
{
struct lpfc_vport *vport = (struct lpfc_vport *)ptr;
struct lpfc_hba *phba = vport->phba;
uint32_t tmo_posted;
unsigned long iflag;
spin_lock_irqsave(&vport->work_port_lock, iflag);
tmo_posted = vport->work_port_events & WORKER_FDMI_TMO;
if (!tmo_posted)
vport->work_port_events |= WORKER_FDMI_TMO;
spin_unlock_irqrestore(&vport->work_port_lock, iflag);
if (!tmo_posted)
lpfc_worker_wake_up(phba);
return;
}
void
lpfc_fdmi_timeout_handler(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp;
ndlp = lpfc_findnode_did(vport, FDMI_DID);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
if (init_utsname()->nodename[0] != '\0')
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_DHBA);
else
mod_timer(&vport->fc_fdmitmo, jiffies + HZ * 60);
}
return;
}
void
lpfc_decode_firmware_rev(struct lpfc_hba *phba, char *fwrevision, int flag)
{
struct lpfc_sli *psli = &phba->sli;
lpfc_vpd_t *vp = &phba->vpd;
uint32_t b1, b2, b3, b4, i, rev;
char c;
uint32_t *ptr, str[4];
uint8_t *fwname;
if (phba->sli_rev == LPFC_SLI_REV4)
sprintf(fwrevision, "%s", vp->rev.opFwName);
else if (vp->rev.rBit) {
if (psli->sli_flag & LPFC_SLI_ACTIVE)
rev = vp->rev.sli2FwRev;
else
rev = vp->rev.sli1FwRev;
b1 = (rev & 0x0000f000) >> 12;
b2 = (rev & 0x00000f00) >> 8;
b3 = (rev & 0x000000c0) >> 6;
b4 = (rev & 0x00000030) >> 4;
switch (b4) {
case 0:
c = 'N';
break;
case 1:
c = 'A';
break;
case 2:
c = 'B';
break;
default:
c = 0;
break;
}
b4 = (rev & 0x0000000f);
if (psli->sli_flag & LPFC_SLI_ACTIVE)
fwname = vp->rev.sli2FwName;
else
fwname = vp->rev.sli1FwName;
for (i = 0; i < 16; i++)
if (fwname[i] == 0x20)
fwname[i] = 0;
ptr = (uint32_t*)fwname;
for (i = 0; i < 3; i++)
str[i] = be32_to_cpu(*ptr++);
if (c == 0) {
if (flag)
sprintf(fwrevision, "%d.%d%d (%s)",
b1, b2, b3, (char *)str);
else
sprintf(fwrevision, "%d.%d%d", b1,
b2, b3);
} else {
if (flag)
sprintf(fwrevision, "%d.%d%d%c%d (%s)",
b1, b2, b3, c,
b4, (char *)str);
else
sprintf(fwrevision, "%d.%d%d%c%d",
b1, b2, b3, c, b4);
}
} else {
rev = vp->rev.smFwRev;
b1 = (rev & 0xff000000) >> 24;
b2 = (rev & 0x00f00000) >> 20;
b3 = (rev & 0x000f0000) >> 16;
c = (rev & 0x0000ff00) >> 8;
b4 = (rev & 0x000000ff);
sprintf(fwrevision, "%d.%d%d%c%d", b1, b2, b3, c, b4);
}
return;
}
| gpl-2.0 |
mausvt/seagate_central_cns3420_2-6-35 | drivers/macintosh/mac_hid.c | 986 | 6032 | /*
* drivers/macintosh/mac_hid.c
*
* HID support stuff for Macintosh computers.
*
* Copyright (C) 2000 Franz Sirl.
*
* This file will soon be removed in favor of an uinput userspace tool.
*/
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/sysctl.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/slab.h>
MODULE_LICENSE("GPL");
static int mouse_emulate_buttons;
static int mouse_button2_keycode = KEY_RIGHTCTRL; /* right control key */
static int mouse_button3_keycode = KEY_RIGHTALT; /* right option key */
static struct input_dev *mac_hid_emumouse_dev;
static int mac_hid_create_emumouse(void)
{
static struct lock_class_key mac_hid_emumouse_dev_event_class;
static struct lock_class_key mac_hid_emumouse_dev_mutex_class;
int err;
mac_hid_emumouse_dev = input_allocate_device();
if (!mac_hid_emumouse_dev)
return -ENOMEM;
lockdep_set_class(&mac_hid_emumouse_dev->event_lock,
&mac_hid_emumouse_dev_event_class);
lockdep_set_class(&mac_hid_emumouse_dev->mutex,
&mac_hid_emumouse_dev_mutex_class);
mac_hid_emumouse_dev->name = "Macintosh mouse button emulation";
mac_hid_emumouse_dev->id.bustype = BUS_ADB;
mac_hid_emumouse_dev->id.vendor = 0x0001;
mac_hid_emumouse_dev->id.product = 0x0001;
mac_hid_emumouse_dev->id.version = 0x0100;
mac_hid_emumouse_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
mac_hid_emumouse_dev->keybit[BIT_WORD(BTN_MOUSE)] =
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT);
mac_hid_emumouse_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
err = input_register_device(mac_hid_emumouse_dev);
if (err) {
input_free_device(mac_hid_emumouse_dev);
mac_hid_emumouse_dev = NULL;
return err;
}
return 0;
}
static void mac_hid_destroy_emumouse(void)
{
input_unregister_device(mac_hid_emumouse_dev);
mac_hid_emumouse_dev = NULL;
}
static bool mac_hid_emumouse_filter(struct input_handle *handle,
unsigned int type, unsigned int code,
int value)
{
unsigned int btn;
if (type != EV_KEY)
return false;
if (code == mouse_button2_keycode)
btn = BTN_MIDDLE;
else if (code == mouse_button3_keycode)
btn = BTN_RIGHT;
else
return false;
input_report_key(mac_hid_emumouse_dev, btn, value);
input_sync(mac_hid_emumouse_dev);
return true;
}
static int mac_hid_emumouse_connect(struct input_handler *handler,
struct input_dev *dev,
const struct input_device_id *id)
{
struct input_handle *handle;
int error;
/* Don't bind to ourselves */
if (dev == mac_hid_emumouse_dev)
return -ENODEV;
handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
handle->dev = dev;
handle->handler = handler;
handle->name = "mac-button-emul";
error = input_register_handle(handle);
if (error) {
printk(KERN_ERR
"mac_hid: Failed to register button emulation handle, "
"error %d\n", error);
goto err_free;
}
error = input_open_device(handle);
if (error) {
printk(KERN_ERR
"mac_hid: Failed to open input device, error %d\n",
error);
goto err_unregister;
}
return 0;
err_unregister:
input_unregister_handle(handle);
err_free:
kfree(handle);
return error;
}
static void mac_hid_emumouse_disconnect(struct input_handle *handle)
{
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
static const struct input_device_id mac_hid_emumouse_ids[] = {
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
.evbit = { BIT_MASK(EV_KEY) },
},
{ },
};
MODULE_DEVICE_TABLE(input, mac_hid_emumouse_ids);
static struct input_handler mac_hid_emumouse_handler = {
.filter = mac_hid_emumouse_filter,
.connect = mac_hid_emumouse_connect,
.disconnect = mac_hid_emumouse_disconnect,
.name = "mac-button-emul",
.id_table = mac_hid_emumouse_ids,
};
static int mac_hid_start_emulation(void)
{
int err;
err = mac_hid_create_emumouse();
if (err)
return err;
err = input_register_handler(&mac_hid_emumouse_handler);
if (err) {
mac_hid_destroy_emumouse();
return err;
}
return 0;
}
static void mac_hid_stop_emulation(void)
{
input_unregister_handler(&mac_hid_emumouse_handler);
mac_hid_destroy_emumouse();
}
static int mac_hid_toggle_emumouse(ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int *valp = table->data;
int old_val = *valp;
int rc;
rc = proc_dointvec(table, write, buffer, lenp, ppos);
if (rc == 0 && write && *valp != old_val) {
if (*valp == 1)
rc = mac_hid_start_emulation();
else if (*valp == 0)
mac_hid_stop_emulation();
else
rc = -EINVAL;
}
/* Restore the old value in case of error */
if (rc)
*valp = old_val;
return rc;
}
/* file(s) in /proc/sys/dev/mac_hid */
static ctl_table mac_hid_files[] = {
{
.procname = "mouse_button_emulation",
.data = &mouse_emulate_buttons,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = mac_hid_toggle_emumouse,
},
{
.procname = "mouse_button2_keycode",
.data = &mouse_button2_keycode,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mouse_button3_keycode",
.data = &mouse_button3_keycode,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
/* dir in /proc/sys/dev */
static ctl_table mac_hid_dir[] = {
{
.procname = "mac_hid",
.maxlen = 0,
.mode = 0555,
.child = mac_hid_files,
},
{ }
};
/* /proc/sys/dev itself, in case that is not there yet */
static ctl_table mac_hid_root_dir[] = {
{
.procname = "dev",
.maxlen = 0,
.mode = 0555,
.child = mac_hid_dir,
},
{ }
};
static struct ctl_table_header *mac_hid_sysctl_header;
static int __init mac_hid_init(void)
{
mac_hid_sysctl_header = register_sysctl_table(mac_hid_root_dir);
if (!mac_hid_sysctl_header)
return -ENOMEM;
return 0;
}
module_init(mac_hid_init);
static void __exit mac_hid_exit(void)
{
unregister_sysctl_table(mac_hid_sysctl_header);
if (mouse_emulate_buttons)
mac_hid_stop_emulation();
}
module_exit(mac_hid_exit);
| gpl-2.0 |
InfinitiveOS-Devices/android_kernel_xiaomi_ferrari | net/core/secure_seq.c | 986 | 4755 | #include <linux/kernel.h>
#include <linux/init.h>
#include <linux/cryptohash.h>
#include <linux/module.h>
#include <linux/cache.h>
#include <linux/random.h>
#include <linux/hrtimer.h>
#include <linux/ktime.h>
#include <linux/string.h>
#include <net/secure_seq.h>
#if IS_ENABLED(CONFIG_IPV6) || IS_ENABLED(CONFIG_INET)
#define NET_SECRET_SIZE (MD5_MESSAGE_BYTES / 4)
static u32 net_secret[NET_SECRET_SIZE] ____cacheline_aligned;
static void net_secret_init(void)
{
u32 tmp;
int i;
if (likely(net_secret[0]))
return;
for (i = NET_SECRET_SIZE; i > 0;) {
do {
get_random_bytes(&tmp, sizeof(tmp));
} while (!tmp);
cmpxchg(&net_secret[--i], 0, tmp);
}
}
#endif
#ifdef CONFIG_INET
static u32 seq_scale(u32 seq)
{
/*
* As close as possible to RFC 793, which
* suggests using a 250 kHz clock.
* Further reading shows this assumes 2 Mb/s networks.
* For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
* For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but
* we also need to limit the resolution so that the u32 seq
* overlaps less than one time per MSL (2 minutes).
* Choosing a clock of 64 ns period is OK. (period of 274 s)
*/
return seq + (ktime_to_ns(ktime_get_real()) >> 6);
}
#endif
#if IS_ENABLED(CONFIG_IPV6)
__u32 secure_tcpv6_sequence_number(const __be32 *saddr, const __be32 *daddr,
__be16 sport, __be16 dport)
{
u32 secret[MD5_MESSAGE_BYTES / 4];
u32 hash[MD5_DIGEST_WORDS];
u32 i;
net_secret_init();
memcpy(hash, saddr, 16);
for (i = 0; i < 4; i++)
secret[i] = net_secret[i] + (__force u32)daddr[i];
secret[4] = net_secret[4] +
(((__force u16)sport << 16) + (__force u16)dport);
for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
secret[i] = net_secret[i];
md5_transform(hash, secret);
return seq_scale(hash[0]);
}
EXPORT_SYMBOL(secure_tcpv6_sequence_number);
u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,
__be16 dport)
{
u32 secret[MD5_MESSAGE_BYTES / 4];
u32 hash[MD5_DIGEST_WORDS];
u32 i;
net_secret_init();
memcpy(hash, saddr, 16);
for (i = 0; i < 4; i++)
secret[i] = net_secret[i] + (__force u32) daddr[i];
secret[4] = net_secret[4] + (__force u32)dport;
for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
secret[i] = net_secret[i];
md5_transform(hash, secret);
return hash[0];
}
EXPORT_SYMBOL(secure_ipv6_port_ephemeral);
#endif
#ifdef CONFIG_INET
__u32 secure_ip_id(__be32 daddr)
{
u32 hash[MD5_DIGEST_WORDS];
net_secret_init();
hash[0] = (__force __u32) daddr;
hash[1] = net_secret[13];
hash[2] = net_secret[14];
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
return hash[0];
}
__u32 secure_ipv6_id(const __be32 daddr[4])
{
__u32 hash[4];
net_secret_init();
memcpy(hash, daddr, 16);
md5_transform(hash, net_secret);
return hash[0];
}
__u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
__be16 sport, __be16 dport)
{
u32 hash[MD5_DIGEST_WORDS];
net_secret_init();
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
return seq_scale(hash[0]);
}
u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
{
u32 hash[MD5_DIGEST_WORDS];
net_secret_init();
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = (__force u32)dport ^ net_secret[14];
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
return hash[0];
}
EXPORT_SYMBOL_GPL(secure_ipv4_port_ephemeral);
#endif
#if IS_ENABLED(CONFIG_IP_DCCP)
u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr,
__be16 sport, __be16 dport)
{
u32 hash[MD5_DIGEST_WORDS];
u64 seq;
net_secret_init();
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
hash[3] = net_secret[15];
md5_transform(hash, net_secret);
seq = hash[0] | (((u64)hash[1]) << 32);
seq += ktime_to_ns(ktime_get_real());
seq &= (1ull << 48) - 1;
return seq;
}
EXPORT_SYMBOL(secure_dccp_sequence_number);
#if IS_ENABLED(CONFIG_IPV6)
u64 secure_dccpv6_sequence_number(__be32 *saddr, __be32 *daddr,
__be16 sport, __be16 dport)
{
u32 secret[MD5_MESSAGE_BYTES / 4];
u32 hash[MD5_DIGEST_WORDS];
u64 seq;
u32 i;
net_secret_init();
memcpy(hash, saddr, 16);
for (i = 0; i < 4; i++)
secret[i] = net_secret[i] + daddr[i];
secret[4] = net_secret[4] +
(((__force u16)sport << 16) + (__force u16)dport);
for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
secret[i] = net_secret[i];
md5_transform(hash, secret);
seq = hash[0] | (((u64)hash[1]) << 32);
seq += ktime_to_ns(ktime_get_real());
seq &= (1ull << 48) - 1;
return seq;
}
EXPORT_SYMBOL(secure_dccpv6_sequence_number);
#endif
#endif
| gpl-2.0 |
sria91/linux | drivers/net/wireless/ti/wlcore/vendor_cmd.c | 1242 | 4508 | /*
* This file is part of wlcore
*
* Copyright (C) 2014 Texas Instruments. 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.
*/
#include <net/mac80211.h>
#include <net/netlink.h>
#include "wlcore.h"
#include "debug.h"
#include "ps.h"
#include "hw_ops.h"
#include "vendor_cmd.h"
static const
struct nla_policy wlcore_vendor_attr_policy[NUM_WLCORE_VENDOR_ATTR] = {
[WLCORE_VENDOR_ATTR_FREQ] = { .type = NLA_U32 },
[WLCORE_VENDOR_ATTR_GROUP_ID] = { .type = NLA_U32 },
[WLCORE_VENDOR_ATTR_GROUP_KEY] = { .type = NLA_BINARY,
.len = WLAN_MAX_KEY_LEN },
};
static int
wlcore_vendor_cmd_smart_config_start(struct wiphy *wiphy,
struct wireless_dev *wdev,
const void *data, int data_len)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct wl1271 *wl = hw->priv;
struct nlattr *tb[NUM_WLCORE_VENDOR_ATTR];
int ret;
wl1271_debug(DEBUG_CMD, "vendor cmd smart config start");
if (!data)
return -EINVAL;
ret = nla_parse(tb, MAX_WLCORE_VENDOR_ATTR, data, data_len,
wlcore_vendor_attr_policy);
if (ret)
return ret;
if (!tb[WLCORE_VENDOR_ATTR_GROUP_ID])
return -EINVAL;
mutex_lock(&wl->mutex);
if (unlikely(wl->state != WLCORE_STATE_ON)) {
ret = -EINVAL;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wlcore_smart_config_start(wl,
nla_get_u32(tb[WLCORE_VENDOR_ATTR_GROUP_ID]));
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return 0;
}
static int
wlcore_vendor_cmd_smart_config_stop(struct wiphy *wiphy,
struct wireless_dev *wdev,
const void *data, int data_len)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct wl1271 *wl = hw->priv;
int ret;
wl1271_debug(DEBUG_CMD, "testmode cmd smart config stop");
mutex_lock(&wl->mutex);
if (unlikely(wl->state != WLCORE_STATE_ON)) {
ret = -EINVAL;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wlcore_smart_config_stop(wl);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int
wlcore_vendor_cmd_smart_config_set_group_key(struct wiphy *wiphy,
struct wireless_dev *wdev,
const void *data, int data_len)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct wl1271 *wl = hw->priv;
struct nlattr *tb[NUM_WLCORE_VENDOR_ATTR];
int ret;
wl1271_debug(DEBUG_CMD, "testmode cmd smart config set group key");
if (!data)
return -EINVAL;
ret = nla_parse(tb, MAX_WLCORE_VENDOR_ATTR, data, data_len,
wlcore_vendor_attr_policy);
if (ret)
return ret;
if (!tb[WLCORE_VENDOR_ATTR_GROUP_ID] ||
!tb[WLCORE_VENDOR_ATTR_GROUP_KEY])
return -EINVAL;
mutex_lock(&wl->mutex);
if (unlikely(wl->state != WLCORE_STATE_ON)) {
ret = -EINVAL;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wlcore_smart_config_set_group_key(wl,
nla_get_u32(tb[WLCORE_VENDOR_ATTR_GROUP_ID]),
nla_len(tb[WLCORE_VENDOR_ATTR_GROUP_KEY]),
nla_data(tb[WLCORE_VENDOR_ATTR_GROUP_KEY]));
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static const struct wiphy_vendor_command wlcore_vendor_commands[] = {
{
.info = {
.vendor_id = TI_OUI,
.subcmd = WLCORE_VENDOR_CMD_SMART_CONFIG_START,
},
.flags = WIPHY_VENDOR_CMD_NEED_NETDEV |
WIPHY_VENDOR_CMD_NEED_RUNNING,
.doit = wlcore_vendor_cmd_smart_config_start,
},
{
.info = {
.vendor_id = TI_OUI,
.subcmd = WLCORE_VENDOR_CMD_SMART_CONFIG_STOP,
},
.flags = WIPHY_VENDOR_CMD_NEED_NETDEV |
WIPHY_VENDOR_CMD_NEED_RUNNING,
.doit = wlcore_vendor_cmd_smart_config_stop,
},
{
.info = {
.vendor_id = TI_OUI,
.subcmd = WLCORE_VENDOR_CMD_SMART_CONFIG_SET_GROUP_KEY,
},
.flags = WIPHY_VENDOR_CMD_NEED_NETDEV |
WIPHY_VENDOR_CMD_NEED_RUNNING,
.doit = wlcore_vendor_cmd_smart_config_set_group_key,
},
};
static const struct nl80211_vendor_cmd_info wlcore_vendor_events[] = {
{
.vendor_id = TI_OUI,
.subcmd = WLCORE_VENDOR_EVENT_SC_SYNC,
},
{
.vendor_id = TI_OUI,
.subcmd = WLCORE_VENDOR_EVENT_SC_DECODE,
},
};
void wlcore_set_vendor_commands(struct wiphy *wiphy)
{
wiphy->vendor_commands = wlcore_vendor_commands;
wiphy->n_vendor_commands = ARRAY_SIZE(wlcore_vendor_commands);
wiphy->vendor_events = wlcore_vendor_events;
wiphy->n_vendor_events = ARRAY_SIZE(wlcore_vendor_events);
}
| gpl-2.0 |
LeeDroid-/Ace-2.6.35 | drivers/mtd/tests/mtd_stresstest.c | 2010 | 7443 | /*
* Copyright (C) 2006-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 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; see the file COPYING. If not, write to the Free Software
* Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Test random reads, writes and erases on MTD device.
*
* Author: Adrian Hunter <ext-adrian.hunter@nokia.com>
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/err.h>
#include <linux/mtd/mtd.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/vmalloc.h>
#define PRINT_PREF KERN_INFO "mtd_stresstest: "
static int dev;
module_param(dev, int, S_IRUGO);
MODULE_PARM_DESC(dev, "MTD device number to use");
static int count = 10000;
module_param(count, int, S_IRUGO);
MODULE_PARM_DESC(count, "Number of operations to do (default is 10000)");
static struct mtd_info *mtd;
static unsigned char *writebuf;
static unsigned char *readbuf;
static unsigned char *bbt;
static int *offsets;
static int pgsize;
static int bufsize;
static int ebcnt;
static int pgcnt;
static unsigned long next = 1;
static inline unsigned int simple_rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)((next / 65536) % 32768);
}
static inline void simple_srand(unsigned long seed)
{
next = seed;
}
static int rand_eb(void)
{
int eb;
again:
if (ebcnt < 32768)
eb = simple_rand();
else
eb = (simple_rand() << 15) | simple_rand();
/* Read or write up 2 eraseblocks at a time - hence 'ebcnt - 1' */
eb %= (ebcnt - 1);
if (bbt[eb])
goto again;
return eb;
}
static int rand_offs(void)
{
int offs;
if (bufsize < 32768)
offs = simple_rand();
else
offs = (simple_rand() << 15) | simple_rand();
offs %= bufsize;
return offs;
}
static int rand_len(int offs)
{
int len;
if (bufsize < 32768)
len = simple_rand();
else
len = (simple_rand() << 15) | simple_rand();
len %= (bufsize - offs);
return len;
}
static int erase_eraseblock(int ebnum)
{
int err;
struct erase_info ei;
loff_t addr = ebnum * mtd->erasesize;
memset(&ei, 0, sizeof(struct erase_info));
ei.mtd = mtd;
ei.addr = addr;
ei.len = mtd->erasesize;
err = mtd->erase(mtd, &ei);
if (unlikely(err)) {
printk(PRINT_PREF "error %d while erasing EB %d\n", err, ebnum);
return err;
}
if (unlikely(ei.state == MTD_ERASE_FAILED)) {
printk(PRINT_PREF "some erase error occurred at EB %d\n",
ebnum);
return -EIO;
}
return 0;
}
static int is_block_bad(int ebnum)
{
loff_t addr = ebnum * mtd->erasesize;
int ret;
ret = mtd->block_isbad(mtd, addr);
if (ret)
printk(PRINT_PREF "block %d is bad\n", ebnum);
return ret;
}
static int do_read(void)
{
size_t read = 0;
int eb = rand_eb();
int offs = rand_offs();
int len = rand_len(offs), err;
loff_t addr;
if (bbt[eb + 1]) {
if (offs >= mtd->erasesize)
offs -= mtd->erasesize;
if (offs + len > mtd->erasesize)
len = mtd->erasesize - offs;
}
addr = eb * mtd->erasesize + offs;
err = mtd->read(mtd, addr, len, &read, readbuf);
if (err == -EUCLEAN)
err = 0;
if (unlikely(err || read != len)) {
printk(PRINT_PREF "error: read failed at 0x%llx\n",
(long long)addr);
if (!err)
err = -EINVAL;
return err;
}
return 0;
}
static int do_write(void)
{
int eb = rand_eb(), offs, err, len;
size_t written = 0;
loff_t addr;
offs = offsets[eb];
if (offs >= mtd->erasesize) {
err = erase_eraseblock(eb);
if (err)
return err;
offs = offsets[eb] = 0;
}
len = rand_len(offs);
len = ((len + pgsize - 1) / pgsize) * pgsize;
if (offs + len > mtd->erasesize) {
if (bbt[eb + 1])
len = mtd->erasesize - offs;
else {
err = erase_eraseblock(eb + 1);
if (err)
return err;
offsets[eb + 1] = 0;
}
}
addr = eb * mtd->erasesize + offs;
err = mtd->write(mtd, addr, len, &written, writebuf);
if (unlikely(err || written != len)) {
printk(PRINT_PREF "error: write failed at 0x%llx\n",
(long long)addr);
if (!err)
err = -EINVAL;
return err;
}
offs += len;
while (offs > mtd->erasesize) {
offsets[eb++] = mtd->erasesize;
offs -= mtd->erasesize;
}
offsets[eb] = offs;
return 0;
}
static int do_operation(void)
{
if (simple_rand() & 1)
return do_read();
else
return do_write();
}
static int scan_for_bad_eraseblocks(void)
{
int i, bad = 0;
bbt = kzalloc(ebcnt, GFP_KERNEL);
if (!bbt) {
printk(PRINT_PREF "error: cannot allocate memory\n");
return -ENOMEM;
}
/* NOR flash does not implement block_isbad */
if (mtd->block_isbad == NULL)
return 0;
printk(PRINT_PREF "scanning for bad eraseblocks\n");
for (i = 0; i < ebcnt; ++i) {
bbt[i] = is_block_bad(i) ? 1 : 0;
if (bbt[i])
bad += 1;
cond_resched();
}
printk(PRINT_PREF "scanned %d eraseblocks, %d are bad\n", i, bad);
return 0;
}
static int __init mtd_stresstest_init(void)
{
int err;
int i, op;
uint64_t tmp;
printk(KERN_INFO "\n");
printk(KERN_INFO "=================================================\n");
printk(PRINT_PREF "MTD device: %d\n", dev);
mtd = get_mtd_device(NULL, dev);
if (IS_ERR(mtd)) {
err = PTR_ERR(mtd);
printk(PRINT_PREF "error: cannot get MTD device\n");
return err;
}
if (mtd->writesize == 1) {
printk(PRINT_PREF "not NAND flash, assume page size is 512 "
"bytes.\n");
pgsize = 512;
} else
pgsize = mtd->writesize;
tmp = mtd->size;
do_div(tmp, mtd->erasesize);
ebcnt = tmp;
pgcnt = mtd->erasesize / pgsize;
printk(PRINT_PREF "MTD device size %llu, eraseblock size %u, "
"page size %u, count of eraseblocks %u, pages per "
"eraseblock %u, OOB size %u\n",
(unsigned long long)mtd->size, mtd->erasesize,
pgsize, ebcnt, pgcnt, mtd->oobsize);
/* Read or write up 2 eraseblocks at a time */
bufsize = mtd->erasesize * 2;
err = -ENOMEM;
readbuf = vmalloc(bufsize);
writebuf = vmalloc(bufsize);
offsets = kmalloc(ebcnt * sizeof(int), GFP_KERNEL);
if (!readbuf || !writebuf || !offsets) {
printk(PRINT_PREF "error: cannot allocate memory\n");
goto out;
}
for (i = 0; i < ebcnt; i++)
offsets[i] = mtd->erasesize;
simple_srand(current->pid);
for (i = 0; i < bufsize; i++)
writebuf[i] = simple_rand();
err = scan_for_bad_eraseblocks();
if (err)
goto out;
/* Do operations */
printk(PRINT_PREF "doing operations\n");
for (op = 0; op < count; op++) {
if ((op & 1023) == 0)
printk(PRINT_PREF "%d operations done\n", op);
err = do_operation();
if (err)
goto out;
cond_resched();
}
printk(PRINT_PREF "finished, %d operations done\n", op);
out:
kfree(offsets);
kfree(bbt);
vfree(writebuf);
vfree(readbuf);
put_mtd_device(mtd);
if (err)
printk(PRINT_PREF "error %d occurred\n", err);
printk(KERN_INFO "=================================================\n");
return err;
}
module_init(mtd_stresstest_init);
static void __exit mtd_stresstest_exit(void)
{
return;
}
module_exit(mtd_stresstest_exit);
MODULE_DESCRIPTION("Stress test module");
MODULE_AUTHOR("Adrian Hunter");
MODULE_LICENSE("GPL");
| gpl-2.0 |
agat63/E4GT_FH13_kernel | arch/arm/mach-omap2/mcbsp.c | 2522 | 4068 | /*
* linux/arch/arm/mach-omap2/mcbsp.c
*
* Copyright (C) 2008 Instituto Nokia de Tecnologia
* Contact: Eduardo Valentin <eduardo.valentin@indt.org.br>
*
* 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.
*
* Multichannel mode not supported.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <mach/irqs.h>
#include <plat/dma.h>
#include <plat/cpu.h>
#include <plat/mcbsp.h>
#include <plat/omap_device.h>
#include <linux/pm_runtime.h>
#include "control.h"
/* McBSP internal signal muxing functions */
void omap2_mcbsp1_mux_clkr_src(u8 mux)
{
u32 v;
v = omap_ctrl_readl(OMAP2_CONTROL_DEVCONF0);
if (mux == CLKR_SRC_CLKR)
v &= ~OMAP2_MCBSP1_CLKR_MASK;
else if (mux == CLKR_SRC_CLKX)
v |= OMAP2_MCBSP1_CLKR_MASK;
omap_ctrl_writel(v, OMAP2_CONTROL_DEVCONF0);
}
EXPORT_SYMBOL(omap2_mcbsp1_mux_clkr_src);
void omap2_mcbsp1_mux_fsr_src(u8 mux)
{
u32 v;
v = omap_ctrl_readl(OMAP2_CONTROL_DEVCONF0);
if (mux == FSR_SRC_FSR)
v &= ~OMAP2_MCBSP1_FSR_MASK;
else if (mux == FSR_SRC_FSX)
v |= OMAP2_MCBSP1_FSR_MASK;
omap_ctrl_writel(v, OMAP2_CONTROL_DEVCONF0);
}
EXPORT_SYMBOL(omap2_mcbsp1_mux_fsr_src);
/* McBSP CLKS source switching function */
int omap2_mcbsp_set_clks_src(u8 id, u8 fck_src_id)
{
struct omap_mcbsp *mcbsp;
struct clk *fck_src;
char *fck_src_name;
int r;
if (!omap_mcbsp_check_valid_id(id)) {
pr_err("%s: Invalid id (%d)\n", __func__, id + 1);
return -EINVAL;
}
mcbsp = id_to_mcbsp_ptr(id);
if (fck_src_id == MCBSP_CLKS_PAD_SRC)
fck_src_name = "pad_fck";
else if (fck_src_id == MCBSP_CLKS_PRCM_SRC)
fck_src_name = "prcm_fck";
else
return -EINVAL;
fck_src = clk_get(mcbsp->dev, fck_src_name);
if (IS_ERR_OR_NULL(fck_src)) {
pr_err("omap-mcbsp: %s: could not clk_get() %s\n", "clks",
fck_src_name);
return -EINVAL;
}
pm_runtime_put_sync(mcbsp->dev);
r = clk_set_parent(mcbsp->fclk, fck_src);
if (IS_ERR_VALUE(r)) {
pr_err("omap-mcbsp: %s: could not clk_set_parent() to %s\n",
"clks", fck_src_name);
clk_put(fck_src);
return -EINVAL;
}
pm_runtime_get_sync(mcbsp->dev);
clk_put(fck_src);
return 0;
}
EXPORT_SYMBOL(omap2_mcbsp_set_clks_src);
struct omap_device_pm_latency omap2_mcbsp_latency[] = {
{
.deactivate_func = omap_device_idle_hwmods,
.activate_func = omap_device_enable_hwmods,
.flags = OMAP_DEVICE_LATENCY_AUTO_ADJUST,
},
};
static int omap_init_mcbsp(struct omap_hwmod *oh, void *unused)
{
int id, count = 1;
char *name = "omap-mcbsp";
struct omap_hwmod *oh_device[2];
struct omap_mcbsp_platform_data *pdata = NULL;
struct omap_device *od;
sscanf(oh->name, "mcbsp%d", &id);
pdata = kzalloc(sizeof(struct omap_mcbsp_platform_data), GFP_KERNEL);
if (!pdata) {
pr_err("%s: No memory for mcbsp\n", __func__);
return -ENOMEM;
}
pdata->mcbsp_config_type = oh->class->rev;
if (oh->class->rev == MCBSP_CONFIG_TYPE3) {
if (id == 2)
/* The FIFO has 1024 + 256 locations */
pdata->buffer_size = 0x500;
else
/* The FIFO has 128 locations */
pdata->buffer_size = 0x80;
}
oh_device[0] = oh;
if (oh->dev_attr) {
oh_device[1] = omap_hwmod_lookup((
(struct omap_mcbsp_dev_attr *)(oh->dev_attr))->sidetone);
count++;
}
od = omap_device_build_ss(name, id, oh_device, count, pdata,
sizeof(*pdata), omap2_mcbsp_latency,
ARRAY_SIZE(omap2_mcbsp_latency), false);
kfree(pdata);
if (IS_ERR(od)) {
pr_err("%s: Can't build omap_device for %s:%s.\n", __func__,
name, oh->name);
return PTR_ERR(od);
}
omap_mcbsp_count++;
return 0;
}
static int __init omap2_mcbsp_init(void)
{
omap_hwmod_for_each_by_class("mcbsp", omap_init_mcbsp, NULL);
mcbsp_ptr = kzalloc(omap_mcbsp_count * sizeof(struct omap_mcbsp *),
GFP_KERNEL);
if (!mcbsp_ptr)
return -ENOMEM;
return omap_mcbsp_init();
}
arch_initcall(omap2_mcbsp_init);
| gpl-2.0 |
sainath24/android_kernel_samsung_smdk4412 | drivers/watchdog/wm831x_wdt.c | 2778 | 9373 | /*
* Watchdog driver for the wm831x PMICs
*
* Copyright (C) 2009 Wolfson Microelectronics
*
* 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
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>
#include <linux/uaccess.h>
#include <linux/gpio.h>
#include <linux/mfd/wm831x/core.h>
#include <linux/mfd/wm831x/pdata.h>
#include <linux/mfd/wm831x/watchdog.h>
static int nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static unsigned long wm831x_wdt_users;
static struct miscdevice wm831x_wdt_miscdev;
static int wm831x_wdt_expect_close;
static DEFINE_MUTEX(wdt_mutex);
static struct wm831x *wm831x;
static unsigned int update_gpio;
static unsigned int update_state;
/* We can't use the sub-second values here but they're included
* for completeness. */
static struct {
int time; /* Seconds */
u16 val; /* WDOG_TO value */
} wm831x_wdt_cfgs[] = {
{ 1, 2 },
{ 2, 3 },
{ 4, 4 },
{ 8, 5 },
{ 16, 6 },
{ 32, 7 },
{ 33, 7 }, /* Actually 32.768s so include both, others round down */
};
static int wm831x_wdt_set_timeout(struct wm831x *wm831x, u16 value)
{
int ret;
mutex_lock(&wdt_mutex);
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_set_bits(wm831x, WM831X_WATCHDOG,
WM831X_WDOG_TO_MASK, value);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm831x_wdt_start(struct wm831x *wm831x)
{
int ret;
mutex_lock(&wdt_mutex);
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_set_bits(wm831x, WM831X_WATCHDOG,
WM831X_WDOG_ENA, WM831X_WDOG_ENA);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm831x_wdt_stop(struct wm831x *wm831x)
{
int ret;
mutex_lock(&wdt_mutex);
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_set_bits(wm831x, WM831X_WATCHDOG,
WM831X_WDOG_ENA, 0);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm831x_wdt_kick(struct wm831x *wm831x)
{
int ret;
u16 reg;
mutex_lock(&wdt_mutex);
if (update_gpio) {
gpio_set_value_cansleep(update_gpio, update_state);
update_state = !update_state;
ret = 0;
goto out;
}
reg = wm831x_reg_read(wm831x, WM831X_WATCHDOG);
if (!(reg & WM831X_WDOG_RST_SRC)) {
dev_err(wm831x->dev, "Hardware watchdog update unsupported\n");
ret = -EINVAL;
goto out;
}
reg |= WM831X_WDOG_RESET;
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_reg_write(wm831x, WM831X_WATCHDOG, reg);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
out:
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm831x_wdt_open(struct inode *inode, struct file *file)
{
int ret;
if (!wm831x)
return -ENODEV;
if (test_and_set_bit(0, &wm831x_wdt_users))
return -EBUSY;
ret = wm831x_wdt_start(wm831x);
if (ret != 0)
return ret;
return nonseekable_open(inode, file);
}
static int wm831x_wdt_release(struct inode *inode, struct file *file)
{
if (wm831x_wdt_expect_close)
wm831x_wdt_stop(wm831x);
else {
dev_warn(wm831x->dev, "Watchdog device closed uncleanly\n");
wm831x_wdt_kick(wm831x);
}
clear_bit(0, &wm831x_wdt_users);
return 0;
}
static ssize_t wm831x_wdt_write(struct file *file,
const char __user *data, size_t count,
loff_t *ppos)
{
size_t i;
if (count) {
wm831x_wdt_kick(wm831x);
if (!nowayout) {
/* In case it was set long ago */
wm831x_wdt_expect_close = 0;
/* scan to see whether or not we got the magic
character */
for (i = 0; i != count; i++) {
char c;
if (get_user(c, data + i))
return -EFAULT;
if (c == 'V')
wm831x_wdt_expect_close = 42;
}
}
}
return count;
}
static const struct watchdog_info ident = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
.identity = "WM831x Watchdog",
};
static long wm831x_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int ret = -ENOTTY, time, i;
void __user *argp = (void __user *)arg;
int __user *p = argp;
u16 reg;
switch (cmd) {
case WDIOC_GETSUPPORT:
ret = copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0;
break;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
ret = put_user(0, p);
break;
case WDIOC_SETOPTIONS:
{
int options;
if (get_user(options, p))
return -EFAULT;
ret = -EINVAL;
/* Setting both simultaneously means at least one must fail */
if (options == WDIOS_DISABLECARD)
ret = wm831x_wdt_start(wm831x);
if (options == WDIOS_ENABLECARD)
ret = wm831x_wdt_stop(wm831x);
break;
}
case WDIOC_KEEPALIVE:
ret = wm831x_wdt_kick(wm831x);
break;
case WDIOC_SETTIMEOUT:
ret = get_user(time, p);
if (ret)
break;
if (time == 0) {
if (nowayout)
ret = -EINVAL;
else
wm831x_wdt_stop(wm831x);
break;
}
for (i = 0; i < ARRAY_SIZE(wm831x_wdt_cfgs); i++)
if (wm831x_wdt_cfgs[i].time == time)
break;
if (i == ARRAY_SIZE(wm831x_wdt_cfgs))
ret = -EINVAL;
else
ret = wm831x_wdt_set_timeout(wm831x,
wm831x_wdt_cfgs[i].val);
break;
case WDIOC_GETTIMEOUT:
reg = wm831x_reg_read(wm831x, WM831X_WATCHDOG);
reg &= WM831X_WDOG_TO_MASK;
for (i = 0; i < ARRAY_SIZE(wm831x_wdt_cfgs); i++)
if (wm831x_wdt_cfgs[i].val == reg)
break;
if (i == ARRAY_SIZE(wm831x_wdt_cfgs)) {
dev_warn(wm831x->dev,
"Unknown watchdog configuration: %x\n", reg);
ret = -EINVAL;
} else
ret = put_user(wm831x_wdt_cfgs[i].time, p);
}
return ret;
}
static const struct file_operations wm831x_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = wm831x_wdt_write,
.unlocked_ioctl = wm831x_wdt_ioctl,
.open = wm831x_wdt_open,
.release = wm831x_wdt_release,
};
static struct miscdevice wm831x_wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wm831x_wdt_fops,
};
static int __devinit wm831x_wdt_probe(struct platform_device *pdev)
{
struct wm831x_pdata *chip_pdata;
struct wm831x_watchdog_pdata *pdata;
int reg, ret;
if (wm831x) {
dev_err(&pdev->dev, "wm831x watchdog already registered\n");
return -EBUSY;
}
wm831x = dev_get_drvdata(pdev->dev.parent);
ret = wm831x_reg_read(wm831x, WM831X_WATCHDOG);
if (ret < 0) {
dev_err(wm831x->dev, "Failed to read watchdog status: %d\n",
ret);
goto err;
}
reg = ret;
if (reg & WM831X_WDOG_DEBUG)
dev_warn(wm831x->dev, "Watchdog is paused\n");
/* Apply any configuration */
if (pdev->dev.parent->platform_data) {
chip_pdata = pdev->dev.parent->platform_data;
pdata = chip_pdata->watchdog;
} else {
pdata = NULL;
}
if (pdata) {
reg &= ~(WM831X_WDOG_SECACT_MASK | WM831X_WDOG_PRIMACT_MASK |
WM831X_WDOG_RST_SRC);
reg |= pdata->primary << WM831X_WDOG_PRIMACT_SHIFT;
reg |= pdata->secondary << WM831X_WDOG_SECACT_SHIFT;
reg |= pdata->software << WM831X_WDOG_RST_SRC_SHIFT;
if (pdata->update_gpio) {
ret = gpio_request(pdata->update_gpio,
"Watchdog update");
if (ret < 0) {
dev_err(wm831x->dev,
"Failed to request update GPIO: %d\n",
ret);
goto err;
}
ret = gpio_direction_output(pdata->update_gpio, 0);
if (ret != 0) {
dev_err(wm831x->dev,
"gpio_direction_output returned: %d\n",
ret);
goto err_gpio;
}
update_gpio = pdata->update_gpio;
/* Make sure the watchdog takes hardware updates */
reg |= WM831X_WDOG_RST_SRC;
}
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_reg_write(wm831x, WM831X_WATCHDOG, reg);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev,
"Failed to unlock security key: %d\n", ret);
goto err_gpio;
}
}
wm831x_wdt_miscdev.parent = &pdev->dev;
ret = misc_register(&wm831x_wdt_miscdev);
if (ret != 0) {
dev_err(wm831x->dev, "Failed to register miscdev: %d\n", ret);
goto err_gpio;
}
return 0;
err_gpio:
if (update_gpio) {
gpio_free(update_gpio);
update_gpio = 0;
}
err:
return ret;
}
static int __devexit wm831x_wdt_remove(struct platform_device *pdev)
{
if (update_gpio) {
gpio_free(update_gpio);
update_gpio = 0;
}
misc_deregister(&wm831x_wdt_miscdev);
return 0;
}
static struct platform_driver wm831x_wdt_driver = {
.probe = wm831x_wdt_probe,
.remove = __devexit_p(wm831x_wdt_remove),
.driver = {
.name = "wm831x-watchdog",
},
};
static int __init wm831x_wdt_init(void)
{
return platform_driver_register(&wm831x_wdt_driver);
}
module_init(wm831x_wdt_init);
static void __exit wm831x_wdt_exit(void)
{
platform_driver_unregister(&wm831x_wdt_driver);
}
module_exit(wm831x_wdt_exit);
MODULE_AUTHOR("Mark Brown");
MODULE_DESCRIPTION("WM831x Watchdog");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm831x-watchdog");
| gpl-2.0 |
dheerajjamwal/Backport_ltsi_3.14.22 | security/tomoyo/tomoyo.c | 3290 | 14937 | /*
* security/tomoyo/tomoyo.c
*
* Copyright (C) 2005-2011 NTT DATA CORPORATION
*/
#include <linux/security.h>
#include "common.h"
/**
* tomoyo_cred_alloc_blank - Target for security_cred_alloc_blank().
*
* @new: Pointer to "struct cred".
* @gfp: Memory allocation flags.
*
* Returns 0.
*/
static int tomoyo_cred_alloc_blank(struct cred *new, gfp_t gfp)
{
new->security = NULL;
return 0;
}
/**
* tomoyo_cred_prepare - Target for security_prepare_creds().
*
* @new: Pointer to "struct cred".
* @old: Pointer to "struct cred".
* @gfp: Memory allocation flags.
*
* Returns 0.
*/
static int tomoyo_cred_prepare(struct cred *new, const struct cred *old,
gfp_t gfp)
{
struct tomoyo_domain_info *domain = old->security;
new->security = domain;
if (domain)
atomic_inc(&domain->users);
return 0;
}
/**
* tomoyo_cred_transfer - Target for security_transfer_creds().
*
* @new: Pointer to "struct cred".
* @old: Pointer to "struct cred".
*/
static void tomoyo_cred_transfer(struct cred *new, const struct cred *old)
{
tomoyo_cred_prepare(new, old, 0);
}
/**
* tomoyo_cred_free - Target for security_cred_free().
*
* @cred: Pointer to "struct cred".
*/
static void tomoyo_cred_free(struct cred *cred)
{
struct tomoyo_domain_info *domain = cred->security;
if (domain)
atomic_dec(&domain->users);
}
/**
* tomoyo_bprm_set_creds - Target for security_bprm_set_creds().
*
* @bprm: Pointer to "struct linux_binprm".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_bprm_set_creds(struct linux_binprm *bprm)
{
int rc;
rc = cap_bprm_set_creds(bprm);
if (rc)
return rc;
/*
* Do only if this function is called for the first time of an execve
* operation.
*/
if (bprm->cred_prepared)
return 0;
#ifndef CONFIG_SECURITY_TOMOYO_OMIT_USERSPACE_LOADER
/*
* Load policy if /sbin/tomoyo-init exists and /sbin/init is requested
* for the first time.
*/
if (!tomoyo_policy_loaded)
tomoyo_load_policy(bprm->filename);
#endif
/*
* Release reference to "struct tomoyo_domain_info" stored inside
* "bprm->cred->security". New reference to "struct tomoyo_domain_info"
* stored inside "bprm->cred->security" will be acquired later inside
* tomoyo_find_next_domain().
*/
atomic_dec(&((struct tomoyo_domain_info *)
bprm->cred->security)->users);
/*
* Tell tomoyo_bprm_check_security() is called for the first time of an
* execve operation.
*/
bprm->cred->security = NULL;
return 0;
}
/**
* tomoyo_bprm_check_security - Target for security_bprm_check().
*
* @bprm: Pointer to "struct linux_binprm".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_bprm_check_security(struct linux_binprm *bprm)
{
struct tomoyo_domain_info *domain = bprm->cred->security;
/*
* Execute permission is checked against pathname passed to do_execve()
* using current domain.
*/
if (!domain) {
const int idx = tomoyo_read_lock();
const int err = tomoyo_find_next_domain(bprm);
tomoyo_read_unlock(idx);
return err;
}
/*
* Read permission is checked against interpreters using next domain.
*/
return tomoyo_check_open_permission(domain, &bprm->file->f_path,
O_RDONLY);
}
/**
* tomoyo_inode_getattr - Target for security_inode_getattr().
*
* @mnt: Pointer to "struct vfsmount".
* @dentry: Pointer to "struct dentry".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
{
struct path path = { mnt, dentry };
return tomoyo_path_perm(TOMOYO_TYPE_GETATTR, &path, NULL);
}
/**
* tomoyo_path_truncate - Target for security_path_truncate().
*
* @path: Pointer to "struct path".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_truncate(struct path *path)
{
return tomoyo_path_perm(TOMOYO_TYPE_TRUNCATE, path, NULL);
}
/**
* tomoyo_path_unlink - Target for security_path_unlink().
*
* @parent: Pointer to "struct path".
* @dentry: Pointer to "struct dentry".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_unlink(struct path *parent, struct dentry *dentry)
{
struct path path = { parent->mnt, dentry };
return tomoyo_path_perm(TOMOYO_TYPE_UNLINK, &path, NULL);
}
/**
* tomoyo_path_mkdir - Target for security_path_mkdir().
*
* @parent: Pointer to "struct path".
* @dentry: Pointer to "struct dentry".
* @mode: DAC permission mode.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_mkdir(struct path *parent, struct dentry *dentry,
umode_t mode)
{
struct path path = { parent->mnt, dentry };
return tomoyo_path_number_perm(TOMOYO_TYPE_MKDIR, &path,
mode & S_IALLUGO);
}
/**
* tomoyo_path_rmdir - Target for security_path_rmdir().
*
* @parent: Pointer to "struct path".
* @dentry: Pointer to "struct dentry".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_rmdir(struct path *parent, struct dentry *dentry)
{
struct path path = { parent->mnt, dentry };
return tomoyo_path_perm(TOMOYO_TYPE_RMDIR, &path, NULL);
}
/**
* tomoyo_path_symlink - Target for security_path_symlink().
*
* @parent: Pointer to "struct path".
* @dentry: Pointer to "struct dentry".
* @old_name: Symlink's content.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_symlink(struct path *parent, struct dentry *dentry,
const char *old_name)
{
struct path path = { parent->mnt, dentry };
return tomoyo_path_perm(TOMOYO_TYPE_SYMLINK, &path, old_name);
}
/**
* tomoyo_path_mknod - Target for security_path_mknod().
*
* @parent: Pointer to "struct path".
* @dentry: Pointer to "struct dentry".
* @mode: DAC permission mode.
* @dev: Device attributes.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_mknod(struct path *parent, struct dentry *dentry,
umode_t mode, unsigned int dev)
{
struct path path = { parent->mnt, dentry };
int type = TOMOYO_TYPE_CREATE;
const unsigned int perm = mode & S_IALLUGO;
switch (mode & S_IFMT) {
case S_IFCHR:
type = TOMOYO_TYPE_MKCHAR;
break;
case S_IFBLK:
type = TOMOYO_TYPE_MKBLOCK;
break;
default:
goto no_dev;
}
return tomoyo_mkdev_perm(type, &path, perm, dev);
no_dev:
switch (mode & S_IFMT) {
case S_IFIFO:
type = TOMOYO_TYPE_MKFIFO;
break;
case S_IFSOCK:
type = TOMOYO_TYPE_MKSOCK;
break;
}
return tomoyo_path_number_perm(type, &path, perm);
}
/**
* tomoyo_path_link - Target for security_path_link().
*
* @old_dentry: Pointer to "struct dentry".
* @new_dir: Pointer to "struct path".
* @new_dentry: Pointer to "struct dentry".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_link(struct dentry *old_dentry, struct path *new_dir,
struct dentry *new_dentry)
{
struct path path1 = { new_dir->mnt, old_dentry };
struct path path2 = { new_dir->mnt, new_dentry };
return tomoyo_path2_perm(TOMOYO_TYPE_LINK, &path1, &path2);
}
/**
* tomoyo_path_rename - Target for security_path_rename().
*
* @old_parent: Pointer to "struct path".
* @old_dentry: Pointer to "struct dentry".
* @new_parent: Pointer to "struct path".
* @new_dentry: Pointer to "struct dentry".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_rename(struct path *old_parent,
struct dentry *old_dentry,
struct path *new_parent,
struct dentry *new_dentry)
{
struct path path1 = { old_parent->mnt, old_dentry };
struct path path2 = { new_parent->mnt, new_dentry };
return tomoyo_path2_perm(TOMOYO_TYPE_RENAME, &path1, &path2);
}
/**
* tomoyo_file_fcntl - Target for security_file_fcntl().
*
* @file: Pointer to "struct file".
* @cmd: Command for fcntl().
* @arg: Argument for @cmd.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_file_fcntl(struct file *file, unsigned int cmd,
unsigned long arg)
{
if (!(cmd == F_SETFL && ((arg ^ file->f_flags) & O_APPEND)))
return 0;
return tomoyo_check_open_permission(tomoyo_domain(), &file->f_path,
O_WRONLY | (arg & O_APPEND));
}
/**
* tomoyo_file_open - Target for security_file_open().
*
* @f: Pointer to "struct file".
* @cred: Pointer to "struct cred".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_file_open(struct file *f, const struct cred *cred)
{
int flags = f->f_flags;
/* Don't check read permission here if called from do_execve(). */
if (current->in_execve)
return 0;
return tomoyo_check_open_permission(tomoyo_domain(), &f->f_path, flags);
}
/**
* tomoyo_file_ioctl - Target for security_file_ioctl().
*
* @file: Pointer to "struct file".
* @cmd: Command for ioctl().
* @arg: Argument for @cmd.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_file_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return tomoyo_path_number_perm(TOMOYO_TYPE_IOCTL, &file->f_path, cmd);
}
/**
* tomoyo_path_chmod - Target for security_path_chmod().
*
* @path: Pointer to "struct path".
* @mode: DAC permission mode.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_chmod(struct path *path, umode_t mode)
{
return tomoyo_path_number_perm(TOMOYO_TYPE_CHMOD, path,
mode & S_IALLUGO);
}
/**
* tomoyo_path_chown - Target for security_path_chown().
*
* @path: Pointer to "struct path".
* @uid: Owner ID.
* @gid: Group ID.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_chown(struct path *path, kuid_t uid, kgid_t gid)
{
int error = 0;
if (uid_valid(uid))
error = tomoyo_path_number_perm(TOMOYO_TYPE_CHOWN, path,
from_kuid(&init_user_ns, uid));
if (!error && gid_valid(gid))
error = tomoyo_path_number_perm(TOMOYO_TYPE_CHGRP, path,
from_kgid(&init_user_ns, gid));
return error;
}
/**
* tomoyo_path_chroot - Target for security_path_chroot().
*
* @path: Pointer to "struct path".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_path_chroot(struct path *path)
{
return tomoyo_path_perm(TOMOYO_TYPE_CHROOT, path, NULL);
}
/**
* tomoyo_sb_mount - Target for security_sb_mount().
*
* @dev_name: Name of device file. Maybe NULL.
* @path: Pointer to "struct path".
* @type: Name of filesystem type. Maybe NULL.
* @flags: Mount options.
* @data: Optional data. Maybe NULL.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_sb_mount(const char *dev_name, struct path *path,
const char *type, unsigned long flags, void *data)
{
return tomoyo_mount_permission(dev_name, path, type, flags, data);
}
/**
* tomoyo_sb_umount - Target for security_sb_umount().
*
* @mnt: Pointer to "struct vfsmount".
* @flags: Unmount options.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_sb_umount(struct vfsmount *mnt, int flags)
{
struct path path = { mnt, mnt->mnt_root };
return tomoyo_path_perm(TOMOYO_TYPE_UMOUNT, &path, NULL);
}
/**
* tomoyo_sb_pivotroot - Target for security_sb_pivotroot().
*
* @old_path: Pointer to "struct path".
* @new_path: Pointer to "struct path".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_sb_pivotroot(struct path *old_path, struct path *new_path)
{
return tomoyo_path2_perm(TOMOYO_TYPE_PIVOT_ROOT, new_path, old_path);
}
/**
* tomoyo_socket_listen - Check permission for listen().
*
* @sock: Pointer to "struct socket".
* @backlog: Backlog parameter.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_socket_listen(struct socket *sock, int backlog)
{
return tomoyo_socket_listen_permission(sock);
}
/**
* tomoyo_socket_connect - Check permission for connect().
*
* @sock: Pointer to "struct socket".
* @addr: Pointer to "struct sockaddr".
* @addr_len: Size of @addr.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_socket_connect(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
return tomoyo_socket_connect_permission(sock, addr, addr_len);
}
/**
* tomoyo_socket_bind - Check permission for bind().
*
* @sock: Pointer to "struct socket".
* @addr: Pointer to "struct sockaddr".
* @addr_len: Size of @addr.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_socket_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
return tomoyo_socket_bind_permission(sock, addr, addr_len);
}
/**
* tomoyo_socket_sendmsg - Check permission for sendmsg().
*
* @sock: Pointer to "struct socket".
* @msg: Pointer to "struct msghdr".
* @size: Size of message.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_socket_sendmsg(struct socket *sock, struct msghdr *msg,
int size)
{
return tomoyo_socket_sendmsg_permission(sock, msg, size);
}
/*
* tomoyo_security_ops is a "struct security_operations" which is used for
* registering TOMOYO.
*/
static struct security_operations tomoyo_security_ops = {
.name = "tomoyo",
.cred_alloc_blank = tomoyo_cred_alloc_blank,
.cred_prepare = tomoyo_cred_prepare,
.cred_transfer = tomoyo_cred_transfer,
.cred_free = tomoyo_cred_free,
.bprm_set_creds = tomoyo_bprm_set_creds,
.bprm_check_security = tomoyo_bprm_check_security,
.file_fcntl = tomoyo_file_fcntl,
.file_open = tomoyo_file_open,
.path_truncate = tomoyo_path_truncate,
.path_unlink = tomoyo_path_unlink,
.path_mkdir = tomoyo_path_mkdir,
.path_rmdir = tomoyo_path_rmdir,
.path_symlink = tomoyo_path_symlink,
.path_mknod = tomoyo_path_mknod,
.path_link = tomoyo_path_link,
.path_rename = tomoyo_path_rename,
.inode_getattr = tomoyo_inode_getattr,
.file_ioctl = tomoyo_file_ioctl,
.path_chmod = tomoyo_path_chmod,
.path_chown = tomoyo_path_chown,
.path_chroot = tomoyo_path_chroot,
.sb_mount = tomoyo_sb_mount,
.sb_umount = tomoyo_sb_umount,
.sb_pivotroot = tomoyo_sb_pivotroot,
.socket_bind = tomoyo_socket_bind,
.socket_connect = tomoyo_socket_connect,
.socket_listen = tomoyo_socket_listen,
.socket_sendmsg = tomoyo_socket_sendmsg,
};
/* Lock for GC. */
DEFINE_SRCU(tomoyo_ss);
/**
* tomoyo_init - Register TOMOYO Linux as a LSM module.
*
* Returns 0.
*/
static int __init tomoyo_init(void)
{
struct cred *cred = (struct cred *) current_cred();
if (!security_module_enable(&tomoyo_security_ops))
return 0;
/* register ourselves with the security framework */
if (register_security(&tomoyo_security_ops))
panic("Failure registering TOMOYO Linux");
printk(KERN_INFO "TOMOYO Linux initialized\n");
cred->security = &tomoyo_kernel_domain;
tomoyo_mm_init();
return 0;
}
security_initcall(tomoyo_init);
| gpl-2.0 |
SlimRoms/kernel_xiaomi_armani | net/sctp/sm_make_chunk.c | 4058 | 102420 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions work with the state functions in sctp_sm_statefuns.c
* to implement the state operations. These functions implement the
* steps which require modifying existing data structures.
*
* This SCTP implementation 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 SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* C. Robin <chris@hundredacre.ac.uk>
* Jon Grimm <jgrimm@us.ibm.com>
* Xingang Guo <xingang.guo@intel.com>
* Dajiang Zhang <dajiang.zhang@nokia.com>
* Sridhar Samudrala <sri@us.ibm.com>
* Daisy Chang <daisyc@us.ibm.com>
* Ardelle Fan <ardelle.fan@intel.com>
* Kevin Gao <kevin.gao@intel.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/scatterlist.h>
#include <linux/crypto.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/skbuff.h>
#include <linux/random.h> /* for get_random_bytes */
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
SCTP_STATIC
struct sctp_chunk *sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen);
static sctp_cookie_param_t *sctp_pack_cookie(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *init_chunk,
int *cookie_len,
const __u8 *raw_addrs, int addrs_len);
static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp);
static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data);
/* What was the inbound interface for this chunk? */
int sctp_chunk_iif(const struct sctp_chunk *chunk)
{
struct sctp_af *af;
int iif = 0;
af = sctp_get_af_specific(ipver2af(ip_hdr(chunk->skb)->version));
if (af)
iif = af->skb_iif(chunk->skb);
return iif;
}
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 2: The ECN capable field is reserved for future use of
* Explicit Congestion Notification.
*/
static const struct sctp_paramhdr ecap_param = {
SCTP_PARAM_ECN_CAPABLE,
cpu_to_be16(sizeof(struct sctp_paramhdr)),
};
static const struct sctp_paramhdr prsctp_param = {
SCTP_PARAM_FWD_TSN_SUPPORT,
cpu_to_be16(sizeof(struct sctp_paramhdr)),
};
/* A helper to initialize an op error inside a
* provided chunk, as most cause codes will be embedded inside an
* abort chunk.
*/
void sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
size_t paylen)
{
sctp_errhdr_t err;
__u16 len;
/* Cause code constants are now defined in network order. */
err.cause = cause_code;
len = sizeof(sctp_errhdr_t) + paylen;
err.length = htons(len);
chunk->subh.err_hdr = sctp_addto_chunk(chunk, sizeof(sctp_errhdr_t), &err);
}
/* A helper to initialize an op error inside a
* provided chunk, as most cause codes will be embedded inside an
* abort chunk. Differs from sctp_init_cause in that it won't oops
* if there isn't enough space in the op error chunk
*/
int sctp_init_cause_fixed(struct sctp_chunk *chunk, __be16 cause_code,
size_t paylen)
{
sctp_errhdr_t err;
__u16 len;
/* Cause code constants are now defined in network order. */
err.cause = cause_code;
len = sizeof(sctp_errhdr_t) + paylen;
err.length = htons(len);
if (skb_tailroom(chunk->skb) < len)
return -ENOSPC;
chunk->subh.err_hdr = sctp_addto_chunk_fixed(chunk,
sizeof(sctp_errhdr_t),
&err);
return 0;
}
/* 3.3.2 Initiation (INIT) (1)
*
* This chunk is used to initiate a SCTP association between two
* endpoints. The format of the INIT chunk is shown below:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 1 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Initiate Tag |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Advertised Receiver Window Credit (a_rwnd) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Outbound Streams | Number of Inbound Streams |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Initial TSN |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / Optional/Variable-Length Parameters /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*
* The INIT chunk contains the following parameters. Unless otherwise
* noted, each parameter MUST only be included once in the INIT chunk.
*
* Fixed Parameters Status
* ----------------------------------------------
* Initiate Tag Mandatory
* Advertised Receiver Window Credit Mandatory
* Number of Outbound Streams Mandatory
* Number of Inbound Streams Mandatory
* Initial TSN Mandatory
*
* Variable Parameters Status Type Value
* -------------------------------------------------------------
* IPv4 Address (Note 1) Optional 5
* IPv6 Address (Note 1) Optional 6
* Cookie Preservative Optional 9
* Reserved for ECN Capable (Note 2) Optional 32768 (0x8000)
* Host Name Address (Note 3) Optional 11
* Supported Address Types (Note 4) Optional 12
*/
struct sctp_chunk *sctp_make_init(const struct sctp_association *asoc,
const struct sctp_bind_addr *bp,
gfp_t gfp, int vparam_len)
{
sctp_inithdr_t init;
union sctp_params addrs;
size_t chunksize;
struct sctp_chunk *retval = NULL;
int num_types, addrs_len = 0;
struct sctp_sock *sp;
sctp_supported_addrs_param_t sat;
__be16 types[2];
sctp_adaptation_ind_param_t aiparam;
sctp_supported_ext_param_t ext_param;
int num_ext = 0;
__u8 extensions[3];
sctp_paramhdr_t *auth_chunks = NULL,
*auth_hmacs = NULL;
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 1: The INIT chunks can contain multiple addresses that
* can be IPv4 and/or IPv6 in any combination.
*/
retval = NULL;
/* Convert the provided bind address list to raw format. */
addrs = sctp_bind_addrs_to_raw(bp, &addrs_len, gfp);
init.init_tag = htonl(asoc->c.my_vtag);
init.a_rwnd = htonl(asoc->rwnd);
init.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
init.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
init.initial_tsn = htonl(asoc->c.initial_tsn);
/* How many address types are needed? */
sp = sctp_sk(asoc->base.sk);
num_types = sp->pf->supported_addrs(sp, types);
chunksize = sizeof(init) + addrs_len;
chunksize += WORD_ROUND(SCTP_SAT_LEN(num_types));
chunksize += sizeof(ecap_param);
if (sctp_prsctp_enable)
chunksize += sizeof(prsctp_param);
/* ADDIP: Section 4.2.7:
* An implementation supporting this extension [ADDIP] MUST list
* the ASCONF,the ASCONF-ACK, and the AUTH chunks in its INIT and
* INIT-ACK parameters.
*/
if (sctp_addip_enable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
chunksize += vparam_len;
/* Account for AUTH related parameters */
if (sctp_auth_enable) {
/* Add random parameter length*/
chunksize += sizeof(asoc->c.auth_random);
/* Add HMACS parameter length if any were defined */
auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
/* Add CHUNKS parameter length */
auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += WORD_ROUND(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
/* If we have any extensions to report, account for that */
if (num_ext)
chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
num_ext);
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 3: An INIT chunk MUST NOT contain more than one Host
* Name address parameter. Moreover, the sender of the INIT
* MUST NOT combine any other address types with the Host Name
* address in the INIT. The receiver of INIT MUST ignore any
* other address types if the Host Name address parameter is
* present in the received INIT chunk.
*
* PLEASE DO NOT FIXME [This version does not support Host Name.]
*/
retval = sctp_make_chunk(asoc, SCTP_CID_INIT, 0, chunksize);
if (!retval)
goto nodata;
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(init), &init);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrs_len, addrs.v);
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 4: This parameter, when present, specifies all the
* address types the sending endpoint can support. The absence
* of this parameter indicates that the sending endpoint can
* support any address type.
*/
sat.param_hdr.type = SCTP_PARAM_SUPPORTED_ADDRESS_TYPES;
sat.param_hdr.length = htons(SCTP_SAT_LEN(num_types));
sctp_addto_chunk(retval, sizeof(sat), &sat);
sctp_addto_chunk(retval, num_types * sizeof(__u16), &types);
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
/* Add the supported extensions parameter. Be nice and add this
* fist before addiding the parameters for the extensions themselves
*/
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length =
htons(sizeof(sctp_supported_ext_param_t) + num_ext);
sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
&ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (sctp_prsctp_enable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
/* Add SCTP-AUTH chunks to the parameter list */
if (sctp_auth_enable) {
sctp_addto_chunk(retval, sizeof(asoc->c.auth_random),
asoc->c.auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
nodata:
kfree(addrs.v);
return retval;
}
struct sctp_chunk *sctp_make_init_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
gfp_t gfp, int unkparam_len)
{
sctp_inithdr_t initack;
struct sctp_chunk *retval;
union sctp_params addrs;
struct sctp_sock *sp;
int addrs_len;
sctp_cookie_param_t *cookie;
int cookie_len;
size_t chunksize;
sctp_adaptation_ind_param_t aiparam;
sctp_supported_ext_param_t ext_param;
int num_ext = 0;
__u8 extensions[3];
sctp_paramhdr_t *auth_chunks = NULL,
*auth_hmacs = NULL,
*auth_random = NULL;
retval = NULL;
/* Note: there may be no addresses to embed. */
addrs = sctp_bind_addrs_to_raw(&asoc->base.bind_addr, &addrs_len, gfp);
initack.init_tag = htonl(asoc->c.my_vtag);
initack.a_rwnd = htonl(asoc->rwnd);
initack.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
initack.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
initack.initial_tsn = htonl(asoc->c.initial_tsn);
/* FIXME: We really ought to build the cookie right
* into the packet instead of allocating more fresh memory.
*/
cookie = sctp_pack_cookie(asoc->ep, asoc, chunk, &cookie_len,
addrs.v, addrs_len);
if (!cookie)
goto nomem_cookie;
/* Calculate the total size of allocation, include the reserved
* space for reporting unknown parameters if it is specified.
*/
sp = sctp_sk(asoc->base.sk);
chunksize = sizeof(initack) + addrs_len + cookie_len + unkparam_len;
/* Tell peer that we'll do ECN only if peer advertised such cap. */
if (asoc->peer.ecn_capable)
chunksize += sizeof(ecap_param);
if (asoc->peer.prsctp_capable)
chunksize += sizeof(prsctp_param);
if (asoc->peer.asconf_capable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
if (asoc->peer.auth_capable) {
auth_random = (sctp_paramhdr_t *)asoc->c.auth_random;
chunksize += ntohs(auth_random->length);
auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += WORD_ROUND(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
if (num_ext)
chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
num_ext);
/* Now allocate and fill out the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_INIT_ACK, 0, chunksize);
if (!retval)
goto nomem_chunk;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
* [INIT ACK back to where the INIT came from.]
*/
retval->transport = chunk->transport;
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(initack), &initack);
retval->param_hdr.v = sctp_addto_chunk(retval, addrs_len, addrs.v);
sctp_addto_chunk(retval, cookie_len, cookie);
if (asoc->peer.ecn_capable)
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length =
htons(sizeof(sctp_supported_ext_param_t) + num_ext);
sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
&ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (asoc->peer.prsctp_capable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
if (asoc->peer.auth_capable) {
sctp_addto_chunk(retval, ntohs(auth_random->length),
auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
/* We need to remove the const qualifier at this point. */
retval->asoc = (struct sctp_association *) asoc;
nomem_chunk:
kfree(cookie);
nomem_cookie:
kfree(addrs.v);
return retval;
}
/* 3.3.11 Cookie Echo (COOKIE ECHO) (10):
*
* This chunk is used only during the initialization of an association.
* It is sent by the initiator of an association to its peer to complete
* the initialization process. This chunk MUST precede any DATA chunk
* sent within the association, but MAY be bundled with one or more DATA
* chunks in the same packet.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 10 |Chunk Flags | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* / Cookie /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Chunk Flags: 8 bit
*
* Set to zero on transmit and ignored on receipt.
*
* Length: 16 bits (unsigned integer)
*
* Set to the size of the chunk in bytes, including the 4 bytes of
* the chunk header and the size of the Cookie.
*
* Cookie: variable size
*
* This field must contain the exact cookie received in the
* State Cookie parameter from the previous INIT ACK.
*
* An implementation SHOULD make the cookie as small as possible
* to insure interoperability.
*/
struct sctp_chunk *sctp_make_cookie_echo(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
void *cookie;
int cookie_len;
cookie = asoc->peer.cookie;
cookie_len = asoc->peer.cookie_len;
/* Build a cookie echo chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_COOKIE_ECHO, 0, cookie_len);
if (!retval)
goto nodata;
retval->subh.cookie_hdr =
sctp_addto_chunk(retval, cookie_len, cookie);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [COOKIE ECHO back to where the INIT ACK came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* 3.3.12 Cookie Acknowledgement (COOKIE ACK) (11):
*
* This chunk is used only during the initialization of an
* association. It is used to acknowledge the receipt of a COOKIE
* ECHO chunk. This chunk MUST precede any DATA or SACK chunk sent
* within the association, but MAY be bundled with one or more DATA
* chunks or SACK chunk in the same SCTP packet.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 11 |Chunk Flags | Length = 4 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Chunk Flags: 8 bits
*
* Set to zero on transmit and ignored on receipt.
*/
struct sctp_chunk *sctp_make_cookie_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_COOKIE_ACK, 0, 0);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [COOKIE ACK back to where the COOKIE ECHO came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/*
* Appendix A: Explicit Congestion Notification:
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Chunk Type=13 | Flags=00000000| Chunk Length = 8 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Lowest TSN Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Note: The CWR is considered a Control chunk.
*/
struct sctp_chunk *sctp_make_cwr(const struct sctp_association *asoc,
const __u32 lowest_tsn,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
sctp_cwrhdr_t cwr;
cwr.lowest_tsn = htonl(lowest_tsn);
retval = sctp_make_chunk(asoc, SCTP_CID_ECN_CWR, 0,
sizeof(sctp_cwrhdr_t));
if (!retval)
goto nodata;
retval->subh.ecn_cwr_hdr =
sctp_addto_chunk(retval, sizeof(cwr), &cwr);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [Report a reduced congestion window back to where the ECNE
* came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Make an ECNE chunk. This is a congestion experienced report. */
struct sctp_chunk *sctp_make_ecne(const struct sctp_association *asoc,
const __u32 lowest_tsn)
{
struct sctp_chunk *retval;
sctp_ecnehdr_t ecne;
ecne.lowest_tsn = htonl(lowest_tsn);
retval = sctp_make_chunk(asoc, SCTP_CID_ECN_ECNE, 0,
sizeof(sctp_ecnehdr_t));
if (!retval)
goto nodata;
retval->subh.ecne_hdr =
sctp_addto_chunk(retval, sizeof(ecne), &ecne);
nodata:
return retval;
}
/* Make a DATA chunk for the given association from the provided
* parameters. However, do not populate the data payload.
*/
struct sctp_chunk *sctp_make_datafrag_empty(struct sctp_association *asoc,
const struct sctp_sndrcvinfo *sinfo,
int data_len, __u8 flags, __u16 ssn)
{
struct sctp_chunk *retval;
struct sctp_datahdr dp;
int chunk_len;
/* We assign the TSN as LATE as possible, not here when
* creating the chunk.
*/
dp.tsn = 0;
dp.stream = htons(sinfo->sinfo_stream);
dp.ppid = sinfo->sinfo_ppid;
/* Set the flags for an unordered send. */
if (sinfo->sinfo_flags & SCTP_UNORDERED) {
flags |= SCTP_DATA_UNORDERED;
dp.ssn = 0;
} else
dp.ssn = htons(ssn);
chunk_len = sizeof(dp) + data_len;
retval = sctp_make_chunk(asoc, SCTP_CID_DATA, flags, chunk_len);
if (!retval)
goto nodata;
retval->subh.data_hdr = sctp_addto_chunk(retval, sizeof(dp), &dp);
memcpy(&retval->sinfo, sinfo, sizeof(struct sctp_sndrcvinfo));
nodata:
return retval;
}
/* Create a selective ackowledgement (SACK) for the given
* association. This reports on which TSN's we've seen to date,
* including duplicates and gaps.
*/
struct sctp_chunk *sctp_make_sack(const struct sctp_association *asoc)
{
struct sctp_chunk *retval;
struct sctp_sackhdr sack;
int len;
__u32 ctsn;
__u16 num_gabs, num_dup_tsns;
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sctp_gap_ack_block gabs[SCTP_MAX_GABS];
memset(gabs, 0, sizeof(gabs));
ctsn = sctp_tsnmap_get_ctsn(map);
SCTP_DEBUG_PRINTK("sackCTSNAck sent: 0x%x.\n", ctsn);
/* How much room is needed in the chunk? */
num_gabs = sctp_tsnmap_num_gabs(map, gabs);
num_dup_tsns = sctp_tsnmap_num_dups(map);
/* Initialize the SACK header. */
sack.cum_tsn_ack = htonl(ctsn);
sack.a_rwnd = htonl(asoc->a_rwnd);
sack.num_gap_ack_blocks = htons(num_gabs);
sack.num_dup_tsns = htons(num_dup_tsns);
len = sizeof(sack)
+ sizeof(struct sctp_gap_ack_block) * num_gabs
+ sizeof(__u32) * num_dup_tsns;
/* Create the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_SACK, 0, len);
if (!retval)
goto nodata;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, etc.) to the same destination transport
* address from which it received the DATA or control chunk to
* which it is replying. This rule should also be followed if
* the endpoint is bundling DATA chunks together with the
* reply chunk.
*
* However, when acknowledging multiple DATA chunks received
* in packets from different source addresses in a single
* SACK, the SACK chunk may be transmitted to one of the
* destination transport addresses from which the DATA or
* control chunks being acknowledged were received.
*
* [BUG: We do not implement the following paragraph.
* Perhaps we should remember the last transport we used for a
* SACK and avoid that (if possible) if we have seen any
* duplicates. --piggy]
*
* When a receiver of a duplicate DATA chunk sends a SACK to a
* multi- homed endpoint it MAY be beneficial to vary the
* destination address and not use the source address of the
* DATA chunk. The reason being that receiving a duplicate
* from a multi-homed endpoint might indicate that the return
* path (as specified in the source address of the DATA chunk)
* for the SACK is broken.
*
* [Send to the address from which we last received a DATA chunk.]
*/
retval->transport = asoc->peer.last_data_from;
retval->subh.sack_hdr =
sctp_addto_chunk(retval, sizeof(sack), &sack);
/* Add the gap ack block information. */
if (num_gabs)
sctp_addto_chunk(retval, sizeof(__u32) * num_gabs,
gabs);
/* Add the duplicate TSN information. */
if (num_dup_tsns)
sctp_addto_chunk(retval, sizeof(__u32) * num_dup_tsns,
sctp_tsnmap_get_dups(map));
nodata:
return retval;
}
/* Make a SHUTDOWN chunk. */
struct sctp_chunk *sctp_make_shutdown(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
sctp_shutdownhdr_t shut;
__u32 ctsn;
ctsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
shut.cum_tsn_ack = htonl(ctsn);
retval = sctp_make_chunk(asoc, SCTP_CID_SHUTDOWN, 0,
sizeof(sctp_shutdownhdr_t));
if (!retval)
goto nodata;
retval->subh.shutdown_hdr =
sctp_addto_chunk(retval, sizeof(shut), &shut);
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
struct sctp_chunk *sctp_make_shutdown_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_SHUTDOWN_ACK, 0, 0);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ACK back to where the SHUTDOWN came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
struct sctp_chunk *sctp_make_shutdown_complete(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
__u8 flags = 0;
/* Set the T-bit if we have no association (vtag will be
* reflected)
*/
flags |= asoc ? 0 : SCTP_CHUNK_FLAG_T;
retval = sctp_make_chunk(asoc, SCTP_CID_SHUTDOWN_COMPLETE, flags, 0);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [Report SHUTDOWN COMPLETE back to where the SHUTDOWN ACK
* came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/* Create an ABORT. Note that we set the T bit if we have no
* association, except when responding to an INIT (sctpimpguide 2.41).
*/
struct sctp_chunk *sctp_make_abort(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const size_t hint)
{
struct sctp_chunk *retval;
__u8 flags = 0;
/* Set the T-bit if we have no association and 'chunk' is not
* an INIT (vtag will be reflected).
*/
if (!asoc) {
if (chunk && chunk->chunk_hdr &&
chunk->chunk_hdr->type == SCTP_CID_INIT)
flags = 0;
else
flags = SCTP_CHUNK_FLAG_T;
}
retval = sctp_make_chunk(asoc, SCTP_CID_ABORT, flags, hint);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ABORT back to where the offender came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/* Helper to create ABORT with a NO_USER_DATA error. */
struct sctp_chunk *sctp_make_abort_no_data(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk, __u32 tsn)
{
struct sctp_chunk *retval;
__be32 payload;
retval = sctp_make_abort(asoc, chunk, sizeof(sctp_errhdr_t)
+ sizeof(tsn));
if (!retval)
goto no_mem;
/* Put the tsn back into network byte order. */
payload = htonl(tsn);
sctp_init_cause(retval, SCTP_ERROR_NO_DATA, sizeof(payload));
sctp_addto_chunk(retval, sizeof(payload), (const void *)&payload);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ABORT back to where the offender came from.]
*/
if (chunk)
retval->transport = chunk->transport;
no_mem:
return retval;
}
/* Helper to create ABORT with a SCTP_ERROR_USER_ABORT error. */
struct sctp_chunk *sctp_make_abort_user(const struct sctp_association *asoc,
const struct msghdr *msg,
size_t paylen)
{
struct sctp_chunk *retval;
void *payload = NULL;
int err;
retval = sctp_make_abort(asoc, NULL, sizeof(sctp_errhdr_t) + paylen);
if (!retval)
goto err_chunk;
if (paylen) {
/* Put the msg_iov together into payload. */
payload = kmalloc(paylen, GFP_KERNEL);
if (!payload)
goto err_payload;
err = memcpy_fromiovec(payload, msg->msg_iov, paylen);
if (err < 0)
goto err_copy;
}
sctp_init_cause(retval, SCTP_ERROR_USER_ABORT, paylen);
sctp_addto_chunk(retval, paylen, payload);
if (paylen)
kfree(payload);
return retval;
err_copy:
kfree(payload);
err_payload:
sctp_chunk_free(retval);
retval = NULL;
err_chunk:
return retval;
}
/* Append bytes to the end of a parameter. Will panic if chunk is not big
* enough.
*/
static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data)
{
void *target;
int chunklen = ntohs(chunk->chunk_hdr->length);
target = skb_put(chunk->skb, len);
if (data)
memcpy(target, data, len);
else
memset(target, 0, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
/* Make an ABORT chunk with a PROTOCOL VIOLATION cause code. */
struct sctp_chunk *sctp_make_abort_violation(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const __u8 *payload,
const size_t paylen)
{
struct sctp_chunk *retval;
struct sctp_paramhdr phdr;
retval = sctp_make_abort(asoc, chunk, sizeof(sctp_errhdr_t) + paylen
+ sizeof(sctp_paramhdr_t));
if (!retval)
goto end;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION, paylen
+ sizeof(sctp_paramhdr_t));
phdr.type = htons(chunk->chunk_hdr->type);
phdr.length = chunk->chunk_hdr->length;
sctp_addto_chunk(retval, paylen, payload);
sctp_addto_param(retval, sizeof(sctp_paramhdr_t), &phdr);
end:
return retval;
}
struct sctp_chunk *sctp_make_violation_paramlen(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
struct sctp_paramhdr *param)
{
struct sctp_chunk *retval;
static const char error[] = "The following parameter had invalid length:";
size_t payload_len = sizeof(error) + sizeof(sctp_errhdr_t) +
sizeof(sctp_paramhdr_t);
retval = sctp_make_abort(asoc, chunk, payload_len);
if (!retval)
goto nodata;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION,
sizeof(error) + sizeof(sctp_paramhdr_t));
sctp_addto_chunk(retval, sizeof(error), error);
sctp_addto_param(retval, sizeof(sctp_paramhdr_t), param);
nodata:
return retval;
}
/* Make a HEARTBEAT chunk. */
struct sctp_chunk *sctp_make_heartbeat(const struct sctp_association *asoc,
const struct sctp_transport *transport)
{
struct sctp_chunk *retval;
sctp_sender_hb_info_t hbinfo;
retval = sctp_make_chunk(asoc, SCTP_CID_HEARTBEAT, 0, sizeof(hbinfo));
if (!retval)
goto nodata;
hbinfo.param_hdr.type = SCTP_PARAM_HEARTBEAT_INFO;
hbinfo.param_hdr.length = htons(sizeof(sctp_sender_hb_info_t));
hbinfo.daddr = transport->ipaddr;
hbinfo.sent_at = jiffies;
hbinfo.hb_nonce = transport->hb_nonce;
/* Cast away the 'const', as this is just telling the chunk
* what transport it belongs to.
*/
retval->transport = (struct sctp_transport *) transport;
retval->subh.hbs_hdr = sctp_addto_chunk(retval, sizeof(hbinfo),
&hbinfo);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_heartbeat_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const void *payload, const size_t paylen)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_HEARTBEAT_ACK, 0, paylen);
if (!retval)
goto nodata;
retval->subh.hbs_hdr = sctp_addto_chunk(retval, paylen, payload);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [HBACK back to where the HEARTBEAT came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Create an Operation Error chunk with the specified space reserved.
* This routine can be used for containing multiple causes in the chunk.
*/
static struct sctp_chunk *sctp_make_op_error_space(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
size_t size)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_ERROR, 0,
sizeof(sctp_errhdr_t) + size);
if (!retval)
goto nodata;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Create an Operation Error chunk of a fixed size,
* specifically, max(asoc->pathmtu, SCTP_DEFAULT_MAXSEGMENT)
* This is a helper function to allocate an error chunk for
* for those invalid parameter codes in which we may not want
* to report all the errors, if the incomming chunk is large
*/
static inline struct sctp_chunk *sctp_make_op_error_fixed(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
size_t size = asoc ? asoc->pathmtu : 0;
if (!size)
size = SCTP_DEFAULT_MAXSEGMENT;
return sctp_make_op_error_space(asoc, chunk, size);
}
/* Create an Operation Error chunk. */
struct sctp_chunk *sctp_make_op_error(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
__be16 cause_code, const void *payload,
size_t paylen, size_t reserve_tail)
{
struct sctp_chunk *retval;
retval = sctp_make_op_error_space(asoc, chunk, paylen + reserve_tail);
if (!retval)
goto nodata;
sctp_init_cause(retval, cause_code, paylen + reserve_tail);
sctp_addto_chunk(retval, paylen, payload);
if (reserve_tail)
sctp_addto_param(retval, reserve_tail, NULL);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_auth(const struct sctp_association *asoc)
{
struct sctp_chunk *retval;
struct sctp_hmac *hmac_desc;
struct sctp_authhdr auth_hdr;
__u8 *hmac;
/* Get the first hmac that the peer told us to use */
hmac_desc = sctp_auth_asoc_get_hmac(asoc);
if (unlikely(!hmac_desc))
return NULL;
retval = sctp_make_chunk(asoc, SCTP_CID_AUTH, 0,
hmac_desc->hmac_len + sizeof(sctp_authhdr_t));
if (!retval)
return NULL;
auth_hdr.hmac_id = htons(hmac_desc->hmac_id);
auth_hdr.shkey_id = htons(asoc->active_key_id);
retval->subh.auth_hdr = sctp_addto_chunk(retval, sizeof(sctp_authhdr_t),
&auth_hdr);
hmac = skb_put(retval->skb, hmac_desc->hmac_len);
memset(hmac, 0, hmac_desc->hmac_len);
/* Adjust the chunk header to include the empty MAC */
retval->chunk_hdr->length =
htons(ntohs(retval->chunk_hdr->length) + hmac_desc->hmac_len);
retval->chunk_end = skb_tail_pointer(retval->skb);
return retval;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Turn an skb into a chunk.
* FIXME: Eventually move the structure directly inside the skb->cb[].
*/
struct sctp_chunk *sctp_chunkify(struct sk_buff *skb,
const struct sctp_association *asoc,
struct sock *sk)
{
struct sctp_chunk *retval;
retval = kmem_cache_zalloc(sctp_chunk_cachep, GFP_ATOMIC);
if (!retval)
goto nodata;
if (!sk) {
SCTP_DEBUG_PRINTK("chunkifying skb %p w/o an sk\n", skb);
}
INIT_LIST_HEAD(&retval->list);
retval->skb = skb;
retval->asoc = (struct sctp_association *)asoc;
retval->has_tsn = 0;
retval->has_ssn = 0;
retval->rtt_in_progress = 0;
retval->sent_at = 0;
retval->singleton = 1;
retval->end_of_packet = 0;
retval->ecn_ce_done = 0;
retval->pdiscard = 0;
/* sctpimpguide-05.txt Section 2.8.2
* M1) Each time a new DATA chunk is transmitted
* set the 'TSN.Missing.Report' count for that TSN to 0. The
* 'TSN.Missing.Report' count will be used to determine missing chunks
* and when to fast retransmit.
*/
retval->tsn_missing_report = 0;
retval->tsn_gap_acked = 0;
retval->fast_retransmit = SCTP_CAN_FRTX;
/* If this is a fragmented message, track all fragments
* of the message (for SEND_FAILED).
*/
retval->msg = NULL;
/* Polish the bead hole. */
INIT_LIST_HEAD(&retval->transmitted_list);
INIT_LIST_HEAD(&retval->frag_list);
SCTP_DBG_OBJCNT_INC(chunk);
atomic_set(&retval->refcnt, 1);
nodata:
return retval;
}
/* Set chunk->source and dest based on the IP header in chunk->skb. */
void sctp_init_addrs(struct sctp_chunk *chunk, union sctp_addr *src,
union sctp_addr *dest)
{
memcpy(&chunk->source, src, sizeof(union sctp_addr));
memcpy(&chunk->dest, dest, sizeof(union sctp_addr));
}
/* Extract the source address from a chunk. */
const union sctp_addr *sctp_source(const struct sctp_chunk *chunk)
{
/* If we have a known transport, use that. */
if (chunk->transport) {
return &chunk->transport->ipaddr;
} else {
/* Otherwise, extract it from the IP header. */
return &chunk->source;
}
}
/* Create a new chunk, setting the type and flags headers from the
* arguments, reserving enough space for a 'paylen' byte payload.
*/
SCTP_STATIC
struct sctp_chunk *sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen)
{
struct sctp_chunk *retval;
sctp_chunkhdr_t *chunk_hdr;
struct sk_buff *skb;
struct sock *sk;
/* No need to allocate LL here, as this is only a chunk. */
skb = alloc_skb(WORD_ROUND(sizeof(sctp_chunkhdr_t) + paylen),
GFP_ATOMIC);
if (!skb)
goto nodata;
/* Make room for the chunk header. */
chunk_hdr = (sctp_chunkhdr_t *)skb_put(skb, sizeof(sctp_chunkhdr_t));
chunk_hdr->type = type;
chunk_hdr->flags = flags;
chunk_hdr->length = htons(sizeof(sctp_chunkhdr_t));
sk = asoc ? asoc->base.sk : NULL;
retval = sctp_chunkify(skb, asoc, sk);
if (!retval) {
kfree_skb(skb);
goto nodata;
}
retval->chunk_hdr = chunk_hdr;
retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(struct sctp_chunkhdr);
/* Determine if the chunk needs to be authenticated */
if (sctp_auth_send_cid(type, asoc))
retval->auth = 1;
/* Set the skb to the belonging sock for accounting. */
skb->sk = sk;
return retval;
nodata:
return NULL;
}
/* Release the memory occupied by a chunk. */
static void sctp_chunk_destroy(struct sctp_chunk *chunk)
{
BUG_ON(!list_empty(&chunk->list));
list_del_init(&chunk->transmitted_list);
/* Free the chunk skb data and the SCTP_chunk stub itself. */
dev_kfree_skb(chunk->skb);
SCTP_DBG_OBJCNT_DEC(chunk);
kmem_cache_free(sctp_chunk_cachep, chunk);
}
/* Possibly, free the chunk. */
void sctp_chunk_free(struct sctp_chunk *chunk)
{
/* Release our reference on the message tracker. */
if (chunk->msg)
sctp_datamsg_put(chunk->msg);
sctp_chunk_put(chunk);
}
/* Grab a reference to the chunk. */
void sctp_chunk_hold(struct sctp_chunk *ch)
{
atomic_inc(&ch->refcnt);
}
/* Release a reference to the chunk. */
void sctp_chunk_put(struct sctp_chunk *ch)
{
if (atomic_dec_and_test(&ch->refcnt))
sctp_chunk_destroy(ch);
}
/* Append bytes to the end of a chunk. Will panic if chunk is not big
* enough.
*/
void *sctp_addto_chunk(struct sctp_chunk *chunk, int len, const void *data)
{
void *target;
void *padding;
int chunklen = ntohs(chunk->chunk_hdr->length);
int padlen = WORD_ROUND(chunklen) - chunklen;
padding = skb_put(chunk->skb, padlen);
target = skb_put(chunk->skb, len);
memset(padding, 0, padlen);
memcpy(target, data, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + padlen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
/* Append bytes to the end of a chunk. Returns NULL if there isn't sufficient
* space in the chunk
*/
void *sctp_addto_chunk_fixed(struct sctp_chunk *chunk,
int len, const void *data)
{
if (skb_tailroom(chunk->skb) >= len)
return sctp_addto_chunk(chunk, len, data);
else
return NULL;
}
/* Append bytes from user space to the end of a chunk. Will panic if
* chunk is not big enough.
* Returns a kernel err value.
*/
int sctp_user_addto_chunk(struct sctp_chunk *chunk, int off, int len,
struct iovec *data)
{
__u8 *target;
int err = 0;
/* Make room in chunk for data. */
target = skb_put(chunk->skb, len);
/* Copy data (whole iovec) into chunk */
if ((err = memcpy_fromiovecend(target, data, off, len)))
goto out;
/* Adjust the chunk length field. */
chunk->chunk_hdr->length =
htons(ntohs(chunk->chunk_hdr->length) + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
out:
return err;
}
/* Helper function to assign a TSN if needed. This assumes that both
* the data_hdr and association have already been assigned.
*/
void sctp_chunk_assign_ssn(struct sctp_chunk *chunk)
{
struct sctp_datamsg *msg;
struct sctp_chunk *lchunk;
struct sctp_stream *stream;
__u16 ssn;
__u16 sid;
if (chunk->has_ssn)
return;
/* All fragments will be on the same stream */
sid = ntohs(chunk->subh.data_hdr->stream);
stream = &chunk->asoc->ssnmap->out;
/* Now assign the sequence number to the entire message.
* All fragments must have the same stream sequence number.
*/
msg = chunk->msg;
list_for_each_entry(lchunk, &msg->chunks, frag_list) {
if (lchunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
ssn = 0;
} else {
if (lchunk->chunk_hdr->flags & SCTP_DATA_LAST_FRAG)
ssn = sctp_ssn_next(stream, sid);
else
ssn = sctp_ssn_peek(stream, sid);
}
lchunk->subh.data_hdr->ssn = htons(ssn);
lchunk->has_ssn = 1;
}
}
/* Helper function to assign a TSN if needed. This assumes that both
* the data_hdr and association have already been assigned.
*/
void sctp_chunk_assign_tsn(struct sctp_chunk *chunk)
{
if (!chunk->has_tsn) {
/* This is the last possible instant to
* assign a TSN.
*/
chunk->subh.data_hdr->tsn =
htonl(sctp_association_get_next_tsn(chunk->asoc));
chunk->has_tsn = 1;
}
}
/* Create a CLOSED association to use with an incoming packet. */
struct sctp_association *sctp_make_temp_asoc(const struct sctp_endpoint *ep,
struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc;
struct sk_buff *skb;
sctp_scope_t scope;
struct sctp_af *af;
/* Create the bare association. */
scope = sctp_scope(sctp_source(chunk));
asoc = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!asoc)
goto nodata;
asoc->temp = 1;
skb = chunk->skb;
/* Create an entry for the source address of the packet. */
af = sctp_get_af_specific(ipver2af(ip_hdr(skb)->version));
if (unlikely(!af))
goto fail;
af->from_skb(&asoc->c.peer_addr, skb, 1);
nodata:
return asoc;
fail:
sctp_association_free(asoc);
return NULL;
}
/* Build a cookie representing asoc.
* This INCLUDES the param header needed to put the cookie in the INIT ACK.
*/
static sctp_cookie_param_t *sctp_pack_cookie(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *init_chunk,
int *cookie_len,
const __u8 *raw_addrs, int addrs_len)
{
sctp_cookie_param_t *retval;
struct sctp_signed_cookie *cookie;
struct scatterlist sg;
int headersize, bodysize;
unsigned int keylen;
char *key;
/* Header size is static data prior to the actual cookie, including
* any padding.
*/
headersize = sizeof(sctp_paramhdr_t) +
(sizeof(struct sctp_signed_cookie) -
sizeof(struct sctp_cookie));
bodysize = sizeof(struct sctp_cookie)
+ ntohs(init_chunk->chunk_hdr->length) + addrs_len;
/* Pad out the cookie to a multiple to make the signature
* functions simpler to write.
*/
if (bodysize % SCTP_COOKIE_MULTIPLE)
bodysize += SCTP_COOKIE_MULTIPLE
- (bodysize % SCTP_COOKIE_MULTIPLE);
*cookie_len = headersize + bodysize;
/* Clear this memory since we are sending this data structure
* out on the network.
*/
retval = kzalloc(*cookie_len, GFP_ATOMIC);
if (!retval)
goto nodata;
cookie = (struct sctp_signed_cookie *) retval->body;
/* Set up the parameter header. */
retval->p.type = SCTP_PARAM_STATE_COOKIE;
retval->p.length = htons(*cookie_len);
/* Copy the cookie part of the association itself. */
cookie->c = asoc->c;
/* Save the raw address list length in the cookie. */
cookie->c.raw_addr_list_len = addrs_len;
/* Remember PR-SCTP capability. */
cookie->c.prsctp_capable = asoc->peer.prsctp_capable;
/* Save adaptation indication in the cookie. */
cookie->c.adaptation_ind = asoc->peer.adaptation_ind;
/* Set an expiration time for the cookie. */
do_gettimeofday(&cookie->c.expiration);
TIMEVAL_ADD(asoc->cookie_life, cookie->c.expiration);
/* Copy the peer's init packet. */
memcpy(&cookie->c.peer_init[0], init_chunk->chunk_hdr,
ntohs(init_chunk->chunk_hdr->length));
/* Copy the raw local address list of the association. */
memcpy((__u8 *)&cookie->c.peer_init[0] +
ntohs(init_chunk->chunk_hdr->length), raw_addrs, addrs_len);
if (sctp_sk(ep->base.sk)->hmac) {
struct hash_desc desc;
/* Sign the message. */
sg_init_one(&sg, &cookie->c, bodysize);
keylen = SCTP_SECRET_SIZE;
key = (char *)ep->secret_key[ep->current_key];
desc.tfm = sctp_sk(ep->base.sk)->hmac;
desc.flags = 0;
if (crypto_hash_setkey(desc.tfm, key, keylen) ||
crypto_hash_digest(&desc, &sg, bodysize, cookie->signature))
goto free_cookie;
}
return retval;
free_cookie:
kfree(retval);
nodata:
*cookie_len = 0;
return NULL;
}
/* Unpack the cookie from COOKIE ECHO chunk, recreating the association. */
struct sctp_association *sctp_unpack_cookie(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk, gfp_t gfp,
int *error, struct sctp_chunk **errp)
{
struct sctp_association *retval = NULL;
struct sctp_signed_cookie *cookie;
struct sctp_cookie *bear_cookie;
int headersize, bodysize, fixed_size;
__u8 *digest = ep->digest;
struct scatterlist sg;
unsigned int keylen, len;
char *key;
sctp_scope_t scope;
struct sk_buff *skb = chunk->skb;
struct timeval tv;
struct hash_desc desc;
/* Header size is static data prior to the actual cookie, including
* any padding.
*/
headersize = sizeof(sctp_chunkhdr_t) +
(sizeof(struct sctp_signed_cookie) -
sizeof(struct sctp_cookie));
bodysize = ntohs(chunk->chunk_hdr->length) - headersize;
fixed_size = headersize + sizeof(struct sctp_cookie);
/* Verify that the chunk looks like it even has a cookie.
* There must be enough room for our cookie and our peer's
* INIT chunk.
*/
len = ntohs(chunk->chunk_hdr->length);
if (len < fixed_size + sizeof(struct sctp_chunkhdr))
goto malformed;
/* Verify that the cookie has been padded out. */
if (bodysize % SCTP_COOKIE_MULTIPLE)
goto malformed;
/* Process the cookie. */
cookie = chunk->subh.cookie_hdr;
bear_cookie = &cookie->c;
if (!sctp_sk(ep->base.sk)->hmac)
goto no_hmac;
/* Check the signature. */
keylen = SCTP_SECRET_SIZE;
sg_init_one(&sg, bear_cookie, bodysize);
key = (char *)ep->secret_key[ep->current_key];
desc.tfm = sctp_sk(ep->base.sk)->hmac;
desc.flags = 0;
memset(digest, 0x00, SCTP_SIGNATURE_SIZE);
if (crypto_hash_setkey(desc.tfm, key, keylen) ||
crypto_hash_digest(&desc, &sg, bodysize, digest)) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
if (memcmp(digest, cookie->signature, SCTP_SIGNATURE_SIZE)) {
/* Try the previous key. */
key = (char *)ep->secret_key[ep->last_key];
memset(digest, 0x00, SCTP_SIGNATURE_SIZE);
if (crypto_hash_setkey(desc.tfm, key, keylen) ||
crypto_hash_digest(&desc, &sg, bodysize, digest)) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
if (memcmp(digest, cookie->signature, SCTP_SIGNATURE_SIZE)) {
/* Yikes! Still bad signature! */
*error = -SCTP_IERROR_BAD_SIG;
goto fail;
}
}
no_hmac:
/* IG Section 2.35.2:
* 3) Compare the port numbers and the verification tag contained
* within the COOKIE ECHO chunk to the actual port numbers and the
* verification tag within the SCTP common header of the received
* packet. If these values do not match the packet MUST be silently
* discarded,
*/
if (ntohl(chunk->sctp_hdr->vtag) != bear_cookie->my_vtag) {
*error = -SCTP_IERROR_BAD_TAG;
goto fail;
}
if (chunk->sctp_hdr->source != bear_cookie->peer_addr.v4.sin_port ||
ntohs(chunk->sctp_hdr->dest) != bear_cookie->my_port) {
*error = -SCTP_IERROR_BAD_PORTS;
goto fail;
}
/* Check to see if the cookie is stale. If there is already
* an association, there is no need to check cookie's expiration
* for init collision case of lost COOKIE ACK.
* If skb has been timestamped, then use the stamp, otherwise
* use current time. This introduces a small possibility that
* that a cookie may be considered expired, but his would only slow
* down the new association establishment instead of every packet.
*/
if (sock_flag(ep->base.sk, SOCK_TIMESTAMP))
skb_get_timestamp(skb, &tv);
else
do_gettimeofday(&tv);
if (!asoc && tv_lt(bear_cookie->expiration, tv)) {
/*
* Section 3.3.10.3 Stale Cookie Error (3)
*
* Cause of error
* ---------------
* Stale Cookie Error: Indicates the receipt of a valid State
* Cookie that has expired.
*/
len = ntohs(chunk->chunk_hdr->length);
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
suseconds_t usecs = (tv.tv_sec -
bear_cookie->expiration.tv_sec) * 1000000L +
tv.tv_usec - bear_cookie->expiration.tv_usec;
__be32 n = htonl(usecs);
sctp_init_cause(*errp, SCTP_ERROR_STALE_COOKIE,
sizeof(n));
sctp_addto_chunk(*errp, sizeof(n), &n);
*error = -SCTP_IERROR_STALE_COOKIE;
} else
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Make a new base association. */
scope = sctp_scope(sctp_source(chunk));
retval = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!retval) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Set up our peer's port number. */
retval->peer.port = ntohs(chunk->sctp_hdr->source);
/* Populate the association from the cookie. */
memcpy(&retval->c, bear_cookie, sizeof(*bear_cookie));
if (sctp_assoc_set_bind_addr_from_cookie(retval, bear_cookie,
GFP_ATOMIC) < 0) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Also, add the destination address. */
if (list_empty(&retval->base.bind_addr.address_list)) {
sctp_add_bind_addr(&retval->base.bind_addr, &chunk->dest,
SCTP_ADDR_SRC, GFP_ATOMIC);
}
retval->next_tsn = retval->c.initial_tsn;
retval->ctsn_ack_point = retval->next_tsn - 1;
retval->addip_serial = retval->c.initial_tsn;
retval->adv_peer_ack_point = retval->ctsn_ack_point;
retval->peer.prsctp_capable = retval->c.prsctp_capable;
retval->peer.adaptation_ind = retval->c.adaptation_ind;
/* The INIT stuff will be done by the side effects. */
return retval;
fail:
if (retval)
sctp_association_free(retval);
return NULL;
malformed:
/* Yikes! The packet is either corrupt or deliberately
* malformed.
*/
*error = -SCTP_IERROR_MALFORMED;
goto fail;
}
/********************************************************************
* 3rd Level Abstractions
********************************************************************/
struct __sctp_missing {
__be32 num_missing;
__be16 type;
} __packed;
/*
* Report a missing mandatory parameter.
*/
static int sctp_process_missing_param(const struct sctp_association *asoc,
sctp_param_t paramtype,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
struct __sctp_missing report;
__u16 len;
len = WORD_ROUND(sizeof(report));
/* Make an ERROR chunk, preparing enough room for
* returning multiple unknown parameters.
*/
if (!*errp)
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
report.num_missing = htonl(1);
report.type = paramtype;
sctp_init_cause(*errp, SCTP_ERROR_MISS_PARAM,
sizeof(report));
sctp_addto_chunk(*errp, sizeof(report), &report);
}
/* Stop processing this chunk. */
return 0;
}
/* Report an Invalid Mandatory Parameter. */
static int sctp_process_inv_mandatory(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
/* Invalid Mandatory Parameter Error has no payload. */
if (!*errp)
*errp = sctp_make_op_error_space(asoc, chunk, 0);
if (*errp)
sctp_init_cause(*errp, SCTP_ERROR_INV_PARAM, 0);
/* Stop processing this chunk. */
return 0;
}
static int sctp_process_inv_paramlength(const struct sctp_association *asoc,
struct sctp_paramhdr *param,
const struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
/* This is a fatal error. Any accumulated non-fatal errors are
* not reported.
*/
if (*errp)
sctp_chunk_free(*errp);
/* Create an error chunk and fill it in with our payload. */
*errp = sctp_make_violation_paramlen(asoc, chunk, param);
return 0;
}
/* Do not attempt to handle the HOST_NAME parm. However, do
* send back an indicator to the peer.
*/
static int sctp_process_hn_param(const struct sctp_association *asoc,
union sctp_params param,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
__u16 len = ntohs(param.p->length);
/* Processing of the HOST_NAME parameter will generate an
* ABORT. If we've accumulated any non-fatal errors, they
* would be unrecognized parameters and we should not include
* them in the ABORT.
*/
if (*errp)
sctp_chunk_free(*errp);
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
sctp_init_cause(*errp, SCTP_ERROR_DNS_FAILED, len);
sctp_addto_chunk(*errp, len, param.v);
}
/* Stop processing this chunk. */
return 0;
}
static int sctp_verify_ext_param(union sctp_params param)
{
__u16 num_ext = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
int have_auth = 0;
int have_asconf = 0;
int i;
for (i = 0; i < num_ext; i++) {
switch (param.ext->chunks[i]) {
case SCTP_CID_AUTH:
have_auth = 1;
break;
case SCTP_CID_ASCONF:
case SCTP_CID_ASCONF_ACK:
have_asconf = 1;
break;
}
}
/* ADD-IP Security: The draft requires us to ABORT or ignore the
* INIT/INIT-ACK if ADD-IP is listed, but AUTH is not. Do this
* only if ADD-IP is turned on and we are not backward-compatible
* mode.
*/
if (sctp_addip_noauth)
return 1;
if (sctp_addip_enable && !have_auth && have_asconf)
return 0;
return 1;
}
static void sctp_process_ext_param(struct sctp_association *asoc,
union sctp_params param)
{
__u16 num_ext = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
int i;
for (i = 0; i < num_ext; i++) {
switch (param.ext->chunks[i]) {
case SCTP_CID_FWD_TSN:
if (sctp_prsctp_enable &&
!asoc->peer.prsctp_capable)
asoc->peer.prsctp_capable = 1;
break;
case SCTP_CID_AUTH:
/* if the peer reports AUTH, assume that he
* supports AUTH.
*/
if (sctp_auth_enable)
asoc->peer.auth_capable = 1;
break;
case SCTP_CID_ASCONF:
case SCTP_CID_ASCONF_ACK:
if (sctp_addip_enable)
asoc->peer.asconf_capable = 1;
break;
default:
break;
}
}
}
/* RFC 3.2.1 & the Implementers Guide 2.2.
*
* The Parameter Types are encoded such that the
* highest-order two bits specify the action that must be
* taken if the processing endpoint does not recognize the
* Parameter Type.
*
* 00 - Stop processing this parameter; do not process any further
* parameters within this chunk
*
* 01 - Stop processing this parameter, do not process any further
* parameters within this chunk, and report the unrecognized
* parameter in an 'Unrecognized Parameter' ERROR chunk.
*
* 10 - Skip this parameter and continue processing.
*
* 11 - Skip this parameter and continue processing but
* report the unrecognized parameter in an
* 'Unrecognized Parameter' ERROR chunk.
*
* Return value:
* SCTP_IERROR_NO_ERROR - continue with the chunk
* SCTP_IERROR_ERROR - stop and report an error.
* SCTP_IERROR_NOMEME - out of memory.
*/
static sctp_ierror_t sctp_process_unk_param(const struct sctp_association *asoc,
union sctp_params param,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
int retval = SCTP_IERROR_NO_ERROR;
switch (param.p->type & SCTP_PARAM_ACTION_MASK) {
case SCTP_PARAM_ACTION_DISCARD:
retval = SCTP_IERROR_ERROR;
break;
case SCTP_PARAM_ACTION_SKIP:
break;
case SCTP_PARAM_ACTION_DISCARD_ERR:
retval = SCTP_IERROR_ERROR;
/* Fall through */
case SCTP_PARAM_ACTION_SKIP_ERR:
/* Make an ERROR chunk, preparing enough room for
* returning multiple unknown parameters.
*/
if (NULL == *errp)
*errp = sctp_make_op_error_fixed(asoc, chunk);
if (*errp) {
if (!sctp_init_cause_fixed(*errp, SCTP_ERROR_UNKNOWN_PARAM,
WORD_ROUND(ntohs(param.p->length))))
sctp_addto_chunk_fixed(*errp,
WORD_ROUND(ntohs(param.p->length)),
param.v);
} else {
/* If there is no memory for generating the ERROR
* report as specified, an ABORT will be triggered
* to the peer and the association won't be
* established.
*/
retval = SCTP_IERROR_NOMEM;
}
break;
default:
break;
}
return retval;
}
/* Verify variable length parameters
* Return values:
* SCTP_IERROR_ABORT - trigger an ABORT
* SCTP_IERROR_NOMEM - out of memory (abort)
* SCTP_IERROR_ERROR - stop processing, trigger an ERROR
* SCTP_IERROR_NO_ERROR - continue with the chunk
*/
static sctp_ierror_t sctp_verify_param(const struct sctp_association *asoc,
union sctp_params param,
sctp_cid_t cid,
struct sctp_chunk *chunk,
struct sctp_chunk **err_chunk)
{
struct sctp_hmac_algo_param *hmacs;
int retval = SCTP_IERROR_NO_ERROR;
__u16 n_elt, id = 0;
int i;
/* FIXME - This routine is not looking at each parameter per the
* chunk type, i.e., unrecognized parameters should be further
* identified based on the chunk id.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV4_ADDRESS:
case SCTP_PARAM_IPV6_ADDRESS:
case SCTP_PARAM_COOKIE_PRESERVATIVE:
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
case SCTP_PARAM_STATE_COOKIE:
case SCTP_PARAM_HEARTBEAT_INFO:
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
case SCTP_PARAM_ECN_CAPABLE:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
break;
case SCTP_PARAM_SUPPORTED_EXT:
if (!sctp_verify_ext_param(param))
return SCTP_IERROR_ABORT;
break;
case SCTP_PARAM_SET_PRIMARY:
if (sctp_addip_enable)
break;
goto fallthrough;
case SCTP_PARAM_HOST_NAME_ADDRESS:
/* Tell the peer, we won't support this param. */
sctp_process_hn_param(asoc, param, chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (sctp_prsctp_enable)
break;
goto fallthrough;
case SCTP_PARAM_RANDOM:
if (!sctp_auth_enable)
goto fallthrough;
/* SCTP-AUTH: Secion 6.1
* If the random number is not 32 byte long the association
* MUST be aborted. The ABORT chunk SHOULD contain the error
* cause 'Protocol Violation'.
*/
if (SCTP_AUTH_RANDOM_LENGTH !=
ntohs(param.p->length) - sizeof(sctp_paramhdr_t)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_CHUNKS:
if (!sctp_auth_enable)
goto fallthrough;
/* SCTP-AUTH: Section 3.2
* The CHUNKS parameter MUST be included once in the INIT or
* INIT-ACK chunk if the sender wants to receive authenticated
* chunks. Its maximum length is 260 bytes.
*/
if (260 < ntohs(param.p->length)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!sctp_auth_enable)
goto fallthrough;
hmacs = (struct sctp_hmac_algo_param *)param.p;
n_elt = (ntohs(param.p->length) - sizeof(sctp_paramhdr_t)) >> 1;
/* SCTP-AUTH: Section 6.1
* The HMAC algorithm based on SHA-1 MUST be supported and
* included in the HMAC-ALGO parameter.
*/
for (i = 0; i < n_elt; i++) {
id = ntohs(hmacs->hmac_ids[i]);
if (id == SCTP_AUTH_HMAC_ID_SHA1)
break;
}
if (id != SCTP_AUTH_HMAC_ID_SHA1) {
sctp_process_inv_paramlength(asoc, param.p, chunk,
err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
fallthrough:
default:
SCTP_DEBUG_PRINTK("Unrecognized param: %d for chunk %d.\n",
ntohs(param.p->type), cid);
retval = sctp_process_unk_param(asoc, param, chunk, err_chunk);
break;
}
return retval;
}
/* Verify the INIT packet before we process it. */
int sctp_verify_init(const struct sctp_association *asoc,
sctp_cid_t cid,
sctp_init_chunk_t *peer_init,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
union sctp_params param;
int has_cookie = 0;
int result;
/* Verify stream values are non-zero. */
if ((0 == peer_init->init_hdr.num_outbound_streams) ||
(0 == peer_init->init_hdr.num_inbound_streams) ||
(0 == peer_init->init_hdr.init_tag) ||
(SCTP_DEFAULT_MINWINDOW > ntohl(peer_init->init_hdr.a_rwnd))) {
return sctp_process_inv_mandatory(asoc, chunk, errp);
}
/* Check for missing mandatory parameters. */
sctp_walk_params(param, peer_init, init_hdr.params) {
if (SCTP_PARAM_STATE_COOKIE == param.p->type)
has_cookie = 1;
} /* for (loop through all parameters) */
/* There is a possibility that a parameter length was bad and
* in that case we would have stoped walking the parameters.
* The current param.p would point at the bad one.
* Current consensus on the mailing list is to generate a PROTOCOL
* VIOLATION error. We build the ERROR chunk here and let the normal
* error handling code build and send the packet.
*/
if (param.v != (void*)chunk->chunk_end)
return sctp_process_inv_paramlength(asoc, param.p, chunk, errp);
/* The only missing mandatory param possible today is
* the state cookie for an INIT-ACK chunk.
*/
if ((SCTP_CID_INIT_ACK == cid) && !has_cookie)
return sctp_process_missing_param(asoc, SCTP_PARAM_STATE_COOKIE,
chunk, errp);
/* Verify all the variable length parameters */
sctp_walk_params(param, peer_init, init_hdr.params) {
result = sctp_verify_param(asoc, param, cid, chunk, errp);
switch (result) {
case SCTP_IERROR_ABORT:
case SCTP_IERROR_NOMEM:
return 0;
case SCTP_IERROR_ERROR:
return 1;
case SCTP_IERROR_NO_ERROR:
default:
break;
}
} /* for (loop through all parameters) */
return 1;
}
/* Unpack the parameters in an INIT packet into an association.
* Returns 0 on failure, else success.
* FIXME: This is an association method.
*/
int sctp_process_init(struct sctp_association *asoc, struct sctp_chunk *chunk,
const union sctp_addr *peer_addr,
sctp_init_chunk_t *peer_init, gfp_t gfp)
{
union sctp_params param;
struct sctp_transport *transport;
struct list_head *pos, *temp;
struct sctp_af *af;
union sctp_addr addr;
char *cookie;
int src_match = 0;
/* We must include the address that the INIT packet came from.
* This is the only address that matters for an INIT packet.
* When processing a COOKIE ECHO, we retrieve the from address
* of the INIT from the cookie.
*/
/* This implementation defaults to making the first transport
* added as the primary transport. The source address seems to
* be a a better choice than any of the embedded addresses.
*/
if(!sctp_assoc_add_peer(asoc, peer_addr, gfp, SCTP_ACTIVE))
goto nomem;
if (sctp_cmp_addr_exact(sctp_source(chunk), peer_addr))
src_match = 1;
/* Process the initialization parameters. */
sctp_walk_params(param, peer_init, init_hdr.params) {
if (!src_match && (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
param.p->type == SCTP_PARAM_IPV6_ADDRESS)) {
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr,
chunk->sctp_hdr->source, 0);
if (sctp_cmp_addr_exact(sctp_source(chunk), &addr))
src_match = 1;
}
if (!sctp_process_param(asoc, param, peer_addr, gfp))
goto clean_up;
}
/* source address of chunk may not match any valid address */
if (!src_match)
goto clean_up;
/* AUTH: After processing the parameters, make sure that we
* have all the required info to potentially do authentications.
*/
if (asoc->peer.auth_capable && (!asoc->peer.peer_random ||
!asoc->peer.peer_hmacs))
asoc->peer.auth_capable = 0;
/* In a non-backward compatible mode, if the peer claims
* support for ADD-IP but not AUTH, the ADD-IP spec states
* that we MUST ABORT the association. Section 6. The section
* also give us an option to silently ignore the packet, which
* is what we'll do here.
*/
if (!sctp_addip_noauth &&
(asoc->peer.asconf_capable && !asoc->peer.auth_capable)) {
asoc->peer.addip_disabled_mask |= (SCTP_PARAM_ADD_IP |
SCTP_PARAM_DEL_IP |
SCTP_PARAM_SET_PRIMARY);
asoc->peer.asconf_capable = 0;
goto clean_up;
}
/* Walk list of transports, removing transports in the UNKNOWN state. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (transport->state == SCTP_UNKNOWN) {
sctp_assoc_rm_peer(asoc, transport);
}
}
/* The fixed INIT headers are always in network byte
* order.
*/
asoc->peer.i.init_tag =
ntohl(peer_init->init_hdr.init_tag);
asoc->peer.i.a_rwnd =
ntohl(peer_init->init_hdr.a_rwnd);
asoc->peer.i.num_outbound_streams =
ntohs(peer_init->init_hdr.num_outbound_streams);
asoc->peer.i.num_inbound_streams =
ntohs(peer_init->init_hdr.num_inbound_streams);
asoc->peer.i.initial_tsn =
ntohl(peer_init->init_hdr.initial_tsn);
/* Apply the upper bounds for output streams based on peer's
* number of inbound streams.
*/
if (asoc->c.sinit_num_ostreams >
ntohs(peer_init->init_hdr.num_inbound_streams)) {
asoc->c.sinit_num_ostreams =
ntohs(peer_init->init_hdr.num_inbound_streams);
}
if (asoc->c.sinit_max_instreams >
ntohs(peer_init->init_hdr.num_outbound_streams)) {
asoc->c.sinit_max_instreams =
ntohs(peer_init->init_hdr.num_outbound_streams);
}
/* Copy Initiation tag from INIT to VT_peer in cookie. */
asoc->c.peer_vtag = asoc->peer.i.init_tag;
/* Peer Rwnd : Current calculated value of the peer's rwnd. */
asoc->peer.rwnd = asoc->peer.i.a_rwnd;
/* Copy cookie in case we need to resend COOKIE-ECHO. */
cookie = asoc->peer.cookie;
if (cookie) {
asoc->peer.cookie = kmemdup(cookie, asoc->peer.cookie_len, gfp);
if (!asoc->peer.cookie)
goto clean_up;
}
/* RFC 2960 7.2.1 The initial value of ssthresh MAY be arbitrarily
* high (for example, implementations MAY use the size of the receiver
* advertised window).
*/
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
transport->ssthresh = asoc->peer.i.a_rwnd;
}
/* Set up the TSN tracking pieces. */
if (!sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, gfp))
goto clean_up;
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* The stream sequence number in all the streams shall start
* from 0 when the association is established. Also, when the
* stream sequence number reaches the value 65535 the next
* stream sequence number shall be set to 0.
*/
/* Allocate storage for the negotiated streams if it is not a temporary
* association.
*/
if (!asoc->temp) {
int error;
asoc->ssnmap = sctp_ssnmap_new(asoc->c.sinit_max_instreams,
asoc->c.sinit_num_ostreams, gfp);
if (!asoc->ssnmap)
goto clean_up;
error = sctp_assoc_set_id(asoc, gfp);
if (error)
goto clean_up;
}
/* ADDIP Section 4.1 ASCONF Chunk Procedures
*
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do the following:
* ...
* A2) A serial number should be assigned to the Chunk. The serial
* number should be a monotonically increasing number. All serial
* numbers are defined to be initialized at the start of the
* association to the same value as the Initial TSN.
*/
asoc->peer.addip_serial = asoc->peer.i.initial_tsn - 1;
return 1;
clean_up:
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (transport->state != SCTP_ACTIVE)
sctp_assoc_rm_peer(asoc, transport);
}
nomem:
return 0;
}
/* Update asoc with the option described in param.
*
* RFC2960 3.3.2.1 Optional/Variable Length Parameters in INIT
*
* asoc is the association to update.
* param is the variable length parameter to use for update.
* cid tells us if this is an INIT, INIT ACK or COOKIE ECHO.
* If the current packet is an INIT we want to minimize the amount of
* work we do. In particular, we should not build transport
* structures for the addresses.
*/
static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp)
{
union sctp_addr addr;
int i;
__u16 sat;
int retval = 1;
sctp_scope_t scope;
time_t stale;
struct sctp_af *af;
union sctp_addr_param *addr_param;
struct sctp_transport *t;
/* We maintain all INIT parameters in network byte order all the
* time. This allows us to not worry about whether the parameters
* came from a fresh INIT, and INIT ACK, or were stored in a cookie.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 != asoc->base.sk->sk_family)
break;
goto do_addr_param;
case SCTP_PARAM_IPV4_ADDRESS:
/* v4 addresses are not allowed on v6-only socket */
if (ipv6_only_sock(asoc->base.sk))
break;
do_addr_param:
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0);
scope = sctp_scope(peer_addr);
if (sctp_in_scope(&addr, scope))
if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
return 0;
break;
case SCTP_PARAM_COOKIE_PRESERVATIVE:
if (!sctp_cookie_preserve_enable)
break;
stale = ntohl(param.life->lifespan_increment);
/* Suggested Cookie Life span increment's unit is msec,
* (1/1000sec).
*/
asoc->cookie_life.tv_sec += stale / 1000;
asoc->cookie_life.tv_usec += (stale % 1000) * 1000;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
SCTP_DEBUG_PRINTK("unimplemented SCTP_HOST_NAME_ADDRESS\n");
break;
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
/* Turn off the default values first so we'll know which
* ones are really set by the peer.
*/
asoc->peer.ipv4_address = 0;
asoc->peer.ipv6_address = 0;
/* Assume that peer supports the address family
* by which it sends a packet.
*/
if (peer_addr->sa.sa_family == AF_INET6)
asoc->peer.ipv6_address = 1;
else if (peer_addr->sa.sa_family == AF_INET)
asoc->peer.ipv4_address = 1;
/* Cycle through address types; avoid divide by 0. */
sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
if (sat)
sat /= sizeof(__u16);
for (i = 0; i < sat; ++i) {
switch (param.sat->types[i]) {
case SCTP_PARAM_IPV4_ADDRESS:
asoc->peer.ipv4_address = 1;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 == asoc->base.sk->sk_family)
asoc->peer.ipv6_address = 1;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
asoc->peer.hostname_address = 1;
break;
default: /* Just ignore anything else. */
break;
}
}
break;
case SCTP_PARAM_STATE_COOKIE:
asoc->peer.cookie_len =
ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
asoc->peer.cookie = param.cookie->body;
break;
case SCTP_PARAM_HEARTBEAT_INFO:
/* Would be odd to receive, but it causes no problems. */
break;
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
/* Rejected during verify stage. */
break;
case SCTP_PARAM_ECN_CAPABLE:
asoc->peer.ecn_capable = 1;
break;
case SCTP_PARAM_ADAPTATION_LAYER_IND:
asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
break;
case SCTP_PARAM_SET_PRIMARY:
if (!sctp_addip_enable)
goto fall_through;
addr_param = param.v + sizeof(sctp_addip_param_t);
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, addr_param,
htons(asoc->peer.port), 0);
/* if the address is invalid, we can't process it.
* XXX: see spec for what to do.
*/
if (!af->addr_valid(&addr, NULL, NULL))
break;
t = sctp_assoc_lookup_paddr(asoc, &addr);
if (!t)
break;
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_PARAM_SUPPORTED_EXT:
sctp_process_ext_param(asoc, param);
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (sctp_prsctp_enable) {
asoc->peer.prsctp_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_RANDOM:
if (!sctp_auth_enable)
goto fall_through;
/* Save peer's random parameter */
asoc->peer.peer_random = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_random) {
retval = 0;
break;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!sctp_auth_enable)
goto fall_through;
/* Save peer's HMAC list */
asoc->peer.peer_hmacs = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_hmacs) {
retval = 0;
break;
}
/* Set the default HMAC the peer requested*/
sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
break;
case SCTP_PARAM_CHUNKS:
if (!sctp_auth_enable)
goto fall_through;
asoc->peer.peer_chunks = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_chunks)
retval = 0;
break;
fall_through:
default:
/* Any unrecognized parameters should have been caught
* and handled by sctp_verify_param() which should be
* called prior to this routine. Simply log the error
* here.
*/
SCTP_DEBUG_PRINTK("Ignoring param: %d for association %p.\n",
ntohs(param.p->type), asoc);
break;
}
return retval;
}
/* Select a new verification tag. */
__u32 sctp_generate_tag(const struct sctp_endpoint *ep)
{
/* I believe that this random number generator complies with RFC1750.
* A tag of 0 is reserved for special cases (e.g. INIT).
*/
__u32 x;
do {
get_random_bytes(&x, sizeof(__u32));
} while (x == 0);
return x;
}
/* Select an initial TSN to send during startup. */
__u32 sctp_generate_tsn(const struct sctp_endpoint *ep)
{
__u32 retval;
get_random_bytes(&retval, sizeof(__u32));
return retval;
}
/*
* ADDIP 3.1.1 Address Configuration Change Chunk (ASCONF)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC1 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Serial Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter #1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / .... /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter #N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Address Parameter and other parameter will not be wrapped in this function
*/
static struct sctp_chunk *sctp_make_asconf(struct sctp_association *asoc,
union sctp_addr *addr,
int vparam_len)
{
sctp_addiphdr_t asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
union sctp_addr_param addrparam;
int addrlen;
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
length += addrlen;
/* Create the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_ASCONF, 0, length);
if (!retval)
return NULL;
asconf.serial = htonl(asoc->addip_serial++);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
/* ADDIP
* 3.2.1 Add IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC001 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 3.2.2 Delete IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC002 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc,
union sctp_addr *laddr,
struct sockaddr *addrs,
int addrcnt,
__be16 flags)
{
sctp_addip_param_t param;
struct sctp_chunk *retval;
union sctp_addr_param addr_param;
union sctp_addr *addr;
void *addr_buf;
struct sctp_af *af;
int paramlen = sizeof(param);
int addr_param_len = 0;
int totallen = 0;
int i;
int del_pickup = 0;
/* Get total length of all the address parameters. */
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
totallen += paramlen;
totallen += addr_param_len;
addr_buf += af->sockaddr_len;
if (asoc->asconf_addr_del_pending && !del_pickup) {
/* reuse the parameter length from the same scope one */
totallen += paramlen;
totallen += addr_param_len;
del_pickup = 1;
SCTP_DEBUG_PRINTK("mkasconf_update_ip: picked same-scope del_pending addr, totallen for all addresses is %d\n", totallen);
}
}
/* Create an asconf chunk with the required length. */
retval = sctp_make_asconf(asoc, laddr, totallen);
if (!retval)
return NULL;
/* Add the address parameters to the asconf chunk. */
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
param.param_hdr.type = flags;
param.param_hdr.length = htons(paramlen + addr_param_len);
param.crr_id = i;
sctp_addto_chunk(retval, paramlen, ¶m);
sctp_addto_chunk(retval, addr_param_len, &addr_param);
addr_buf += af->sockaddr_len;
}
if (flags == SCTP_PARAM_ADD_IP && del_pickup) {
addr = asoc->asconf_addr_del_pending;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
param.param_hdr.type = SCTP_PARAM_DEL_IP;
param.param_hdr.length = htons(paramlen + addr_param_len);
param.crr_id = i;
sctp_addto_chunk(retval, paramlen, ¶m);
sctp_addto_chunk(retval, addr_param_len, &addr_param);
}
return retval;
}
/* ADDIP
* 3.2.4 Set Primary IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type =0xC004 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Create an ASCONF chunk with Set Primary IP address parameter.
*/
struct sctp_chunk *sctp_make_asconf_set_prim(struct sctp_association *asoc,
union sctp_addr *addr)
{
sctp_addip_param_t param;
struct sctp_chunk *retval;
int len = sizeof(param);
union sctp_addr_param addrparam;
int addrlen;
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
len += addrlen;
/* Create the chunk and make asconf header. */
retval = sctp_make_asconf(asoc, addr, len);
if (!retval)
return NULL;
param.param_hdr.type = SCTP_PARAM_SET_PRIMARY;
param.param_hdr.length = htons(len);
param.crr_id = 0;
sctp_addto_chunk(retval, sizeof(param), ¶m);
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
/* ADDIP 3.1.2 Address Configuration Acknowledgement Chunk (ASCONF-ACK)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0x80 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Serial Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter Response#1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / .... /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter Response#N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Create an ASCONF_ACK chunk with enough space for the parameter responses.
*/
static struct sctp_chunk *sctp_make_asconf_ack(const struct sctp_association *asoc,
__u32 serial, int vparam_len)
{
sctp_addiphdr_t asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
/* Create the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_ASCONF_ACK, 0, length);
if (!retval)
return NULL;
asconf.serial = htonl(serial);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
return retval;
}
/* Add response parameters to an ASCONF_ACK chunk. */
static void sctp_add_asconf_response(struct sctp_chunk *chunk, __be32 crr_id,
__be16 err_code, sctp_addip_param_t *asconf_param)
{
sctp_addip_param_t ack_param;
sctp_errhdr_t err_param;
int asconf_param_len = 0;
int err_param_len = 0;
__be16 response_type;
if (SCTP_ERROR_NO_ERROR == err_code) {
response_type = SCTP_PARAM_SUCCESS_REPORT;
} else {
response_type = SCTP_PARAM_ERR_CAUSE;
err_param_len = sizeof(err_param);
if (asconf_param)
asconf_param_len =
ntohs(asconf_param->param_hdr.length);
}
/* Add Success Indication or Error Cause Indication parameter. */
ack_param.param_hdr.type = response_type;
ack_param.param_hdr.length = htons(sizeof(ack_param) +
err_param_len +
asconf_param_len);
ack_param.crr_id = crr_id;
sctp_addto_chunk(chunk, sizeof(ack_param), &ack_param);
if (SCTP_ERROR_NO_ERROR == err_code)
return;
/* Add Error Cause parameter. */
err_param.cause = err_code;
err_param.length = htons(err_param_len + asconf_param_len);
sctp_addto_chunk(chunk, err_param_len, &err_param);
/* Add the failed TLV copied from ASCONF chunk. */
if (asconf_param)
sctp_addto_chunk(chunk, asconf_param_len, asconf_param);
}
/* Process a asconf parameter. */
static __be16 sctp_process_asconf_param(struct sctp_association *asoc,
struct sctp_chunk *asconf,
sctp_addip_param_t *asconf_param)
{
struct sctp_transport *peer;
struct sctp_af *af;
union sctp_addr addr;
union sctp_addr_param *addr_param;
addr_param = (void *)asconf_param + sizeof(sctp_addip_param_t);
if (asconf_param->param_hdr.type != SCTP_PARAM_ADD_IP &&
asconf_param->param_hdr.type != SCTP_PARAM_DEL_IP &&
asconf_param->param_hdr.type != SCTP_PARAM_SET_PRIMARY)
return SCTP_ERROR_UNKNOWN_PARAM;
switch (addr_param->p.type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (!asoc->peer.ipv6_address)
return SCTP_ERROR_DNS_FAILED;
break;
case SCTP_PARAM_IPV4_ADDRESS:
if (!asoc->peer.ipv4_address)
return SCTP_ERROR_DNS_FAILED;
break;
default:
return SCTP_ERROR_DNS_FAILED;
}
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
if (unlikely(!af))
return SCTP_ERROR_DNS_FAILED;
af->from_addr_param(&addr, addr_param, htons(asoc->peer.port), 0);
/* ADDIP 4.2.1 This parameter MUST NOT contain a broadcast
* or multicast address.
* (note: wildcard is permitted and requires special handling so
* make sure we check for that)
*/
if (!af->is_any(&addr) && !af->addr_valid(&addr, NULL, asconf->skb))
return SCTP_ERROR_DNS_FAILED;
switch (asconf_param->param_hdr.type) {
case SCTP_PARAM_ADD_IP:
/* Section 4.2.1:
* If the address 0.0.0.0 or ::0 is provided, the source
* address of the packet MUST be added.
*/
if (af->is_any(&addr))
memcpy(&addr, &asconf->source, sizeof(addr));
/* ADDIP 4.3 D9) If an endpoint receives an ADD IP address
* request and does not have the local resources to add this
* new address to the association, it MUST return an Error
* Cause TLV set to the new error code 'Operation Refused
* Due to Resource Shortage'.
*/
peer = sctp_assoc_add_peer(asoc, &addr, GFP_ATOMIC, SCTP_UNCONFIRMED);
if (!peer)
return SCTP_ERROR_RSRC_LOW;
/* Start the heartbeat timer. */
if (!mod_timer(&peer->hb_timer, sctp_transport_timeout(peer)))
sctp_transport_hold(peer);
asoc->new_transport = peer;
break;
case SCTP_PARAM_DEL_IP:
/* ADDIP 4.3 D7) If a request is received to delete the
* last remaining IP address of a peer endpoint, the receiver
* MUST send an Error Cause TLV with the error cause set to the
* new error code 'Request to Delete Last Remaining IP Address'.
*/
if (asoc->peer.transport_count == 1)
return SCTP_ERROR_DEL_LAST_IP;
/* ADDIP 4.3 D8) If a request is received to delete an IP
* address which is also the source address of the IP packet
* which contained the ASCONF chunk, the receiver MUST reject
* this request. To reject the request the receiver MUST send
* an Error Cause TLV set to the new error code 'Request to
* Delete Source IP Address'
*/
if (sctp_cmp_addr_exact(&asconf->source, &addr))
return SCTP_ERROR_DEL_SRC_IP;
/* Section 4.2.2
* If the address 0.0.0.0 or ::0 is provided, all
* addresses of the peer except the source address of the
* packet MUST be deleted.
*/
if (af->is_any(&addr)) {
sctp_assoc_set_primary(asoc, asconf->transport);
sctp_assoc_del_nonprimary_peers(asoc,
asconf->transport);
} else
sctp_assoc_del_peer(asoc, &addr);
break;
case SCTP_PARAM_SET_PRIMARY:
/* ADDIP Section 4.2.4
* If the address 0.0.0.0 or ::0 is provided, the receiver
* MAY mark the source address of the packet as its
* primary.
*/
if (af->is_any(&addr))
memcpy(&addr.v4, sctp_source(asconf), sizeof(addr));
peer = sctp_assoc_lookup_paddr(asoc, &addr);
if (!peer)
return SCTP_ERROR_DNS_FAILED;
sctp_assoc_set_primary(asoc, peer);
break;
}
return SCTP_ERROR_NO_ERROR;
}
/* Verify the ASCONF packet before we process it. */
int sctp_verify_asconf(const struct sctp_association *asoc,
struct sctp_paramhdr *param_hdr, void *chunk_end,
struct sctp_paramhdr **errp) {
sctp_addip_param_t *asconf_param;
union sctp_params param;
int length, plen;
param.v = (sctp_paramhdr_t *) param_hdr;
while (param.v <= chunk_end - sizeof(sctp_paramhdr_t)) {
length = ntohs(param.p->length);
*errp = param.p;
if (param.v > chunk_end - length ||
length < sizeof(sctp_paramhdr_t))
return 0;
switch (param.p->type) {
case SCTP_PARAM_ADD_IP:
case SCTP_PARAM_DEL_IP:
case SCTP_PARAM_SET_PRIMARY:
asconf_param = (sctp_addip_param_t *)param.v;
plen = ntohs(asconf_param->param_hdr.length);
if (plen < sizeof(sctp_addip_param_t) +
sizeof(sctp_paramhdr_t))
return 0;
break;
case SCTP_PARAM_SUCCESS_REPORT:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
if (length != sizeof(sctp_addip_param_t))
return 0;
break;
default:
break;
}
param.v += WORD_ROUND(length);
}
if (param.v != chunk_end)
return 0;
return 1;
}
/* Process an incoming ASCONF chunk with the next expected serial no. and
* return an ASCONF_ACK chunk to be sent in response.
*/
struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc,
struct sctp_chunk *asconf)
{
sctp_addiphdr_t *hdr;
union sctp_addr_param *addr_param;
sctp_addip_param_t *asconf_param;
struct sctp_chunk *asconf_ack;
__be16 err_code;
int length = 0;
int chunk_len;
__u32 serial;
int all_param_pass = 1;
chunk_len = ntohs(asconf->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
hdr = (sctp_addiphdr_t *)asconf->skb->data;
serial = ntohl(hdr->serial);
/* Skip the addiphdr and store a pointer to address parameter. */
length = sizeof(sctp_addiphdr_t);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
chunk_len -= length;
/* Skip the address parameter and store a pointer to the first
* asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
chunk_len -= length;
/* create an ASCONF_ACK chunk.
* Based on the definitions of parameters, we know that the size of
* ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF
* parameters.
*/
asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4);
if (!asconf_ack)
goto done;
/* Process the TLVs contained within the ASCONF chunk. */
while (chunk_len > 0) {
err_code = sctp_process_asconf_param(asoc, asconf,
asconf_param);
/* ADDIP 4.1 A7)
* If an error response is received for a TLV parameter,
* all TLVs with no response before the failed TLV are
* considered successful if not reported. All TLVs after
* the failed response are considered unsuccessful unless
* a specific success indication is present for the parameter.
*/
if (SCTP_ERROR_NO_ERROR != err_code)
all_param_pass = 0;
if (!all_param_pass)
sctp_add_asconf_response(asconf_ack,
asconf_param->crr_id, err_code,
asconf_param);
/* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add
* an IP address sends an 'Out of Resource' in its response, it
* MUST also fail any subsequent add or delete requests bundled
* in the ASCONF.
*/
if (SCTP_ERROR_RSRC_LOW == err_code)
goto done;
/* Move to the next ASCONF param. */
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
chunk_len -= length;
}
done:
asoc->peer.addip_serial++;
/* If we are sending a new ASCONF_ACK hold a reference to it in assoc
* after freeing the reference to old asconf ack if any.
*/
if (asconf_ack) {
sctp_chunk_hold(asconf_ack);
list_add_tail(&asconf_ack->transmitted_list,
&asoc->asconf_ack_list);
}
return asconf_ack;
}
/* Process a asconf parameter that is successfully acked. */
static void sctp_asconf_param_success(struct sctp_association *asoc,
sctp_addip_param_t *asconf_param)
{
struct sctp_af *af;
union sctp_addr addr;
struct sctp_bind_addr *bp = &asoc->base.bind_addr;
union sctp_addr_param *addr_param;
struct sctp_transport *transport;
struct sctp_sockaddr_entry *saddr;
addr_param = (void *)asconf_param + sizeof(sctp_addip_param_t);
/* We have checked the packet before, so we do not check again. */
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
af->from_addr_param(&addr, addr_param, htons(bp->port), 0);
switch (asconf_param->param_hdr.type) {
case SCTP_PARAM_ADD_IP:
/* This is always done in BH context with a socket lock
* held, so the list can not change.
*/
local_bh_disable();
list_for_each_entry(saddr, &bp->address_list, list) {
if (sctp_cmp_addr_exact(&saddr->a, &addr))
saddr->state = SCTP_ADDR_SRC;
}
local_bh_enable();
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
dst_release(transport->dst);
transport->dst = NULL;
}
break;
case SCTP_PARAM_DEL_IP:
local_bh_disable();
sctp_del_bind_addr(bp, &addr);
if (asoc->asconf_addr_del_pending != NULL &&
sctp_cmp_addr_exact(asoc->asconf_addr_del_pending, &addr)) {
kfree(asoc->asconf_addr_del_pending);
asoc->asconf_addr_del_pending = NULL;
}
local_bh_enable();
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
dst_release(transport->dst);
transport->dst = NULL;
}
break;
default:
break;
}
}
/* Get the corresponding ASCONF response error code from the ASCONF_ACK chunk
* for the given asconf parameter. If there is no response for this parameter,
* return the error code based on the third argument 'no_err'.
* ADDIP 4.1
* A7) If an error response is received for a TLV parameter, all TLVs with no
* response before the failed TLV are considered successful if not reported.
* All TLVs after the failed response are considered unsuccessful unless a
* specific success indication is present for the parameter.
*/
static __be16 sctp_get_asconf_response(struct sctp_chunk *asconf_ack,
sctp_addip_param_t *asconf_param,
int no_err)
{
sctp_addip_param_t *asconf_ack_param;
sctp_errhdr_t *err_param;
int length;
int asconf_ack_len;
__be16 err_code;
if (no_err)
err_code = SCTP_ERROR_NO_ERROR;
else
err_code = SCTP_ERROR_REQ_REFUSED;
asconf_ack_len = ntohs(asconf_ack->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
/* Skip the addiphdr from the asconf_ack chunk and store a pointer to
* the first asconf_ack parameter.
*/
length = sizeof(sctp_addiphdr_t);
asconf_ack_param = (sctp_addip_param_t *)(asconf_ack->skb->data +
length);
asconf_ack_len -= length;
while (asconf_ack_len > 0) {
if (asconf_ack_param->crr_id == asconf_param->crr_id) {
switch(asconf_ack_param->param_hdr.type) {
case SCTP_PARAM_SUCCESS_REPORT:
return SCTP_ERROR_NO_ERROR;
case SCTP_PARAM_ERR_CAUSE:
length = sizeof(sctp_addip_param_t);
err_param = (void *)asconf_ack_param + length;
asconf_ack_len -= length;
if (asconf_ack_len > 0)
return err_param->cause;
else
return SCTP_ERROR_INV_PARAM;
break;
default:
return SCTP_ERROR_INV_PARAM;
}
}
length = ntohs(asconf_ack_param->param_hdr.length);
asconf_ack_param = (void *)asconf_ack_param + length;
asconf_ack_len -= length;
}
return err_code;
}
/* Process an incoming ASCONF_ACK chunk against the cached last ASCONF chunk. */
int sctp_process_asconf_ack(struct sctp_association *asoc,
struct sctp_chunk *asconf_ack)
{
struct sctp_chunk *asconf = asoc->addip_last_asconf;
union sctp_addr_param *addr_param;
sctp_addip_param_t *asconf_param;
int length = 0;
int asconf_len = asconf->skb->len;
int all_param_pass = 0;
int no_err = 1;
int retval = 0;
__be16 err_code = SCTP_ERROR_NO_ERROR;
/* Skip the chunkhdr and addiphdr from the last asconf sent and store
* a pointer to address parameter.
*/
length = sizeof(sctp_addip_chunk_t);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
asconf_len -= length;
/* Skip the address parameter in the last asconf sent and store a
* pointer to the first asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
asconf_len -= length;
/* ADDIP 4.1
* A8) If there is no response(s) to specific TLV parameter(s), and no
* failures are indicated, then all request(s) are considered
* successful.
*/
if (asconf_ack->skb->len == sizeof(sctp_addiphdr_t))
all_param_pass = 1;
/* Process the TLVs contained in the last sent ASCONF chunk. */
while (asconf_len > 0) {
if (all_param_pass)
err_code = SCTP_ERROR_NO_ERROR;
else {
err_code = sctp_get_asconf_response(asconf_ack,
asconf_param,
no_err);
if (no_err && (SCTP_ERROR_NO_ERROR != err_code))
no_err = 0;
}
switch (err_code) {
case SCTP_ERROR_NO_ERROR:
sctp_asconf_param_success(asoc, asconf_param);
break;
case SCTP_ERROR_RSRC_LOW:
retval = 1;
break;
case SCTP_ERROR_UNKNOWN_PARAM:
/* Disable sending this type of asconf parameter in
* future.
*/
asoc->peer.addip_disabled_mask |=
asconf_param->param_hdr.type;
break;
case SCTP_ERROR_REQ_REFUSED:
case SCTP_ERROR_DEL_LAST_IP:
case SCTP_ERROR_DEL_SRC_IP:
default:
break;
}
/* Skip the processed asconf parameter and move to the next
* one.
*/
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
asconf_len -= length;
}
if (no_err && asoc->src_out_of_asoc_ok) {
asoc->src_out_of_asoc_ok = 0;
sctp_transport_immediate_rtx(asoc->peer.primary_path);
}
/* Free the cached last sent asconf chunk. */
list_del_init(&asconf->transmitted_list);
sctp_chunk_free(asconf);
asoc->addip_last_asconf = NULL;
return retval;
}
/* Make a FWD TSN chunk. */
struct sctp_chunk *sctp_make_fwdtsn(const struct sctp_association *asoc,
__u32 new_cum_tsn, size_t nstreams,
struct sctp_fwdtsn_skip *skiplist)
{
struct sctp_chunk *retval = NULL;
struct sctp_fwdtsn_hdr ftsn_hdr;
struct sctp_fwdtsn_skip skip;
size_t hint;
int i;
hint = (nstreams + 1) * sizeof(__u32);
retval = sctp_make_chunk(asoc, SCTP_CID_FWD_TSN, 0, hint);
if (!retval)
return NULL;
ftsn_hdr.new_cum_tsn = htonl(new_cum_tsn);
retval->subh.fwdtsn_hdr =
sctp_addto_chunk(retval, sizeof(ftsn_hdr), &ftsn_hdr);
for (i = 0; i < nstreams; i++) {
skip.stream = skiplist[i].stream;
skip.ssn = skiplist[i].ssn;
sctp_addto_chunk(retval, sizeof(skip), &skip);
}
return retval;
}
| gpl-2.0 |
mirsys/linux-3.4.y | net/sctp/sm_make_chunk.c | 4058 | 102420 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions work with the state functions in sctp_sm_statefuns.c
* to implement the state operations. These functions implement the
* steps which require modifying existing data structures.
*
* This SCTP implementation 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 SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* C. Robin <chris@hundredacre.ac.uk>
* Jon Grimm <jgrimm@us.ibm.com>
* Xingang Guo <xingang.guo@intel.com>
* Dajiang Zhang <dajiang.zhang@nokia.com>
* Sridhar Samudrala <sri@us.ibm.com>
* Daisy Chang <daisyc@us.ibm.com>
* Ardelle Fan <ardelle.fan@intel.com>
* Kevin Gao <kevin.gao@intel.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/scatterlist.h>
#include <linux/crypto.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/skbuff.h>
#include <linux/random.h> /* for get_random_bytes */
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
SCTP_STATIC
struct sctp_chunk *sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen);
static sctp_cookie_param_t *sctp_pack_cookie(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *init_chunk,
int *cookie_len,
const __u8 *raw_addrs, int addrs_len);
static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp);
static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data);
/* What was the inbound interface for this chunk? */
int sctp_chunk_iif(const struct sctp_chunk *chunk)
{
struct sctp_af *af;
int iif = 0;
af = sctp_get_af_specific(ipver2af(ip_hdr(chunk->skb)->version));
if (af)
iif = af->skb_iif(chunk->skb);
return iif;
}
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 2: The ECN capable field is reserved for future use of
* Explicit Congestion Notification.
*/
static const struct sctp_paramhdr ecap_param = {
SCTP_PARAM_ECN_CAPABLE,
cpu_to_be16(sizeof(struct sctp_paramhdr)),
};
static const struct sctp_paramhdr prsctp_param = {
SCTP_PARAM_FWD_TSN_SUPPORT,
cpu_to_be16(sizeof(struct sctp_paramhdr)),
};
/* A helper to initialize an op error inside a
* provided chunk, as most cause codes will be embedded inside an
* abort chunk.
*/
void sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
size_t paylen)
{
sctp_errhdr_t err;
__u16 len;
/* Cause code constants are now defined in network order. */
err.cause = cause_code;
len = sizeof(sctp_errhdr_t) + paylen;
err.length = htons(len);
chunk->subh.err_hdr = sctp_addto_chunk(chunk, sizeof(sctp_errhdr_t), &err);
}
/* A helper to initialize an op error inside a
* provided chunk, as most cause codes will be embedded inside an
* abort chunk. Differs from sctp_init_cause in that it won't oops
* if there isn't enough space in the op error chunk
*/
int sctp_init_cause_fixed(struct sctp_chunk *chunk, __be16 cause_code,
size_t paylen)
{
sctp_errhdr_t err;
__u16 len;
/* Cause code constants are now defined in network order. */
err.cause = cause_code;
len = sizeof(sctp_errhdr_t) + paylen;
err.length = htons(len);
if (skb_tailroom(chunk->skb) < len)
return -ENOSPC;
chunk->subh.err_hdr = sctp_addto_chunk_fixed(chunk,
sizeof(sctp_errhdr_t),
&err);
return 0;
}
/* 3.3.2 Initiation (INIT) (1)
*
* This chunk is used to initiate a SCTP association between two
* endpoints. The format of the INIT chunk is shown below:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 1 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Initiate Tag |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Advertised Receiver Window Credit (a_rwnd) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Outbound Streams | Number of Inbound Streams |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Initial TSN |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / Optional/Variable-Length Parameters /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*
* The INIT chunk contains the following parameters. Unless otherwise
* noted, each parameter MUST only be included once in the INIT chunk.
*
* Fixed Parameters Status
* ----------------------------------------------
* Initiate Tag Mandatory
* Advertised Receiver Window Credit Mandatory
* Number of Outbound Streams Mandatory
* Number of Inbound Streams Mandatory
* Initial TSN Mandatory
*
* Variable Parameters Status Type Value
* -------------------------------------------------------------
* IPv4 Address (Note 1) Optional 5
* IPv6 Address (Note 1) Optional 6
* Cookie Preservative Optional 9
* Reserved for ECN Capable (Note 2) Optional 32768 (0x8000)
* Host Name Address (Note 3) Optional 11
* Supported Address Types (Note 4) Optional 12
*/
struct sctp_chunk *sctp_make_init(const struct sctp_association *asoc,
const struct sctp_bind_addr *bp,
gfp_t gfp, int vparam_len)
{
sctp_inithdr_t init;
union sctp_params addrs;
size_t chunksize;
struct sctp_chunk *retval = NULL;
int num_types, addrs_len = 0;
struct sctp_sock *sp;
sctp_supported_addrs_param_t sat;
__be16 types[2];
sctp_adaptation_ind_param_t aiparam;
sctp_supported_ext_param_t ext_param;
int num_ext = 0;
__u8 extensions[3];
sctp_paramhdr_t *auth_chunks = NULL,
*auth_hmacs = NULL;
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 1: The INIT chunks can contain multiple addresses that
* can be IPv4 and/or IPv6 in any combination.
*/
retval = NULL;
/* Convert the provided bind address list to raw format. */
addrs = sctp_bind_addrs_to_raw(bp, &addrs_len, gfp);
init.init_tag = htonl(asoc->c.my_vtag);
init.a_rwnd = htonl(asoc->rwnd);
init.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
init.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
init.initial_tsn = htonl(asoc->c.initial_tsn);
/* How many address types are needed? */
sp = sctp_sk(asoc->base.sk);
num_types = sp->pf->supported_addrs(sp, types);
chunksize = sizeof(init) + addrs_len;
chunksize += WORD_ROUND(SCTP_SAT_LEN(num_types));
chunksize += sizeof(ecap_param);
if (sctp_prsctp_enable)
chunksize += sizeof(prsctp_param);
/* ADDIP: Section 4.2.7:
* An implementation supporting this extension [ADDIP] MUST list
* the ASCONF,the ASCONF-ACK, and the AUTH chunks in its INIT and
* INIT-ACK parameters.
*/
if (sctp_addip_enable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
chunksize += vparam_len;
/* Account for AUTH related parameters */
if (sctp_auth_enable) {
/* Add random parameter length*/
chunksize += sizeof(asoc->c.auth_random);
/* Add HMACS parameter length if any were defined */
auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
/* Add CHUNKS parameter length */
auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += WORD_ROUND(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
/* If we have any extensions to report, account for that */
if (num_ext)
chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
num_ext);
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 3: An INIT chunk MUST NOT contain more than one Host
* Name address parameter. Moreover, the sender of the INIT
* MUST NOT combine any other address types with the Host Name
* address in the INIT. The receiver of INIT MUST ignore any
* other address types if the Host Name address parameter is
* present in the received INIT chunk.
*
* PLEASE DO NOT FIXME [This version does not support Host Name.]
*/
retval = sctp_make_chunk(asoc, SCTP_CID_INIT, 0, chunksize);
if (!retval)
goto nodata;
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(init), &init);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrs_len, addrs.v);
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 4: This parameter, when present, specifies all the
* address types the sending endpoint can support. The absence
* of this parameter indicates that the sending endpoint can
* support any address type.
*/
sat.param_hdr.type = SCTP_PARAM_SUPPORTED_ADDRESS_TYPES;
sat.param_hdr.length = htons(SCTP_SAT_LEN(num_types));
sctp_addto_chunk(retval, sizeof(sat), &sat);
sctp_addto_chunk(retval, num_types * sizeof(__u16), &types);
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
/* Add the supported extensions parameter. Be nice and add this
* fist before addiding the parameters for the extensions themselves
*/
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length =
htons(sizeof(sctp_supported_ext_param_t) + num_ext);
sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
&ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (sctp_prsctp_enable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
/* Add SCTP-AUTH chunks to the parameter list */
if (sctp_auth_enable) {
sctp_addto_chunk(retval, sizeof(asoc->c.auth_random),
asoc->c.auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
nodata:
kfree(addrs.v);
return retval;
}
struct sctp_chunk *sctp_make_init_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
gfp_t gfp, int unkparam_len)
{
sctp_inithdr_t initack;
struct sctp_chunk *retval;
union sctp_params addrs;
struct sctp_sock *sp;
int addrs_len;
sctp_cookie_param_t *cookie;
int cookie_len;
size_t chunksize;
sctp_adaptation_ind_param_t aiparam;
sctp_supported_ext_param_t ext_param;
int num_ext = 0;
__u8 extensions[3];
sctp_paramhdr_t *auth_chunks = NULL,
*auth_hmacs = NULL,
*auth_random = NULL;
retval = NULL;
/* Note: there may be no addresses to embed. */
addrs = sctp_bind_addrs_to_raw(&asoc->base.bind_addr, &addrs_len, gfp);
initack.init_tag = htonl(asoc->c.my_vtag);
initack.a_rwnd = htonl(asoc->rwnd);
initack.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
initack.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
initack.initial_tsn = htonl(asoc->c.initial_tsn);
/* FIXME: We really ought to build the cookie right
* into the packet instead of allocating more fresh memory.
*/
cookie = sctp_pack_cookie(asoc->ep, asoc, chunk, &cookie_len,
addrs.v, addrs_len);
if (!cookie)
goto nomem_cookie;
/* Calculate the total size of allocation, include the reserved
* space for reporting unknown parameters if it is specified.
*/
sp = sctp_sk(asoc->base.sk);
chunksize = sizeof(initack) + addrs_len + cookie_len + unkparam_len;
/* Tell peer that we'll do ECN only if peer advertised such cap. */
if (asoc->peer.ecn_capable)
chunksize += sizeof(ecap_param);
if (asoc->peer.prsctp_capable)
chunksize += sizeof(prsctp_param);
if (asoc->peer.asconf_capable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
if (asoc->peer.auth_capable) {
auth_random = (sctp_paramhdr_t *)asoc->c.auth_random;
chunksize += ntohs(auth_random->length);
auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += WORD_ROUND(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
if (num_ext)
chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
num_ext);
/* Now allocate and fill out the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_INIT_ACK, 0, chunksize);
if (!retval)
goto nomem_chunk;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
* [INIT ACK back to where the INIT came from.]
*/
retval->transport = chunk->transport;
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(initack), &initack);
retval->param_hdr.v = sctp_addto_chunk(retval, addrs_len, addrs.v);
sctp_addto_chunk(retval, cookie_len, cookie);
if (asoc->peer.ecn_capable)
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length =
htons(sizeof(sctp_supported_ext_param_t) + num_ext);
sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
&ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (asoc->peer.prsctp_capable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
if (asoc->peer.auth_capable) {
sctp_addto_chunk(retval, ntohs(auth_random->length),
auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
/* We need to remove the const qualifier at this point. */
retval->asoc = (struct sctp_association *) asoc;
nomem_chunk:
kfree(cookie);
nomem_cookie:
kfree(addrs.v);
return retval;
}
/* 3.3.11 Cookie Echo (COOKIE ECHO) (10):
*
* This chunk is used only during the initialization of an association.
* It is sent by the initiator of an association to its peer to complete
* the initialization process. This chunk MUST precede any DATA chunk
* sent within the association, but MAY be bundled with one or more DATA
* chunks in the same packet.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 10 |Chunk Flags | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* / Cookie /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Chunk Flags: 8 bit
*
* Set to zero on transmit and ignored on receipt.
*
* Length: 16 bits (unsigned integer)
*
* Set to the size of the chunk in bytes, including the 4 bytes of
* the chunk header and the size of the Cookie.
*
* Cookie: variable size
*
* This field must contain the exact cookie received in the
* State Cookie parameter from the previous INIT ACK.
*
* An implementation SHOULD make the cookie as small as possible
* to insure interoperability.
*/
struct sctp_chunk *sctp_make_cookie_echo(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
void *cookie;
int cookie_len;
cookie = asoc->peer.cookie;
cookie_len = asoc->peer.cookie_len;
/* Build a cookie echo chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_COOKIE_ECHO, 0, cookie_len);
if (!retval)
goto nodata;
retval->subh.cookie_hdr =
sctp_addto_chunk(retval, cookie_len, cookie);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [COOKIE ECHO back to where the INIT ACK came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* 3.3.12 Cookie Acknowledgement (COOKIE ACK) (11):
*
* This chunk is used only during the initialization of an
* association. It is used to acknowledge the receipt of a COOKIE
* ECHO chunk. This chunk MUST precede any DATA or SACK chunk sent
* within the association, but MAY be bundled with one or more DATA
* chunks or SACK chunk in the same SCTP packet.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 11 |Chunk Flags | Length = 4 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Chunk Flags: 8 bits
*
* Set to zero on transmit and ignored on receipt.
*/
struct sctp_chunk *sctp_make_cookie_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_COOKIE_ACK, 0, 0);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [COOKIE ACK back to where the COOKIE ECHO came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/*
* Appendix A: Explicit Congestion Notification:
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Chunk Type=13 | Flags=00000000| Chunk Length = 8 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Lowest TSN Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Note: The CWR is considered a Control chunk.
*/
struct sctp_chunk *sctp_make_cwr(const struct sctp_association *asoc,
const __u32 lowest_tsn,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
sctp_cwrhdr_t cwr;
cwr.lowest_tsn = htonl(lowest_tsn);
retval = sctp_make_chunk(asoc, SCTP_CID_ECN_CWR, 0,
sizeof(sctp_cwrhdr_t));
if (!retval)
goto nodata;
retval->subh.ecn_cwr_hdr =
sctp_addto_chunk(retval, sizeof(cwr), &cwr);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [Report a reduced congestion window back to where the ECNE
* came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Make an ECNE chunk. This is a congestion experienced report. */
struct sctp_chunk *sctp_make_ecne(const struct sctp_association *asoc,
const __u32 lowest_tsn)
{
struct sctp_chunk *retval;
sctp_ecnehdr_t ecne;
ecne.lowest_tsn = htonl(lowest_tsn);
retval = sctp_make_chunk(asoc, SCTP_CID_ECN_ECNE, 0,
sizeof(sctp_ecnehdr_t));
if (!retval)
goto nodata;
retval->subh.ecne_hdr =
sctp_addto_chunk(retval, sizeof(ecne), &ecne);
nodata:
return retval;
}
/* Make a DATA chunk for the given association from the provided
* parameters. However, do not populate the data payload.
*/
struct sctp_chunk *sctp_make_datafrag_empty(struct sctp_association *asoc,
const struct sctp_sndrcvinfo *sinfo,
int data_len, __u8 flags, __u16 ssn)
{
struct sctp_chunk *retval;
struct sctp_datahdr dp;
int chunk_len;
/* We assign the TSN as LATE as possible, not here when
* creating the chunk.
*/
dp.tsn = 0;
dp.stream = htons(sinfo->sinfo_stream);
dp.ppid = sinfo->sinfo_ppid;
/* Set the flags for an unordered send. */
if (sinfo->sinfo_flags & SCTP_UNORDERED) {
flags |= SCTP_DATA_UNORDERED;
dp.ssn = 0;
} else
dp.ssn = htons(ssn);
chunk_len = sizeof(dp) + data_len;
retval = sctp_make_chunk(asoc, SCTP_CID_DATA, flags, chunk_len);
if (!retval)
goto nodata;
retval->subh.data_hdr = sctp_addto_chunk(retval, sizeof(dp), &dp);
memcpy(&retval->sinfo, sinfo, sizeof(struct sctp_sndrcvinfo));
nodata:
return retval;
}
/* Create a selective ackowledgement (SACK) for the given
* association. This reports on which TSN's we've seen to date,
* including duplicates and gaps.
*/
struct sctp_chunk *sctp_make_sack(const struct sctp_association *asoc)
{
struct sctp_chunk *retval;
struct sctp_sackhdr sack;
int len;
__u32 ctsn;
__u16 num_gabs, num_dup_tsns;
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sctp_gap_ack_block gabs[SCTP_MAX_GABS];
memset(gabs, 0, sizeof(gabs));
ctsn = sctp_tsnmap_get_ctsn(map);
SCTP_DEBUG_PRINTK("sackCTSNAck sent: 0x%x.\n", ctsn);
/* How much room is needed in the chunk? */
num_gabs = sctp_tsnmap_num_gabs(map, gabs);
num_dup_tsns = sctp_tsnmap_num_dups(map);
/* Initialize the SACK header. */
sack.cum_tsn_ack = htonl(ctsn);
sack.a_rwnd = htonl(asoc->a_rwnd);
sack.num_gap_ack_blocks = htons(num_gabs);
sack.num_dup_tsns = htons(num_dup_tsns);
len = sizeof(sack)
+ sizeof(struct sctp_gap_ack_block) * num_gabs
+ sizeof(__u32) * num_dup_tsns;
/* Create the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_SACK, 0, len);
if (!retval)
goto nodata;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, etc.) to the same destination transport
* address from which it received the DATA or control chunk to
* which it is replying. This rule should also be followed if
* the endpoint is bundling DATA chunks together with the
* reply chunk.
*
* However, when acknowledging multiple DATA chunks received
* in packets from different source addresses in a single
* SACK, the SACK chunk may be transmitted to one of the
* destination transport addresses from which the DATA or
* control chunks being acknowledged were received.
*
* [BUG: We do not implement the following paragraph.
* Perhaps we should remember the last transport we used for a
* SACK and avoid that (if possible) if we have seen any
* duplicates. --piggy]
*
* When a receiver of a duplicate DATA chunk sends a SACK to a
* multi- homed endpoint it MAY be beneficial to vary the
* destination address and not use the source address of the
* DATA chunk. The reason being that receiving a duplicate
* from a multi-homed endpoint might indicate that the return
* path (as specified in the source address of the DATA chunk)
* for the SACK is broken.
*
* [Send to the address from which we last received a DATA chunk.]
*/
retval->transport = asoc->peer.last_data_from;
retval->subh.sack_hdr =
sctp_addto_chunk(retval, sizeof(sack), &sack);
/* Add the gap ack block information. */
if (num_gabs)
sctp_addto_chunk(retval, sizeof(__u32) * num_gabs,
gabs);
/* Add the duplicate TSN information. */
if (num_dup_tsns)
sctp_addto_chunk(retval, sizeof(__u32) * num_dup_tsns,
sctp_tsnmap_get_dups(map));
nodata:
return retval;
}
/* Make a SHUTDOWN chunk. */
struct sctp_chunk *sctp_make_shutdown(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
sctp_shutdownhdr_t shut;
__u32 ctsn;
ctsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
shut.cum_tsn_ack = htonl(ctsn);
retval = sctp_make_chunk(asoc, SCTP_CID_SHUTDOWN, 0,
sizeof(sctp_shutdownhdr_t));
if (!retval)
goto nodata;
retval->subh.shutdown_hdr =
sctp_addto_chunk(retval, sizeof(shut), &shut);
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
struct sctp_chunk *sctp_make_shutdown_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_SHUTDOWN_ACK, 0, 0);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ACK back to where the SHUTDOWN came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
struct sctp_chunk *sctp_make_shutdown_complete(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
__u8 flags = 0;
/* Set the T-bit if we have no association (vtag will be
* reflected)
*/
flags |= asoc ? 0 : SCTP_CHUNK_FLAG_T;
retval = sctp_make_chunk(asoc, SCTP_CID_SHUTDOWN_COMPLETE, flags, 0);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [Report SHUTDOWN COMPLETE back to where the SHUTDOWN ACK
* came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/* Create an ABORT. Note that we set the T bit if we have no
* association, except when responding to an INIT (sctpimpguide 2.41).
*/
struct sctp_chunk *sctp_make_abort(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const size_t hint)
{
struct sctp_chunk *retval;
__u8 flags = 0;
/* Set the T-bit if we have no association and 'chunk' is not
* an INIT (vtag will be reflected).
*/
if (!asoc) {
if (chunk && chunk->chunk_hdr &&
chunk->chunk_hdr->type == SCTP_CID_INIT)
flags = 0;
else
flags = SCTP_CHUNK_FLAG_T;
}
retval = sctp_make_chunk(asoc, SCTP_CID_ABORT, flags, hint);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ABORT back to where the offender came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/* Helper to create ABORT with a NO_USER_DATA error. */
struct sctp_chunk *sctp_make_abort_no_data(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk, __u32 tsn)
{
struct sctp_chunk *retval;
__be32 payload;
retval = sctp_make_abort(asoc, chunk, sizeof(sctp_errhdr_t)
+ sizeof(tsn));
if (!retval)
goto no_mem;
/* Put the tsn back into network byte order. */
payload = htonl(tsn);
sctp_init_cause(retval, SCTP_ERROR_NO_DATA, sizeof(payload));
sctp_addto_chunk(retval, sizeof(payload), (const void *)&payload);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ABORT back to where the offender came from.]
*/
if (chunk)
retval->transport = chunk->transport;
no_mem:
return retval;
}
/* Helper to create ABORT with a SCTP_ERROR_USER_ABORT error. */
struct sctp_chunk *sctp_make_abort_user(const struct sctp_association *asoc,
const struct msghdr *msg,
size_t paylen)
{
struct sctp_chunk *retval;
void *payload = NULL;
int err;
retval = sctp_make_abort(asoc, NULL, sizeof(sctp_errhdr_t) + paylen);
if (!retval)
goto err_chunk;
if (paylen) {
/* Put the msg_iov together into payload. */
payload = kmalloc(paylen, GFP_KERNEL);
if (!payload)
goto err_payload;
err = memcpy_fromiovec(payload, msg->msg_iov, paylen);
if (err < 0)
goto err_copy;
}
sctp_init_cause(retval, SCTP_ERROR_USER_ABORT, paylen);
sctp_addto_chunk(retval, paylen, payload);
if (paylen)
kfree(payload);
return retval;
err_copy:
kfree(payload);
err_payload:
sctp_chunk_free(retval);
retval = NULL;
err_chunk:
return retval;
}
/* Append bytes to the end of a parameter. Will panic if chunk is not big
* enough.
*/
static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data)
{
void *target;
int chunklen = ntohs(chunk->chunk_hdr->length);
target = skb_put(chunk->skb, len);
if (data)
memcpy(target, data, len);
else
memset(target, 0, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
/* Make an ABORT chunk with a PROTOCOL VIOLATION cause code. */
struct sctp_chunk *sctp_make_abort_violation(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const __u8 *payload,
const size_t paylen)
{
struct sctp_chunk *retval;
struct sctp_paramhdr phdr;
retval = sctp_make_abort(asoc, chunk, sizeof(sctp_errhdr_t) + paylen
+ sizeof(sctp_paramhdr_t));
if (!retval)
goto end;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION, paylen
+ sizeof(sctp_paramhdr_t));
phdr.type = htons(chunk->chunk_hdr->type);
phdr.length = chunk->chunk_hdr->length;
sctp_addto_chunk(retval, paylen, payload);
sctp_addto_param(retval, sizeof(sctp_paramhdr_t), &phdr);
end:
return retval;
}
struct sctp_chunk *sctp_make_violation_paramlen(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
struct sctp_paramhdr *param)
{
struct sctp_chunk *retval;
static const char error[] = "The following parameter had invalid length:";
size_t payload_len = sizeof(error) + sizeof(sctp_errhdr_t) +
sizeof(sctp_paramhdr_t);
retval = sctp_make_abort(asoc, chunk, payload_len);
if (!retval)
goto nodata;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION,
sizeof(error) + sizeof(sctp_paramhdr_t));
sctp_addto_chunk(retval, sizeof(error), error);
sctp_addto_param(retval, sizeof(sctp_paramhdr_t), param);
nodata:
return retval;
}
/* Make a HEARTBEAT chunk. */
struct sctp_chunk *sctp_make_heartbeat(const struct sctp_association *asoc,
const struct sctp_transport *transport)
{
struct sctp_chunk *retval;
sctp_sender_hb_info_t hbinfo;
retval = sctp_make_chunk(asoc, SCTP_CID_HEARTBEAT, 0, sizeof(hbinfo));
if (!retval)
goto nodata;
hbinfo.param_hdr.type = SCTP_PARAM_HEARTBEAT_INFO;
hbinfo.param_hdr.length = htons(sizeof(sctp_sender_hb_info_t));
hbinfo.daddr = transport->ipaddr;
hbinfo.sent_at = jiffies;
hbinfo.hb_nonce = transport->hb_nonce;
/* Cast away the 'const', as this is just telling the chunk
* what transport it belongs to.
*/
retval->transport = (struct sctp_transport *) transport;
retval->subh.hbs_hdr = sctp_addto_chunk(retval, sizeof(hbinfo),
&hbinfo);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_heartbeat_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const void *payload, const size_t paylen)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_HEARTBEAT_ACK, 0, paylen);
if (!retval)
goto nodata;
retval->subh.hbs_hdr = sctp_addto_chunk(retval, paylen, payload);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [HBACK back to where the HEARTBEAT came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Create an Operation Error chunk with the specified space reserved.
* This routine can be used for containing multiple causes in the chunk.
*/
static struct sctp_chunk *sctp_make_op_error_space(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
size_t size)
{
struct sctp_chunk *retval;
retval = sctp_make_chunk(asoc, SCTP_CID_ERROR, 0,
sizeof(sctp_errhdr_t) + size);
if (!retval)
goto nodata;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Create an Operation Error chunk of a fixed size,
* specifically, max(asoc->pathmtu, SCTP_DEFAULT_MAXSEGMENT)
* This is a helper function to allocate an error chunk for
* for those invalid parameter codes in which we may not want
* to report all the errors, if the incomming chunk is large
*/
static inline struct sctp_chunk *sctp_make_op_error_fixed(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
size_t size = asoc ? asoc->pathmtu : 0;
if (!size)
size = SCTP_DEFAULT_MAXSEGMENT;
return sctp_make_op_error_space(asoc, chunk, size);
}
/* Create an Operation Error chunk. */
struct sctp_chunk *sctp_make_op_error(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
__be16 cause_code, const void *payload,
size_t paylen, size_t reserve_tail)
{
struct sctp_chunk *retval;
retval = sctp_make_op_error_space(asoc, chunk, paylen + reserve_tail);
if (!retval)
goto nodata;
sctp_init_cause(retval, cause_code, paylen + reserve_tail);
sctp_addto_chunk(retval, paylen, payload);
if (reserve_tail)
sctp_addto_param(retval, reserve_tail, NULL);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_auth(const struct sctp_association *asoc)
{
struct sctp_chunk *retval;
struct sctp_hmac *hmac_desc;
struct sctp_authhdr auth_hdr;
__u8 *hmac;
/* Get the first hmac that the peer told us to use */
hmac_desc = sctp_auth_asoc_get_hmac(asoc);
if (unlikely(!hmac_desc))
return NULL;
retval = sctp_make_chunk(asoc, SCTP_CID_AUTH, 0,
hmac_desc->hmac_len + sizeof(sctp_authhdr_t));
if (!retval)
return NULL;
auth_hdr.hmac_id = htons(hmac_desc->hmac_id);
auth_hdr.shkey_id = htons(asoc->active_key_id);
retval->subh.auth_hdr = sctp_addto_chunk(retval, sizeof(sctp_authhdr_t),
&auth_hdr);
hmac = skb_put(retval->skb, hmac_desc->hmac_len);
memset(hmac, 0, hmac_desc->hmac_len);
/* Adjust the chunk header to include the empty MAC */
retval->chunk_hdr->length =
htons(ntohs(retval->chunk_hdr->length) + hmac_desc->hmac_len);
retval->chunk_end = skb_tail_pointer(retval->skb);
return retval;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Turn an skb into a chunk.
* FIXME: Eventually move the structure directly inside the skb->cb[].
*/
struct sctp_chunk *sctp_chunkify(struct sk_buff *skb,
const struct sctp_association *asoc,
struct sock *sk)
{
struct sctp_chunk *retval;
retval = kmem_cache_zalloc(sctp_chunk_cachep, GFP_ATOMIC);
if (!retval)
goto nodata;
if (!sk) {
SCTP_DEBUG_PRINTK("chunkifying skb %p w/o an sk\n", skb);
}
INIT_LIST_HEAD(&retval->list);
retval->skb = skb;
retval->asoc = (struct sctp_association *)asoc;
retval->has_tsn = 0;
retval->has_ssn = 0;
retval->rtt_in_progress = 0;
retval->sent_at = 0;
retval->singleton = 1;
retval->end_of_packet = 0;
retval->ecn_ce_done = 0;
retval->pdiscard = 0;
/* sctpimpguide-05.txt Section 2.8.2
* M1) Each time a new DATA chunk is transmitted
* set the 'TSN.Missing.Report' count for that TSN to 0. The
* 'TSN.Missing.Report' count will be used to determine missing chunks
* and when to fast retransmit.
*/
retval->tsn_missing_report = 0;
retval->tsn_gap_acked = 0;
retval->fast_retransmit = SCTP_CAN_FRTX;
/* If this is a fragmented message, track all fragments
* of the message (for SEND_FAILED).
*/
retval->msg = NULL;
/* Polish the bead hole. */
INIT_LIST_HEAD(&retval->transmitted_list);
INIT_LIST_HEAD(&retval->frag_list);
SCTP_DBG_OBJCNT_INC(chunk);
atomic_set(&retval->refcnt, 1);
nodata:
return retval;
}
/* Set chunk->source and dest based on the IP header in chunk->skb. */
void sctp_init_addrs(struct sctp_chunk *chunk, union sctp_addr *src,
union sctp_addr *dest)
{
memcpy(&chunk->source, src, sizeof(union sctp_addr));
memcpy(&chunk->dest, dest, sizeof(union sctp_addr));
}
/* Extract the source address from a chunk. */
const union sctp_addr *sctp_source(const struct sctp_chunk *chunk)
{
/* If we have a known transport, use that. */
if (chunk->transport) {
return &chunk->transport->ipaddr;
} else {
/* Otherwise, extract it from the IP header. */
return &chunk->source;
}
}
/* Create a new chunk, setting the type and flags headers from the
* arguments, reserving enough space for a 'paylen' byte payload.
*/
SCTP_STATIC
struct sctp_chunk *sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen)
{
struct sctp_chunk *retval;
sctp_chunkhdr_t *chunk_hdr;
struct sk_buff *skb;
struct sock *sk;
/* No need to allocate LL here, as this is only a chunk. */
skb = alloc_skb(WORD_ROUND(sizeof(sctp_chunkhdr_t) + paylen),
GFP_ATOMIC);
if (!skb)
goto nodata;
/* Make room for the chunk header. */
chunk_hdr = (sctp_chunkhdr_t *)skb_put(skb, sizeof(sctp_chunkhdr_t));
chunk_hdr->type = type;
chunk_hdr->flags = flags;
chunk_hdr->length = htons(sizeof(sctp_chunkhdr_t));
sk = asoc ? asoc->base.sk : NULL;
retval = sctp_chunkify(skb, asoc, sk);
if (!retval) {
kfree_skb(skb);
goto nodata;
}
retval->chunk_hdr = chunk_hdr;
retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(struct sctp_chunkhdr);
/* Determine if the chunk needs to be authenticated */
if (sctp_auth_send_cid(type, asoc))
retval->auth = 1;
/* Set the skb to the belonging sock for accounting. */
skb->sk = sk;
return retval;
nodata:
return NULL;
}
/* Release the memory occupied by a chunk. */
static void sctp_chunk_destroy(struct sctp_chunk *chunk)
{
BUG_ON(!list_empty(&chunk->list));
list_del_init(&chunk->transmitted_list);
/* Free the chunk skb data and the SCTP_chunk stub itself. */
dev_kfree_skb(chunk->skb);
SCTP_DBG_OBJCNT_DEC(chunk);
kmem_cache_free(sctp_chunk_cachep, chunk);
}
/* Possibly, free the chunk. */
void sctp_chunk_free(struct sctp_chunk *chunk)
{
/* Release our reference on the message tracker. */
if (chunk->msg)
sctp_datamsg_put(chunk->msg);
sctp_chunk_put(chunk);
}
/* Grab a reference to the chunk. */
void sctp_chunk_hold(struct sctp_chunk *ch)
{
atomic_inc(&ch->refcnt);
}
/* Release a reference to the chunk. */
void sctp_chunk_put(struct sctp_chunk *ch)
{
if (atomic_dec_and_test(&ch->refcnt))
sctp_chunk_destroy(ch);
}
/* Append bytes to the end of a chunk. Will panic if chunk is not big
* enough.
*/
void *sctp_addto_chunk(struct sctp_chunk *chunk, int len, const void *data)
{
void *target;
void *padding;
int chunklen = ntohs(chunk->chunk_hdr->length);
int padlen = WORD_ROUND(chunklen) - chunklen;
padding = skb_put(chunk->skb, padlen);
target = skb_put(chunk->skb, len);
memset(padding, 0, padlen);
memcpy(target, data, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + padlen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
/* Append bytes to the end of a chunk. Returns NULL if there isn't sufficient
* space in the chunk
*/
void *sctp_addto_chunk_fixed(struct sctp_chunk *chunk,
int len, const void *data)
{
if (skb_tailroom(chunk->skb) >= len)
return sctp_addto_chunk(chunk, len, data);
else
return NULL;
}
/* Append bytes from user space to the end of a chunk. Will panic if
* chunk is not big enough.
* Returns a kernel err value.
*/
int sctp_user_addto_chunk(struct sctp_chunk *chunk, int off, int len,
struct iovec *data)
{
__u8 *target;
int err = 0;
/* Make room in chunk for data. */
target = skb_put(chunk->skb, len);
/* Copy data (whole iovec) into chunk */
if ((err = memcpy_fromiovecend(target, data, off, len)))
goto out;
/* Adjust the chunk length field. */
chunk->chunk_hdr->length =
htons(ntohs(chunk->chunk_hdr->length) + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
out:
return err;
}
/* Helper function to assign a TSN if needed. This assumes that both
* the data_hdr and association have already been assigned.
*/
void sctp_chunk_assign_ssn(struct sctp_chunk *chunk)
{
struct sctp_datamsg *msg;
struct sctp_chunk *lchunk;
struct sctp_stream *stream;
__u16 ssn;
__u16 sid;
if (chunk->has_ssn)
return;
/* All fragments will be on the same stream */
sid = ntohs(chunk->subh.data_hdr->stream);
stream = &chunk->asoc->ssnmap->out;
/* Now assign the sequence number to the entire message.
* All fragments must have the same stream sequence number.
*/
msg = chunk->msg;
list_for_each_entry(lchunk, &msg->chunks, frag_list) {
if (lchunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
ssn = 0;
} else {
if (lchunk->chunk_hdr->flags & SCTP_DATA_LAST_FRAG)
ssn = sctp_ssn_next(stream, sid);
else
ssn = sctp_ssn_peek(stream, sid);
}
lchunk->subh.data_hdr->ssn = htons(ssn);
lchunk->has_ssn = 1;
}
}
/* Helper function to assign a TSN if needed. This assumes that both
* the data_hdr and association have already been assigned.
*/
void sctp_chunk_assign_tsn(struct sctp_chunk *chunk)
{
if (!chunk->has_tsn) {
/* This is the last possible instant to
* assign a TSN.
*/
chunk->subh.data_hdr->tsn =
htonl(sctp_association_get_next_tsn(chunk->asoc));
chunk->has_tsn = 1;
}
}
/* Create a CLOSED association to use with an incoming packet. */
struct sctp_association *sctp_make_temp_asoc(const struct sctp_endpoint *ep,
struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc;
struct sk_buff *skb;
sctp_scope_t scope;
struct sctp_af *af;
/* Create the bare association. */
scope = sctp_scope(sctp_source(chunk));
asoc = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!asoc)
goto nodata;
asoc->temp = 1;
skb = chunk->skb;
/* Create an entry for the source address of the packet. */
af = sctp_get_af_specific(ipver2af(ip_hdr(skb)->version));
if (unlikely(!af))
goto fail;
af->from_skb(&asoc->c.peer_addr, skb, 1);
nodata:
return asoc;
fail:
sctp_association_free(asoc);
return NULL;
}
/* Build a cookie representing asoc.
* This INCLUDES the param header needed to put the cookie in the INIT ACK.
*/
static sctp_cookie_param_t *sctp_pack_cookie(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *init_chunk,
int *cookie_len,
const __u8 *raw_addrs, int addrs_len)
{
sctp_cookie_param_t *retval;
struct sctp_signed_cookie *cookie;
struct scatterlist sg;
int headersize, bodysize;
unsigned int keylen;
char *key;
/* Header size is static data prior to the actual cookie, including
* any padding.
*/
headersize = sizeof(sctp_paramhdr_t) +
(sizeof(struct sctp_signed_cookie) -
sizeof(struct sctp_cookie));
bodysize = sizeof(struct sctp_cookie)
+ ntohs(init_chunk->chunk_hdr->length) + addrs_len;
/* Pad out the cookie to a multiple to make the signature
* functions simpler to write.
*/
if (bodysize % SCTP_COOKIE_MULTIPLE)
bodysize += SCTP_COOKIE_MULTIPLE
- (bodysize % SCTP_COOKIE_MULTIPLE);
*cookie_len = headersize + bodysize;
/* Clear this memory since we are sending this data structure
* out on the network.
*/
retval = kzalloc(*cookie_len, GFP_ATOMIC);
if (!retval)
goto nodata;
cookie = (struct sctp_signed_cookie *) retval->body;
/* Set up the parameter header. */
retval->p.type = SCTP_PARAM_STATE_COOKIE;
retval->p.length = htons(*cookie_len);
/* Copy the cookie part of the association itself. */
cookie->c = asoc->c;
/* Save the raw address list length in the cookie. */
cookie->c.raw_addr_list_len = addrs_len;
/* Remember PR-SCTP capability. */
cookie->c.prsctp_capable = asoc->peer.prsctp_capable;
/* Save adaptation indication in the cookie. */
cookie->c.adaptation_ind = asoc->peer.adaptation_ind;
/* Set an expiration time for the cookie. */
do_gettimeofday(&cookie->c.expiration);
TIMEVAL_ADD(asoc->cookie_life, cookie->c.expiration);
/* Copy the peer's init packet. */
memcpy(&cookie->c.peer_init[0], init_chunk->chunk_hdr,
ntohs(init_chunk->chunk_hdr->length));
/* Copy the raw local address list of the association. */
memcpy((__u8 *)&cookie->c.peer_init[0] +
ntohs(init_chunk->chunk_hdr->length), raw_addrs, addrs_len);
if (sctp_sk(ep->base.sk)->hmac) {
struct hash_desc desc;
/* Sign the message. */
sg_init_one(&sg, &cookie->c, bodysize);
keylen = SCTP_SECRET_SIZE;
key = (char *)ep->secret_key[ep->current_key];
desc.tfm = sctp_sk(ep->base.sk)->hmac;
desc.flags = 0;
if (crypto_hash_setkey(desc.tfm, key, keylen) ||
crypto_hash_digest(&desc, &sg, bodysize, cookie->signature))
goto free_cookie;
}
return retval;
free_cookie:
kfree(retval);
nodata:
*cookie_len = 0;
return NULL;
}
/* Unpack the cookie from COOKIE ECHO chunk, recreating the association. */
struct sctp_association *sctp_unpack_cookie(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk, gfp_t gfp,
int *error, struct sctp_chunk **errp)
{
struct sctp_association *retval = NULL;
struct sctp_signed_cookie *cookie;
struct sctp_cookie *bear_cookie;
int headersize, bodysize, fixed_size;
__u8 *digest = ep->digest;
struct scatterlist sg;
unsigned int keylen, len;
char *key;
sctp_scope_t scope;
struct sk_buff *skb = chunk->skb;
struct timeval tv;
struct hash_desc desc;
/* Header size is static data prior to the actual cookie, including
* any padding.
*/
headersize = sizeof(sctp_chunkhdr_t) +
(sizeof(struct sctp_signed_cookie) -
sizeof(struct sctp_cookie));
bodysize = ntohs(chunk->chunk_hdr->length) - headersize;
fixed_size = headersize + sizeof(struct sctp_cookie);
/* Verify that the chunk looks like it even has a cookie.
* There must be enough room for our cookie and our peer's
* INIT chunk.
*/
len = ntohs(chunk->chunk_hdr->length);
if (len < fixed_size + sizeof(struct sctp_chunkhdr))
goto malformed;
/* Verify that the cookie has been padded out. */
if (bodysize % SCTP_COOKIE_MULTIPLE)
goto malformed;
/* Process the cookie. */
cookie = chunk->subh.cookie_hdr;
bear_cookie = &cookie->c;
if (!sctp_sk(ep->base.sk)->hmac)
goto no_hmac;
/* Check the signature. */
keylen = SCTP_SECRET_SIZE;
sg_init_one(&sg, bear_cookie, bodysize);
key = (char *)ep->secret_key[ep->current_key];
desc.tfm = sctp_sk(ep->base.sk)->hmac;
desc.flags = 0;
memset(digest, 0x00, SCTP_SIGNATURE_SIZE);
if (crypto_hash_setkey(desc.tfm, key, keylen) ||
crypto_hash_digest(&desc, &sg, bodysize, digest)) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
if (memcmp(digest, cookie->signature, SCTP_SIGNATURE_SIZE)) {
/* Try the previous key. */
key = (char *)ep->secret_key[ep->last_key];
memset(digest, 0x00, SCTP_SIGNATURE_SIZE);
if (crypto_hash_setkey(desc.tfm, key, keylen) ||
crypto_hash_digest(&desc, &sg, bodysize, digest)) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
if (memcmp(digest, cookie->signature, SCTP_SIGNATURE_SIZE)) {
/* Yikes! Still bad signature! */
*error = -SCTP_IERROR_BAD_SIG;
goto fail;
}
}
no_hmac:
/* IG Section 2.35.2:
* 3) Compare the port numbers and the verification tag contained
* within the COOKIE ECHO chunk to the actual port numbers and the
* verification tag within the SCTP common header of the received
* packet. If these values do not match the packet MUST be silently
* discarded,
*/
if (ntohl(chunk->sctp_hdr->vtag) != bear_cookie->my_vtag) {
*error = -SCTP_IERROR_BAD_TAG;
goto fail;
}
if (chunk->sctp_hdr->source != bear_cookie->peer_addr.v4.sin_port ||
ntohs(chunk->sctp_hdr->dest) != bear_cookie->my_port) {
*error = -SCTP_IERROR_BAD_PORTS;
goto fail;
}
/* Check to see if the cookie is stale. If there is already
* an association, there is no need to check cookie's expiration
* for init collision case of lost COOKIE ACK.
* If skb has been timestamped, then use the stamp, otherwise
* use current time. This introduces a small possibility that
* that a cookie may be considered expired, but his would only slow
* down the new association establishment instead of every packet.
*/
if (sock_flag(ep->base.sk, SOCK_TIMESTAMP))
skb_get_timestamp(skb, &tv);
else
do_gettimeofday(&tv);
if (!asoc && tv_lt(bear_cookie->expiration, tv)) {
/*
* Section 3.3.10.3 Stale Cookie Error (3)
*
* Cause of error
* ---------------
* Stale Cookie Error: Indicates the receipt of a valid State
* Cookie that has expired.
*/
len = ntohs(chunk->chunk_hdr->length);
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
suseconds_t usecs = (tv.tv_sec -
bear_cookie->expiration.tv_sec) * 1000000L +
tv.tv_usec - bear_cookie->expiration.tv_usec;
__be32 n = htonl(usecs);
sctp_init_cause(*errp, SCTP_ERROR_STALE_COOKIE,
sizeof(n));
sctp_addto_chunk(*errp, sizeof(n), &n);
*error = -SCTP_IERROR_STALE_COOKIE;
} else
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Make a new base association. */
scope = sctp_scope(sctp_source(chunk));
retval = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!retval) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Set up our peer's port number. */
retval->peer.port = ntohs(chunk->sctp_hdr->source);
/* Populate the association from the cookie. */
memcpy(&retval->c, bear_cookie, sizeof(*bear_cookie));
if (sctp_assoc_set_bind_addr_from_cookie(retval, bear_cookie,
GFP_ATOMIC) < 0) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Also, add the destination address. */
if (list_empty(&retval->base.bind_addr.address_list)) {
sctp_add_bind_addr(&retval->base.bind_addr, &chunk->dest,
SCTP_ADDR_SRC, GFP_ATOMIC);
}
retval->next_tsn = retval->c.initial_tsn;
retval->ctsn_ack_point = retval->next_tsn - 1;
retval->addip_serial = retval->c.initial_tsn;
retval->adv_peer_ack_point = retval->ctsn_ack_point;
retval->peer.prsctp_capable = retval->c.prsctp_capable;
retval->peer.adaptation_ind = retval->c.adaptation_ind;
/* The INIT stuff will be done by the side effects. */
return retval;
fail:
if (retval)
sctp_association_free(retval);
return NULL;
malformed:
/* Yikes! The packet is either corrupt or deliberately
* malformed.
*/
*error = -SCTP_IERROR_MALFORMED;
goto fail;
}
/********************************************************************
* 3rd Level Abstractions
********************************************************************/
struct __sctp_missing {
__be32 num_missing;
__be16 type;
} __packed;
/*
* Report a missing mandatory parameter.
*/
static int sctp_process_missing_param(const struct sctp_association *asoc,
sctp_param_t paramtype,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
struct __sctp_missing report;
__u16 len;
len = WORD_ROUND(sizeof(report));
/* Make an ERROR chunk, preparing enough room for
* returning multiple unknown parameters.
*/
if (!*errp)
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
report.num_missing = htonl(1);
report.type = paramtype;
sctp_init_cause(*errp, SCTP_ERROR_MISS_PARAM,
sizeof(report));
sctp_addto_chunk(*errp, sizeof(report), &report);
}
/* Stop processing this chunk. */
return 0;
}
/* Report an Invalid Mandatory Parameter. */
static int sctp_process_inv_mandatory(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
/* Invalid Mandatory Parameter Error has no payload. */
if (!*errp)
*errp = sctp_make_op_error_space(asoc, chunk, 0);
if (*errp)
sctp_init_cause(*errp, SCTP_ERROR_INV_PARAM, 0);
/* Stop processing this chunk. */
return 0;
}
static int sctp_process_inv_paramlength(const struct sctp_association *asoc,
struct sctp_paramhdr *param,
const struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
/* This is a fatal error. Any accumulated non-fatal errors are
* not reported.
*/
if (*errp)
sctp_chunk_free(*errp);
/* Create an error chunk and fill it in with our payload. */
*errp = sctp_make_violation_paramlen(asoc, chunk, param);
return 0;
}
/* Do not attempt to handle the HOST_NAME parm. However, do
* send back an indicator to the peer.
*/
static int sctp_process_hn_param(const struct sctp_association *asoc,
union sctp_params param,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
__u16 len = ntohs(param.p->length);
/* Processing of the HOST_NAME parameter will generate an
* ABORT. If we've accumulated any non-fatal errors, they
* would be unrecognized parameters and we should not include
* them in the ABORT.
*/
if (*errp)
sctp_chunk_free(*errp);
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
sctp_init_cause(*errp, SCTP_ERROR_DNS_FAILED, len);
sctp_addto_chunk(*errp, len, param.v);
}
/* Stop processing this chunk. */
return 0;
}
static int sctp_verify_ext_param(union sctp_params param)
{
__u16 num_ext = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
int have_auth = 0;
int have_asconf = 0;
int i;
for (i = 0; i < num_ext; i++) {
switch (param.ext->chunks[i]) {
case SCTP_CID_AUTH:
have_auth = 1;
break;
case SCTP_CID_ASCONF:
case SCTP_CID_ASCONF_ACK:
have_asconf = 1;
break;
}
}
/* ADD-IP Security: The draft requires us to ABORT or ignore the
* INIT/INIT-ACK if ADD-IP is listed, but AUTH is not. Do this
* only if ADD-IP is turned on and we are not backward-compatible
* mode.
*/
if (sctp_addip_noauth)
return 1;
if (sctp_addip_enable && !have_auth && have_asconf)
return 0;
return 1;
}
static void sctp_process_ext_param(struct sctp_association *asoc,
union sctp_params param)
{
__u16 num_ext = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
int i;
for (i = 0; i < num_ext; i++) {
switch (param.ext->chunks[i]) {
case SCTP_CID_FWD_TSN:
if (sctp_prsctp_enable &&
!asoc->peer.prsctp_capable)
asoc->peer.prsctp_capable = 1;
break;
case SCTP_CID_AUTH:
/* if the peer reports AUTH, assume that he
* supports AUTH.
*/
if (sctp_auth_enable)
asoc->peer.auth_capable = 1;
break;
case SCTP_CID_ASCONF:
case SCTP_CID_ASCONF_ACK:
if (sctp_addip_enable)
asoc->peer.asconf_capable = 1;
break;
default:
break;
}
}
}
/* RFC 3.2.1 & the Implementers Guide 2.2.
*
* The Parameter Types are encoded such that the
* highest-order two bits specify the action that must be
* taken if the processing endpoint does not recognize the
* Parameter Type.
*
* 00 - Stop processing this parameter; do not process any further
* parameters within this chunk
*
* 01 - Stop processing this parameter, do not process any further
* parameters within this chunk, and report the unrecognized
* parameter in an 'Unrecognized Parameter' ERROR chunk.
*
* 10 - Skip this parameter and continue processing.
*
* 11 - Skip this parameter and continue processing but
* report the unrecognized parameter in an
* 'Unrecognized Parameter' ERROR chunk.
*
* Return value:
* SCTP_IERROR_NO_ERROR - continue with the chunk
* SCTP_IERROR_ERROR - stop and report an error.
* SCTP_IERROR_NOMEME - out of memory.
*/
static sctp_ierror_t sctp_process_unk_param(const struct sctp_association *asoc,
union sctp_params param,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
int retval = SCTP_IERROR_NO_ERROR;
switch (param.p->type & SCTP_PARAM_ACTION_MASK) {
case SCTP_PARAM_ACTION_DISCARD:
retval = SCTP_IERROR_ERROR;
break;
case SCTP_PARAM_ACTION_SKIP:
break;
case SCTP_PARAM_ACTION_DISCARD_ERR:
retval = SCTP_IERROR_ERROR;
/* Fall through */
case SCTP_PARAM_ACTION_SKIP_ERR:
/* Make an ERROR chunk, preparing enough room for
* returning multiple unknown parameters.
*/
if (NULL == *errp)
*errp = sctp_make_op_error_fixed(asoc, chunk);
if (*errp) {
if (!sctp_init_cause_fixed(*errp, SCTP_ERROR_UNKNOWN_PARAM,
WORD_ROUND(ntohs(param.p->length))))
sctp_addto_chunk_fixed(*errp,
WORD_ROUND(ntohs(param.p->length)),
param.v);
} else {
/* If there is no memory for generating the ERROR
* report as specified, an ABORT will be triggered
* to the peer and the association won't be
* established.
*/
retval = SCTP_IERROR_NOMEM;
}
break;
default:
break;
}
return retval;
}
/* Verify variable length parameters
* Return values:
* SCTP_IERROR_ABORT - trigger an ABORT
* SCTP_IERROR_NOMEM - out of memory (abort)
* SCTP_IERROR_ERROR - stop processing, trigger an ERROR
* SCTP_IERROR_NO_ERROR - continue with the chunk
*/
static sctp_ierror_t sctp_verify_param(const struct sctp_association *asoc,
union sctp_params param,
sctp_cid_t cid,
struct sctp_chunk *chunk,
struct sctp_chunk **err_chunk)
{
struct sctp_hmac_algo_param *hmacs;
int retval = SCTP_IERROR_NO_ERROR;
__u16 n_elt, id = 0;
int i;
/* FIXME - This routine is not looking at each parameter per the
* chunk type, i.e., unrecognized parameters should be further
* identified based on the chunk id.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV4_ADDRESS:
case SCTP_PARAM_IPV6_ADDRESS:
case SCTP_PARAM_COOKIE_PRESERVATIVE:
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
case SCTP_PARAM_STATE_COOKIE:
case SCTP_PARAM_HEARTBEAT_INFO:
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
case SCTP_PARAM_ECN_CAPABLE:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
break;
case SCTP_PARAM_SUPPORTED_EXT:
if (!sctp_verify_ext_param(param))
return SCTP_IERROR_ABORT;
break;
case SCTP_PARAM_SET_PRIMARY:
if (sctp_addip_enable)
break;
goto fallthrough;
case SCTP_PARAM_HOST_NAME_ADDRESS:
/* Tell the peer, we won't support this param. */
sctp_process_hn_param(asoc, param, chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (sctp_prsctp_enable)
break;
goto fallthrough;
case SCTP_PARAM_RANDOM:
if (!sctp_auth_enable)
goto fallthrough;
/* SCTP-AUTH: Secion 6.1
* If the random number is not 32 byte long the association
* MUST be aborted. The ABORT chunk SHOULD contain the error
* cause 'Protocol Violation'.
*/
if (SCTP_AUTH_RANDOM_LENGTH !=
ntohs(param.p->length) - sizeof(sctp_paramhdr_t)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_CHUNKS:
if (!sctp_auth_enable)
goto fallthrough;
/* SCTP-AUTH: Section 3.2
* The CHUNKS parameter MUST be included once in the INIT or
* INIT-ACK chunk if the sender wants to receive authenticated
* chunks. Its maximum length is 260 bytes.
*/
if (260 < ntohs(param.p->length)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!sctp_auth_enable)
goto fallthrough;
hmacs = (struct sctp_hmac_algo_param *)param.p;
n_elt = (ntohs(param.p->length) - sizeof(sctp_paramhdr_t)) >> 1;
/* SCTP-AUTH: Section 6.1
* The HMAC algorithm based on SHA-1 MUST be supported and
* included in the HMAC-ALGO parameter.
*/
for (i = 0; i < n_elt; i++) {
id = ntohs(hmacs->hmac_ids[i]);
if (id == SCTP_AUTH_HMAC_ID_SHA1)
break;
}
if (id != SCTP_AUTH_HMAC_ID_SHA1) {
sctp_process_inv_paramlength(asoc, param.p, chunk,
err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
fallthrough:
default:
SCTP_DEBUG_PRINTK("Unrecognized param: %d for chunk %d.\n",
ntohs(param.p->type), cid);
retval = sctp_process_unk_param(asoc, param, chunk, err_chunk);
break;
}
return retval;
}
/* Verify the INIT packet before we process it. */
int sctp_verify_init(const struct sctp_association *asoc,
sctp_cid_t cid,
sctp_init_chunk_t *peer_init,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
union sctp_params param;
int has_cookie = 0;
int result;
/* Verify stream values are non-zero. */
if ((0 == peer_init->init_hdr.num_outbound_streams) ||
(0 == peer_init->init_hdr.num_inbound_streams) ||
(0 == peer_init->init_hdr.init_tag) ||
(SCTP_DEFAULT_MINWINDOW > ntohl(peer_init->init_hdr.a_rwnd))) {
return sctp_process_inv_mandatory(asoc, chunk, errp);
}
/* Check for missing mandatory parameters. */
sctp_walk_params(param, peer_init, init_hdr.params) {
if (SCTP_PARAM_STATE_COOKIE == param.p->type)
has_cookie = 1;
} /* for (loop through all parameters) */
/* There is a possibility that a parameter length was bad and
* in that case we would have stoped walking the parameters.
* The current param.p would point at the bad one.
* Current consensus on the mailing list is to generate a PROTOCOL
* VIOLATION error. We build the ERROR chunk here and let the normal
* error handling code build and send the packet.
*/
if (param.v != (void*)chunk->chunk_end)
return sctp_process_inv_paramlength(asoc, param.p, chunk, errp);
/* The only missing mandatory param possible today is
* the state cookie for an INIT-ACK chunk.
*/
if ((SCTP_CID_INIT_ACK == cid) && !has_cookie)
return sctp_process_missing_param(asoc, SCTP_PARAM_STATE_COOKIE,
chunk, errp);
/* Verify all the variable length parameters */
sctp_walk_params(param, peer_init, init_hdr.params) {
result = sctp_verify_param(asoc, param, cid, chunk, errp);
switch (result) {
case SCTP_IERROR_ABORT:
case SCTP_IERROR_NOMEM:
return 0;
case SCTP_IERROR_ERROR:
return 1;
case SCTP_IERROR_NO_ERROR:
default:
break;
}
} /* for (loop through all parameters) */
return 1;
}
/* Unpack the parameters in an INIT packet into an association.
* Returns 0 on failure, else success.
* FIXME: This is an association method.
*/
int sctp_process_init(struct sctp_association *asoc, struct sctp_chunk *chunk,
const union sctp_addr *peer_addr,
sctp_init_chunk_t *peer_init, gfp_t gfp)
{
union sctp_params param;
struct sctp_transport *transport;
struct list_head *pos, *temp;
struct sctp_af *af;
union sctp_addr addr;
char *cookie;
int src_match = 0;
/* We must include the address that the INIT packet came from.
* This is the only address that matters for an INIT packet.
* When processing a COOKIE ECHO, we retrieve the from address
* of the INIT from the cookie.
*/
/* This implementation defaults to making the first transport
* added as the primary transport. The source address seems to
* be a a better choice than any of the embedded addresses.
*/
if(!sctp_assoc_add_peer(asoc, peer_addr, gfp, SCTP_ACTIVE))
goto nomem;
if (sctp_cmp_addr_exact(sctp_source(chunk), peer_addr))
src_match = 1;
/* Process the initialization parameters. */
sctp_walk_params(param, peer_init, init_hdr.params) {
if (!src_match && (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
param.p->type == SCTP_PARAM_IPV6_ADDRESS)) {
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr,
chunk->sctp_hdr->source, 0);
if (sctp_cmp_addr_exact(sctp_source(chunk), &addr))
src_match = 1;
}
if (!sctp_process_param(asoc, param, peer_addr, gfp))
goto clean_up;
}
/* source address of chunk may not match any valid address */
if (!src_match)
goto clean_up;
/* AUTH: After processing the parameters, make sure that we
* have all the required info to potentially do authentications.
*/
if (asoc->peer.auth_capable && (!asoc->peer.peer_random ||
!asoc->peer.peer_hmacs))
asoc->peer.auth_capable = 0;
/* In a non-backward compatible mode, if the peer claims
* support for ADD-IP but not AUTH, the ADD-IP spec states
* that we MUST ABORT the association. Section 6. The section
* also give us an option to silently ignore the packet, which
* is what we'll do here.
*/
if (!sctp_addip_noauth &&
(asoc->peer.asconf_capable && !asoc->peer.auth_capable)) {
asoc->peer.addip_disabled_mask |= (SCTP_PARAM_ADD_IP |
SCTP_PARAM_DEL_IP |
SCTP_PARAM_SET_PRIMARY);
asoc->peer.asconf_capable = 0;
goto clean_up;
}
/* Walk list of transports, removing transports in the UNKNOWN state. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (transport->state == SCTP_UNKNOWN) {
sctp_assoc_rm_peer(asoc, transport);
}
}
/* The fixed INIT headers are always in network byte
* order.
*/
asoc->peer.i.init_tag =
ntohl(peer_init->init_hdr.init_tag);
asoc->peer.i.a_rwnd =
ntohl(peer_init->init_hdr.a_rwnd);
asoc->peer.i.num_outbound_streams =
ntohs(peer_init->init_hdr.num_outbound_streams);
asoc->peer.i.num_inbound_streams =
ntohs(peer_init->init_hdr.num_inbound_streams);
asoc->peer.i.initial_tsn =
ntohl(peer_init->init_hdr.initial_tsn);
/* Apply the upper bounds for output streams based on peer's
* number of inbound streams.
*/
if (asoc->c.sinit_num_ostreams >
ntohs(peer_init->init_hdr.num_inbound_streams)) {
asoc->c.sinit_num_ostreams =
ntohs(peer_init->init_hdr.num_inbound_streams);
}
if (asoc->c.sinit_max_instreams >
ntohs(peer_init->init_hdr.num_outbound_streams)) {
asoc->c.sinit_max_instreams =
ntohs(peer_init->init_hdr.num_outbound_streams);
}
/* Copy Initiation tag from INIT to VT_peer in cookie. */
asoc->c.peer_vtag = asoc->peer.i.init_tag;
/* Peer Rwnd : Current calculated value of the peer's rwnd. */
asoc->peer.rwnd = asoc->peer.i.a_rwnd;
/* Copy cookie in case we need to resend COOKIE-ECHO. */
cookie = asoc->peer.cookie;
if (cookie) {
asoc->peer.cookie = kmemdup(cookie, asoc->peer.cookie_len, gfp);
if (!asoc->peer.cookie)
goto clean_up;
}
/* RFC 2960 7.2.1 The initial value of ssthresh MAY be arbitrarily
* high (for example, implementations MAY use the size of the receiver
* advertised window).
*/
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
transport->ssthresh = asoc->peer.i.a_rwnd;
}
/* Set up the TSN tracking pieces. */
if (!sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, gfp))
goto clean_up;
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* The stream sequence number in all the streams shall start
* from 0 when the association is established. Also, when the
* stream sequence number reaches the value 65535 the next
* stream sequence number shall be set to 0.
*/
/* Allocate storage for the negotiated streams if it is not a temporary
* association.
*/
if (!asoc->temp) {
int error;
asoc->ssnmap = sctp_ssnmap_new(asoc->c.sinit_max_instreams,
asoc->c.sinit_num_ostreams, gfp);
if (!asoc->ssnmap)
goto clean_up;
error = sctp_assoc_set_id(asoc, gfp);
if (error)
goto clean_up;
}
/* ADDIP Section 4.1 ASCONF Chunk Procedures
*
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do the following:
* ...
* A2) A serial number should be assigned to the Chunk. The serial
* number should be a monotonically increasing number. All serial
* numbers are defined to be initialized at the start of the
* association to the same value as the Initial TSN.
*/
asoc->peer.addip_serial = asoc->peer.i.initial_tsn - 1;
return 1;
clean_up:
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (transport->state != SCTP_ACTIVE)
sctp_assoc_rm_peer(asoc, transport);
}
nomem:
return 0;
}
/* Update asoc with the option described in param.
*
* RFC2960 3.3.2.1 Optional/Variable Length Parameters in INIT
*
* asoc is the association to update.
* param is the variable length parameter to use for update.
* cid tells us if this is an INIT, INIT ACK or COOKIE ECHO.
* If the current packet is an INIT we want to minimize the amount of
* work we do. In particular, we should not build transport
* structures for the addresses.
*/
static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp)
{
union sctp_addr addr;
int i;
__u16 sat;
int retval = 1;
sctp_scope_t scope;
time_t stale;
struct sctp_af *af;
union sctp_addr_param *addr_param;
struct sctp_transport *t;
/* We maintain all INIT parameters in network byte order all the
* time. This allows us to not worry about whether the parameters
* came from a fresh INIT, and INIT ACK, or were stored in a cookie.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 != asoc->base.sk->sk_family)
break;
goto do_addr_param;
case SCTP_PARAM_IPV4_ADDRESS:
/* v4 addresses are not allowed on v6-only socket */
if (ipv6_only_sock(asoc->base.sk))
break;
do_addr_param:
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0);
scope = sctp_scope(peer_addr);
if (sctp_in_scope(&addr, scope))
if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
return 0;
break;
case SCTP_PARAM_COOKIE_PRESERVATIVE:
if (!sctp_cookie_preserve_enable)
break;
stale = ntohl(param.life->lifespan_increment);
/* Suggested Cookie Life span increment's unit is msec,
* (1/1000sec).
*/
asoc->cookie_life.tv_sec += stale / 1000;
asoc->cookie_life.tv_usec += (stale % 1000) * 1000;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
SCTP_DEBUG_PRINTK("unimplemented SCTP_HOST_NAME_ADDRESS\n");
break;
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
/* Turn off the default values first so we'll know which
* ones are really set by the peer.
*/
asoc->peer.ipv4_address = 0;
asoc->peer.ipv6_address = 0;
/* Assume that peer supports the address family
* by which it sends a packet.
*/
if (peer_addr->sa.sa_family == AF_INET6)
asoc->peer.ipv6_address = 1;
else if (peer_addr->sa.sa_family == AF_INET)
asoc->peer.ipv4_address = 1;
/* Cycle through address types; avoid divide by 0. */
sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
if (sat)
sat /= sizeof(__u16);
for (i = 0; i < sat; ++i) {
switch (param.sat->types[i]) {
case SCTP_PARAM_IPV4_ADDRESS:
asoc->peer.ipv4_address = 1;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 == asoc->base.sk->sk_family)
asoc->peer.ipv6_address = 1;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
asoc->peer.hostname_address = 1;
break;
default: /* Just ignore anything else. */
break;
}
}
break;
case SCTP_PARAM_STATE_COOKIE:
asoc->peer.cookie_len =
ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
asoc->peer.cookie = param.cookie->body;
break;
case SCTP_PARAM_HEARTBEAT_INFO:
/* Would be odd to receive, but it causes no problems. */
break;
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
/* Rejected during verify stage. */
break;
case SCTP_PARAM_ECN_CAPABLE:
asoc->peer.ecn_capable = 1;
break;
case SCTP_PARAM_ADAPTATION_LAYER_IND:
asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
break;
case SCTP_PARAM_SET_PRIMARY:
if (!sctp_addip_enable)
goto fall_through;
addr_param = param.v + sizeof(sctp_addip_param_t);
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, addr_param,
htons(asoc->peer.port), 0);
/* if the address is invalid, we can't process it.
* XXX: see spec for what to do.
*/
if (!af->addr_valid(&addr, NULL, NULL))
break;
t = sctp_assoc_lookup_paddr(asoc, &addr);
if (!t)
break;
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_PARAM_SUPPORTED_EXT:
sctp_process_ext_param(asoc, param);
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (sctp_prsctp_enable) {
asoc->peer.prsctp_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_RANDOM:
if (!sctp_auth_enable)
goto fall_through;
/* Save peer's random parameter */
asoc->peer.peer_random = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_random) {
retval = 0;
break;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!sctp_auth_enable)
goto fall_through;
/* Save peer's HMAC list */
asoc->peer.peer_hmacs = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_hmacs) {
retval = 0;
break;
}
/* Set the default HMAC the peer requested*/
sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
break;
case SCTP_PARAM_CHUNKS:
if (!sctp_auth_enable)
goto fall_through;
asoc->peer.peer_chunks = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_chunks)
retval = 0;
break;
fall_through:
default:
/* Any unrecognized parameters should have been caught
* and handled by sctp_verify_param() which should be
* called prior to this routine. Simply log the error
* here.
*/
SCTP_DEBUG_PRINTK("Ignoring param: %d for association %p.\n",
ntohs(param.p->type), asoc);
break;
}
return retval;
}
/* Select a new verification tag. */
__u32 sctp_generate_tag(const struct sctp_endpoint *ep)
{
/* I believe that this random number generator complies with RFC1750.
* A tag of 0 is reserved for special cases (e.g. INIT).
*/
__u32 x;
do {
get_random_bytes(&x, sizeof(__u32));
} while (x == 0);
return x;
}
/* Select an initial TSN to send during startup. */
__u32 sctp_generate_tsn(const struct sctp_endpoint *ep)
{
__u32 retval;
get_random_bytes(&retval, sizeof(__u32));
return retval;
}
/*
* ADDIP 3.1.1 Address Configuration Change Chunk (ASCONF)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC1 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Serial Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter #1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / .... /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter #N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Address Parameter and other parameter will not be wrapped in this function
*/
static struct sctp_chunk *sctp_make_asconf(struct sctp_association *asoc,
union sctp_addr *addr,
int vparam_len)
{
sctp_addiphdr_t asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
union sctp_addr_param addrparam;
int addrlen;
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
length += addrlen;
/* Create the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_ASCONF, 0, length);
if (!retval)
return NULL;
asconf.serial = htonl(asoc->addip_serial++);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
/* ADDIP
* 3.2.1 Add IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC001 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 3.2.2 Delete IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC002 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc,
union sctp_addr *laddr,
struct sockaddr *addrs,
int addrcnt,
__be16 flags)
{
sctp_addip_param_t param;
struct sctp_chunk *retval;
union sctp_addr_param addr_param;
union sctp_addr *addr;
void *addr_buf;
struct sctp_af *af;
int paramlen = sizeof(param);
int addr_param_len = 0;
int totallen = 0;
int i;
int del_pickup = 0;
/* Get total length of all the address parameters. */
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
totallen += paramlen;
totallen += addr_param_len;
addr_buf += af->sockaddr_len;
if (asoc->asconf_addr_del_pending && !del_pickup) {
/* reuse the parameter length from the same scope one */
totallen += paramlen;
totallen += addr_param_len;
del_pickup = 1;
SCTP_DEBUG_PRINTK("mkasconf_update_ip: picked same-scope del_pending addr, totallen for all addresses is %d\n", totallen);
}
}
/* Create an asconf chunk with the required length. */
retval = sctp_make_asconf(asoc, laddr, totallen);
if (!retval)
return NULL;
/* Add the address parameters to the asconf chunk. */
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
param.param_hdr.type = flags;
param.param_hdr.length = htons(paramlen + addr_param_len);
param.crr_id = i;
sctp_addto_chunk(retval, paramlen, ¶m);
sctp_addto_chunk(retval, addr_param_len, &addr_param);
addr_buf += af->sockaddr_len;
}
if (flags == SCTP_PARAM_ADD_IP && del_pickup) {
addr = asoc->asconf_addr_del_pending;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
param.param_hdr.type = SCTP_PARAM_DEL_IP;
param.param_hdr.length = htons(paramlen + addr_param_len);
param.crr_id = i;
sctp_addto_chunk(retval, paramlen, ¶m);
sctp_addto_chunk(retval, addr_param_len, &addr_param);
}
return retval;
}
/* ADDIP
* 3.2.4 Set Primary IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type =0xC004 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Create an ASCONF chunk with Set Primary IP address parameter.
*/
struct sctp_chunk *sctp_make_asconf_set_prim(struct sctp_association *asoc,
union sctp_addr *addr)
{
sctp_addip_param_t param;
struct sctp_chunk *retval;
int len = sizeof(param);
union sctp_addr_param addrparam;
int addrlen;
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
len += addrlen;
/* Create the chunk and make asconf header. */
retval = sctp_make_asconf(asoc, addr, len);
if (!retval)
return NULL;
param.param_hdr.type = SCTP_PARAM_SET_PRIMARY;
param.param_hdr.length = htons(len);
param.crr_id = 0;
sctp_addto_chunk(retval, sizeof(param), ¶m);
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
/* ADDIP 3.1.2 Address Configuration Acknowledgement Chunk (ASCONF-ACK)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0x80 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Serial Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter Response#1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / .... /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter Response#N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Create an ASCONF_ACK chunk with enough space for the parameter responses.
*/
static struct sctp_chunk *sctp_make_asconf_ack(const struct sctp_association *asoc,
__u32 serial, int vparam_len)
{
sctp_addiphdr_t asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
/* Create the chunk. */
retval = sctp_make_chunk(asoc, SCTP_CID_ASCONF_ACK, 0, length);
if (!retval)
return NULL;
asconf.serial = htonl(serial);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
return retval;
}
/* Add response parameters to an ASCONF_ACK chunk. */
static void sctp_add_asconf_response(struct sctp_chunk *chunk, __be32 crr_id,
__be16 err_code, sctp_addip_param_t *asconf_param)
{
sctp_addip_param_t ack_param;
sctp_errhdr_t err_param;
int asconf_param_len = 0;
int err_param_len = 0;
__be16 response_type;
if (SCTP_ERROR_NO_ERROR == err_code) {
response_type = SCTP_PARAM_SUCCESS_REPORT;
} else {
response_type = SCTP_PARAM_ERR_CAUSE;
err_param_len = sizeof(err_param);
if (asconf_param)
asconf_param_len =
ntohs(asconf_param->param_hdr.length);
}
/* Add Success Indication or Error Cause Indication parameter. */
ack_param.param_hdr.type = response_type;
ack_param.param_hdr.length = htons(sizeof(ack_param) +
err_param_len +
asconf_param_len);
ack_param.crr_id = crr_id;
sctp_addto_chunk(chunk, sizeof(ack_param), &ack_param);
if (SCTP_ERROR_NO_ERROR == err_code)
return;
/* Add Error Cause parameter. */
err_param.cause = err_code;
err_param.length = htons(err_param_len + asconf_param_len);
sctp_addto_chunk(chunk, err_param_len, &err_param);
/* Add the failed TLV copied from ASCONF chunk. */
if (asconf_param)
sctp_addto_chunk(chunk, asconf_param_len, asconf_param);
}
/* Process a asconf parameter. */
static __be16 sctp_process_asconf_param(struct sctp_association *asoc,
struct sctp_chunk *asconf,
sctp_addip_param_t *asconf_param)
{
struct sctp_transport *peer;
struct sctp_af *af;
union sctp_addr addr;
union sctp_addr_param *addr_param;
addr_param = (void *)asconf_param + sizeof(sctp_addip_param_t);
if (asconf_param->param_hdr.type != SCTP_PARAM_ADD_IP &&
asconf_param->param_hdr.type != SCTP_PARAM_DEL_IP &&
asconf_param->param_hdr.type != SCTP_PARAM_SET_PRIMARY)
return SCTP_ERROR_UNKNOWN_PARAM;
switch (addr_param->p.type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (!asoc->peer.ipv6_address)
return SCTP_ERROR_DNS_FAILED;
break;
case SCTP_PARAM_IPV4_ADDRESS:
if (!asoc->peer.ipv4_address)
return SCTP_ERROR_DNS_FAILED;
break;
default:
return SCTP_ERROR_DNS_FAILED;
}
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
if (unlikely(!af))
return SCTP_ERROR_DNS_FAILED;
af->from_addr_param(&addr, addr_param, htons(asoc->peer.port), 0);
/* ADDIP 4.2.1 This parameter MUST NOT contain a broadcast
* or multicast address.
* (note: wildcard is permitted and requires special handling so
* make sure we check for that)
*/
if (!af->is_any(&addr) && !af->addr_valid(&addr, NULL, asconf->skb))
return SCTP_ERROR_DNS_FAILED;
switch (asconf_param->param_hdr.type) {
case SCTP_PARAM_ADD_IP:
/* Section 4.2.1:
* If the address 0.0.0.0 or ::0 is provided, the source
* address of the packet MUST be added.
*/
if (af->is_any(&addr))
memcpy(&addr, &asconf->source, sizeof(addr));
/* ADDIP 4.3 D9) If an endpoint receives an ADD IP address
* request and does not have the local resources to add this
* new address to the association, it MUST return an Error
* Cause TLV set to the new error code 'Operation Refused
* Due to Resource Shortage'.
*/
peer = sctp_assoc_add_peer(asoc, &addr, GFP_ATOMIC, SCTP_UNCONFIRMED);
if (!peer)
return SCTP_ERROR_RSRC_LOW;
/* Start the heartbeat timer. */
if (!mod_timer(&peer->hb_timer, sctp_transport_timeout(peer)))
sctp_transport_hold(peer);
asoc->new_transport = peer;
break;
case SCTP_PARAM_DEL_IP:
/* ADDIP 4.3 D7) If a request is received to delete the
* last remaining IP address of a peer endpoint, the receiver
* MUST send an Error Cause TLV with the error cause set to the
* new error code 'Request to Delete Last Remaining IP Address'.
*/
if (asoc->peer.transport_count == 1)
return SCTP_ERROR_DEL_LAST_IP;
/* ADDIP 4.3 D8) If a request is received to delete an IP
* address which is also the source address of the IP packet
* which contained the ASCONF chunk, the receiver MUST reject
* this request. To reject the request the receiver MUST send
* an Error Cause TLV set to the new error code 'Request to
* Delete Source IP Address'
*/
if (sctp_cmp_addr_exact(&asconf->source, &addr))
return SCTP_ERROR_DEL_SRC_IP;
/* Section 4.2.2
* If the address 0.0.0.0 or ::0 is provided, all
* addresses of the peer except the source address of the
* packet MUST be deleted.
*/
if (af->is_any(&addr)) {
sctp_assoc_set_primary(asoc, asconf->transport);
sctp_assoc_del_nonprimary_peers(asoc,
asconf->transport);
} else
sctp_assoc_del_peer(asoc, &addr);
break;
case SCTP_PARAM_SET_PRIMARY:
/* ADDIP Section 4.2.4
* If the address 0.0.0.0 or ::0 is provided, the receiver
* MAY mark the source address of the packet as its
* primary.
*/
if (af->is_any(&addr))
memcpy(&addr.v4, sctp_source(asconf), sizeof(addr));
peer = sctp_assoc_lookup_paddr(asoc, &addr);
if (!peer)
return SCTP_ERROR_DNS_FAILED;
sctp_assoc_set_primary(asoc, peer);
break;
}
return SCTP_ERROR_NO_ERROR;
}
/* Verify the ASCONF packet before we process it. */
int sctp_verify_asconf(const struct sctp_association *asoc,
struct sctp_paramhdr *param_hdr, void *chunk_end,
struct sctp_paramhdr **errp) {
sctp_addip_param_t *asconf_param;
union sctp_params param;
int length, plen;
param.v = (sctp_paramhdr_t *) param_hdr;
while (param.v <= chunk_end - sizeof(sctp_paramhdr_t)) {
length = ntohs(param.p->length);
*errp = param.p;
if (param.v > chunk_end - length ||
length < sizeof(sctp_paramhdr_t))
return 0;
switch (param.p->type) {
case SCTP_PARAM_ADD_IP:
case SCTP_PARAM_DEL_IP:
case SCTP_PARAM_SET_PRIMARY:
asconf_param = (sctp_addip_param_t *)param.v;
plen = ntohs(asconf_param->param_hdr.length);
if (plen < sizeof(sctp_addip_param_t) +
sizeof(sctp_paramhdr_t))
return 0;
break;
case SCTP_PARAM_SUCCESS_REPORT:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
if (length != sizeof(sctp_addip_param_t))
return 0;
break;
default:
break;
}
param.v += WORD_ROUND(length);
}
if (param.v != chunk_end)
return 0;
return 1;
}
/* Process an incoming ASCONF chunk with the next expected serial no. and
* return an ASCONF_ACK chunk to be sent in response.
*/
struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc,
struct sctp_chunk *asconf)
{
sctp_addiphdr_t *hdr;
union sctp_addr_param *addr_param;
sctp_addip_param_t *asconf_param;
struct sctp_chunk *asconf_ack;
__be16 err_code;
int length = 0;
int chunk_len;
__u32 serial;
int all_param_pass = 1;
chunk_len = ntohs(asconf->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
hdr = (sctp_addiphdr_t *)asconf->skb->data;
serial = ntohl(hdr->serial);
/* Skip the addiphdr and store a pointer to address parameter. */
length = sizeof(sctp_addiphdr_t);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
chunk_len -= length;
/* Skip the address parameter and store a pointer to the first
* asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
chunk_len -= length;
/* create an ASCONF_ACK chunk.
* Based on the definitions of parameters, we know that the size of
* ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF
* parameters.
*/
asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4);
if (!asconf_ack)
goto done;
/* Process the TLVs contained within the ASCONF chunk. */
while (chunk_len > 0) {
err_code = sctp_process_asconf_param(asoc, asconf,
asconf_param);
/* ADDIP 4.1 A7)
* If an error response is received for a TLV parameter,
* all TLVs with no response before the failed TLV are
* considered successful if not reported. All TLVs after
* the failed response are considered unsuccessful unless
* a specific success indication is present for the parameter.
*/
if (SCTP_ERROR_NO_ERROR != err_code)
all_param_pass = 0;
if (!all_param_pass)
sctp_add_asconf_response(asconf_ack,
asconf_param->crr_id, err_code,
asconf_param);
/* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add
* an IP address sends an 'Out of Resource' in its response, it
* MUST also fail any subsequent add or delete requests bundled
* in the ASCONF.
*/
if (SCTP_ERROR_RSRC_LOW == err_code)
goto done;
/* Move to the next ASCONF param. */
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
chunk_len -= length;
}
done:
asoc->peer.addip_serial++;
/* If we are sending a new ASCONF_ACK hold a reference to it in assoc
* after freeing the reference to old asconf ack if any.
*/
if (asconf_ack) {
sctp_chunk_hold(asconf_ack);
list_add_tail(&asconf_ack->transmitted_list,
&asoc->asconf_ack_list);
}
return asconf_ack;
}
/* Process a asconf parameter that is successfully acked. */
static void sctp_asconf_param_success(struct sctp_association *asoc,
sctp_addip_param_t *asconf_param)
{
struct sctp_af *af;
union sctp_addr addr;
struct sctp_bind_addr *bp = &asoc->base.bind_addr;
union sctp_addr_param *addr_param;
struct sctp_transport *transport;
struct sctp_sockaddr_entry *saddr;
addr_param = (void *)asconf_param + sizeof(sctp_addip_param_t);
/* We have checked the packet before, so we do not check again. */
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
af->from_addr_param(&addr, addr_param, htons(bp->port), 0);
switch (asconf_param->param_hdr.type) {
case SCTP_PARAM_ADD_IP:
/* This is always done in BH context with a socket lock
* held, so the list can not change.
*/
local_bh_disable();
list_for_each_entry(saddr, &bp->address_list, list) {
if (sctp_cmp_addr_exact(&saddr->a, &addr))
saddr->state = SCTP_ADDR_SRC;
}
local_bh_enable();
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
dst_release(transport->dst);
transport->dst = NULL;
}
break;
case SCTP_PARAM_DEL_IP:
local_bh_disable();
sctp_del_bind_addr(bp, &addr);
if (asoc->asconf_addr_del_pending != NULL &&
sctp_cmp_addr_exact(asoc->asconf_addr_del_pending, &addr)) {
kfree(asoc->asconf_addr_del_pending);
asoc->asconf_addr_del_pending = NULL;
}
local_bh_enable();
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
dst_release(transport->dst);
transport->dst = NULL;
}
break;
default:
break;
}
}
/* Get the corresponding ASCONF response error code from the ASCONF_ACK chunk
* for the given asconf parameter. If there is no response for this parameter,
* return the error code based on the third argument 'no_err'.
* ADDIP 4.1
* A7) If an error response is received for a TLV parameter, all TLVs with no
* response before the failed TLV are considered successful if not reported.
* All TLVs after the failed response are considered unsuccessful unless a
* specific success indication is present for the parameter.
*/
static __be16 sctp_get_asconf_response(struct sctp_chunk *asconf_ack,
sctp_addip_param_t *asconf_param,
int no_err)
{
sctp_addip_param_t *asconf_ack_param;
sctp_errhdr_t *err_param;
int length;
int asconf_ack_len;
__be16 err_code;
if (no_err)
err_code = SCTP_ERROR_NO_ERROR;
else
err_code = SCTP_ERROR_REQ_REFUSED;
asconf_ack_len = ntohs(asconf_ack->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
/* Skip the addiphdr from the asconf_ack chunk and store a pointer to
* the first asconf_ack parameter.
*/
length = sizeof(sctp_addiphdr_t);
asconf_ack_param = (sctp_addip_param_t *)(asconf_ack->skb->data +
length);
asconf_ack_len -= length;
while (asconf_ack_len > 0) {
if (asconf_ack_param->crr_id == asconf_param->crr_id) {
switch(asconf_ack_param->param_hdr.type) {
case SCTP_PARAM_SUCCESS_REPORT:
return SCTP_ERROR_NO_ERROR;
case SCTP_PARAM_ERR_CAUSE:
length = sizeof(sctp_addip_param_t);
err_param = (void *)asconf_ack_param + length;
asconf_ack_len -= length;
if (asconf_ack_len > 0)
return err_param->cause;
else
return SCTP_ERROR_INV_PARAM;
break;
default:
return SCTP_ERROR_INV_PARAM;
}
}
length = ntohs(asconf_ack_param->param_hdr.length);
asconf_ack_param = (void *)asconf_ack_param + length;
asconf_ack_len -= length;
}
return err_code;
}
/* Process an incoming ASCONF_ACK chunk against the cached last ASCONF chunk. */
int sctp_process_asconf_ack(struct sctp_association *asoc,
struct sctp_chunk *asconf_ack)
{
struct sctp_chunk *asconf = asoc->addip_last_asconf;
union sctp_addr_param *addr_param;
sctp_addip_param_t *asconf_param;
int length = 0;
int asconf_len = asconf->skb->len;
int all_param_pass = 0;
int no_err = 1;
int retval = 0;
__be16 err_code = SCTP_ERROR_NO_ERROR;
/* Skip the chunkhdr and addiphdr from the last asconf sent and store
* a pointer to address parameter.
*/
length = sizeof(sctp_addip_chunk_t);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
asconf_len -= length;
/* Skip the address parameter in the last asconf sent and store a
* pointer to the first asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
asconf_len -= length;
/* ADDIP 4.1
* A8) If there is no response(s) to specific TLV parameter(s), and no
* failures are indicated, then all request(s) are considered
* successful.
*/
if (asconf_ack->skb->len == sizeof(sctp_addiphdr_t))
all_param_pass = 1;
/* Process the TLVs contained in the last sent ASCONF chunk. */
while (asconf_len > 0) {
if (all_param_pass)
err_code = SCTP_ERROR_NO_ERROR;
else {
err_code = sctp_get_asconf_response(asconf_ack,
asconf_param,
no_err);
if (no_err && (SCTP_ERROR_NO_ERROR != err_code))
no_err = 0;
}
switch (err_code) {
case SCTP_ERROR_NO_ERROR:
sctp_asconf_param_success(asoc, asconf_param);
break;
case SCTP_ERROR_RSRC_LOW:
retval = 1;
break;
case SCTP_ERROR_UNKNOWN_PARAM:
/* Disable sending this type of asconf parameter in
* future.
*/
asoc->peer.addip_disabled_mask |=
asconf_param->param_hdr.type;
break;
case SCTP_ERROR_REQ_REFUSED:
case SCTP_ERROR_DEL_LAST_IP:
case SCTP_ERROR_DEL_SRC_IP:
default:
break;
}
/* Skip the processed asconf parameter and move to the next
* one.
*/
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
asconf_len -= length;
}
if (no_err && asoc->src_out_of_asoc_ok) {
asoc->src_out_of_asoc_ok = 0;
sctp_transport_immediate_rtx(asoc->peer.primary_path);
}
/* Free the cached last sent asconf chunk. */
list_del_init(&asconf->transmitted_list);
sctp_chunk_free(asconf);
asoc->addip_last_asconf = NULL;
return retval;
}
/* Make a FWD TSN chunk. */
struct sctp_chunk *sctp_make_fwdtsn(const struct sctp_association *asoc,
__u32 new_cum_tsn, size_t nstreams,
struct sctp_fwdtsn_skip *skiplist)
{
struct sctp_chunk *retval = NULL;
struct sctp_fwdtsn_hdr ftsn_hdr;
struct sctp_fwdtsn_skip skip;
size_t hint;
int i;
hint = (nstreams + 1) * sizeof(__u32);
retval = sctp_make_chunk(asoc, SCTP_CID_FWD_TSN, 0, hint);
if (!retval)
return NULL;
ftsn_hdr.new_cum_tsn = htonl(new_cum_tsn);
retval->subh.fwdtsn_hdr =
sctp_addto_chunk(retval, sizeof(ftsn_hdr), &ftsn_hdr);
for (i = 0; i < nstreams; i++) {
skip.stream = skiplist[i].stream;
skip.ssn = skiplist[i].ssn;
sctp_addto_chunk(retval, sizeof(skip), &skip);
}
return retval;
}
| gpl-2.0 |
uarka/linux-next | net/netfilter/nf_conntrack_snmp.c | 4570 | 2272 | /*
* SNMP service broadcast connection tracking helper
*
* (c) 2011 Jiri Olsa <jolsa@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/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/in.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <linux/netfilter/nf_conntrack_snmp.h>
#define SNMP_PORT 161
MODULE_AUTHOR("Jiri Olsa <jolsa@redhat.com>");
MODULE_DESCRIPTION("SNMP service broadcast connection tracking helper");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NFCT_HELPER("snmp");
static unsigned int timeout __read_mostly = 30;
module_param(timeout, uint, S_IRUSR);
MODULE_PARM_DESC(timeout, "timeout for master connection/replies in seconds");
int (*nf_nat_snmp_hook)(struct sk_buff *skb,
unsigned int protoff,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo);
EXPORT_SYMBOL_GPL(nf_nat_snmp_hook);
static int snmp_conntrack_help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
typeof(nf_nat_snmp_hook) nf_nat_snmp;
nf_conntrack_broadcast_help(skb, protoff, ct, ctinfo, timeout);
nf_nat_snmp = rcu_dereference(nf_nat_snmp_hook);
if (nf_nat_snmp && ct->status & IPS_NAT_MASK)
return nf_nat_snmp(skb, protoff, ct, ctinfo);
return NF_ACCEPT;
}
static struct nf_conntrack_expect_policy exp_policy = {
.max_expected = 1,
};
static struct nf_conntrack_helper helper __read_mostly = {
.name = "snmp",
.tuple.src.l3num = NFPROTO_IPV4,
.tuple.src.u.udp.port = cpu_to_be16(SNMP_PORT),
.tuple.dst.protonum = IPPROTO_UDP,
.me = THIS_MODULE,
.help = snmp_conntrack_help,
.expect_policy = &exp_policy,
};
static int __init nf_conntrack_snmp_init(void)
{
exp_policy.timeout = timeout;
return nf_conntrack_helper_register(&helper);
}
static void __exit nf_conntrack_snmp_fini(void)
{
nf_conntrack_helper_unregister(&helper);
}
module_init(nf_conntrack_snmp_init);
module_exit(nf_conntrack_snmp_fini);
| gpl-2.0 |
shskyinfo/android_kernel_lge_e610 | arch/arm/mach-davinci/clock.c | 4826 | 14835 | /*
* Clock and PLL control for DaVinci devices
*
* Copyright (C) 2006-2007 Texas Instruments.
* Copyright (C) 2008-2009 Deep Root Systems, LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <mach/hardware.h>
#include <mach/clock.h>
#include <mach/psc.h>
#include <mach/cputype.h>
#include "clock.h"
static LIST_HEAD(clocks);
static DEFINE_MUTEX(clocks_mutex);
static DEFINE_SPINLOCK(clockfw_lock);
static void __clk_enable(struct clk *clk)
{
if (clk->parent)
__clk_enable(clk->parent);
if (clk->usecount++ == 0 && (clk->flags & CLK_PSC))
davinci_psc_config(clk->domain, clk->gpsc, clk->lpsc,
true, clk->flags);
}
static void __clk_disable(struct clk *clk)
{
if (WARN_ON(clk->usecount == 0))
return;
if (--clk->usecount == 0 && !(clk->flags & CLK_PLL) &&
(clk->flags & CLK_PSC))
davinci_psc_config(clk->domain, clk->gpsc, clk->lpsc,
false, clk->flags);
if (clk->parent)
__clk_disable(clk->parent);
}
int clk_enable(struct clk *clk)
{
unsigned long flags;
if (clk == NULL || IS_ERR(clk))
return -EINVAL;
spin_lock_irqsave(&clockfw_lock, flags);
__clk_enable(clk);
spin_unlock_irqrestore(&clockfw_lock, flags);
return 0;
}
EXPORT_SYMBOL(clk_enable);
void clk_disable(struct clk *clk)
{
unsigned long flags;
if (clk == NULL || IS_ERR(clk))
return;
spin_lock_irqsave(&clockfw_lock, flags);
__clk_disable(clk);
spin_unlock_irqrestore(&clockfw_lock, flags);
}
EXPORT_SYMBOL(clk_disable);
unsigned long clk_get_rate(struct clk *clk)
{
if (clk == NULL || IS_ERR(clk))
return -EINVAL;
return clk->rate;
}
EXPORT_SYMBOL(clk_get_rate);
long clk_round_rate(struct clk *clk, unsigned long rate)
{
if (clk == NULL || IS_ERR(clk))
return -EINVAL;
if (clk->round_rate)
return clk->round_rate(clk, rate);
return clk->rate;
}
EXPORT_SYMBOL(clk_round_rate);
/* Propagate rate to children */
static void propagate_rate(struct clk *root)
{
struct clk *clk;
list_for_each_entry(clk, &root->children, childnode) {
if (clk->recalc)
clk->rate = clk->recalc(clk);
propagate_rate(clk);
}
}
int clk_set_rate(struct clk *clk, unsigned long rate)
{
unsigned long flags;
int ret = -EINVAL;
if (clk == NULL || IS_ERR(clk))
return ret;
if (clk->set_rate)
ret = clk->set_rate(clk, rate);
spin_lock_irqsave(&clockfw_lock, flags);
if (ret == 0) {
if (clk->recalc)
clk->rate = clk->recalc(clk);
propagate_rate(clk);
}
spin_unlock_irqrestore(&clockfw_lock, flags);
return ret;
}
EXPORT_SYMBOL(clk_set_rate);
int clk_set_parent(struct clk *clk, struct clk *parent)
{
unsigned long flags;
if (clk == NULL || IS_ERR(clk))
return -EINVAL;
/* Cannot change parent on enabled clock */
if (WARN_ON(clk->usecount))
return -EINVAL;
mutex_lock(&clocks_mutex);
clk->parent = parent;
list_del_init(&clk->childnode);
list_add(&clk->childnode, &clk->parent->children);
mutex_unlock(&clocks_mutex);
spin_lock_irqsave(&clockfw_lock, flags);
if (clk->recalc)
clk->rate = clk->recalc(clk);
propagate_rate(clk);
spin_unlock_irqrestore(&clockfw_lock, flags);
return 0;
}
EXPORT_SYMBOL(clk_set_parent);
int clk_register(struct clk *clk)
{
if (clk == NULL || IS_ERR(clk))
return -EINVAL;
if (WARN(clk->parent && !clk->parent->rate,
"CLK: %s parent %s has no rate!\n",
clk->name, clk->parent->name))
return -EINVAL;
INIT_LIST_HEAD(&clk->children);
mutex_lock(&clocks_mutex);
list_add_tail(&clk->node, &clocks);
if (clk->parent)
list_add_tail(&clk->childnode, &clk->parent->children);
mutex_unlock(&clocks_mutex);
/* If rate is already set, use it */
if (clk->rate)
return 0;
/* Else, see if there is a way to calculate it */
if (clk->recalc)
clk->rate = clk->recalc(clk);
/* Otherwise, default to parent rate */
else if (clk->parent)
clk->rate = clk->parent->rate;
return 0;
}
EXPORT_SYMBOL(clk_register);
void clk_unregister(struct clk *clk)
{
if (clk == NULL || IS_ERR(clk))
return;
mutex_lock(&clocks_mutex);
list_del(&clk->node);
list_del(&clk->childnode);
mutex_unlock(&clocks_mutex);
}
EXPORT_SYMBOL(clk_unregister);
#ifdef CONFIG_DAVINCI_RESET_CLOCKS
/*
* Disable any unused clocks left on by the bootloader
*/
static int __init clk_disable_unused(void)
{
struct clk *ck;
spin_lock_irq(&clockfw_lock);
list_for_each_entry(ck, &clocks, node) {
if (ck->usecount > 0)
continue;
if (!(ck->flags & CLK_PSC))
continue;
/* ignore if in Disabled or SwRstDisable states */
if (!davinci_psc_is_clk_active(ck->gpsc, ck->lpsc))
continue;
pr_debug("Clocks: disable unused %s\n", ck->name);
davinci_psc_config(ck->domain, ck->gpsc, ck->lpsc,
false, ck->flags);
}
spin_unlock_irq(&clockfw_lock);
return 0;
}
late_initcall(clk_disable_unused);
#endif
static unsigned long clk_sysclk_recalc(struct clk *clk)
{
u32 v, plldiv;
struct pll_data *pll;
unsigned long rate = clk->rate;
/* If this is the PLL base clock, no more calculations needed */
if (clk->pll_data)
return rate;
if (WARN_ON(!clk->parent))
return rate;
rate = clk->parent->rate;
/* Otherwise, the parent must be a PLL */
if (WARN_ON(!clk->parent->pll_data))
return rate;
pll = clk->parent->pll_data;
/* If pre-PLL, source clock is before the multiplier and divider(s) */
if (clk->flags & PRE_PLL)
rate = pll->input_rate;
if (!clk->div_reg)
return rate;
v = __raw_readl(pll->base + clk->div_reg);
if (v & PLLDIV_EN) {
plldiv = (v & pll->div_ratio_mask) + 1;
if (plldiv)
rate /= plldiv;
}
return rate;
}
int davinci_set_sysclk_rate(struct clk *clk, unsigned long rate)
{
unsigned v;
struct pll_data *pll;
unsigned long input;
unsigned ratio = 0;
/* If this is the PLL base clock, wrong function to call */
if (clk->pll_data)
return -EINVAL;
/* There must be a parent... */
if (WARN_ON(!clk->parent))
return -EINVAL;
/* ... the parent must be a PLL... */
if (WARN_ON(!clk->parent->pll_data))
return -EINVAL;
/* ... and this clock must have a divider. */
if (WARN_ON(!clk->div_reg))
return -EINVAL;
pll = clk->parent->pll_data;
input = clk->parent->rate;
/* If pre-PLL, source clock is before the multiplier and divider(s) */
if (clk->flags & PRE_PLL)
input = pll->input_rate;
if (input > rate) {
/*
* Can afford to provide an output little higher than requested
* only if maximum rate supported by hardware on this sysclk
* is known.
*/
if (clk->maxrate) {
ratio = DIV_ROUND_CLOSEST(input, rate);
if (input / ratio > clk->maxrate)
ratio = 0;
}
if (ratio == 0)
ratio = DIV_ROUND_UP(input, rate);
ratio--;
}
if (ratio > pll->div_ratio_mask)
return -EINVAL;
do {
v = __raw_readl(pll->base + PLLSTAT);
} while (v & PLLSTAT_GOSTAT);
v = __raw_readl(pll->base + clk->div_reg);
v &= ~pll->div_ratio_mask;
v |= ratio | PLLDIV_EN;
__raw_writel(v, pll->base + clk->div_reg);
v = __raw_readl(pll->base + PLLCMD);
v |= PLLCMD_GOSET;
__raw_writel(v, pll->base + PLLCMD);
do {
v = __raw_readl(pll->base + PLLSTAT);
} while (v & PLLSTAT_GOSTAT);
return 0;
}
EXPORT_SYMBOL(davinci_set_sysclk_rate);
static unsigned long clk_leafclk_recalc(struct clk *clk)
{
if (WARN_ON(!clk->parent))
return clk->rate;
return clk->parent->rate;
}
int davinci_simple_set_rate(struct clk *clk, unsigned long rate)
{
clk->rate = rate;
return 0;
}
static unsigned long clk_pllclk_recalc(struct clk *clk)
{
u32 ctrl, mult = 1, prediv = 1, postdiv = 1;
u8 bypass;
struct pll_data *pll = clk->pll_data;
unsigned long rate = clk->rate;
ctrl = __raw_readl(pll->base + PLLCTL);
rate = pll->input_rate = clk->parent->rate;
if (ctrl & PLLCTL_PLLEN) {
bypass = 0;
mult = __raw_readl(pll->base + PLLM);
if (cpu_is_davinci_dm365())
mult = 2 * (mult & PLLM_PLLM_MASK);
else
mult = (mult & PLLM_PLLM_MASK) + 1;
} else
bypass = 1;
if (pll->flags & PLL_HAS_PREDIV) {
prediv = __raw_readl(pll->base + PREDIV);
if (prediv & PLLDIV_EN)
prediv = (prediv & pll->div_ratio_mask) + 1;
else
prediv = 1;
}
/* pre-divider is fixed, but (some?) chips won't report that */
if (cpu_is_davinci_dm355() && pll->num == 1)
prediv = 8;
if (pll->flags & PLL_HAS_POSTDIV) {
postdiv = __raw_readl(pll->base + POSTDIV);
if (postdiv & PLLDIV_EN)
postdiv = (postdiv & pll->div_ratio_mask) + 1;
else
postdiv = 1;
}
if (!bypass) {
rate /= prediv;
rate *= mult;
rate /= postdiv;
}
pr_debug("PLL%d: input = %lu MHz [ ",
pll->num, clk->parent->rate / 1000000);
if (bypass)
pr_debug("bypass ");
if (prediv > 1)
pr_debug("/ %d ", prediv);
if (mult > 1)
pr_debug("* %d ", mult);
if (postdiv > 1)
pr_debug("/ %d ", postdiv);
pr_debug("] --> %lu MHz output.\n", rate / 1000000);
return rate;
}
/**
* davinci_set_pllrate - set the output rate of a given PLL.
*
* Note: Currently tested to work with OMAP-L138 only.
*
* @pll: pll whose rate needs to be changed.
* @prediv: The pre divider value. Passing 0 disables the pre-divider.
* @pllm: The multiplier value. Passing 0 leads to multiply-by-one.
* @postdiv: The post divider value. Passing 0 disables the post-divider.
*/
int davinci_set_pllrate(struct pll_data *pll, unsigned int prediv,
unsigned int mult, unsigned int postdiv)
{
u32 ctrl;
unsigned int locktime;
unsigned long flags;
if (pll->base == NULL)
return -EINVAL;
/*
* PLL lock time required per OMAP-L138 datasheet is
* (2000 * prediv)/sqrt(pllm) OSCIN cycles. We approximate sqrt(pllm)
* as 4 and OSCIN cycle as 25 MHz.
*/
if (prediv) {
locktime = ((2000 * prediv) / 100);
prediv = (prediv - 1) | PLLDIV_EN;
} else {
locktime = PLL_LOCK_TIME;
}
if (postdiv)
postdiv = (postdiv - 1) | PLLDIV_EN;
if (mult)
mult = mult - 1;
/* Protect against simultaneous calls to PLL setting seqeunce */
spin_lock_irqsave(&clockfw_lock, flags);
ctrl = __raw_readl(pll->base + PLLCTL);
/* Switch the PLL to bypass mode */
ctrl &= ~(PLLCTL_PLLENSRC | PLLCTL_PLLEN);
__raw_writel(ctrl, pll->base + PLLCTL);
udelay(PLL_BYPASS_TIME);
/* Reset and enable PLL */
ctrl &= ~(PLLCTL_PLLRST | PLLCTL_PLLDIS);
__raw_writel(ctrl, pll->base + PLLCTL);
if (pll->flags & PLL_HAS_PREDIV)
__raw_writel(prediv, pll->base + PREDIV);
__raw_writel(mult, pll->base + PLLM);
if (pll->flags & PLL_HAS_POSTDIV)
__raw_writel(postdiv, pll->base + POSTDIV);
udelay(PLL_RESET_TIME);
/* Bring PLL out of reset */
ctrl |= PLLCTL_PLLRST;
__raw_writel(ctrl, pll->base + PLLCTL);
udelay(locktime);
/* Remove PLL from bypass mode */
ctrl |= PLLCTL_PLLEN;
__raw_writel(ctrl, pll->base + PLLCTL);
spin_unlock_irqrestore(&clockfw_lock, flags);
return 0;
}
EXPORT_SYMBOL(davinci_set_pllrate);
/**
* davinci_set_refclk_rate() - Set the reference clock rate
* @rate: The new rate.
*
* Sets the reference clock rate to a given value. This will most likely
* result in the entire clock tree getting updated.
*
* This is used to support boards which use a reference clock different
* than that used by default in <soc>.c file. The reference clock rate
* should be updated early in the boot process; ideally soon after the
* clock tree has been initialized once with the default reference clock
* rate (davinci_common_init()).
*
* Returns 0 on success, error otherwise.
*/
int davinci_set_refclk_rate(unsigned long rate)
{
struct clk *refclk;
refclk = clk_get(NULL, "ref");
if (IS_ERR(refclk)) {
pr_err("%s: failed to get reference clock.\n", __func__);
return PTR_ERR(refclk);
}
clk_set_rate(refclk, rate);
clk_put(refclk);
return 0;
}
int __init davinci_clk_init(struct clk_lookup *clocks)
{
struct clk_lookup *c;
struct clk *clk;
size_t num_clocks = 0;
for (c = clocks; c->clk; c++) {
clk = c->clk;
if (!clk->recalc) {
/* Check if clock is a PLL */
if (clk->pll_data)
clk->recalc = clk_pllclk_recalc;
/* Else, if it is a PLL-derived clock */
else if (clk->flags & CLK_PLL)
clk->recalc = clk_sysclk_recalc;
/* Otherwise, it is a leaf clock (PSC clock) */
else if (clk->parent)
clk->recalc = clk_leafclk_recalc;
}
if (clk->pll_data) {
struct pll_data *pll = clk->pll_data;
if (!pll->div_ratio_mask)
pll->div_ratio_mask = PLLDIV_RATIO_MASK;
if (pll->phys_base && !pll->base) {
pll->base = ioremap(pll->phys_base, SZ_4K);
WARN_ON(!pll->base);
}
}
if (clk->recalc)
clk->rate = clk->recalc(clk);
if (clk->lpsc)
clk->flags |= CLK_PSC;
clk_register(clk);
num_clocks++;
/* Turn on clocks that Linux doesn't otherwise manage */
if (clk->flags & ALWAYS_ENABLED)
clk_enable(clk);
}
clkdev_add_table(clocks, num_clocks);
return 0;
}
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#define CLKNAME_MAX 10 /* longest clock name */
#define NEST_DELTA 2
#define NEST_MAX 4
static void
dump_clock(struct seq_file *s, unsigned nest, struct clk *parent)
{
char *state;
char buf[CLKNAME_MAX + NEST_DELTA * NEST_MAX];
struct clk *clk;
unsigned i;
if (parent->flags & CLK_PLL)
state = "pll";
else if (parent->flags & CLK_PSC)
state = "psc";
else
state = "";
/* <nest spaces> name <pad to end> */
memset(buf, ' ', sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
i = strlen(parent->name);
memcpy(buf + nest, parent->name,
min(i, (unsigned)(sizeof(buf) - 1 - nest)));
seq_printf(s, "%s users=%2d %-3s %9ld Hz\n",
buf, parent->usecount, state, clk_get_rate(parent));
/* REVISIT show device associations too */
/* cost is now small, but not linear... */
list_for_each_entry(clk, &parent->children, childnode) {
dump_clock(s, nest + NEST_DELTA, clk);
}
}
static int davinci_ck_show(struct seq_file *m, void *v)
{
struct clk *clk;
/*
* Show clock tree; We trust nonzero usecounts equate to PSC enables...
*/
mutex_lock(&clocks_mutex);
list_for_each_entry(clk, &clocks, node)
if (!clk->parent)
dump_clock(m, 0, clk);
mutex_unlock(&clocks_mutex);
return 0;
}
static int davinci_ck_open(struct inode *inode, struct file *file)
{
return single_open(file, davinci_ck_show, NULL);
}
static const struct file_operations davinci_ck_operations = {
.open = davinci_ck_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init davinci_clk_debugfs_init(void)
{
debugfs_create_file("davinci_clocks", S_IFREG | S_IRUGO, NULL, NULL,
&davinci_ck_operations);
return 0;
}
device_initcall(davinci_clk_debugfs_init);
#endif /* CONFIG_DEBUG_FS */
| gpl-2.0 |
estiko/lenovo_a706_xoplax | arch/mips/oprofile/common.c | 5082 | 2900 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2004, 2005 Ralf Baechle
* Copyright (C) 2005 MIPS Technologies, Inc.
*/
#include <linux/compiler.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/oprofile.h>
#include <linux/smp.h>
#include <asm/cpu-info.h>
#include "op_impl.h"
extern struct op_mips_model op_model_mipsxx_ops __weak;
extern struct op_mips_model op_model_rm9000_ops __weak;
extern struct op_mips_model op_model_loongson2_ops __weak;
static struct op_mips_model *model;
static struct op_counter_config ctr[20];
static int op_mips_setup(void)
{
/* Pre-compute the values to stuff in the hardware registers. */
model->reg_setup(ctr);
/* Configure the registers on all cpus. */
on_each_cpu(model->cpu_setup, NULL, 1);
return 0;
}
static int op_mips_create_files(struct super_block *sb, struct dentry *root)
{
int i;
for (i = 0; i < model->num_counters; ++i) {
struct dentry *dir;
char buf[4];
snprintf(buf, sizeof buf, "%d", i);
dir = oprofilefs_mkdir(sb, root, buf);
oprofilefs_create_ulong(sb, dir, "enabled", &ctr[i].enabled);
oprofilefs_create_ulong(sb, dir, "event", &ctr[i].event);
oprofilefs_create_ulong(sb, dir, "count", &ctr[i].count);
oprofilefs_create_ulong(sb, dir, "kernel", &ctr[i].kernel);
oprofilefs_create_ulong(sb, dir, "user", &ctr[i].user);
oprofilefs_create_ulong(sb, dir, "exl", &ctr[i].exl);
/* Dummy. */
oprofilefs_create_ulong(sb, dir, "unit_mask", &ctr[i].unit_mask);
}
return 0;
}
static int op_mips_start(void)
{
on_each_cpu(model->cpu_start, NULL, 1);
return 0;
}
static void op_mips_stop(void)
{
/* Disable performance monitoring for all counters. */
on_each_cpu(model->cpu_stop, NULL, 1);
}
int __init oprofile_arch_init(struct oprofile_operations *ops)
{
struct op_mips_model *lmodel = NULL;
int res;
switch (current_cpu_type()) {
case CPU_5KC:
case CPU_20KC:
case CPU_24K:
case CPU_25KF:
case CPU_34K:
case CPU_1004K:
case CPU_74K:
case CPU_SB1:
case CPU_SB1A:
case CPU_R10000:
case CPU_R12000:
case CPU_R14000:
lmodel = &op_model_mipsxx_ops;
break;
case CPU_RM9000:
lmodel = &op_model_rm9000_ops;
break;
case CPU_LOONGSON2:
lmodel = &op_model_loongson2_ops;
break;
};
if (!lmodel)
return -ENODEV;
res = lmodel->init();
if (res)
return res;
model = lmodel;
ops->create_files = op_mips_create_files;
ops->setup = op_mips_setup;
//ops->shutdown = op_mips_shutdown;
ops->start = op_mips_start;
ops->stop = op_mips_stop;
ops->cpu_type = lmodel->cpu_type;
ops->backtrace = op_mips_backtrace;
printk(KERN_INFO "oprofile: using %s performance monitoring.\n",
lmodel->cpu_type);
return 0;
}
void oprofile_arch_exit(void)
{
if (model)
model->exit();
}
| gpl-2.0 |
huhuikevin/kernel_imx | drivers/staging/iio/iio_simple_dummy_events.c | 5082 | 5461 | /**
* Copyright (c) 2011 Jonathan Cameron
*
* 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.
*
* Event handling elements of industrial I/O reference driver.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include "iio.h"
#include "sysfs.h"
#include "events.h"
#include "iio_simple_dummy.h"
/* Evgen 'fakes' interrupt events for this example */
#include "iio_dummy_evgen.h"
/**
* iio_simple_dummy_read_event_config() - is event enabled?
* @indio_dev: the device instance data
* @event_code: event code of the event being queried
*
* This function would normally query the relevant registers or a cache to
* discover if the event generation is enabled on the device.
*/
int iio_simple_dummy_read_event_config(struct iio_dev *indio_dev,
u64 event_code)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
return st->event_en;
}
/**
* iio_simple_dummy_write_event_config() - set whether event is enabled
* @indio_dev: the device instance data
* @event_code: event code of event being enabled/disabled
* @state: whether to enable or disable the device.
*
* This function would normally set the relevant registers on the devices
* so that it generates the specified event. Here it just sets up a cached
* value.
*/
int iio_simple_dummy_write_event_config(struct iio_dev *indio_dev,
u64 event_code,
int state)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
/*
* Deliberately over the top code splitting to illustrate
* how this is done when multiple events exist.
*/
switch (IIO_EVENT_CODE_EXTRACT_CHAN_TYPE(event_code)) {
case IIO_VOLTAGE:
switch (IIO_EVENT_CODE_EXTRACT_TYPE(event_code)) {
case IIO_EV_TYPE_THRESH:
if (IIO_EVENT_CODE_EXTRACT_DIR(event_code) ==
IIO_EV_DIR_RISING)
st->event_en = state;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
default:
return -EINVAL;
}
return 0;
}
/**
* iio_simple_dummy_read_event_value() - get value associated with event
* @indio_dev: device instance specific data
* @event_code: event code for the event whose value is being queried
* @val: value for the event code.
*
* Many devices provide a large set of events of which only a subset may
* be enabled at a time, with value registers whose meaning changes depending
* on the event enabled. This often means that the driver must cache the values
* associated with each possible events so that the right value is in place when
* the enabled event is changed.
*/
int iio_simple_dummy_read_event_value(struct iio_dev *indio_dev,
u64 event_code,
int *val)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
*val = st->event_val;
return 0;
}
/**
* iio_simple_dummy_write_event_value() - set value associate with event
* @indio_dev: device instance specific data
* @event_code: event code for the event whose value is being set
* @val: the value to be set.
*/
int iio_simple_dummy_write_event_value(struct iio_dev *indio_dev,
u64 event_code,
int val)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
st->event_val = val;
return 0;
}
/**
* iio_simple_dummy_event_handler() - identify and pass on event
* @irq: irq of event line
* @private: pointer to device instance state.
*
* This handler is responsible for querying the device to find out what
* event occured and for then pushing that event towards userspace.
* Here only one event occurs so we push that directly on with locally
* grabbed timestamp.
*/
static irqreturn_t iio_simple_dummy_event_handler(int irq, void *private)
{
struct iio_dev *indio_dev = private;
iio_push_event(indio_dev,
IIO_EVENT_CODE(IIO_VOLTAGE, 0, 0,
IIO_EV_DIR_RISING,
IIO_EV_TYPE_THRESH, 0, 0, 0),
iio_get_time_ns());
return IRQ_HANDLED;
}
/**
* iio_simple_dummy_events_register() - setup interrupt handling for events
* @indio_dev: device instance data
*
* This function requests the threaded interrupt to handle the events.
* Normally the irq is a hardware interrupt and the number comes
* from board configuration files. Here we get it from a companion
* module that fakes the interrupt for us. Note that module in
* no way forms part of this example. Just assume that events magically
* appear via the provided interrupt.
*/
int iio_simple_dummy_events_register(struct iio_dev *indio_dev)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
int ret;
/* Fire up event source - normally not present */
st->event_irq = iio_dummy_evgen_get_irq();
if (st->event_irq < 0) {
ret = st->event_irq;
goto error_ret;
}
ret = request_threaded_irq(st->event_irq,
NULL,
&iio_simple_dummy_event_handler,
IRQF_ONESHOT,
"iio_simple_event",
indio_dev);
if (ret < 0)
goto error_free_evgen;
return 0;
error_free_evgen:
iio_dummy_evgen_release_irq(st->event_irq);
error_ret:
return ret;
}
/**
* iio_simple_dummy_events_unregister() - tidy up interrupt handling on remove
* @indio_dev: device instance data
*/
int iio_simple_dummy_events_unregister(struct iio_dev *indio_dev)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
free_irq(st->event_irq, indio_dev);
/* Not part of normal driver */
iio_dummy_evgen_release_irq(st->event_irq);
return 0;
}
| gpl-2.0 |
jsr-d10/android_kernel_jsr_msm8226 | drivers/staging/iio/iio_simple_dummy_events.c | 5082 | 5461 | /**
* Copyright (c) 2011 Jonathan Cameron
*
* 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.
*
* Event handling elements of industrial I/O reference driver.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include "iio.h"
#include "sysfs.h"
#include "events.h"
#include "iio_simple_dummy.h"
/* Evgen 'fakes' interrupt events for this example */
#include "iio_dummy_evgen.h"
/**
* iio_simple_dummy_read_event_config() - is event enabled?
* @indio_dev: the device instance data
* @event_code: event code of the event being queried
*
* This function would normally query the relevant registers or a cache to
* discover if the event generation is enabled on the device.
*/
int iio_simple_dummy_read_event_config(struct iio_dev *indio_dev,
u64 event_code)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
return st->event_en;
}
/**
* iio_simple_dummy_write_event_config() - set whether event is enabled
* @indio_dev: the device instance data
* @event_code: event code of event being enabled/disabled
* @state: whether to enable or disable the device.
*
* This function would normally set the relevant registers on the devices
* so that it generates the specified event. Here it just sets up a cached
* value.
*/
int iio_simple_dummy_write_event_config(struct iio_dev *indio_dev,
u64 event_code,
int state)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
/*
* Deliberately over the top code splitting to illustrate
* how this is done when multiple events exist.
*/
switch (IIO_EVENT_CODE_EXTRACT_CHAN_TYPE(event_code)) {
case IIO_VOLTAGE:
switch (IIO_EVENT_CODE_EXTRACT_TYPE(event_code)) {
case IIO_EV_TYPE_THRESH:
if (IIO_EVENT_CODE_EXTRACT_DIR(event_code) ==
IIO_EV_DIR_RISING)
st->event_en = state;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
default:
return -EINVAL;
}
return 0;
}
/**
* iio_simple_dummy_read_event_value() - get value associated with event
* @indio_dev: device instance specific data
* @event_code: event code for the event whose value is being queried
* @val: value for the event code.
*
* Many devices provide a large set of events of which only a subset may
* be enabled at a time, with value registers whose meaning changes depending
* on the event enabled. This often means that the driver must cache the values
* associated with each possible events so that the right value is in place when
* the enabled event is changed.
*/
int iio_simple_dummy_read_event_value(struct iio_dev *indio_dev,
u64 event_code,
int *val)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
*val = st->event_val;
return 0;
}
/**
* iio_simple_dummy_write_event_value() - set value associate with event
* @indio_dev: device instance specific data
* @event_code: event code for the event whose value is being set
* @val: the value to be set.
*/
int iio_simple_dummy_write_event_value(struct iio_dev *indio_dev,
u64 event_code,
int val)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
st->event_val = val;
return 0;
}
/**
* iio_simple_dummy_event_handler() - identify and pass on event
* @irq: irq of event line
* @private: pointer to device instance state.
*
* This handler is responsible for querying the device to find out what
* event occured and for then pushing that event towards userspace.
* Here only one event occurs so we push that directly on with locally
* grabbed timestamp.
*/
static irqreturn_t iio_simple_dummy_event_handler(int irq, void *private)
{
struct iio_dev *indio_dev = private;
iio_push_event(indio_dev,
IIO_EVENT_CODE(IIO_VOLTAGE, 0, 0,
IIO_EV_DIR_RISING,
IIO_EV_TYPE_THRESH, 0, 0, 0),
iio_get_time_ns());
return IRQ_HANDLED;
}
/**
* iio_simple_dummy_events_register() - setup interrupt handling for events
* @indio_dev: device instance data
*
* This function requests the threaded interrupt to handle the events.
* Normally the irq is a hardware interrupt and the number comes
* from board configuration files. Here we get it from a companion
* module that fakes the interrupt for us. Note that module in
* no way forms part of this example. Just assume that events magically
* appear via the provided interrupt.
*/
int iio_simple_dummy_events_register(struct iio_dev *indio_dev)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
int ret;
/* Fire up event source - normally not present */
st->event_irq = iio_dummy_evgen_get_irq();
if (st->event_irq < 0) {
ret = st->event_irq;
goto error_ret;
}
ret = request_threaded_irq(st->event_irq,
NULL,
&iio_simple_dummy_event_handler,
IRQF_ONESHOT,
"iio_simple_event",
indio_dev);
if (ret < 0)
goto error_free_evgen;
return 0;
error_free_evgen:
iio_dummy_evgen_release_irq(st->event_irq);
error_ret:
return ret;
}
/**
* iio_simple_dummy_events_unregister() - tidy up interrupt handling on remove
* @indio_dev: device instance data
*/
int iio_simple_dummy_events_unregister(struct iio_dev *indio_dev)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
free_irq(st->event_irq, indio_dev);
/* Not part of normal driver */
iio_dummy_evgen_release_irq(st->event_irq);
return 0;
}
| gpl-2.0 |
IOKP-kitkat/kernel_samsung_jf | fs/ext3/xattr.c | 5082 | 35449 | /*
* linux/fs/ext3/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* Fix by Harrison Xing <harrison@mountainviewdata.com>.
* Ext3 code with a lot of help from Eric Jarman <ejarman@acm.org>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <luka.renko@hermes.si>.
* xattr consolidation Copyright (c) 2004 James Morris <jmorris@redhat.com>,
* Red Hat Inc.
* ea-in-inode support by Alex Tomas <alex@clusterfs.com> aka bzzz
* and Andreas Gruenbacher <agruen@suse.de>.
*/
/*
* Extended attributes are stored directly in inodes (on file systems with
* inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
* field contains the block number if an inode uses an additional block. All
* attributes must fit in the inode and one additional block. Blocks that
* contain the identical set of attributes may be shared among several inodes.
* Identical blocks are detected by keeping a cache of blocks that have
* recently been accessed.
*
* The attributes in inodes and on blocks have a different header; the entries
* are stored in the same format:
*
* +------------------+
* | header |
* | entry 1 | |
* | entry 2 | | growing downwards
* | entry 3 | v
* | four null bytes |
* | . . . |
* | value 1 | ^
* | value 3 | | growing upwards
* | value 2 | |
* +------------------+
*
* The header is followed by multiple entry descriptors. In disk blocks, the
* entry descriptors are kept sorted. In inodes, they are unsorted. The
* attribute values are aligned to the end of the block in no specific order.
*
* Locking strategy
* ----------------
* EXT3_I(inode)->i_file_acl is protected by EXT3_I(inode)->xattr_sem.
* EA blocks are only changed if they are exclusive to an inode, so
* holding xattr_sem also means that nothing but the EA block's reference
* count can change. Multiple writers to the same block are synchronized
* by the buffer lock.
*/
#include "ext3.h"
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include "xattr.h"
#include "acl.h"
#define BHDR(bh) ((struct ext3_xattr_header *)((bh)->b_data))
#define ENTRY(ptr) ((struct ext3_xattr_entry *)(ptr))
#define BFIRST(bh) ENTRY(BHDR(bh)+1)
#define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
#define IHDR(inode, raw_inode) \
((struct ext3_xattr_ibody_header *) \
((void *)raw_inode + \
EXT3_GOOD_OLD_INODE_SIZE + \
EXT3_I(inode)->i_extra_isize))
#define IFIRST(hdr) ((struct ext3_xattr_entry *)((hdr)+1))
#ifdef EXT3_XATTR_DEBUG
# define ea_idebug(inode, f...) do { \
printk(KERN_DEBUG "inode %s:%lu: ", \
inode->i_sb->s_id, inode->i_ino); \
printk(f); \
printk("\n"); \
} while (0)
# define ea_bdebug(bh, f...) do { \
char b[BDEVNAME_SIZE]; \
printk(KERN_DEBUG "block %s:%lu: ", \
bdevname(bh->b_bdev, b), \
(unsigned long) bh->b_blocknr); \
printk(f); \
printk("\n"); \
} while (0)
#else
# define ea_idebug(f...)
# define ea_bdebug(f...)
#endif
static void ext3_xattr_cache_insert(struct buffer_head *);
static struct buffer_head *ext3_xattr_cache_find(struct inode *,
struct ext3_xattr_header *,
struct mb_cache_entry **);
static void ext3_xattr_rehash(struct ext3_xattr_header *,
struct ext3_xattr_entry *);
static int ext3_xattr_list(struct dentry *dentry, char *buffer,
size_t buffer_size);
static struct mb_cache *ext3_xattr_cache;
static const struct xattr_handler *ext3_xattr_handler_map[] = {
[EXT3_XATTR_INDEX_USER] = &ext3_xattr_user_handler,
#ifdef CONFIG_EXT3_FS_POSIX_ACL
[EXT3_XATTR_INDEX_POSIX_ACL_ACCESS] = &ext3_xattr_acl_access_handler,
[EXT3_XATTR_INDEX_POSIX_ACL_DEFAULT] = &ext3_xattr_acl_default_handler,
#endif
[EXT3_XATTR_INDEX_TRUSTED] = &ext3_xattr_trusted_handler,
#ifdef CONFIG_EXT3_FS_SECURITY
[EXT3_XATTR_INDEX_SECURITY] = &ext3_xattr_security_handler,
#endif
};
const struct xattr_handler *ext3_xattr_handlers[] = {
&ext3_xattr_user_handler,
&ext3_xattr_trusted_handler,
#ifdef CONFIG_EXT3_FS_POSIX_ACL
&ext3_xattr_acl_access_handler,
&ext3_xattr_acl_default_handler,
#endif
#ifdef CONFIG_EXT3_FS_SECURITY
&ext3_xattr_security_handler,
#endif
NULL
};
static inline const struct xattr_handler *
ext3_xattr_handler(int name_index)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(ext3_xattr_handler_map))
handler = ext3_xattr_handler_map[name_index];
return handler;
}
/*
* Inode operation listxattr()
*
* dentry->d_inode->i_mutex: don't care
*/
ssize_t
ext3_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext3_xattr_list(dentry, buffer, size);
}
static int
ext3_xattr_check_names(struct ext3_xattr_entry *entry, void *end)
{
while (!IS_LAST_ENTRY(entry)) {
struct ext3_xattr_entry *next = EXT3_XATTR_NEXT(entry);
if ((void *)next >= end)
return -EIO;
entry = next;
}
return 0;
}
static inline int
ext3_xattr_check_block(struct buffer_head *bh)
{
int error;
if (BHDR(bh)->h_magic != cpu_to_le32(EXT3_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1))
return -EIO;
error = ext3_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size);
return error;
}
static inline int
ext3_xattr_check_entry(struct ext3_xattr_entry *entry, size_t size)
{
size_t value_size = le32_to_cpu(entry->e_value_size);
if (entry->e_value_block != 0 || value_size > size ||
le16_to_cpu(entry->e_value_offs) + value_size > size)
return -EIO;
return 0;
}
static int
ext3_xattr_find_entry(struct ext3_xattr_entry **pentry, int name_index,
const char *name, size_t size, int sorted)
{
struct ext3_xattr_entry *entry;
size_t name_len;
int cmp = 1;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
entry = *pentry;
for (; !IS_LAST_ENTRY(entry); entry = EXT3_XATTR_NEXT(entry)) {
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
if (cmp <= 0 && (sorted || cmp == 0))
break;
}
*pentry = entry;
if (!cmp && ext3_xattr_check_entry(entry, size))
return -EIO;
return cmp ? -ENODATA : 0;
}
static int
ext3_xattr_block_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext3_xattr_entry *entry;
size_t size;
int error;
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
error = -ENODATA;
if (!EXT3_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %u", EXT3_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT3_I(inode)->i_file_acl);
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext3_xattr_check_block(bh)) {
bad_block: ext3_error(inode->i_sb, __func__,
"inode %lu: bad block "E3FSBLK, inode->i_ino,
EXT3_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext3_xattr_cache_insert(bh);
entry = BFIRST(bh);
error = ext3_xattr_find_entry(&entry, name_index, name, bh->b_size, 1);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
return error;
}
static int
ext3_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct ext3_xattr_ibody_header *header;
struct ext3_xattr_entry *entry;
struct ext3_inode *raw_inode;
struct ext3_iloc iloc;
size_t size;
void *end;
int error;
if (!ext3_test_inode_state(inode, EXT3_STATE_XATTR))
return -ENODATA;
error = ext3_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext3_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT3_SB(inode->i_sb)->s_inode_size;
error = ext3_xattr_check_names(entry, end);
if (error)
goto cleanup;
error = ext3_xattr_find_entry(&entry, name_index, name,
end - (void *)entry, 0);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, (void *)IFIRST(header) +
le16_to_cpu(entry->e_value_offs), size);
}
error = size;
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext3_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext3_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
down_read(&EXT3_I(inode)->xattr_sem);
error = ext3_xattr_ibody_get(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = ext3_xattr_block_get(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT3_I(inode)->xattr_sem);
return error;
}
static int
ext3_xattr_list_entries(struct dentry *dentry, struct ext3_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT3_XATTR_NEXT(entry)) {
const struct xattr_handler *handler =
ext3_xattr_handler(entry->e_name_index);
if (handler) {
size_t size = handler->list(dentry, buffer, rest,
entry->e_name,
entry->e_name_len,
handler->flags);
if (buffer) {
if (size > rest)
return -ERANGE;
buffer += size;
}
rest -= size;
}
}
return buffer_size - rest;
}
static int
ext3_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct buffer_head *bh = NULL;
int error;
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT3_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %u", EXT3_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT3_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext3_xattr_check_block(bh)) {
ext3_error(inode->i_sb, __func__,
"inode %lu: bad block "E3FSBLK, inode->i_ino,
EXT3_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext3_xattr_cache_insert(bh);
error = ext3_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
ext3_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct ext3_xattr_ibody_header *header;
struct ext3_inode *raw_inode;
struct ext3_iloc iloc;
void *end;
int error;
if (!ext3_test_inode_state(inode, EXT3_STATE_XATTR))
return 0;
error = ext3_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext3_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT3_SB(inode->i_sb)->s_inode_size;
error = ext3_xattr_check_names(IFIRST(header), end);
if (error)
goto cleanup;
error = ext3_xattr_list_entries(dentry, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext3_xattr_list()
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
static int
ext3_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
int i_error, b_error;
down_read(&EXT3_I(dentry->d_inode)->xattr_sem);
i_error = ext3_xattr_ibody_list(dentry, buffer, buffer_size);
if (i_error < 0) {
b_error = 0;
} else {
if (buffer) {
buffer += i_error;
buffer_size -= i_error;
}
b_error = ext3_xattr_block_list(dentry, buffer, buffer_size);
if (b_error < 0)
i_error = 0;
}
up_read(&EXT3_I(dentry->d_inode)->xattr_sem);
return i_error + b_error;
}
/*
* If the EXT3_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext3_xattr_update_super_block(handle_t *handle,
struct super_block *sb)
{
if (EXT3_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_EXT_ATTR))
return;
if (ext3_journal_get_write_access(handle, EXT3_SB(sb)->s_sbh) == 0) {
EXT3_SET_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_EXT_ATTR);
ext3_journal_dirty_metadata(handle, EXT3_SB(sb)->s_sbh);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement
* it; otherwise free the block.
*/
static void
ext3_xattr_release_block(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
struct mb_cache_entry *ce = NULL;
int error = 0;
ce = mb_cache_entry_get(ext3_xattr_cache, bh->b_bdev, bh->b_blocknr);
error = ext3_journal_get_write_access(handle, bh);
if (error)
goto out;
lock_buffer(bh);
if (BHDR(bh)->h_refcount == cpu_to_le32(1)) {
ea_bdebug(bh, "refcount now=0; freeing");
if (ce)
mb_cache_entry_free(ce);
ext3_free_blocks(handle, inode, bh->b_blocknr, 1);
get_bh(bh);
ext3_forget(handle, 1, inode, bh, bh->b_blocknr);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
error = ext3_journal_dirty_metadata(handle, bh);
if (IS_SYNC(inode))
handle->h_sync = 1;
dquot_free_block(inode, 1);
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
if (ce)
mb_cache_entry_release(ce);
}
unlock_buffer(bh);
out:
ext3_std_error(inode->i_sb, error);
return;
}
struct ext3_xattr_info {
int name_index;
const char *name;
const void *value;
size_t value_len;
};
struct ext3_xattr_search {
struct ext3_xattr_entry *first;
void *base;
void *end;
struct ext3_xattr_entry *here;
int not_found;
};
static int
ext3_xattr_set_entry(struct ext3_xattr_info *i, struct ext3_xattr_search *s)
{
struct ext3_xattr_entry *last;
size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = EXT3_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found) {
if (!s->here->e_value_block && s->here->e_value_size) {
size_t size = le32_to_cpu(s->here->e_value_size);
free += EXT3_XATTR_SIZE(size);
}
free += EXT3_XATTR_LEN(name_len);
}
if (i->value) {
if (free < EXT3_XATTR_SIZE(i->value_len) ||
free < EXT3_XATTR_LEN(name_len) +
EXT3_XATTR_SIZE(i->value_len))
return -ENOSPC;
}
if (i->value && s->not_found) {
/* Insert the new name. */
size_t size = EXT3_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
memmove((void *)s->here + size, s->here, rest);
memset(s->here, 0, size);
s->here->e_name_index = i->name_index;
s->here->e_name_len = name_len;
memcpy(s->here->e_name, i->name, name_len);
} else {
if (!s->here->e_value_block && s->here->e_value_size) {
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(s->here->e_value_offs);
void *val = s->base + offs;
size_t size = EXT3_XATTR_SIZE(
le32_to_cpu(s->here->e_value_size));
if (i->value && size == EXT3_XATTR_SIZE(i->value_len)) {
/* The old and the new value have the same
size. Just replace. */
s->here->e_value_size =
cpu_to_le32(i->value_len);
memset(val + size - EXT3_XATTR_PAD, 0,
EXT3_XATTR_PAD); /* Clear pad bytes. */
memcpy(val, i->value, i->value_len);
return 0;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
s->here->e_value_size = 0;
s->here->e_value_offs = 0;
min_offs += size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_block &&
last->e_value_size && o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT3_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove the old name. */
size_t size = EXT3_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(s->here, (void *)s->here + size,
(void *)last - (void *)s->here + sizeof(__u32));
memset(last, 0, size);
}
}
if (i->value) {
/* Insert the new value. */
s->here->e_value_size = cpu_to_le32(i->value_len);
if (i->value_len) {
size_t size = EXT3_XATTR_SIZE(i->value_len);
void *val = s->base + min_offs - size;
s->here->e_value_offs = cpu_to_le16(min_offs - size);
memset(val + size - EXT3_XATTR_PAD, 0,
EXT3_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, i->value, i->value_len);
}
}
return 0;
}
struct ext3_xattr_block_find {
struct ext3_xattr_search s;
struct buffer_head *bh;
};
static int
ext3_xattr_block_find(struct inode *inode, struct ext3_xattr_info *i,
struct ext3_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
int error;
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
i->name_index, i->name, i->value, (long)i->value_len);
if (EXT3_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = sb_bread(sb, EXT3_I(inode)->i_file_acl);
error = -EIO;
if (!bs->bh)
goto cleanup;
ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
atomic_read(&(bs->bh->b_count)),
le32_to_cpu(BHDR(bs->bh)->h_refcount));
if (ext3_xattr_check_block(bs->bh)) {
ext3_error(sb, __func__,
"inode %lu: bad block "E3FSBLK, inode->i_ino,
EXT3_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* Find the named attribute. */
bs->s.base = BHDR(bs->bh);
bs->s.first = BFIRST(bs->bh);
bs->s.end = bs->bh->b_data + bs->bh->b_size;
bs->s.here = bs->s.first;
error = ext3_xattr_find_entry(&bs->s.here, i->name_index,
i->name, bs->bh->b_size, 1);
if (error && error != -ENODATA)
goto cleanup;
bs->s.not_found = error;
}
error = 0;
cleanup:
return error;
}
static int
ext3_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext3_xattr_info *i,
struct ext3_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext3_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
#define header(x) ((struct ext3_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext3_xattr_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
error = ext3_journal_get_write_access(handle, bs->bh);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
if (ce) {
mb_cache_entry_free(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "modifying in-place");
error = ext3_xattr_set_entry(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext3_xattr_rehash(header(s->base),
s->here);
ext3_xattr_cache_insert(bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EIO)
goto bad_block;
if (!error)
error = ext3_journal_dirty_metadata(handle,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
journal_release_buffer(handle, bs->bh);
if (ce) {
mb_cache_entry_release(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "cloning");
s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
/* assert(header == s->base) */
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT3_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = ext3_xattr_set_entry(i, s);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext3_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = ext3_xattr_cache_find(inode, header(s->base), &ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
/* The old block is released after updating
the inode. */
error = dquot_alloc_block(inode, 1);
if (error)
goto cleanup;
error = ext3_journal_get_write_access(handle,
new_bh);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "reusing; refcount now=%d",
le32_to_cpu(BHDR(new_bh)->h_refcount));
unlock_buffer(new_bh);
error = ext3_journal_dirty_metadata(handle,
new_bh);
if (error)
goto cleanup_dquot;
}
mb_cache_entry_release(ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext3_fsblk_t goal = ext3_group_first_block_no(sb,
EXT3_I(inode)->i_block_group);
ext3_fsblk_t block;
/*
* Protect us agaist concurrent allocations to the
* same inode from ext3_..._writepage(). Reservation
* code does not expect racing allocations.
*/
mutex_lock(&EXT3_I(inode)->truncate_mutex);
block = ext3_new_block(handle, inode, goal, &error);
mutex_unlock(&EXT3_I(inode)->truncate_mutex);
if (error)
goto cleanup;
ea_idebug(inode, "creating block %d", block);
new_bh = sb_getblk(sb, block);
if (!new_bh) {
getblk_failed:
ext3_free_blocks(handle, inode, block, 1);
error = -EIO;
goto cleanup;
}
lock_buffer(new_bh);
error = ext3_journal_get_create_access(handle, new_bh);
if (error) {
unlock_buffer(new_bh);
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext3_xattr_cache_insert(new_bh);
error = ext3_journal_dirty_metadata(handle, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT3_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
ext3_xattr_release_block(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
mb_cache_entry_release(ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
dquot_free_block(inode, 1);
goto cleanup;
bad_block:
ext3_error(inode->i_sb, __func__,
"inode %lu: bad block "E3FSBLK, inode->i_ino,
EXT3_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
struct ext3_xattr_ibody_find {
struct ext3_xattr_search s;
struct ext3_iloc iloc;
};
static int
ext3_xattr_ibody_find(struct inode *inode, struct ext3_xattr_info *i,
struct ext3_xattr_ibody_find *is)
{
struct ext3_xattr_ibody_header *header;
struct ext3_inode *raw_inode;
int error;
if (EXT3_I(inode)->i_extra_isize == 0)
return 0;
raw_inode = ext3_raw_inode(&is->iloc);
header = IHDR(inode, raw_inode);
is->s.base = is->s.first = IFIRST(header);
is->s.here = is->s.first;
is->s.end = (void *)raw_inode + EXT3_SB(inode->i_sb)->s_inode_size;
if (ext3_test_inode_state(inode, EXT3_STATE_XATTR)) {
error = ext3_xattr_check_names(IFIRST(header), is->s.end);
if (error)
return error;
/* Find the named attribute. */
error = ext3_xattr_find_entry(&is->s.here, i->name_index,
i->name, is->s.end -
(void *)is->s.base, 0);
if (error && error != -ENODATA)
return error;
is->s.not_found = error;
}
return 0;
}
static int
ext3_xattr_ibody_set(handle_t *handle, struct inode *inode,
struct ext3_xattr_info *i,
struct ext3_xattr_ibody_find *is)
{
struct ext3_xattr_ibody_header *header;
struct ext3_xattr_search *s = &is->s;
int error;
if (EXT3_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = ext3_xattr_set_entry(i, s);
if (error)
return error;
header = IHDR(inode, ext3_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT3_XATTR_MAGIC);
ext3_set_inode_state(inode, EXT3_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
ext3_clear_inode_state(inode, EXT3_STATE_XATTR);
}
return 0;
}
/*
* ext3_xattr_set_handle()
*
* Create, replace or remove an extended attribute for this inode. Value
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
ext3_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
const char *name, const void *value, size_t value_len,
int flags)
{
struct ext3_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
};
struct ext3_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext3_xattr_block_find bs = {
.s = { .not_found = -ENODATA, },
};
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
down_write(&EXT3_I(inode)->xattr_sem);
error = ext3_get_inode_loc(inode, &is.iloc);
if (error)
goto cleanup;
error = ext3_journal_get_write_access(handle, is.iloc.bh);
if (error)
goto cleanup;
if (ext3_test_inode_state(inode, EXT3_STATE_NEW)) {
struct ext3_inode *raw_inode = ext3_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT3_SB(inode->i_sb)->s_inode_size);
ext3_clear_inode_state(inode, EXT3_STATE_NEW);
}
error = ext3_xattr_ibody_find(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = ext3_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
if (is.s.not_found && bs.s.not_found) {
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (!value)
goto cleanup;
} else {
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
}
if (!value) {
if (!is.s.not_found)
error = ext3_xattr_ibody_set(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = ext3_xattr_block_set(handle, inode, &i, &bs);
} else {
error = ext3_xattr_ibody_set(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = ext3_xattr_block_set(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT3_I(inode)->i_file_acl && !bs.s.base) {
error = ext3_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
}
error = ext3_xattr_block_set(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = ext3_xattr_ibody_set(handle, inode, &i,
&is);
}
}
}
if (!error) {
ext3_xattr_update_super_block(handle, inode->i_sb);
inode->i_ctime = CURRENT_TIME_SEC;
error = ext3_mark_iloc_dirty(handle, inode, &is.iloc);
/*
* The bh is consumed by ext3_mark_iloc_dirty, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
handle->h_sync = 1;
}
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
up_write(&EXT3_I(inode)->xattr_sem);
return error;
}
/*
* ext3_xattr_set()
*
* Like ext3_xattr_set_handle, but start from an inode. This extended
* attribute modification is a filesystem transaction by itself.
*
* Returns 0, or a negative error number on failure.
*/
int
ext3_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
handle_t *handle;
int error, retries = 0;
retry:
handle = ext3_journal_start(inode, EXT3_DATA_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = ext3_xattr_set_handle(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext3_journal_stop(handle);
if (error == -ENOSPC &&
ext3_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
return error;
}
/*
* ext3_xattr_delete_inode()
*
* Free extended attribute resources associated with this inode. This
* is called immediately before an inode is freed. We have exclusive
* access to the inode.
*/
void
ext3_xattr_delete_inode(handle_t *handle, struct inode *inode)
{
struct buffer_head *bh = NULL;
if (!EXT3_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT3_I(inode)->i_file_acl);
if (!bh) {
ext3_error(inode->i_sb, __func__,
"inode %lu: block "E3FSBLK" read error", inode->i_ino,
EXT3_I(inode)->i_file_acl);
goto cleanup;
}
if (BHDR(bh)->h_magic != cpu_to_le32(EXT3_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
ext3_error(inode->i_sb, __func__,
"inode %lu: bad block "E3FSBLK, inode->i_ino,
EXT3_I(inode)->i_file_acl);
goto cleanup;
}
ext3_xattr_release_block(handle, inode, bh);
EXT3_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* ext3_xattr_put_super()
*
* This is called when a file system is unmounted.
*/
void
ext3_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* ext3_xattr_cache_insert()
*
* Create a new entry in the extended attribute cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static void
ext3_xattr_cache_insert(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext3_xattr_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
mb_cache_entry_release(ce);
}
}
/*
* ext3_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext3_xattr_cmp(struct ext3_xattr_header *header1,
struct ext3_xattr_header *header2)
{
struct ext3_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EIO;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT3_XATTR_NEXT(entry1);
entry2 = EXT3_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* ext3_xattr_cache_find()
*
* Find an identical extended attribute block.
*
* Returns a pointer to the block found, or NULL if such a block was
* not found or an error occurred.
*/
static struct buffer_head *
ext3_xattr_cache_find(struct inode *inode, struct ext3_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext3_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext3_error(inode->i_sb, __func__,
"inode %lu: block %lu read error",
inode->i_ino, (unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT3_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT3_XATTR_REFCOUNT_MAX);
} else if (ext3_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* ext3_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static inline void ext3_xattr_hash_entry(struct ext3_xattr_header *header,
struct ext3_xattr_entry *entry)
{
__u32 hash = 0;
char *name = entry->e_name;
int n;
for (n=0; n < entry->e_name_len; n++) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
*name++;
}
if (entry->e_value_block == 0 && entry->e_value_size != 0) {
__le32 *value = (__le32 *)((char *)header +
le16_to_cpu(entry->e_value_offs));
for (n = (le32_to_cpu(entry->e_value_size) +
EXT3_XATTR_ROUND) >> EXT3_XATTR_PAD_BITS; n; n--) {
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
}
entry->e_hash = cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext3_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext3_xattr_rehash(struct ext3_xattr_header *header,
struct ext3_xattr_entry *entry)
{
struct ext3_xattr_entry *here;
__u32 hash = 0;
ext3_xattr_hash_entry(header, entry);
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT3_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
int __init
init_ext3_xattr(void)
{
ext3_xattr_cache = mb_cache_create("ext3_xattr", 6);
if (!ext3_xattr_cache)
return -ENOMEM;
return 0;
}
void
exit_ext3_xattr(void)
{
if (ext3_xattr_cache)
mb_cache_destroy(ext3_xattr_cache);
ext3_xattr_cache = NULL;
}
| gpl-2.0 |
tyler6389/android_kernel_samsung_frescolte | drivers/misc/tifm_core.c | 5338 | 8407 | /*
* tifm_core.c - TI FlashMedia driver
*
* Copyright (C) 2006 Alex Dubov <oakad@yahoo.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/tifm.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/idr.h>
#include <linux/module.h>
#define DRIVER_NAME "tifm_core"
#define DRIVER_VERSION "0.8"
static struct workqueue_struct *workqueue;
static DEFINE_IDR(tifm_adapter_idr);
static DEFINE_SPINLOCK(tifm_adapter_lock);
static const char *tifm_media_type_name(unsigned char type, unsigned char nt)
{
const char *card_type_name[3][3] = {
{ "SmartMedia/xD", "MemoryStick", "MMC/SD" },
{ "XD", "MS", "SD"},
{ "xd", "ms", "sd"}
};
if (nt > 2 || type < 1 || type > 3)
return NULL;
return card_type_name[nt][type - 1];
}
static int tifm_dev_match(struct tifm_dev *sock, struct tifm_device_id *id)
{
if (sock->type == id->type)
return 1;
return 0;
}
static int tifm_bus_match(struct device *dev, struct device_driver *drv)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
struct tifm_driver *fm_drv = container_of(drv, struct tifm_driver,
driver);
struct tifm_device_id *ids = fm_drv->id_table;
if (ids) {
while (ids->type) {
if (tifm_dev_match(sock, ids))
return 1;
++ids;
}
}
return 0;
}
static int tifm_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
if (add_uevent_var(env, "TIFM_CARD_TYPE=%s", tifm_media_type_name(sock->type, 1)))
return -ENOMEM;
return 0;
}
static int tifm_device_probe(struct device *dev)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver,
driver);
int rc = -ENODEV;
get_device(dev);
if (dev->driver && drv->probe) {
rc = drv->probe(sock);
if (!rc)
return 0;
}
put_device(dev);
return rc;
}
static void tifm_dummy_event(struct tifm_dev *sock)
{
return;
}
static int tifm_device_remove(struct device *dev)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver,
driver);
if (dev->driver && drv->remove) {
sock->card_event = tifm_dummy_event;
sock->data_event = tifm_dummy_event;
drv->remove(sock);
sock->dev.driver = NULL;
}
put_device(dev);
return 0;
}
#ifdef CONFIG_PM
static int tifm_device_suspend(struct device *dev, pm_message_t state)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver,
driver);
if (dev->driver && drv->suspend)
return drv->suspend(sock, state);
return 0;
}
static int tifm_device_resume(struct device *dev)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
struct tifm_driver *drv = container_of(dev->driver, struct tifm_driver,
driver);
if (dev->driver && drv->resume)
return drv->resume(sock);
return 0;
}
#else
#define tifm_device_suspend NULL
#define tifm_device_resume NULL
#endif /* CONFIG_PM */
static ssize_t type_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
return sprintf(buf, "%x", sock->type);
}
static struct device_attribute tifm_dev_attrs[] = {
__ATTR(type, S_IRUGO, type_show, NULL),
__ATTR_NULL
};
static struct bus_type tifm_bus_type = {
.name = "tifm",
.dev_attrs = tifm_dev_attrs,
.match = tifm_bus_match,
.uevent = tifm_uevent,
.probe = tifm_device_probe,
.remove = tifm_device_remove,
.suspend = tifm_device_suspend,
.resume = tifm_device_resume
};
static void tifm_free(struct device *dev)
{
struct tifm_adapter *fm = container_of(dev, struct tifm_adapter, dev);
kfree(fm);
}
static struct class tifm_adapter_class = {
.name = "tifm_adapter",
.dev_release = tifm_free
};
struct tifm_adapter *tifm_alloc_adapter(unsigned int num_sockets,
struct device *dev)
{
struct tifm_adapter *fm;
fm = kzalloc(sizeof(struct tifm_adapter)
+ sizeof(struct tifm_dev*) * num_sockets, GFP_KERNEL);
if (fm) {
fm->dev.class = &tifm_adapter_class;
fm->dev.parent = dev;
device_initialize(&fm->dev);
spin_lock_init(&fm->lock);
fm->num_sockets = num_sockets;
}
return fm;
}
EXPORT_SYMBOL(tifm_alloc_adapter);
int tifm_add_adapter(struct tifm_adapter *fm)
{
int rc;
if (!idr_pre_get(&tifm_adapter_idr, GFP_KERNEL))
return -ENOMEM;
spin_lock(&tifm_adapter_lock);
rc = idr_get_new(&tifm_adapter_idr, fm, &fm->id);
spin_unlock(&tifm_adapter_lock);
if (rc)
return rc;
dev_set_name(&fm->dev, "tifm%u", fm->id);
rc = device_add(&fm->dev);
if (rc) {
spin_lock(&tifm_adapter_lock);
idr_remove(&tifm_adapter_idr, fm->id);
spin_unlock(&tifm_adapter_lock);
}
return rc;
}
EXPORT_SYMBOL(tifm_add_adapter);
void tifm_remove_adapter(struct tifm_adapter *fm)
{
unsigned int cnt;
flush_workqueue(workqueue);
for (cnt = 0; cnt < fm->num_sockets; ++cnt) {
if (fm->sockets[cnt])
device_unregister(&fm->sockets[cnt]->dev);
}
spin_lock(&tifm_adapter_lock);
idr_remove(&tifm_adapter_idr, fm->id);
spin_unlock(&tifm_adapter_lock);
device_del(&fm->dev);
}
EXPORT_SYMBOL(tifm_remove_adapter);
void tifm_free_adapter(struct tifm_adapter *fm)
{
put_device(&fm->dev);
}
EXPORT_SYMBOL(tifm_free_adapter);
void tifm_free_device(struct device *dev)
{
struct tifm_dev *sock = container_of(dev, struct tifm_dev, dev);
kfree(sock);
}
EXPORT_SYMBOL(tifm_free_device);
struct tifm_dev *tifm_alloc_device(struct tifm_adapter *fm, unsigned int id,
unsigned char type)
{
struct tifm_dev *sock = NULL;
if (!tifm_media_type_name(type, 0))
return sock;
sock = kzalloc(sizeof(struct tifm_dev), GFP_KERNEL);
if (sock) {
spin_lock_init(&sock->lock);
sock->type = type;
sock->socket_id = id;
sock->card_event = tifm_dummy_event;
sock->data_event = tifm_dummy_event;
sock->dev.parent = fm->dev.parent;
sock->dev.bus = &tifm_bus_type;
sock->dev.dma_mask = fm->dev.parent->dma_mask;
sock->dev.release = tifm_free_device;
dev_set_name(&sock->dev, "tifm_%s%u:%u",
tifm_media_type_name(type, 2), fm->id, id);
printk(KERN_INFO DRIVER_NAME
": %s card detected in socket %u:%u\n",
tifm_media_type_name(type, 0), fm->id, id);
}
return sock;
}
EXPORT_SYMBOL(tifm_alloc_device);
void tifm_eject(struct tifm_dev *sock)
{
struct tifm_adapter *fm = dev_get_drvdata(sock->dev.parent);
fm->eject(fm, sock);
}
EXPORT_SYMBOL(tifm_eject);
int tifm_has_ms_pif(struct tifm_dev *sock)
{
struct tifm_adapter *fm = dev_get_drvdata(sock->dev.parent);
return fm->has_ms_pif(fm, sock);
}
EXPORT_SYMBOL(tifm_has_ms_pif);
int tifm_map_sg(struct tifm_dev *sock, struct scatterlist *sg, int nents,
int direction)
{
return pci_map_sg(to_pci_dev(sock->dev.parent), sg, nents, direction);
}
EXPORT_SYMBOL(tifm_map_sg);
void tifm_unmap_sg(struct tifm_dev *sock, struct scatterlist *sg, int nents,
int direction)
{
pci_unmap_sg(to_pci_dev(sock->dev.parent), sg, nents, direction);
}
EXPORT_SYMBOL(tifm_unmap_sg);
void tifm_queue_work(struct work_struct *work)
{
queue_work(workqueue, work);
}
EXPORT_SYMBOL(tifm_queue_work);
int tifm_register_driver(struct tifm_driver *drv)
{
drv->driver.bus = &tifm_bus_type;
return driver_register(&drv->driver);
}
EXPORT_SYMBOL(tifm_register_driver);
void tifm_unregister_driver(struct tifm_driver *drv)
{
driver_unregister(&drv->driver);
}
EXPORT_SYMBOL(tifm_unregister_driver);
static int __init tifm_init(void)
{
int rc;
workqueue = create_freezable_workqueue("tifm");
if (!workqueue)
return -ENOMEM;
rc = bus_register(&tifm_bus_type);
if (rc)
goto err_out_wq;
rc = class_register(&tifm_adapter_class);
if (!rc)
return 0;
bus_unregister(&tifm_bus_type);
err_out_wq:
destroy_workqueue(workqueue);
return rc;
}
static void __exit tifm_exit(void)
{
class_unregister(&tifm_adapter_class);
bus_unregister(&tifm_bus_type);
destroy_workqueue(workqueue);
}
subsys_initcall(tifm_init);
module_exit(tifm_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Alex Dubov");
MODULE_DESCRIPTION("TI FlashMedia core driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
| gpl-2.0 |
civato/CivZ-SnapKat-SM_9005-900T | sound/pci/au88x0/au88x0_a3d.c | 8154 | 25257 | /***************************************************************************
* au88x0_a3d.c
*
* Fri Jul 18 14:16:22 2003
* Copyright 2003 mjander
* mjander@users.sourceforge.net
*
* A3D. You may think i'm crazy, but this may work someday. Who knows...
****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "au88x0_a3d.h"
#include "au88x0_a3ddata.c"
#include "au88x0_xtalk.h"
#include "au88x0.h"
static void
a3dsrc_SetTimeConsts(a3dsrc_t * a, short HrtfTrack, short ItdTrack,
short GTrack, short CTrack)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfTrackTC), HrtfTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDTrackTC), ItdTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainTrackTC), GTrack);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_CoeffTrackTC), CTrack);
}
#if 0
static void
a3dsrc_GetTimeConsts(a3dsrc_t * a, short *HrtfTrack, short *ItdTrack,
short *GTrack, short *CTrack)
{
// stub!
}
#endif
/* Atmospheric absorption. */
static void
a3dsrc_SetAtmosTarget(a3dsrc_t * a, short aa, short b, short c, short d,
short e)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A21Target),
(e << 0x10) | d);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B10Target),
(b << 0x10) | aa);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B2Target), c);
}
static void
a3dsrc_SetAtmosCurrent(a3dsrc_t * a, short aa, short b, short c, short d,
short e)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A12Current),
(e << 0x10) | d);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B01Current),
(b << 0x10) | aa);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B2Current), c);
}
static void
a3dsrc_SetAtmosState(a3dsrc_t * a, short x1, short x2, short y1, short y2)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_x1), x1);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_x2), x2);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_y1), y1);
hwwrite(vortex->mmio, a3d_addrA(a->slice, a->source, A3D_A_y2), y2);
}
#if 0
static void
a3dsrc_GetAtmosTarget(a3dsrc_t * a, short *aa, short *b, short *c,
short *d, short *e)
{
}
static void
a3dsrc_GetAtmosCurrent(a3dsrc_t * a, short *bb01, short *ab01, short *b2,
short *aa12, short *ba12)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*aa12 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_A12Current));
*ba12 =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_A12Current));
*ab01 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_B01Current));
*bb01 =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_B01Current));
*b2 =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_B2Current));
}
static void
a3dsrc_GetAtmosState(a3dsrc_t * a, short *x1, short *x2, short *y1, short *y2)
{
}
#endif
/* HRTF */
static void
a3dsrc_SetHrtfTarget(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfTarget) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void
a3dsrc_SetHrtfCurrent(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfCurrent) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void
a3dsrc_SetHrtfState(a3dsrc_t * a, a3d_Hrtf_t const aa, a3d_Hrtf_t const b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfDelayLine) + (i << 2),
(b[i] << 0x10) | aa[i]);
}
static void a3dsrc_SetHrtfOutput(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutL), left);
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutR), right);
}
#if 0
static void a3dsrc_GetHrtfTarget(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfTarget + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfTarget + (i << 2)));
}
static void a3dsrc_GetHrtfCurrent(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfCurrent + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfCurrent + (i << 2)));
}
static void a3dsrc_GetHrtfState(a3dsrc_t * a, a3d_Hrtf_t aa, a3d_Hrtf_t b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
// FIXME: verify this!
for (i = 0; i < HRTF_SZ; i++)
aa[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_HrtfDelayLine + (i << 2)));
for (i = 0; i < HRTF_SZ; i++)
b[i] =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source,
A3D_B_HrtfDelayLine + (i << 2)));
}
static void a3dsrc_GetHrtfOutput(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*left =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutL));
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_HrtfOutR));
}
#endif
/* Interaural Time Difference.
* "The other main clue that humans use to locate sounds, is called
* Interaural Time Difference (ITD). The differences in distance from
* the sound source to a listeners ears means that the sound will
* reach one ear slightly before the other....", found somewhere with google.*/
static void a3dsrc_SetItdTarget(a3dsrc_t * a, short litd, short ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
if (litd < 0)
litd = 0;
if (litd > 0x57FF)
litd = 0x57FF;
if (ritd < 0)
ritd = 0;
if (ritd > 0x57FF)
ritd = 0x57FF;
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDTarget),
(ritd << 0x10) | litd);
//hwwrite(vortex->mmio, addr(0x191DF+5, this04, this08), (ritd<<0x10)|litd);
}
static void a3dsrc_SetItdCurrent(a3dsrc_t * a, short litd, short ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
if (litd < 0)
litd = 0;
if (litd > 0x57FF)
litd = 0x57FF;
if (ritd < 0)
ritd = 0;
if (ritd > 0x57FF)
ritd = 0x57FF;
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDCurrent),
(ritd << 0x10) | litd);
//hwwrite(vortex->mmio, addr(0x191DF+1, this04, this08), (ritd<<0x10)|litd);
}
static void a3dsrc_SetItdDline(a3dsrc_t * a, a3d_ItdDline_t const dline)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
/* 45 != 40 -> Check this ! */
for (i = 0; i < DLINE_SZ; i++)
hwwrite(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_ITDDelayLine) + (i << 2), dline[i]);
}
#if 0
static void a3dsrc_GetItdTarget(a3dsrc_t * a, short *litd, short *ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ritd =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDTarget));
*litd =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDTarget));
}
static void a3dsrc_GetItdCurrent(a3dsrc_t * a, short *litd, short *ritd)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ritd =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_ITDCurrent));
*litd =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_ITDCurrent));
}
static void a3dsrc_GetItdDline(a3dsrc_t * a, a3d_ItdDline_t dline)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < DLINE_SZ; i++)
dline[i] =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source,
A3D_A_ITDDelayLine + (i << 2)));
}
#endif
/* This is may be used for ILD Interaural Level Difference. */
static void a3dsrc_SetGainTarget(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainTarget),
(right << 0x10) | left);
}
static void a3dsrc_SetGainCurrent(a3dsrc_t * a, short left, short right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainCurrent),
(right << 0x10) | left);
}
#if 0
static void a3dsrc_GetGainTarget(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainTarget));
*left =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainTarget));
}
static void a3dsrc_GetGainCurrent(a3dsrc_t * a, short *left, short *right)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*right =
hwread(vortex->mmio,
a3d_addrA(a->slice, a->source, A3D_A_GainCurrent));
*left =
hwread(vortex->mmio,
a3d_addrB(a->slice, a->source, A3D_B_GainCurrent));
}
/* CA3dIO this func seems to be inlined all over this place. */
static void CA3dIO_WriteReg(a3dsrc_t * a, unsigned long addr, short aa, short b)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, addr, (aa << 0x10) | b);
}
#endif
/* Generic A3D stuff */
static void a3dsrc_SetA3DSampleRate(a3dsrc_t * a, int sr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int esp0 = 0;
esp0 = (((esp0 & 0x7fffffff) | 0xB8000000) & 0x7) | ((sr & 0x1f) << 3);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd), esp0);
//hwwrite(vortex->mmio, 0x19C38 + (this08<<0xd), esp0);
}
static void a3dsrc_EnableA3D(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd),
0xF0000001);
//hwwrite(vortex->mmio, 0x19C38 + (this08<<0xd), 0xF0000001);
}
static void a3dsrc_DisableA3D(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd),
0xF0000000);
}
static void a3dsrc_SetA3DControlReg(a3dsrc_t * a, unsigned long ctrl)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd), ctrl);
}
static void a3dsrc_SetA3DPointerReg(a3dsrc_t * a, unsigned long ptr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
hwwrite(vortex->mmio, A3D_SLICE_Pointers + ((a->slice) << 0xd), ptr);
}
#if 0
static void a3dsrc_GetA3DSampleRate(a3dsrc_t * a, int *sr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*sr = ((hwread(vortex->mmio, A3D_SLICE_Control + (a->slice << 0xd))
>> 3) & 0x1f);
//*sr = ((hwread(vortex->mmio, 0x19C38 + (this08<<0xd))>>3)&0x1f);
}
static void a3dsrc_GetA3DControlReg(a3dsrc_t * a, unsigned long *ctrl)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ctrl = hwread(vortex->mmio, A3D_SLICE_Control + ((a->slice) << 0xd));
}
static void a3dsrc_GetA3DPointerReg(a3dsrc_t * a, unsigned long *ptr)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
*ptr = hwread(vortex->mmio, A3D_SLICE_Pointers + ((a->slice) << 0xd));
}
#endif
static void a3dsrc_ZeroSliceIO(a3dsrc_t * a)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
int i;
for (i = 0; i < 8; i++)
hwwrite(vortex->mmio,
A3D_SLICE_VDBDest +
((((a->slice) << 0xb) + i) << 2), 0);
for (i = 0; i < 4; i++)
hwwrite(vortex->mmio,
A3D_SLICE_VDBSource +
((((a->slice) << 0xb) + i) << 2), 0);
}
/* Reset Single A3D source. */
static void a3dsrc_ZeroState(a3dsrc_t * a)
{
/*
printk(KERN_DEBUG "vortex: ZeroState slice: %d, source %d\n",
a->slice, a->source);
*/
a3dsrc_SetAtmosState(a, 0, 0, 0, 0);
a3dsrc_SetHrtfState(a, A3dHrirZeros, A3dHrirZeros);
a3dsrc_SetItdDline(a, A3dItdDlineZeros);
a3dsrc_SetHrtfOutput(a, 0, 0);
a3dsrc_SetTimeConsts(a, 0, 0, 0, 0);
a3dsrc_SetAtmosCurrent(a, 0, 0, 0, 0, 0);
a3dsrc_SetAtmosTarget(a, 0, 0, 0, 0, 0);
a3dsrc_SetItdCurrent(a, 0, 0);
a3dsrc_SetItdTarget(a, 0, 0);
a3dsrc_SetGainCurrent(a, 0, 0);
a3dsrc_SetGainTarget(a, 0, 0);
a3dsrc_SetHrtfCurrent(a, A3dHrirZeros, A3dHrirZeros);
a3dsrc_SetHrtfTarget(a, A3dHrirZeros, A3dHrirZeros);
}
/* Reset entire A3D engine */
static void a3dsrc_ZeroStateA3D(a3dsrc_t * a)
{
int i, var, var2;
if ((a->vortex) == NULL) {
printk(KERN_ERR "vortex: ZeroStateA3D: ERROR: a->vortex is NULL\n");
return;
}
a3dsrc_SetA3DControlReg(a, 0);
a3dsrc_SetA3DPointerReg(a, 0);
var = a->slice;
var2 = a->source;
for (i = 0; i < 4; i++) {
a->slice = i;
a3dsrc_ZeroSliceIO(a);
//a3dsrc_ZeroState(a);
}
a->source = var2;
a->slice = var;
}
/* Program A3D block as pass through */
static void a3dsrc_ProgramPipe(a3dsrc_t * a)
{
a3dsrc_SetTimeConsts(a, 0, 0, 0, 0);
a3dsrc_SetAtmosCurrent(a, 0, 0x4000, 0, 0, 0);
a3dsrc_SetAtmosTarget(a, 0x4000, 0, 0, 0, 0);
a3dsrc_SetItdCurrent(a, 0, 0);
a3dsrc_SetItdTarget(a, 0, 0);
a3dsrc_SetGainCurrent(a, 0x7fff, 0x7fff);
a3dsrc_SetGainTarget(a, 0x7fff, 0x7fff);
/* SET HRTF HERE */
/* Single spike leads to identity transfer function. */
a3dsrc_SetHrtfCurrent(a, A3dHrirImpulse, A3dHrirImpulse);
a3dsrc_SetHrtfTarget(a, A3dHrirImpulse, A3dHrirImpulse);
/* Test: Sounds saturated. */
//a3dsrc_SetHrtfCurrent(a, A3dHrirSatTest, A3dHrirSatTest);
//a3dsrc_SetHrtfTarget(a, A3dHrirSatTest, A3dHrirSatTest);
}
/* VDB = Vortex audio Dataflow Bus */
#if 0
static void a3dsrc_ClearVDBData(a3dsrc_t * a, unsigned long aa)
{
vortex_t *vortex = (vortex_t *) (a->vortex);
// ((aa >> 2) << 8) - (aa >> 2)
hwwrite(vortex->mmio,
a3d_addrS(a->slice, A3D_SLICE_VDBDest) + (a->source << 2), 0);
hwwrite(vortex->mmio,
a3d_addrS(a->slice,
A3D_SLICE_VDBDest + 4) + (a->source << 2), 0);
/*
hwwrite(vortex->mmio, 0x19c00 + (((aa>>2)*255*4)+aa)*8, 0);
hwwrite(vortex->mmio, 0x19c04 + (((aa>>2)*255*4)+aa)*8, 0);
*/
}
#endif
/* A3D HwSource stuff. */
static void vortex_A3dSourceHw_Initialize(vortex_t * v, int source, int slice)
{
a3dsrc_t *a3dsrc = &(v->a3d[source + (slice * 4)]);
//a3dsrc_t *a3dsrc = &(v->a3d[source + (slice*4)]);
a3dsrc->vortex = (void *)v;
a3dsrc->source = source; /* source */
a3dsrc->slice = slice; /* slice */
a3dsrc_ZeroState(a3dsrc);
/* Added by me. */
a3dsrc_SetA3DSampleRate(a3dsrc, 0x11);
}
static int Vort3DRend_Initialize(vortex_t * v, unsigned short mode)
{
v->xt_mode = mode; /* this_14 */
vortex_XtalkHw_init(v);
vortex_XtalkHw_SetGainsAllChan(v);
switch (v->xt_mode) {
case XT_SPEAKER0:
vortex_XtalkHw_ProgramXtalkNarrow(v);
break;
case XT_SPEAKER1:
vortex_XtalkHw_ProgramXtalkWide(v);
break;
default:
case XT_HEADPHONE:
vortex_XtalkHw_ProgramPipe(v);
break;
case XT_DIAMOND:
vortex_XtalkHw_ProgramDiamondXtalk(v);
break;
}
vortex_XtalkHw_SetSampleRate(v, 0x11);
vortex_XtalkHw_Enable(v);
return 0;
}
/* 3D Sound entry points. */
static int vortex_a3d_register_controls(vortex_t * vortex);
static void vortex_a3d_unregister_controls(vortex_t * vortex);
/* A3D base support init/shudown */
static void __devinit vortex_Vort3D_enable(vortex_t * v)
{
int i;
Vort3DRend_Initialize(v, XT_HEADPHONE);
for (i = 0; i < NR_A3D; i++) {
vortex_A3dSourceHw_Initialize(v, i % 4, i >> 2);
a3dsrc_ZeroStateA3D(&(v->a3d[0]));
}
/* Register ALSA controls */
vortex_a3d_register_controls(v);
}
static void vortex_Vort3D_disable(vortex_t * v)
{
vortex_XtalkHw_Disable(v);
vortex_a3d_unregister_controls(v);
}
/* Make A3D subsystem connections. */
static void vortex_Vort3D_connect(vortex_t * v, int en)
{
int i;
// Disable AU8810 routes, since they seem to be wrong (in au8810.h).
#ifdef CHIP_AU8810
return;
#endif
#if 1
/* Alloc Xtalk mixin resources */
v->mixxtlk[0] =
vortex_adb_checkinout(v, v->fixed_res, en, VORTEX_RESOURCE_MIXIN);
if (v->mixxtlk[0] < 0) {
printk
("vortex: vortex_Vort3D: ERROR: not enough free mixer resources.\n");
return;
}
v->mixxtlk[1] =
vortex_adb_checkinout(v, v->fixed_res, en, VORTEX_RESOURCE_MIXIN);
if (v->mixxtlk[1] < 0) {
printk
("vortex: vortex_Vort3D: ERROR: not enough free mixer resources.\n");
return;
}
#endif
/* Connect A3D -> XTALK */
for (i = 0; i < 4; i++) {
// 2 outputs per each A3D slice.
vortex_route(v, en, 0x11, ADB_A3DOUT(i * 2), ADB_XTALKIN(i));
vortex_route(v, en, 0x11, ADB_A3DOUT(i * 2) + 1, ADB_XTALKIN(5 + i));
}
#if 0
vortex_route(v, en, 0x11, ADB_XTALKOUT(0), ADB_EQIN(2));
vortex_route(v, en, 0x11, ADB_XTALKOUT(1), ADB_EQIN(3));
#else
/* Connect XTalk -> mixer */
vortex_route(v, en, 0x11, ADB_XTALKOUT(0), ADB_MIXIN(v->mixxtlk[0]));
vortex_route(v, en, 0x11, ADB_XTALKOUT(1), ADB_MIXIN(v->mixxtlk[1]));
vortex_connection_mixin_mix(v, en, v->mixxtlk[0], v->mixplayb[0], 0);
vortex_connection_mixin_mix(v, en, v->mixxtlk[1], v->mixplayb[1], 0);
vortex_mix_setinputvolumebyte(v, v->mixplayb[0], v->mixxtlk[0],
en ? MIX_DEFIGAIN : VOL_MIN);
vortex_mix_setinputvolumebyte(v, v->mixplayb[1], v->mixxtlk[1],
en ? MIX_DEFIGAIN : VOL_MIN);
if (VORTEX_IS_QUAD(v)) {
vortex_connection_mixin_mix(v, en, v->mixxtlk[0],
v->mixplayb[2], 0);
vortex_connection_mixin_mix(v, en, v->mixxtlk[1],
v->mixplayb[3], 0);
vortex_mix_setinputvolumebyte(v, v->mixplayb[2],
v->mixxtlk[0],
en ? MIX_DEFIGAIN : VOL_MIN);
vortex_mix_setinputvolumebyte(v, v->mixplayb[3],
v->mixxtlk[1],
en ? MIX_DEFIGAIN : VOL_MIN);
}
#endif
}
/* Initialize one single A3D source. */
static void vortex_Vort3D_InitializeSource(a3dsrc_t * a, int en)
{
if (a->vortex == NULL) {
printk
("vortex: Vort3D_InitializeSource: A3D source not initialized\n");
return;
}
if (en) {
a3dsrc_ProgramPipe(a);
a3dsrc_SetA3DSampleRate(a, 0x11);
a3dsrc_SetTimeConsts(a, HrtfTCDefault,
ItdTCDefault, GainTCDefault,
CoefTCDefault);
/* Remark: zero gain is muted. */
//a3dsrc_SetGainTarget(a,0,0);
//a3dsrc_SetGainCurrent(a,0,0);
a3dsrc_EnableA3D(a);
} else {
a3dsrc_DisableA3D(a);
a3dsrc_ZeroState(a);
}
}
/* Conversion of coordinates into 3D parameters. */
static void vortex_a3d_coord2hrtf(a3d_Hrtf_t hrtf, int *coord)
{
/* FIXME: implement this. */
}
static void vortex_a3d_coord2itd(a3d_Itd_t itd, int *coord)
{
/* FIXME: implement this. */
}
static void vortex_a3d_coord2ild(a3d_LRGains_t ild, int left, int right)
{
/* FIXME: implement this. */
}
static void vortex_a3d_translate_filter(a3d_atmos_t filter, int *params)
{
/* FIXME: implement this. */
}
/* ALSA control interface. */
static int
snd_vortex_a3d_hrtf_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 6;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_itd_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_ild_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_filter_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 4;
uinfo->value.integer.min = 0x00000000;
uinfo->value.integer.max = 0xffffffff;
return 0;
}
static int
snd_vortex_a3d_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
//a3dsrc_t *a = kcontrol->private_data;
/* No read yet. Would this be really useable/needed ? */
return 0;
}
static int
snd_vortex_a3d_hrtf_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int changed = 1, i;
int coord[6];
for (i = 0; i < 6; i++)
coord[i] = ucontrol->value.integer.value[i];
/* Translate orientation coordinates to a3d params. */
vortex_a3d_coord2hrtf(a->hrtf[0], coord);
vortex_a3d_coord2hrtf(a->hrtf[1], coord);
a3dsrc_SetHrtfTarget(a, a->hrtf[0], a->hrtf[1]);
a3dsrc_SetHrtfCurrent(a, a->hrtf[0], a->hrtf[1]);
return changed;
}
static int
snd_vortex_a3d_itd_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int coord[6];
int i, changed = 1;
for (i = 0; i < 6; i++)
coord[i] = ucontrol->value.integer.value[i];
/* Translate orientation coordinates to a3d params. */
vortex_a3d_coord2itd(a->hrtf[0], coord);
vortex_a3d_coord2itd(a->hrtf[1], coord);
/* Inter aural time difference. */
a3dsrc_SetItdTarget(a, a->itd[0], a->itd[1]);
a3dsrc_SetItdCurrent(a, a->itd[0], a->itd[1]);
a3dsrc_SetItdDline(a, a->dline);
return changed;
}
static int
snd_vortex_a3d_ild_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int changed = 1;
int l, r;
/* There may be some scale tranlation needed here. */
l = ucontrol->value.integer.value[0];
r = ucontrol->value.integer.value[1];
vortex_a3d_coord2ild(a->ild, l, r);
/* Left Right panning. */
a3dsrc_SetGainTarget(a, l, r);
a3dsrc_SetGainCurrent(a, l, r);
return changed;
}
static int
snd_vortex_a3d_filter_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
a3dsrc_t *a = kcontrol->private_data;
int i, changed = 1;
int params[6];
for (i = 0; i < 6; i++)
params[i] = ucontrol->value.integer.value[i];
/* Translate generic filter params to a3d filter params. */
vortex_a3d_translate_filter(a->filter, params);
/* Atmospheric absorption and filtering. */
a3dsrc_SetAtmosTarget(a, a->filter[0],
a->filter[1], a->filter[2],
a->filter[3], a->filter[4]);
a3dsrc_SetAtmosCurrent(a, a->filter[0],
a->filter[1], a->filter[2],
a->filter[3], a->filter[4]);
return changed;
}
static struct snd_kcontrol_new vortex_a3d_kcontrol __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "Playback PCM advanced processing",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_vortex_a3d_hrtf_info,
.get = snd_vortex_a3d_get,
.put = snd_vortex_a3d_hrtf_put,
};
/* Control (un)registration. */
static int __devinit vortex_a3d_register_controls(vortex_t * vortex)
{
struct snd_kcontrol *kcontrol;
int err, i;
/* HRTF controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_HRTF;
kcontrol->info = snd_vortex_a3d_hrtf_info;
kcontrol->put = snd_vortex_a3d_hrtf_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* ITD controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_ITD;
kcontrol->info = snd_vortex_a3d_itd_info;
kcontrol->put = snd_vortex_a3d_itd_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* ILD (gains) controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_GAINS;
kcontrol->info = snd_vortex_a3d_ild_info;
kcontrol->put = snd_vortex_a3d_ild_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
/* Filter controls. */
for (i = 0; i < NR_A3D; i++) {
if ((kcontrol =
snd_ctl_new1(&vortex_a3d_kcontrol, &vortex->a3d[i])) == NULL)
return -ENOMEM;
kcontrol->id.numid = CTRLID_FILTER;
kcontrol->info = snd_vortex_a3d_filter_info;
kcontrol->put = snd_vortex_a3d_filter_put;
if ((err = snd_ctl_add(vortex->card, kcontrol)) < 0)
return err;
}
return 0;
}
static void vortex_a3d_unregister_controls(vortex_t * vortex)
{
}
/* End of File*/
| gpl-2.0 |
metredigm/linux | drivers/power/rt9455_charger.c | 219 | 49749 | /*
* Driver for Richtek RT9455WSC battery charger.
*
* Copyright (C) 2015 Intel 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.
*
* 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/interrupt.h>
#include <linux/delay.h>
#include <linux/of_irq.h>
#include <linux/of_device.h>
#include <linux/pm_runtime.h>
#include <linux/power_supply.h>
#include <linux/i2c.h>
#include <linux/acpi.h>
#include <linux/usb/phy.h>
#include <linux/regmap.h>
#define RT9455_MANUFACTURER "Richtek"
#define RT9455_MODEL_NAME "RT9455"
#define RT9455_DRIVER_NAME "rt9455-charger"
#define RT9455_IRQ_NAME "interrupt"
#define RT9455_PWR_RDY_DELAY 1 /* 1 second */
#define RT9455_MAX_CHARGING_TIME 21600 /* 6 hrs */
#define RT9455_BATT_PRESENCE_DELAY 60 /* 60 seconds */
#define RT9455_CHARGE_MODE 0x00
#define RT9455_BOOST_MODE 0x01
#define RT9455_FAULT 0x03
#define RT9455_IAICR_100MA 0x00
#define RT9455_IAICR_500MA 0x01
#define RT9455_IAICR_NO_LIMIT 0x03
#define RT9455_CHARGE_DISABLE 0x00
#define RT9455_CHARGE_ENABLE 0x01
#define RT9455_PWR_FAULT 0x00
#define RT9455_PWR_GOOD 0x01
#define RT9455_REG_CTRL1 0x00 /* CTRL1 reg address */
#define RT9455_REG_CTRL2 0x01 /* CTRL2 reg address */
#define RT9455_REG_CTRL3 0x02 /* CTRL3 reg address */
#define RT9455_REG_DEV_ID 0x03 /* DEV_ID reg address */
#define RT9455_REG_CTRL4 0x04 /* CTRL4 reg address */
#define RT9455_REG_CTRL5 0x05 /* CTRL5 reg address */
#define RT9455_REG_CTRL6 0x06 /* CTRL6 reg address */
#define RT9455_REG_CTRL7 0x07 /* CTRL7 reg address */
#define RT9455_REG_IRQ1 0x08 /* IRQ1 reg address */
#define RT9455_REG_IRQ2 0x09 /* IRQ2 reg address */
#define RT9455_REG_IRQ3 0x0A /* IRQ3 reg address */
#define RT9455_REG_MASK1 0x0B /* MASK1 reg address */
#define RT9455_REG_MASK2 0x0C /* MASK2 reg address */
#define RT9455_REG_MASK3 0x0D /* MASK3 reg address */
enum rt9455_fields {
F_STAT, F_BOOST, F_PWR_RDY, F_OTG_PIN_POLARITY, /* CTRL1 reg fields */
F_IAICR, F_TE_SHDN_EN, F_HIGHER_OCP, F_TE, F_IAICR_INT, F_HIZ,
F_OPA_MODE, /* CTRL2 reg fields */
F_VOREG, F_OTG_PL, F_OTG_EN, /* CTRL3 reg fields */
F_VENDOR_ID, F_CHIP_REV, /* DEV_ID reg fields */
F_RST, /* CTRL4 reg fields */
F_TMR_EN, F_MIVR, F_IPREC, F_IEOC_PERCENTAGE, /* CTRL5 reg fields*/
F_IAICR_SEL, F_ICHRG, F_VPREC, /* CTRL6 reg fields */
F_BATD_EN, F_CHG_EN, F_VMREG, /* CTRL7 reg fields */
F_TSDI, F_VINOVPI, F_BATAB, /* IRQ1 reg fields */
F_CHRVPI, F_CHBATOVI, F_CHTERMI, F_CHRCHGI, F_CH32MI, F_CHTREGI,
F_CHMIVRI, /* IRQ2 reg fields */
F_BSTBUSOVI, F_BSTOLI, F_BSTLOWVI, F_BST32SI, /* IRQ3 reg fields */
F_TSDM, F_VINOVPIM, F_BATABM, /* MASK1 reg fields */
F_CHRVPIM, F_CHBATOVIM, F_CHTERMIM, F_CHRCHGIM, F_CH32MIM, F_CHTREGIM,
F_CHMIVRIM, /* MASK2 reg fields */
F_BSTVINOVIM, F_BSTOLIM, F_BSTLOWVIM, F_BST32SIM, /* MASK3 reg fields */
F_MAX_FIELDS
};
static const struct reg_field rt9455_reg_fields[] = {
[F_STAT] = REG_FIELD(RT9455_REG_CTRL1, 4, 5),
[F_BOOST] = REG_FIELD(RT9455_REG_CTRL1, 3, 3),
[F_PWR_RDY] = REG_FIELD(RT9455_REG_CTRL1, 2, 2),
[F_OTG_PIN_POLARITY] = REG_FIELD(RT9455_REG_CTRL1, 1, 1),
[F_IAICR] = REG_FIELD(RT9455_REG_CTRL2, 6, 7),
[F_TE_SHDN_EN] = REG_FIELD(RT9455_REG_CTRL2, 5, 5),
[F_HIGHER_OCP] = REG_FIELD(RT9455_REG_CTRL2, 4, 4),
[F_TE] = REG_FIELD(RT9455_REG_CTRL2, 3, 3),
[F_IAICR_INT] = REG_FIELD(RT9455_REG_CTRL2, 2, 2),
[F_HIZ] = REG_FIELD(RT9455_REG_CTRL2, 1, 1),
[F_OPA_MODE] = REG_FIELD(RT9455_REG_CTRL2, 0, 0),
[F_VOREG] = REG_FIELD(RT9455_REG_CTRL3, 2, 7),
[F_OTG_PL] = REG_FIELD(RT9455_REG_CTRL3, 1, 1),
[F_OTG_EN] = REG_FIELD(RT9455_REG_CTRL3, 0, 0),
[F_VENDOR_ID] = REG_FIELD(RT9455_REG_DEV_ID, 4, 7),
[F_CHIP_REV] = REG_FIELD(RT9455_REG_DEV_ID, 0, 3),
[F_RST] = REG_FIELD(RT9455_REG_CTRL4, 7, 7),
[F_TMR_EN] = REG_FIELD(RT9455_REG_CTRL5, 7, 7),
[F_MIVR] = REG_FIELD(RT9455_REG_CTRL5, 4, 5),
[F_IPREC] = REG_FIELD(RT9455_REG_CTRL5, 2, 3),
[F_IEOC_PERCENTAGE] = REG_FIELD(RT9455_REG_CTRL5, 0, 1),
[F_IAICR_SEL] = REG_FIELD(RT9455_REG_CTRL6, 7, 7),
[F_ICHRG] = REG_FIELD(RT9455_REG_CTRL6, 4, 6),
[F_VPREC] = REG_FIELD(RT9455_REG_CTRL6, 0, 2),
[F_BATD_EN] = REG_FIELD(RT9455_REG_CTRL7, 6, 6),
[F_CHG_EN] = REG_FIELD(RT9455_REG_CTRL7, 4, 4),
[F_VMREG] = REG_FIELD(RT9455_REG_CTRL7, 0, 3),
[F_TSDI] = REG_FIELD(RT9455_REG_IRQ1, 7, 7),
[F_VINOVPI] = REG_FIELD(RT9455_REG_IRQ1, 6, 6),
[F_BATAB] = REG_FIELD(RT9455_REG_IRQ1, 0, 0),
[F_CHRVPI] = REG_FIELD(RT9455_REG_IRQ2, 7, 7),
[F_CHBATOVI] = REG_FIELD(RT9455_REG_IRQ2, 5, 5),
[F_CHTERMI] = REG_FIELD(RT9455_REG_IRQ2, 4, 4),
[F_CHRCHGI] = REG_FIELD(RT9455_REG_IRQ2, 3, 3),
[F_CH32MI] = REG_FIELD(RT9455_REG_IRQ2, 2, 2),
[F_CHTREGI] = REG_FIELD(RT9455_REG_IRQ2, 1, 1),
[F_CHMIVRI] = REG_FIELD(RT9455_REG_IRQ2, 0, 0),
[F_BSTBUSOVI] = REG_FIELD(RT9455_REG_IRQ3, 7, 7),
[F_BSTOLI] = REG_FIELD(RT9455_REG_IRQ3, 6, 6),
[F_BSTLOWVI] = REG_FIELD(RT9455_REG_IRQ3, 5, 5),
[F_BST32SI] = REG_FIELD(RT9455_REG_IRQ3, 3, 3),
[F_TSDM] = REG_FIELD(RT9455_REG_MASK1, 7, 7),
[F_VINOVPIM] = REG_FIELD(RT9455_REG_MASK1, 6, 6),
[F_BATABM] = REG_FIELD(RT9455_REG_MASK1, 0, 0),
[F_CHRVPIM] = REG_FIELD(RT9455_REG_MASK2, 7, 7),
[F_CHBATOVIM] = REG_FIELD(RT9455_REG_MASK2, 5, 5),
[F_CHTERMIM] = REG_FIELD(RT9455_REG_MASK2, 4, 4),
[F_CHRCHGIM] = REG_FIELD(RT9455_REG_MASK2, 3, 3),
[F_CH32MIM] = REG_FIELD(RT9455_REG_MASK2, 2, 2),
[F_CHTREGIM] = REG_FIELD(RT9455_REG_MASK2, 1, 1),
[F_CHMIVRIM] = REG_FIELD(RT9455_REG_MASK2, 0, 0),
[F_BSTVINOVIM] = REG_FIELD(RT9455_REG_MASK3, 7, 7),
[F_BSTOLIM] = REG_FIELD(RT9455_REG_MASK3, 6, 6),
[F_BSTLOWVIM] = REG_FIELD(RT9455_REG_MASK3, 5, 5),
[F_BST32SIM] = REG_FIELD(RT9455_REG_MASK3, 3, 3),
};
#define GET_MASK(fid) (BIT(rt9455_reg_fields[fid].msb + 1) - \
BIT(rt9455_reg_fields[fid].lsb))
/*
* Each array initialised below shows the possible real-world values for a
* group of bits belonging to RT9455 registers. The arrays are sorted in
* ascending order. The index of each real-world value represents the value
* that is encoded in the group of bits belonging to RT9455 registers.
*/
/* REG06[6:4] (ICHRG) in uAh */
static const int rt9455_ichrg_values[] = {
500000, 650000, 800000, 950000, 1100000, 1250000, 1400000, 1550000
};
/*
* When the charger is in charge mode, REG02[7:2] represent battery regulation
* voltage.
*/
/* REG02[7:2] (VOREG) in uV */
static const int rt9455_voreg_values[] = {
3500000, 3520000, 3540000, 3560000, 3580000, 3600000, 3620000, 3640000,
3660000, 3680000, 3700000, 3720000, 3740000, 3760000, 3780000, 3800000,
3820000, 3840000, 3860000, 3880000, 3900000, 3920000, 3940000, 3960000,
3980000, 4000000, 4020000, 4040000, 4060000, 4080000, 4100000, 4120000,
4140000, 4160000, 4180000, 4200000, 4220000, 4240000, 4260000, 4280000,
4300000, 4330000, 4350000, 4370000, 4390000, 4410000, 4430000, 4450000,
4450000, 4450000, 4450000, 4450000, 4450000, 4450000, 4450000, 4450000,
4450000, 4450000, 4450000, 4450000, 4450000, 4450000, 4450000, 4450000
};
/*
* When the charger is in boost mode, REG02[7:2] represent boost output
* voltage.
*/
/* REG02[7:2] (Boost output voltage) in uV */
static const int rt9455_boost_voltage_values[] = {
4425000, 4450000, 4475000, 4500000, 4525000, 4550000, 4575000, 4600000,
4625000, 4650000, 4675000, 4700000, 4725000, 4750000, 4775000, 4800000,
4825000, 4850000, 4875000, 4900000, 4925000, 4950000, 4975000, 5000000,
5025000, 5050000, 5075000, 5100000, 5125000, 5150000, 5175000, 5200000,
5225000, 5250000, 5275000, 5300000, 5325000, 5350000, 5375000, 5400000,
5425000, 5450000, 5475000, 5500000, 5525000, 5550000, 5575000, 5600000,
5600000, 5600000, 5600000, 5600000, 5600000, 5600000, 5600000, 5600000,
5600000, 5600000, 5600000, 5600000, 5600000, 5600000, 5600000, 5600000,
};
/* REG07[3:0] (VMREG) in uV */
static const int rt9455_vmreg_values[] = {
4200000, 4220000, 4240000, 4260000, 4280000, 4300000, 4320000, 4340000,
4360000, 4380000, 4400000, 4430000, 4450000, 4450000, 4450000, 4450000
};
/* REG05[5:4] (IEOC_PERCENTAGE) */
static const int rt9455_ieoc_percentage_values[] = {
10, 30, 20, 30
};
/* REG05[1:0] (MIVR) in uV */
static const int rt9455_mivr_values[] = {
4000000, 4250000, 4500000, 5000000
};
/* REG05[1:0] (IAICR) in uA */
static const int rt9455_iaicr_values[] = {
100000, 500000, 1000000, 2000000
};
struct rt9455_info {
struct i2c_client *client;
struct regmap *regmap;
struct regmap_field *regmap_fields[F_MAX_FIELDS];
struct power_supply *charger;
#if IS_ENABLED(CONFIG_USB_PHY)
struct usb_phy *usb_phy;
struct notifier_block nb;
#endif
struct delayed_work pwr_rdy_work;
struct delayed_work max_charging_time_work;
struct delayed_work batt_presence_work;
u32 voreg;
u32 boost_voltage;
};
/*
* Iterate through each element of the 'tbl' array until an element whose value
* is greater than v is found. Return the index of the respective element,
* or the index of the last element in the array, if no such element is found.
*/
static unsigned int rt9455_find_idx(const int tbl[], int tbl_size, int v)
{
int i;
/*
* No need to iterate until the last index in the table because
* if no element greater than v is found in the table,
* or if only the last element is greater than v,
* function returns the index of the last element.
*/
for (i = 0; i < tbl_size - 1; i++)
if (v <= tbl[i])
return i;
return (tbl_size - 1);
}
static int rt9455_get_field_val(struct rt9455_info *info,
enum rt9455_fields field,
const int tbl[], int tbl_size, int *val)
{
unsigned int v;
int ret;
ret = regmap_field_read(info->regmap_fields[field], &v);
if (ret)
return ret;
v = (v >= tbl_size) ? (tbl_size - 1) : v;
*val = tbl[v];
return 0;
}
static int rt9455_set_field_val(struct rt9455_info *info,
enum rt9455_fields field,
const int tbl[], int tbl_size, int val)
{
unsigned int idx = rt9455_find_idx(tbl, tbl_size, val);
return regmap_field_write(info->regmap_fields[field], idx);
}
static int rt9455_register_reset(struct rt9455_info *info)
{
struct device *dev = &info->client->dev;
unsigned int v;
int ret, limit = 100;
ret = regmap_field_write(info->regmap_fields[F_RST], 0x01);
if (ret) {
dev_err(dev, "Failed to set RST bit\n");
return ret;
}
/*
* To make sure that reset operation has finished, loop until RST bit
* is set to 0.
*/
do {
ret = regmap_field_read(info->regmap_fields[F_RST], &v);
if (ret) {
dev_err(dev, "Failed to read RST bit\n");
return ret;
}
if (!v)
break;
usleep_range(10, 100);
} while (--limit);
if (!limit)
return -EIO;
return 0;
}
/* Charger power supply property routines */
static enum power_supply_property rt9455_charger_properties[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX,
POWER_SUPPLY_PROP_SCOPE,
POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT,
POWER_SUPPLY_PROP_MODEL_NAME,
POWER_SUPPLY_PROP_MANUFACTURER,
};
static char *rt9455_charger_supplied_to[] = {
"main-battery",
};
static int rt9455_charger_get_status(struct rt9455_info *info,
union power_supply_propval *val)
{
unsigned int v, pwr_rdy;
int ret;
ret = regmap_field_read(info->regmap_fields[F_PWR_RDY],
&pwr_rdy);
if (ret) {
dev_err(&info->client->dev, "Failed to read PWR_RDY bit\n");
return ret;
}
/*
* If PWR_RDY bit is unset, the battery is discharging. Otherwise,
* STAT bits value must be checked.
*/
if (!pwr_rdy) {
val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
return 0;
}
ret = regmap_field_read(info->regmap_fields[F_STAT], &v);
if (ret) {
dev_err(&info->client->dev, "Failed to read STAT bits\n");
return ret;
}
switch (v) {
case 0:
/*
* If PWR_RDY bit is set, but STAT bits value is 0, the charger
* may be in one of the following cases:
* 1. CHG_EN bit is 0.
* 2. CHG_EN bit is 1 but the battery is not connected.
* In any of these cases, POWER_SUPPLY_STATUS_NOT_CHARGING is
* returned.
*/
val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
return 0;
case 1:
val->intval = POWER_SUPPLY_STATUS_CHARGING;
return 0;
case 2:
val->intval = POWER_SUPPLY_STATUS_FULL;
return 0;
default:
val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
return 0;
}
}
static int rt9455_charger_get_health(struct rt9455_info *info,
union power_supply_propval *val)
{
struct device *dev = &info->client->dev;
unsigned int v;
int ret;
val->intval = POWER_SUPPLY_HEALTH_GOOD;
ret = regmap_read(info->regmap, RT9455_REG_IRQ1, &v);
if (ret) {
dev_err(dev, "Failed to read IRQ1 register\n");
return ret;
}
if (v & GET_MASK(F_TSDI)) {
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
return 0;
}
if (v & GET_MASK(F_VINOVPI)) {
val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
return 0;
}
if (v & GET_MASK(F_BATAB)) {
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
return 0;
}
ret = regmap_read(info->regmap, RT9455_REG_IRQ2, &v);
if (ret) {
dev_err(dev, "Failed to read IRQ2 register\n");
return ret;
}
if (v & GET_MASK(F_CHBATOVI)) {
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
return 0;
}
if (v & GET_MASK(F_CH32MI)) {
val->intval = POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE;
return 0;
}
ret = regmap_read(info->regmap, RT9455_REG_IRQ3, &v);
if (ret) {
dev_err(dev, "Failed to read IRQ3 register\n");
return ret;
}
if (v & GET_MASK(F_BSTBUSOVI)) {
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
return 0;
}
if (v & GET_MASK(F_BSTOLI)) {
val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
return 0;
}
if (v & GET_MASK(F_BSTLOWVI)) {
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
return 0;
}
if (v & GET_MASK(F_BST32SI)) {
val->intval = POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE;
return 0;
}
ret = regmap_field_read(info->regmap_fields[F_STAT], &v);
if (ret) {
dev_err(dev, "Failed to read STAT bits\n");
return ret;
}
if (v == RT9455_FAULT) {
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
return 0;
}
return 0;
}
static int rt9455_charger_get_battery_presence(struct rt9455_info *info,
union power_supply_propval *val)
{
unsigned int v;
int ret;
ret = regmap_field_read(info->regmap_fields[F_BATAB], &v);
if (ret) {
dev_err(&info->client->dev, "Failed to read BATAB bit\n");
return ret;
}
/*
* Since BATAB is 1 when battery is NOT present and 0 otherwise,
* !BATAB is returned.
*/
val->intval = !v;
return 0;
}
static int rt9455_charger_get_online(struct rt9455_info *info,
union power_supply_propval *val)
{
unsigned int v;
int ret;
ret = regmap_field_read(info->regmap_fields[F_PWR_RDY], &v);
if (ret) {
dev_err(&info->client->dev, "Failed to read PWR_RDY bit\n");
return ret;
}
val->intval = (int)v;
return 0;
}
static int rt9455_charger_get_current(struct rt9455_info *info,
union power_supply_propval *val)
{
int curr;
int ret;
ret = rt9455_get_field_val(info, F_ICHRG,
rt9455_ichrg_values,
ARRAY_SIZE(rt9455_ichrg_values),
&curr);
if (ret) {
dev_err(&info->client->dev, "Failed to read ICHRG value\n");
return ret;
}
val->intval = curr;
return 0;
}
static int rt9455_charger_get_current_max(struct rt9455_info *info,
union power_supply_propval *val)
{
int idx = ARRAY_SIZE(rt9455_ichrg_values) - 1;
val->intval = rt9455_ichrg_values[idx];
return 0;
}
static int rt9455_charger_get_voltage(struct rt9455_info *info,
union power_supply_propval *val)
{
int voltage;
int ret;
ret = rt9455_get_field_val(info, F_VOREG,
rt9455_voreg_values,
ARRAY_SIZE(rt9455_voreg_values),
&voltage);
if (ret) {
dev_err(&info->client->dev, "Failed to read VOREG value\n");
return ret;
}
val->intval = voltage;
return 0;
}
static int rt9455_charger_get_voltage_max(struct rt9455_info *info,
union power_supply_propval *val)
{
int idx = ARRAY_SIZE(rt9455_vmreg_values) - 1;
val->intval = rt9455_vmreg_values[idx];
return 0;
}
static int rt9455_charger_get_term_current(struct rt9455_info *info,
union power_supply_propval *val)
{
struct device *dev = &info->client->dev;
int ichrg, ieoc_percentage, ret;
ret = rt9455_get_field_val(info, F_ICHRG,
rt9455_ichrg_values,
ARRAY_SIZE(rt9455_ichrg_values),
&ichrg);
if (ret) {
dev_err(dev, "Failed to read ICHRG value\n");
return ret;
}
ret = rt9455_get_field_val(info, F_IEOC_PERCENTAGE,
rt9455_ieoc_percentage_values,
ARRAY_SIZE(rt9455_ieoc_percentage_values),
&ieoc_percentage);
if (ret) {
dev_err(dev, "Failed to read IEOC value\n");
return ret;
}
val->intval = ichrg * ieoc_percentage / 100;
return 0;
}
static int rt9455_charger_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct rt9455_info *info = power_supply_get_drvdata(psy);
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
return rt9455_charger_get_status(info, val);
case POWER_SUPPLY_PROP_HEALTH:
return rt9455_charger_get_health(info, val);
case POWER_SUPPLY_PROP_PRESENT:
return rt9455_charger_get_battery_presence(info, val);
case POWER_SUPPLY_PROP_ONLINE:
return rt9455_charger_get_online(info, val);
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT:
return rt9455_charger_get_current(info, val);
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
return rt9455_charger_get_current_max(info, val);
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
return rt9455_charger_get_voltage(info, val);
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
return rt9455_charger_get_voltage_max(info, val);
case POWER_SUPPLY_PROP_SCOPE:
val->intval = POWER_SUPPLY_SCOPE_SYSTEM;
return 0;
case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
return rt9455_charger_get_term_current(info, val);
case POWER_SUPPLY_PROP_MODEL_NAME:
val->strval = RT9455_MODEL_NAME;
return 0;
case POWER_SUPPLY_PROP_MANUFACTURER:
val->strval = RT9455_MANUFACTURER;
return 0;
default:
return -ENODATA;
}
}
static int rt9455_hw_init(struct rt9455_info *info, u32 ichrg,
u32 ieoc_percentage,
u32 mivr, u32 iaicr)
{
struct device *dev = &info->client->dev;
int idx, ret;
ret = rt9455_register_reset(info);
if (ret) {
dev_err(dev, "Power On Reset failed\n");
return ret;
}
/* Set TE bit in order to enable end of charge detection */
ret = regmap_field_write(info->regmap_fields[F_TE], 1);
if (ret) {
dev_err(dev, "Failed to set TE bit\n");
return ret;
}
/* Set TE_SHDN_EN bit in order to enable end of charge detection */
ret = regmap_field_write(info->regmap_fields[F_TE_SHDN_EN], 1);
if (ret) {
dev_err(dev, "Failed to set TE_SHDN_EN bit\n");
return ret;
}
/*
* Set BATD_EN bit in order to enable battery detection
* when charging is done
*/
ret = regmap_field_write(info->regmap_fields[F_BATD_EN], 1);
if (ret) {
dev_err(dev, "Failed to set BATD_EN bit\n");
return ret;
}
/*
* Disable Safety Timer. In charge mode, this timer terminates charging
* if no read or write via I2C is done within 32 minutes. This timer
* avoids overcharging the baterry when the OS is not loaded and the
* charger is connected to a power source.
* In boost mode, this timer triggers BST32SI interrupt if no read or
* write via I2C is done within 32 seconds.
* When the OS is loaded and the charger driver is inserted, it is used
* delayed_work, named max_charging_time_work, to avoid overcharging
* the battery.
*/
ret = regmap_field_write(info->regmap_fields[F_TMR_EN], 0x00);
if (ret) {
dev_err(dev, "Failed to disable Safety Timer\n");
return ret;
}
/* Set ICHRG to value retrieved from device-specific data */
ret = rt9455_set_field_val(info, F_ICHRG,
rt9455_ichrg_values,
ARRAY_SIZE(rt9455_ichrg_values), ichrg);
if (ret) {
dev_err(dev, "Failed to set ICHRG value\n");
return ret;
}
/* Set IEOC Percentage to value retrieved from device-specific data */
ret = rt9455_set_field_val(info, F_IEOC_PERCENTAGE,
rt9455_ieoc_percentage_values,
ARRAY_SIZE(rt9455_ieoc_percentage_values),
ieoc_percentage);
if (ret) {
dev_err(dev, "Failed to set IEOC Percentage value\n");
return ret;
}
/* Set VOREG to value retrieved from device-specific data */
ret = rt9455_set_field_val(info, F_VOREG,
rt9455_voreg_values,
ARRAY_SIZE(rt9455_voreg_values),
info->voreg);
if (ret) {
dev_err(dev, "Failed to set VOREG value\n");
return ret;
}
/* Set VMREG value to maximum (4.45V). */
idx = ARRAY_SIZE(rt9455_vmreg_values) - 1;
ret = rt9455_set_field_val(info, F_VMREG,
rt9455_vmreg_values,
ARRAY_SIZE(rt9455_vmreg_values),
rt9455_vmreg_values[idx]);
if (ret) {
dev_err(dev, "Failed to set VMREG value\n");
return ret;
}
/*
* Set MIVR to value retrieved from device-specific data.
* If no value is specified, default value for MIVR is 4.5V.
*/
if (mivr == -1)
mivr = 4500000;
ret = rt9455_set_field_val(info, F_MIVR,
rt9455_mivr_values,
ARRAY_SIZE(rt9455_mivr_values), mivr);
if (ret) {
dev_err(dev, "Failed to set MIVR value\n");
return ret;
}
/*
* Set IAICR to value retrieved from device-specific data.
* If no value is specified, default value for IAICR is 500 mA.
*/
if (iaicr == -1)
iaicr = 500000;
ret = rt9455_set_field_val(info, F_IAICR,
rt9455_iaicr_values,
ARRAY_SIZE(rt9455_iaicr_values), iaicr);
if (ret) {
dev_err(dev, "Failed to set IAICR value\n");
return ret;
}
/*
* Set IAICR_INT bit so that IAICR value is determined by IAICR bits
* and not by OTG pin.
*/
ret = regmap_field_write(info->regmap_fields[F_IAICR_INT], 0x01);
if (ret) {
dev_err(dev, "Failed to set IAICR_INT bit\n");
return ret;
}
/*
* Disable CHMIVRI interrupt. Because the driver sets MIVR value,
* CHMIVRI is triggered, but there is no action to be taken by the
* driver when CHMIVRI is triggered.
*/
ret = regmap_field_write(info->regmap_fields[F_CHMIVRIM], 0x01);
if (ret) {
dev_err(dev, "Failed to mask CHMIVRI interrupt\n");
return ret;
}
return 0;
}
#if IS_ENABLED(CONFIG_USB_PHY)
/*
* Before setting the charger into boost mode, boost output voltage is
* set. This is needed because boost output voltage may differ from battery
* regulation voltage. F_VOREG bits represent either battery regulation voltage
* or boost output voltage, depending on the mode the charger is. Both battery
* regulation voltage and boost output voltage are read from DT/ACPI during
* probe.
*/
static int rt9455_set_boost_voltage_before_boost_mode(struct rt9455_info *info)
{
struct device *dev = &info->client->dev;
int ret;
ret = rt9455_set_field_val(info, F_VOREG,
rt9455_boost_voltage_values,
ARRAY_SIZE(rt9455_boost_voltage_values),
info->boost_voltage);
if (ret) {
dev_err(dev, "Failed to set boost output voltage value\n");
return ret;
}
return 0;
}
#endif
/*
* Before setting the charger into charge mode, battery regulation voltage is
* set. This is needed because boost output voltage may differ from battery
* regulation voltage. F_VOREG bits represent either battery regulation voltage
* or boost output voltage, depending on the mode the charger is. Both battery
* regulation voltage and boost output voltage are read from DT/ACPI during
* probe.
*/
static int rt9455_set_voreg_before_charge_mode(struct rt9455_info *info)
{
struct device *dev = &info->client->dev;
int ret;
ret = rt9455_set_field_val(info, F_VOREG,
rt9455_voreg_values,
ARRAY_SIZE(rt9455_voreg_values),
info->voreg);
if (ret) {
dev_err(dev, "Failed to set VOREG value\n");
return ret;
}
return 0;
}
static int rt9455_irq_handler_check_irq1_register(struct rt9455_info *info,
bool *_is_battery_absent,
bool *_alert_userspace)
{
unsigned int irq1, mask1, mask2;
struct device *dev = &info->client->dev;
bool is_battery_absent = false;
bool alert_userspace = false;
int ret;
ret = regmap_read(info->regmap, RT9455_REG_IRQ1, &irq1);
if (ret) {
dev_err(dev, "Failed to read IRQ1 register\n");
return ret;
}
ret = regmap_read(info->regmap, RT9455_REG_MASK1, &mask1);
if (ret) {
dev_err(dev, "Failed to read MASK1 register\n");
return ret;
}
if (irq1 & GET_MASK(F_TSDI)) {
dev_err(dev, "Thermal shutdown fault occurred\n");
alert_userspace = true;
}
if (irq1 & GET_MASK(F_VINOVPI)) {
dev_err(dev, "Overvoltage input occurred\n");
alert_userspace = true;
}
if (irq1 & GET_MASK(F_BATAB)) {
dev_err(dev, "Battery absence occurred\n");
is_battery_absent = true;
alert_userspace = true;
if ((mask1 & GET_MASK(F_BATABM)) == 0) {
ret = regmap_field_write(info->regmap_fields[F_BATABM],
0x01);
if (ret) {
dev_err(dev, "Failed to mask BATAB interrupt\n");
return ret;
}
}
ret = regmap_read(info->regmap, RT9455_REG_MASK2, &mask2);
if (ret) {
dev_err(dev, "Failed to read MASK2 register\n");
return ret;
}
if (mask2 & GET_MASK(F_CHTERMIM)) {
ret = regmap_field_write(
info->regmap_fields[F_CHTERMIM], 0x00);
if (ret) {
dev_err(dev, "Failed to unmask CHTERMI interrupt\n");
return ret;
}
}
if (mask2 & GET_MASK(F_CHRCHGIM)) {
ret = regmap_field_write(
info->regmap_fields[F_CHRCHGIM], 0x00);
if (ret) {
dev_err(dev, "Failed to unmask CHRCHGI interrupt\n");
return ret;
}
}
/*
* When the battery is absent, max_charging_time_work is
* cancelled, since no charging is done.
*/
cancel_delayed_work_sync(&info->max_charging_time_work);
/*
* Since no interrupt is triggered when the battery is
* reconnected, max_charging_time_work is not rescheduled.
* Therefore, batt_presence_work is scheduled to check whether
* the battery is still absent or not.
*/
queue_delayed_work(system_power_efficient_wq,
&info->batt_presence_work,
RT9455_BATT_PRESENCE_DELAY * HZ);
}
*_is_battery_absent = is_battery_absent;
if (alert_userspace)
*_alert_userspace = alert_userspace;
return 0;
}
static int rt9455_irq_handler_check_irq2_register(struct rt9455_info *info,
bool is_battery_absent,
bool *_alert_userspace)
{
unsigned int irq2, mask2;
struct device *dev = &info->client->dev;
bool alert_userspace = false;
int ret;
ret = regmap_read(info->regmap, RT9455_REG_IRQ2, &irq2);
if (ret) {
dev_err(dev, "Failed to read IRQ2 register\n");
return ret;
}
ret = regmap_read(info->regmap, RT9455_REG_MASK2, &mask2);
if (ret) {
dev_err(dev, "Failed to read MASK2 register\n");
return ret;
}
if (irq2 & GET_MASK(F_CHRVPI)) {
dev_dbg(dev, "Charger fault occurred\n");
/*
* CHRVPI bit is set in 2 cases:
* 1. when the power source is connected to the charger.
* 2. when the power source is disconnected from the charger.
* To identify the case, PWR_RDY bit is checked. Because
* PWR_RDY bit is set / cleared after CHRVPI interrupt is
* triggered, it is used delayed_work to later read PWR_RDY bit.
* Also, do not set to true alert_userspace, because there is no
* need to notify userspace when CHRVPI interrupt has occurred.
* Userspace will be notified after PWR_RDY bit is read.
*/
queue_delayed_work(system_power_efficient_wq,
&info->pwr_rdy_work,
RT9455_PWR_RDY_DELAY * HZ);
}
if (irq2 & GET_MASK(F_CHBATOVI)) {
dev_err(dev, "Battery OVP occurred\n");
alert_userspace = true;
}
if (irq2 & GET_MASK(F_CHTERMI)) {
dev_dbg(dev, "Charge terminated\n");
if (!is_battery_absent) {
if ((mask2 & GET_MASK(F_CHTERMIM)) == 0) {
ret = regmap_field_write(
info->regmap_fields[F_CHTERMIM], 0x01);
if (ret) {
dev_err(dev, "Failed to mask CHTERMI interrupt\n");
return ret;
}
/*
* Update MASK2 value, since CHTERMIM bit is
* set.
*/
mask2 = mask2 | GET_MASK(F_CHTERMIM);
}
cancel_delayed_work_sync(&info->max_charging_time_work);
alert_userspace = true;
}
}
if (irq2 & GET_MASK(F_CHRCHGI)) {
dev_dbg(dev, "Recharge request\n");
ret = regmap_field_write(info->regmap_fields[F_CHG_EN],
RT9455_CHARGE_ENABLE);
if (ret) {
dev_err(dev, "Failed to enable charging\n");
return ret;
}
if (mask2 & GET_MASK(F_CHTERMIM)) {
ret = regmap_field_write(
info->regmap_fields[F_CHTERMIM], 0x00);
if (ret) {
dev_err(dev, "Failed to unmask CHTERMI interrupt\n");
return ret;
}
/* Update MASK2 value, since CHTERMIM bit is cleared. */
mask2 = mask2 & ~GET_MASK(F_CHTERMIM);
}
if (!is_battery_absent) {
/*
* No need to check whether the charger is connected to
* power source when CHRCHGI is received, since CHRCHGI
* is not triggered if the charger is not connected to
* the power source.
*/
queue_delayed_work(system_power_efficient_wq,
&info->max_charging_time_work,
RT9455_MAX_CHARGING_TIME * HZ);
alert_userspace = true;
}
}
if (irq2 & GET_MASK(F_CH32MI)) {
dev_err(dev, "Charger fault. 32 mins timeout occurred\n");
alert_userspace = true;
}
if (irq2 & GET_MASK(F_CHTREGI)) {
dev_warn(dev,
"Charger warning. Thermal regulation loop active\n");
alert_userspace = true;
}
if (irq2 & GET_MASK(F_CHMIVRI)) {
dev_dbg(dev,
"Charger warning. Input voltage MIVR loop active\n");
}
if (alert_userspace)
*_alert_userspace = alert_userspace;
return 0;
}
static int rt9455_irq_handler_check_irq3_register(struct rt9455_info *info,
bool *_alert_userspace)
{
unsigned int irq3, mask3;
struct device *dev = &info->client->dev;
bool alert_userspace = false;
int ret;
ret = regmap_read(info->regmap, RT9455_REG_IRQ3, &irq3);
if (ret) {
dev_err(dev, "Failed to read IRQ3 register\n");
return ret;
}
ret = regmap_read(info->regmap, RT9455_REG_MASK3, &mask3);
if (ret) {
dev_err(dev, "Failed to read MASK3 register\n");
return ret;
}
if (irq3 & GET_MASK(F_BSTBUSOVI)) {
dev_err(dev, "Boost fault. Overvoltage input occurred\n");
alert_userspace = true;
}
if (irq3 & GET_MASK(F_BSTOLI)) {
dev_err(dev, "Boost fault. Overload\n");
alert_userspace = true;
}
if (irq3 & GET_MASK(F_BSTLOWVI)) {
dev_err(dev, "Boost fault. Battery voltage too low\n");
alert_userspace = true;
}
if (irq3 & GET_MASK(F_BST32SI)) {
dev_err(dev, "Boost fault. 32 seconds timeout occurred.\n");
alert_userspace = true;
}
if (alert_userspace) {
dev_info(dev, "Boost fault occurred, therefore the charger goes into charge mode\n");
ret = rt9455_set_voreg_before_charge_mode(info);
if (ret) {
dev_err(dev, "Failed to set VOREG before entering charge mode\n");
return ret;
}
ret = regmap_field_write(info->regmap_fields[F_OPA_MODE],
RT9455_CHARGE_MODE);
if (ret) {
dev_err(dev, "Failed to set charger in charge mode\n");
return ret;
}
*_alert_userspace = alert_userspace;
}
return 0;
}
static irqreturn_t rt9455_irq_handler_thread(int irq, void *data)
{
struct rt9455_info *info = data;
struct device *dev;
bool alert_userspace = false;
bool is_battery_absent = false;
unsigned int status;
int ret;
if (!info)
return IRQ_NONE;
dev = &info->client->dev;
if (irq != info->client->irq) {
dev_err(dev, "Interrupt is not for RT9455 charger\n");
return IRQ_NONE;
}
ret = regmap_field_read(info->regmap_fields[F_STAT], &status);
if (ret) {
dev_err(dev, "Failed to read STAT bits\n");
return IRQ_HANDLED;
}
dev_dbg(dev, "Charger status is %d\n", status);
/*
* Each function that processes an IRQ register receives as output
* parameter alert_userspace pointer. alert_userspace is set to true
* in such a function only if an interrupt has occurred in the
* respective interrupt register. This way, it is avoided the following
* case: interrupt occurs only in IRQ1 register,
* rt9455_irq_handler_check_irq1_register() function sets to true
* alert_userspace, but rt9455_irq_handler_check_irq2_register()
* and rt9455_irq_handler_check_irq3_register() functions set to false
* alert_userspace and power_supply_changed() is never called.
*/
ret = rt9455_irq_handler_check_irq1_register(info, &is_battery_absent,
&alert_userspace);
if (ret) {
dev_err(dev, "Failed to handle IRQ1 register\n");
return IRQ_HANDLED;
}
ret = rt9455_irq_handler_check_irq2_register(info, is_battery_absent,
&alert_userspace);
if (ret) {
dev_err(dev, "Failed to handle IRQ2 register\n");
return IRQ_HANDLED;
}
ret = rt9455_irq_handler_check_irq3_register(info, &alert_userspace);
if (ret) {
dev_err(dev, "Failed to handle IRQ3 register\n");
return IRQ_HANDLED;
}
if (alert_userspace) {
/*
* Sometimes, an interrupt occurs while rt9455_probe() function
* is executing and power_supply_register() is not yet called.
* Do not call power_supply_changed() in this case.
*/
if (info->charger)
power_supply_changed(info->charger);
}
return IRQ_HANDLED;
}
static int rt9455_discover_charger(struct rt9455_info *info, u32 *ichrg,
u32 *ieoc_percentage,
u32 *mivr, u32 *iaicr)
{
struct device *dev = &info->client->dev;
int ret;
if (!dev->of_node && !ACPI_HANDLE(dev)) {
dev_err(dev, "No support for either device tree or ACPI\n");
return -EINVAL;
}
/*
* ICHRG, IEOC_PERCENTAGE, VOREG and boost output voltage are mandatory
* parameters.
*/
ret = device_property_read_u32(dev, "richtek,output-charge-current",
ichrg);
if (ret) {
dev_err(dev, "Error: missing \"output-charge-current\" property\n");
return ret;
}
ret = device_property_read_u32(dev, "richtek,end-of-charge-percentage",
ieoc_percentage);
if (ret) {
dev_err(dev, "Error: missing \"end-of-charge-percentage\" property\n");
return ret;
}
ret = device_property_read_u32(dev,
"richtek,battery-regulation-voltage",
&info->voreg);
if (ret) {
dev_err(dev, "Error: missing \"battery-regulation-voltage\" property\n");
return ret;
}
ret = device_property_read_u32(dev, "richtek,boost-output-voltage",
&info->boost_voltage);
if (ret) {
dev_err(dev, "Error: missing \"boost-output-voltage\" property\n");
return ret;
}
/*
* MIVR and IAICR are optional parameters. Do not return error if one of
* them is not present in ACPI table or device tree specification.
*/
device_property_read_u32(dev, "richtek,min-input-voltage-regulation",
mivr);
device_property_read_u32(dev, "richtek,avg-input-current-regulation",
iaicr);
return 0;
}
#if IS_ENABLED(CONFIG_USB_PHY)
static int rt9455_usb_event_none(struct rt9455_info *info,
u8 opa_mode, u8 iaicr)
{
struct device *dev = &info->client->dev;
int ret;
if (opa_mode == RT9455_BOOST_MODE) {
ret = rt9455_set_voreg_before_charge_mode(info);
if (ret) {
dev_err(dev, "Failed to set VOREG before entering charge mode\n");
return ret;
}
/*
* If the charger is in boost mode, and it has received
* USB_EVENT_NONE, this means the consumer device powered by the
* charger is not connected anymore.
* In this case, the charger goes into charge mode.
*/
dev_dbg(dev, "USB_EVENT_NONE received, therefore the charger goes into charge mode\n");
ret = regmap_field_write(info->regmap_fields[F_OPA_MODE],
RT9455_CHARGE_MODE);
if (ret) {
dev_err(dev, "Failed to set charger in charge mode\n");
return NOTIFY_DONE;
}
}
dev_dbg(dev, "USB_EVENT_NONE received, therefore IAICR is set to its minimum value\n");
if (iaicr != RT9455_IAICR_100MA) {
ret = regmap_field_write(info->regmap_fields[F_IAICR],
RT9455_IAICR_100MA);
if (ret) {
dev_err(dev, "Failed to set IAICR value\n");
return NOTIFY_DONE;
}
}
return NOTIFY_OK;
}
static int rt9455_usb_event_vbus(struct rt9455_info *info,
u8 opa_mode, u8 iaicr)
{
struct device *dev = &info->client->dev;
int ret;
if (opa_mode == RT9455_BOOST_MODE) {
ret = rt9455_set_voreg_before_charge_mode(info);
if (ret) {
dev_err(dev, "Failed to set VOREG before entering charge mode\n");
return ret;
}
/*
* If the charger is in boost mode, and it has received
* USB_EVENT_VBUS, this means the consumer device powered by the
* charger is not connected anymore.
* In this case, the charger goes into charge mode.
*/
dev_dbg(dev, "USB_EVENT_VBUS received, therefore the charger goes into charge mode\n");
ret = regmap_field_write(info->regmap_fields[F_OPA_MODE],
RT9455_CHARGE_MODE);
if (ret) {
dev_err(dev, "Failed to set charger in charge mode\n");
return NOTIFY_DONE;
}
}
dev_dbg(dev, "USB_EVENT_VBUS received, therefore IAICR is set to 500 mA\n");
if (iaicr != RT9455_IAICR_500MA) {
ret = regmap_field_write(info->regmap_fields[F_IAICR],
RT9455_IAICR_500MA);
if (ret) {
dev_err(dev, "Failed to set IAICR value\n");
return NOTIFY_DONE;
}
}
return NOTIFY_OK;
}
static int rt9455_usb_event_id(struct rt9455_info *info,
u8 opa_mode, u8 iaicr)
{
struct device *dev = &info->client->dev;
int ret;
if (opa_mode == RT9455_CHARGE_MODE) {
ret = rt9455_set_boost_voltage_before_boost_mode(info);
if (ret) {
dev_err(dev, "Failed to set boost output voltage before entering boost mode\n");
return ret;
}
/*
* If the charger is in charge mode, and it has received
* USB_EVENT_ID, this means a consumer device is connected and
* it should be powered by the charger.
* In this case, the charger goes into boost mode.
*/
dev_dbg(dev, "USB_EVENT_ID received, therefore the charger goes into boost mode\n");
ret = regmap_field_write(info->regmap_fields[F_OPA_MODE],
RT9455_BOOST_MODE);
if (ret) {
dev_err(dev, "Failed to set charger in boost mode\n");
return NOTIFY_DONE;
}
}
dev_dbg(dev, "USB_EVENT_ID received, therefore IAICR is set to its minimum value\n");
if (iaicr != RT9455_IAICR_100MA) {
ret = regmap_field_write(info->regmap_fields[F_IAICR],
RT9455_IAICR_100MA);
if (ret) {
dev_err(dev, "Failed to set IAICR value\n");
return NOTIFY_DONE;
}
}
return NOTIFY_OK;
}
static int rt9455_usb_event_charger(struct rt9455_info *info,
u8 opa_mode, u8 iaicr)
{
struct device *dev = &info->client->dev;
int ret;
if (opa_mode == RT9455_BOOST_MODE) {
ret = rt9455_set_voreg_before_charge_mode(info);
if (ret) {
dev_err(dev, "Failed to set VOREG before entering charge mode\n");
return ret;
}
/*
* If the charger is in boost mode, and it has received
* USB_EVENT_CHARGER, this means the consumer device powered by
* the charger is not connected anymore.
* In this case, the charger goes into charge mode.
*/
dev_dbg(dev, "USB_EVENT_CHARGER received, therefore the charger goes into charge mode\n");
ret = regmap_field_write(info->regmap_fields[F_OPA_MODE],
RT9455_CHARGE_MODE);
if (ret) {
dev_err(dev, "Failed to set charger in charge mode\n");
return NOTIFY_DONE;
}
}
dev_dbg(dev, "USB_EVENT_CHARGER received, therefore IAICR is set to no current limit\n");
if (iaicr != RT9455_IAICR_NO_LIMIT) {
ret = regmap_field_write(info->regmap_fields[F_IAICR],
RT9455_IAICR_NO_LIMIT);
if (ret) {
dev_err(dev, "Failed to set IAICR value\n");
return NOTIFY_DONE;
}
}
return NOTIFY_OK;
}
static int rt9455_usb_event(struct notifier_block *nb,
unsigned long event, void *power)
{
struct rt9455_info *info = container_of(nb, struct rt9455_info, nb);
struct device *dev = &info->client->dev;
unsigned int opa_mode, iaicr;
int ret;
/*
* Determine whether the charger is in charge mode
* or in boost mode.
*/
ret = regmap_field_read(info->regmap_fields[F_OPA_MODE],
&opa_mode);
if (ret) {
dev_err(dev, "Failed to read OPA_MODE value\n");
return NOTIFY_DONE;
}
ret = regmap_field_read(info->regmap_fields[F_IAICR],
&iaicr);
if (ret) {
dev_err(dev, "Failed to read IAICR value\n");
return NOTIFY_DONE;
}
dev_dbg(dev, "Received USB event %lu\n", event);
switch (event) {
case USB_EVENT_NONE:
return rt9455_usb_event_none(info, opa_mode, iaicr);
case USB_EVENT_VBUS:
return rt9455_usb_event_vbus(info, opa_mode, iaicr);
case USB_EVENT_ID:
return rt9455_usb_event_id(info, opa_mode, iaicr);
case USB_EVENT_CHARGER:
return rt9455_usb_event_charger(info, opa_mode, iaicr);
default:
dev_err(dev, "Unknown USB event\n");
}
return NOTIFY_DONE;
}
#endif
static void rt9455_pwr_rdy_work_callback(struct work_struct *work)
{
struct rt9455_info *info = container_of(work, struct rt9455_info,
pwr_rdy_work.work);
struct device *dev = &info->client->dev;
unsigned int pwr_rdy;
int ret;
ret = regmap_field_read(info->regmap_fields[F_PWR_RDY], &pwr_rdy);
if (ret) {
dev_err(dev, "Failed to read PWR_RDY bit\n");
return;
}
switch (pwr_rdy) {
case RT9455_PWR_FAULT:
dev_dbg(dev, "Charger disconnected from power source\n");
cancel_delayed_work_sync(&info->max_charging_time_work);
break;
case RT9455_PWR_GOOD:
dev_dbg(dev, "Charger connected to power source\n");
ret = regmap_field_write(info->regmap_fields[F_CHG_EN],
RT9455_CHARGE_ENABLE);
if (ret) {
dev_err(dev, "Failed to enable charging\n");
return;
}
queue_delayed_work(system_power_efficient_wq,
&info->max_charging_time_work,
RT9455_MAX_CHARGING_TIME * HZ);
break;
}
/*
* Notify userspace that the charger has been either connected to or
* disconnected from the power source.
*/
power_supply_changed(info->charger);
}
static void rt9455_max_charging_time_work_callback(struct work_struct *work)
{
struct rt9455_info *info = container_of(work, struct rt9455_info,
max_charging_time_work.work);
struct device *dev = &info->client->dev;
int ret;
dev_err(dev, "Battery has been charging for at least 6 hours and is not yet fully charged. Battery is dead, therefore charging is disabled.\n");
ret = regmap_field_write(info->regmap_fields[F_CHG_EN],
RT9455_CHARGE_DISABLE);
if (ret)
dev_err(dev, "Failed to disable charging\n");
}
static void rt9455_batt_presence_work_callback(struct work_struct *work)
{
struct rt9455_info *info = container_of(work, struct rt9455_info,
batt_presence_work.work);
struct device *dev = &info->client->dev;
unsigned int irq1, mask1;
int ret;
ret = regmap_read(info->regmap, RT9455_REG_IRQ1, &irq1);
if (ret) {
dev_err(dev, "Failed to read IRQ1 register\n");
return;
}
/*
* If the battery is still absent, batt_presence_work is rescheduled.
* Otherwise, max_charging_time is scheduled.
*/
if (irq1 & GET_MASK(F_BATAB)) {
queue_delayed_work(system_power_efficient_wq,
&info->batt_presence_work,
RT9455_BATT_PRESENCE_DELAY * HZ);
} else {
queue_delayed_work(system_power_efficient_wq,
&info->max_charging_time_work,
RT9455_MAX_CHARGING_TIME * HZ);
ret = regmap_read(info->regmap, RT9455_REG_MASK1, &mask1);
if (ret) {
dev_err(dev, "Failed to read MASK1 register\n");
return;
}
if (mask1 & GET_MASK(F_BATABM)) {
ret = regmap_field_write(info->regmap_fields[F_BATABM],
0x00);
if (ret)
dev_err(dev, "Failed to unmask BATAB interrupt\n");
}
/*
* Notify userspace that the battery is now connected to the
* charger.
*/
power_supply_changed(info->charger);
}
}
static const struct power_supply_desc rt9455_charger_desc = {
.name = RT9455_DRIVER_NAME,
.type = POWER_SUPPLY_TYPE_USB,
.properties = rt9455_charger_properties,
.num_properties = ARRAY_SIZE(rt9455_charger_properties),
.get_property = rt9455_charger_get_property,
};
static bool rt9455_is_writeable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case RT9455_REG_DEV_ID:
case RT9455_REG_IRQ1:
case RT9455_REG_IRQ2:
case RT9455_REG_IRQ3:
return false;
default:
return true;
}
}
static bool rt9455_is_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case RT9455_REG_DEV_ID:
case RT9455_REG_CTRL5:
case RT9455_REG_CTRL6:
return false;
default:
return true;
}
}
static const struct regmap_config rt9455_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.writeable_reg = rt9455_is_writeable_reg,
.volatile_reg = rt9455_is_volatile_reg,
.max_register = RT9455_REG_MASK3,
.cache_type = REGCACHE_RBTREE,
};
static int rt9455_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct device *dev = &client->dev;
struct rt9455_info *info;
struct power_supply_config rt9455_charger_config = {};
/*
* Mandatory device-specific data values. Also, VOREG and boost output
* voltage are mandatory values, but they are stored in rt9455_info
* structure.
*/
u32 ichrg, ieoc_percentage;
/* Optional device-specific data values. */
u32 mivr = -1, iaicr = -1;
int i, ret;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(dev, "No support for SMBUS_BYTE_DATA\n");
return -ENODEV;
}
info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->client = client;
i2c_set_clientdata(client, info);
info->regmap = devm_regmap_init_i2c(client,
&rt9455_regmap_config);
if (IS_ERR(info->regmap)) {
dev_err(dev, "Failed to initialize register map\n");
return -EINVAL;
}
for (i = 0; i < F_MAX_FIELDS; i++) {
info->regmap_fields[i] =
devm_regmap_field_alloc(dev, info->regmap,
rt9455_reg_fields[i]);
if (IS_ERR(info->regmap_fields[i])) {
dev_err(dev,
"Failed to allocate regmap field = %d\n", i);
return PTR_ERR(info->regmap_fields[i]);
}
}
ret = rt9455_discover_charger(info, &ichrg, &ieoc_percentage,
&mivr, &iaicr);
if (ret) {
dev_err(dev, "Failed to discover charger\n");
return ret;
}
#if IS_ENABLED(CONFIG_USB_PHY)
info->usb_phy = devm_usb_get_phy(dev, USB_PHY_TYPE_USB2);
if (IS_ERR(info->usb_phy)) {
dev_err(dev, "Failed to get USB transceiver\n");
} else {
info->nb.notifier_call = rt9455_usb_event;
ret = usb_register_notifier(info->usb_phy, &info->nb);
if (ret) {
dev_err(dev, "Failed to register USB notifier\n");
/*
* If usb_register_notifier() fails, set notifier_call
* to NULL, to avoid calling usb_unregister_notifier().
*/
info->nb.notifier_call = NULL;
}
}
#endif
INIT_DEFERRABLE_WORK(&info->pwr_rdy_work, rt9455_pwr_rdy_work_callback);
INIT_DEFERRABLE_WORK(&info->max_charging_time_work,
rt9455_max_charging_time_work_callback);
INIT_DEFERRABLE_WORK(&info->batt_presence_work,
rt9455_batt_presence_work_callback);
rt9455_charger_config.of_node = dev->of_node;
rt9455_charger_config.drv_data = info;
rt9455_charger_config.supplied_to = rt9455_charger_supplied_to;
rt9455_charger_config.num_supplicants =
ARRAY_SIZE(rt9455_charger_supplied_to);
ret = devm_request_threaded_irq(dev, client->irq, NULL,
rt9455_irq_handler_thread,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
RT9455_DRIVER_NAME, info);
if (ret) {
dev_err(dev, "Failed to register IRQ handler\n");
goto put_usb_notifier;
}
ret = rt9455_hw_init(info, ichrg, ieoc_percentage, mivr, iaicr);
if (ret) {
dev_err(dev, "Failed to set charger to its default values\n");
goto put_usb_notifier;
}
info->charger = devm_power_supply_register(dev, &rt9455_charger_desc,
&rt9455_charger_config);
if (IS_ERR(info->charger)) {
dev_err(dev, "Failed to register charger\n");
ret = PTR_ERR(info->charger);
goto put_usb_notifier;
}
return 0;
put_usb_notifier:
#if IS_ENABLED(CONFIG_USB_PHY)
if (info->nb.notifier_call) {
usb_unregister_notifier(info->usb_phy, &info->nb);
info->nb.notifier_call = NULL;
}
#endif
return ret;
}
static int rt9455_remove(struct i2c_client *client)
{
int ret;
struct rt9455_info *info = i2c_get_clientdata(client);
ret = rt9455_register_reset(info);
if (ret)
dev_err(&info->client->dev, "Failed to set charger to its default values\n");
#if IS_ENABLED(CONFIG_USB_PHY)
if (info->nb.notifier_call)
usb_unregister_notifier(info->usb_phy, &info->nb);
#endif
cancel_delayed_work_sync(&info->pwr_rdy_work);
cancel_delayed_work_sync(&info->max_charging_time_work);
cancel_delayed_work_sync(&info->batt_presence_work);
return ret;
}
static const struct i2c_device_id rt9455_i2c_id_table[] = {
{ RT9455_DRIVER_NAME, 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, rt9455_i2c_id_table);
static const struct of_device_id rt9455_of_match[] = {
{ .compatible = "richtek,rt9455", },
{ },
};
MODULE_DEVICE_TABLE(of, rt9455_of_match);
static const struct acpi_device_id rt9455_i2c_acpi_match[] = {
{ "RT945500", 0 },
{ }
};
MODULE_DEVICE_TABLE(acpi, rt9455_i2c_acpi_match);
static struct i2c_driver rt9455_driver = {
.probe = rt9455_probe,
.remove = rt9455_remove,
.id_table = rt9455_i2c_id_table,
.driver = {
.name = RT9455_DRIVER_NAME,
.of_match_table = of_match_ptr(rt9455_of_match),
.acpi_match_table = ACPI_PTR(rt9455_i2c_acpi_match),
},
};
module_i2c_driver(rt9455_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Anda-Maria Nicolae <anda-maria.nicolae@intel.com>");
MODULE_ALIAS("i2c:rt9455-charger");
MODULE_DESCRIPTION("Richtek RT9455 Charger Driver");
| gpl-2.0 |
emceethemouth/kernel_cancro | security/integrity/ima/ima_policy.c | 987 | 12724 | /*
* Copyright (C) 2008 IBM Corporation
* Author: Mimi Zohar <zohar@us.ibm.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.
*
* ima_policy.c
* - initialize default measure policy rules
*
*/
#include <linux/module.h>
#include <linux/list.h>
#include <linux/security.h>
#include <linux/magic.h>
#include <linux/parser.h>
#include <linux/slab.h>
#include "ima.h"
/* flags definitions */
#define IMA_FUNC 0x0001
#define IMA_MASK 0x0002
#define IMA_FSMAGIC 0x0004
#define IMA_UID 0x0008
enum ima_action { UNKNOWN = -1, DONT_MEASURE = 0, MEASURE };
#define MAX_LSM_RULES 6
enum lsm_rule_types { LSM_OBJ_USER, LSM_OBJ_ROLE, LSM_OBJ_TYPE,
LSM_SUBJ_USER, LSM_SUBJ_ROLE, LSM_SUBJ_TYPE
};
struct ima_measure_rule_entry {
struct list_head list;
enum ima_action action;
unsigned int flags;
enum ima_hooks func;
int mask;
unsigned long fsmagic;
uid_t uid;
struct {
void *rule; /* LSM file metadata specific */
int type; /* audit type */
} lsm[MAX_LSM_RULES];
};
/*
* Without LSM specific knowledge, the default policy can only be
* written in terms of .action, .func, .mask, .fsmagic, and .uid
*/
/*
* The minimum rule set to allow for full TCB coverage. Measures all files
* opened or mmap for exec and everything read by root. Dangerous because
* normal users can easily run the machine out of memory simply building
* and running executables.
*/
static struct ima_measure_rule_entry default_rules[] = {
{.action = DONT_MEASURE,.fsmagic = PROC_SUPER_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = SYSFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = DEBUGFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = TMPFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = SECURITYFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = SELINUX_MAGIC,.flags = IMA_FSMAGIC},
{.action = MEASURE,.func = FILE_MMAP,.mask = MAY_EXEC,
.flags = IMA_FUNC | IMA_MASK},
{.action = MEASURE,.func = BPRM_CHECK,.mask = MAY_EXEC,
.flags = IMA_FUNC | IMA_MASK},
{.action = MEASURE,.func = FILE_CHECK,.mask = MAY_READ,.uid = 0,
.flags = IMA_FUNC | IMA_MASK | IMA_UID},
};
static LIST_HEAD(measure_default_rules);
static LIST_HEAD(measure_policy_rules);
static struct list_head *ima_measure;
static DEFINE_MUTEX(ima_measure_mutex);
static bool ima_use_tcb __initdata;
static int __init default_policy_setup(char *str)
{
ima_use_tcb = 1;
return 1;
}
__setup("ima_tcb", default_policy_setup);
/**
* ima_match_rules - determine whether an inode matches the measure rule.
* @rule: a pointer to a rule
* @inode: a pointer to an inode
* @func: LIM hook identifier
* @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
*
* Returns true on rule match, false on failure.
*/
static bool ima_match_rules(struct ima_measure_rule_entry *rule,
struct inode *inode, enum ima_hooks func, int mask)
{
struct task_struct *tsk = current;
const struct cred *cred = current_cred();
int i;
if ((rule->flags & IMA_FUNC) && rule->func != func)
return false;
if ((rule->flags & IMA_MASK) && rule->mask != mask)
return false;
if ((rule->flags & IMA_FSMAGIC)
&& rule->fsmagic != inode->i_sb->s_magic)
return false;
if ((rule->flags & IMA_UID) && rule->uid != cred->uid)
return false;
for (i = 0; i < MAX_LSM_RULES; i++) {
int rc = 0;
u32 osid, sid;
if (!rule->lsm[i].rule)
continue;
switch (i) {
case LSM_OBJ_USER:
case LSM_OBJ_ROLE:
case LSM_OBJ_TYPE:
security_inode_getsecid(inode, &osid);
rc = security_filter_rule_match(osid,
rule->lsm[i].type,
Audit_equal,
rule->lsm[i].rule,
NULL);
break;
case LSM_SUBJ_USER:
case LSM_SUBJ_ROLE:
case LSM_SUBJ_TYPE:
security_task_getsecid(tsk, &sid);
rc = security_filter_rule_match(sid,
rule->lsm[i].type,
Audit_equal,
rule->lsm[i].rule,
NULL);
default:
break;
}
if (!rc)
return false;
}
return true;
}
/**
* ima_match_policy - decision based on LSM and other conditions
* @inode: pointer to an inode for which the policy decision is being made
* @func: IMA hook identifier
* @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
*
* Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
* conditions.
*
* (There is no need for locking when walking the policy list,
* as elements in the list are never deleted, nor does the list
* change.)
*/
int ima_match_policy(struct inode *inode, enum ima_hooks func, int mask)
{
struct ima_measure_rule_entry *entry;
list_for_each_entry(entry, ima_measure, list) {
bool rc;
rc = ima_match_rules(entry, inode, func, mask);
if (rc)
return entry->action;
}
return 0;
}
/**
* ima_init_policy - initialize the default measure rules.
*
* ima_measure points to either the measure_default_rules or the
* the new measure_policy_rules.
*/
void __init ima_init_policy(void)
{
int i, entries;
/* if !ima_use_tcb set entries = 0 so we load NO default rules */
if (ima_use_tcb)
entries = ARRAY_SIZE(default_rules);
else
entries = 0;
for (i = 0; i < entries; i++)
list_add_tail(&default_rules[i].list, &measure_default_rules);
ima_measure = &measure_default_rules;
}
/**
* ima_update_policy - update default_rules with new measure rules
*
* Called on file .release to update the default rules with a complete new
* policy. Once updated, the policy is locked, no additional rules can be
* added to the policy.
*/
void ima_update_policy(void)
{
const char *op = "policy_update";
const char *cause = "already exists";
int result = 1;
int audit_info = 0;
if (ima_measure == &measure_default_rules) {
ima_measure = &measure_policy_rules;
cause = "complete";
result = 0;
}
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, cause, result, audit_info);
}
enum {
Opt_err = -1,
Opt_measure = 1, Opt_dont_measure,
Opt_obj_user, Opt_obj_role, Opt_obj_type,
Opt_subj_user, Opt_subj_role, Opt_subj_type,
Opt_func, Opt_mask, Opt_fsmagic, Opt_uid
};
static match_table_t policy_tokens = {
{Opt_measure, "measure"},
{Opt_dont_measure, "dont_measure"},
{Opt_obj_user, "obj_user=%s"},
{Opt_obj_role, "obj_role=%s"},
{Opt_obj_type, "obj_type=%s"},
{Opt_subj_user, "subj_user=%s"},
{Opt_subj_role, "subj_role=%s"},
{Opt_subj_type, "subj_type=%s"},
{Opt_func, "func=%s"},
{Opt_mask, "mask=%s"},
{Opt_fsmagic, "fsmagic=%s"},
{Opt_uid, "uid=%s"},
{Opt_err, NULL}
};
static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,
char *args, int lsm_rule, int audit_type)
{
int result;
if (entry->lsm[lsm_rule].rule)
return -EINVAL;
entry->lsm[lsm_rule].type = audit_type;
result = security_filter_rule_init(entry->lsm[lsm_rule].type,
Audit_equal, args,
&entry->lsm[lsm_rule].rule);
if (!entry->lsm[lsm_rule].rule)
return -EINVAL;
return result;
}
static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
{
audit_log_format(ab, "%s=", key);
audit_log_untrustedstring(ab, value);
audit_log_format(ab, " ");
}
static int ima_parse_rule(char *rule, struct ima_measure_rule_entry *entry)
{
struct audit_buffer *ab;
char *p;
int result = 0;
ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_INTEGRITY_RULE);
entry->uid = -1;
entry->action = UNKNOWN;
while ((p = strsep(&rule, " \t")) != NULL) {
substring_t args[MAX_OPT_ARGS];
int token;
unsigned long lnum;
if (result < 0)
break;
if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
continue;
token = match_token(p, policy_tokens, args);
switch (token) {
case Opt_measure:
ima_log_string(ab, "action", "measure");
if (entry->action != UNKNOWN)
result = -EINVAL;
entry->action = MEASURE;
break;
case Opt_dont_measure:
ima_log_string(ab, "action", "dont_measure");
if (entry->action != UNKNOWN)
result = -EINVAL;
entry->action = DONT_MEASURE;
break;
case Opt_func:
ima_log_string(ab, "func", args[0].from);
if (entry->func)
result = -EINVAL;
if (strcmp(args[0].from, "FILE_CHECK") == 0)
entry->func = FILE_CHECK;
/* PATH_CHECK is for backwards compat */
else if (strcmp(args[0].from, "PATH_CHECK") == 0)
entry->func = FILE_CHECK;
else if (strcmp(args[0].from, "FILE_MMAP") == 0)
entry->func = FILE_MMAP;
else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
entry->func = BPRM_CHECK;
else
result = -EINVAL;
if (!result)
entry->flags |= IMA_FUNC;
break;
case Opt_mask:
ima_log_string(ab, "mask", args[0].from);
if (entry->mask)
result = -EINVAL;
if ((strcmp(args[0].from, "MAY_EXEC")) == 0)
entry->mask = MAY_EXEC;
else if (strcmp(args[0].from, "MAY_WRITE") == 0)
entry->mask = MAY_WRITE;
else if (strcmp(args[0].from, "MAY_READ") == 0)
entry->mask = MAY_READ;
else if (strcmp(args[0].from, "MAY_APPEND") == 0)
entry->mask = MAY_APPEND;
else
result = -EINVAL;
if (!result)
entry->flags |= IMA_MASK;
break;
case Opt_fsmagic:
ima_log_string(ab, "fsmagic", args[0].from);
if (entry->fsmagic) {
result = -EINVAL;
break;
}
result = strict_strtoul(args[0].from, 16,
&entry->fsmagic);
if (!result)
entry->flags |= IMA_FSMAGIC;
break;
case Opt_uid:
ima_log_string(ab, "uid", args[0].from);
if (entry->uid != -1) {
result = -EINVAL;
break;
}
result = strict_strtoul(args[0].from, 10, &lnum);
if (!result) {
entry->uid = (uid_t) lnum;
if (entry->uid != lnum)
result = -EINVAL;
else
entry->flags |= IMA_UID;
}
break;
case Opt_obj_user:
ima_log_string(ab, "obj_user", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_OBJ_USER,
AUDIT_OBJ_USER);
break;
case Opt_obj_role:
ima_log_string(ab, "obj_role", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_OBJ_ROLE,
AUDIT_OBJ_ROLE);
break;
case Opt_obj_type:
ima_log_string(ab, "obj_type", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_OBJ_TYPE,
AUDIT_OBJ_TYPE);
break;
case Opt_subj_user:
ima_log_string(ab, "subj_user", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_SUBJ_USER,
AUDIT_SUBJ_USER);
break;
case Opt_subj_role:
ima_log_string(ab, "subj_role", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_SUBJ_ROLE,
AUDIT_SUBJ_ROLE);
break;
case Opt_subj_type:
ima_log_string(ab, "subj_type", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_SUBJ_TYPE,
AUDIT_SUBJ_TYPE);
break;
case Opt_err:
ima_log_string(ab, "UNKNOWN", p);
result = -EINVAL;
break;
}
}
if (!result && (entry->action == UNKNOWN))
result = -EINVAL;
audit_log_format(ab, "res=%d", !result);
audit_log_end(ab);
return result;
}
/**
* ima_parse_add_rule - add a rule to measure_policy_rules
* @rule - ima measurement policy rule
*
* Uses a mutex to protect the policy list from multiple concurrent writers.
* Returns the length of the rule parsed, an error code on failure
*/
ssize_t ima_parse_add_rule(char *rule)
{
const char *op = "update_policy";
char *p;
struct ima_measure_rule_entry *entry;
ssize_t result, len;
int audit_info = 0;
/* Prevent installed policy from changing */
if (ima_measure != &measure_default_rules) {
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, "already exists",
-EACCES, audit_info);
return -EACCES;
}
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry) {
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, "-ENOMEM", -ENOMEM, audit_info);
return -ENOMEM;
}
INIT_LIST_HEAD(&entry->list);
p = strsep(&rule, "\n");
len = strlen(p) + 1;
if (*p == '#') {
kfree(entry);
return len;
}
result = ima_parse_rule(p, entry);
if (result) {
kfree(entry);
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, "invalid policy", result,
audit_info);
return result;
}
mutex_lock(&ima_measure_mutex);
list_add_tail(&entry->list, &measure_policy_rules);
mutex_unlock(&ima_measure_mutex);
return len;
}
/* ima_delete_rules called to cleanup invalid policy */
void ima_delete_rules(void)
{
struct ima_measure_rule_entry *entry, *tmp;
mutex_lock(&ima_measure_mutex);
list_for_each_entry_safe(entry, tmp, &measure_policy_rules, list) {
list_del(&entry->list);
kfree(entry);
}
mutex_unlock(&ima_measure_mutex);
}
| gpl-2.0 |
tommytarts/QuantumKernelS3 | arch/arm/mach-msm/perf_event_msm_l2.c | 987 | 26520 | /*
* Copyright (c) 2011, 2012 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/irq.h>
#include <asm/pmu.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#define MAX_SCORPION_L2_CTRS 10
#define SCORPION_L2CYCLE_CTR_BIT 31
#define SCORPION_L2CYCLE_CTR_RAW_CODE 0xfe
#define SCORPIONL2_PMNC_E (1 << 0) /* Enable all counters */
#define SCORPION_L2_EVT_PREFIX 3
#define SCORPION_MAX_L2_REG 4
#define L2_EVT_MASK 0xfffff
#define L2_EVT_PREFIX_MASK 0xf0000
#define L2_EVT_PREFIX_SHIFT 16
#define L2_SLAVE_EVT_PREFIX 4
#define PMCR_NUM_EV_SHIFT 11
#define PMCR_NUM_EV_MASK 0x1f
/*
* The L2 PMU is shared between all CPU's, so protect
* its bitmap access.
*/
struct pmu_constraints {
u64 pmu_bitmap;
u8 codes[64];
raw_spinlock_t lock;
} l2_pmu_constraints = {
.pmu_bitmap = 0,
.codes = {-1},
.lock = __RAW_SPIN_LOCK_UNLOCKED(l2_pmu_constraints.lock),
};
/* NRCCG format for perf RAW codes. */
PMU_FORMAT_ATTR(l2_prefix, "config:16-19");
PMU_FORMAT_ATTR(l2_reg, "config:12-15");
PMU_FORMAT_ATTR(l2_code, "config:4-11");
PMU_FORMAT_ATTR(l2_grp, "config:0-3");
static struct attribute *msm_l2_ev_formats[] = {
&format_attr_l2_prefix.attr,
&format_attr_l2_reg.attr,
&format_attr_l2_code.attr,
&format_attr_l2_grp.attr,
NULL,
};
/*
* Format group is essential to access PMU's from userspace
* via their .name field.
*/
static struct attribute_group msm_l2_pmu_format_group = {
.name = "format",
.attrs = msm_l2_ev_formats,
};
static const struct attribute_group *msm_l2_pmu_attr_grps[] = {
&msm_l2_pmu_format_group,
NULL,
};
static u32 total_l2_ctrs;
static u32 l2_cycle_ctr_idx;
static u32 pmu_type;
static struct arm_pmu scorpion_l2_pmu;
static u32 l2_orig_filter_prefix = 0x000f0030;
/* L2 slave port traffic filtering */
static u32 l2_slv_filter_prefix = 0x000f0010;
static struct perf_event *l2_events[MAX_SCORPION_L2_CTRS];
static unsigned long l2_used_mask[BITS_TO_LONGS(MAX_SCORPION_L2_CTRS)];
static struct pmu_hw_events scorpion_l2_pmu_hw_events = {
.events = l2_events,
.used_mask = l2_used_mask,
.pmu_lock =
__RAW_SPIN_LOCK_UNLOCKED(scorpion_l2_pmu_hw_events.pmu_lock),
};
struct scorpion_l2_scorp_evt {
u32 evt_type;
u32 val;
u8 grp;
u32 evt_type_act;
};
enum scorpion_perf_types {
SCORPIONL2_TOTAL_BANK_REQ = 0x90,
SCORPIONL2_DSIDE_READ = 0x91,
SCORPIONL2_DSIDE_WRITE = 0x92,
SCORPIONL2_ISIDE_READ = 0x93,
SCORPIONL2_L2CACHE_ISIDE_READ = 0x94,
SCORPIONL2_L2CACHE_BANK_REQ = 0x95,
SCORPIONL2_L2CACHE_DSIDE_READ = 0x96,
SCORPIONL2_L2CACHE_DSIDE_WRITE = 0x97,
SCORPIONL2_L2NOCACHE_DSIDE_WRITE = 0x98,
SCORPIONL2_L2NOCACHE_ISIDE_READ = 0x99,
SCORPIONL2_L2NOCACHE_TOTAL_REQ = 0x9a,
SCORPIONL2_L2NOCACHE_DSIDE_READ = 0x9b,
SCORPIONL2_DSIDE_READ_NOL1 = 0x9c,
SCORPIONL2_L2CACHE_WRITETHROUGH = 0x9d,
SCORPIONL2_BARRIERS = 0x9e,
SCORPIONL2_HARDWARE_TABLE_WALKS = 0x9f,
SCORPIONL2_MVA_POC = 0xa0,
SCORPIONL2_L2CACHE_HW_TABLE_WALKS = 0xa1,
SCORPIONL2_SETWAY_CACHE_OPS = 0xa2,
SCORPIONL2_DSIDE_WRITE_HITS = 0xa3,
SCORPIONL2_ISIDE_READ_HITS = 0xa4,
SCORPIONL2_CACHE_DSIDE_READ_NOL1 = 0xa5,
SCORPIONL2_TOTAL_CACHE_HITS = 0xa6,
SCORPIONL2_CACHE_MATCH_MISS = 0xa7,
SCORPIONL2_DREAD_HIT_L1_DATA = 0xa8,
SCORPIONL2_L2LINE_LOCKED = 0xa9,
SCORPIONL2_HW_TABLE_WALK_HIT = 0xaa,
SCORPIONL2_CACHE_MVA_POC = 0xab,
SCORPIONL2_L2ALLOC_DWRITE_MISS = 0xac,
SCORPIONL2_CORRECTED_TAG_ARRAY = 0xad,
SCORPIONL2_CORRECTED_DATA_ARRAY = 0xae,
SCORPIONL2_CORRECTED_REPLACEMENT_ARRAY = 0xaf,
SCORPIONL2_PMBUS_MPAAF = 0xb0,
SCORPIONL2_PMBUS_MPWDAF = 0xb1,
SCORPIONL2_PMBUS_MPBRT = 0xb2,
SCORPIONL2_CPU0_GRANT = 0xb3,
SCORPIONL2_CPU1_GRANT = 0xb4,
SCORPIONL2_CPU0_NOGRANT = 0xb5,
SCORPIONL2_CPU1_NOGRANT = 0xb6,
SCORPIONL2_CPU0_LOSING_ARB = 0xb7,
SCORPIONL2_CPU1_LOSING_ARB = 0xb8,
SCORPIONL2_SLAVEPORT_NOGRANT = 0xb9,
SCORPIONL2_SLAVEPORT_BPQ_FULL = 0xba,
SCORPIONL2_SLAVEPORT_LOSING_ARB = 0xbb,
SCORPIONL2_SLAVEPORT_GRANT = 0xbc,
SCORPIONL2_SLAVEPORT_GRANTLOCK = 0xbd,
SCORPIONL2_L2EM_STREX_PASS = 0xbe,
SCORPIONL2_L2EM_STREX_FAIL = 0xbf,
SCORPIONL2_LDREX_RESERVE_L2EM = 0xc0,
SCORPIONL2_SLAVEPORT_LDREX = 0xc1,
SCORPIONL2_CPU0_L2EM_CLEARED = 0xc2,
SCORPIONL2_CPU1_L2EM_CLEARED = 0xc3,
SCORPIONL2_SLAVEPORT_L2EM_CLEARED = 0xc4,
SCORPIONL2_CPU0_CLAMPED = 0xc5,
SCORPIONL2_CPU1_CLAMPED = 0xc6,
SCORPIONL2_CPU0_WAIT = 0xc7,
SCORPIONL2_CPU1_WAIT = 0xc8,
SCORPIONL2_CPU0_NONAMBAS_WAIT = 0xc9,
SCORPIONL2_CPU1_NONAMBAS_WAIT = 0xca,
SCORPIONL2_CPU0_DSB_WAIT = 0xcb,
SCORPIONL2_CPU1_DSB_WAIT = 0xcc,
SCORPIONL2_AXI_READ = 0xcd,
SCORPIONL2_AXI_WRITE = 0xce,
SCORPIONL2_1BEAT_WRITE = 0xcf,
SCORPIONL2_2BEAT_WRITE = 0xd0,
SCORPIONL2_4BEAT_WRITE = 0xd1,
SCORPIONL2_8BEAT_WRITE = 0xd2,
SCORPIONL2_12BEAT_WRITE = 0xd3,
SCORPIONL2_16BEAT_WRITE = 0xd4,
SCORPIONL2_1BEAT_DSIDE_READ = 0xd5,
SCORPIONL2_2BEAT_DSIDE_READ = 0xd6,
SCORPIONL2_4BEAT_DSIDE_READ = 0xd7,
SCORPIONL2_8BEAT_DSIDE_READ = 0xd8,
SCORPIONL2_CSYS_READ_1BEAT = 0xd9,
SCORPIONL2_CSYS_READ_2BEAT = 0xda,
SCORPIONL2_CSYS_READ_4BEAT = 0xdb,
SCORPIONL2_CSYS_READ_8BEAT = 0xdc,
SCORPIONL2_4BEAT_IFETCH_READ = 0xdd,
SCORPIONL2_8BEAT_IFETCH_READ = 0xde,
SCORPIONL2_CSYS_WRITE_1BEAT = 0xdf,
SCORPIONL2_CSYS_WRITE_2BEAT = 0xe0,
SCORPIONL2_AXI_READ_DATA_BEAT = 0xe1,
SCORPIONL2_AXI_WRITE_EVT1 = 0xe2,
SCORPIONL2_AXI_WRITE_EVT2 = 0xe3,
SCORPIONL2_LDREX_REQ = 0xe4,
SCORPIONL2_STREX_PASS = 0xe5,
SCORPIONL2_STREX_FAIL = 0xe6,
SCORPIONL2_CPREAD = 0xe7,
SCORPIONL2_CPWRITE = 0xe8,
SCORPIONL2_BARRIER_REQ = 0xe9,
SCORPIONL2_AXI_READ_SLVPORT = 0xea,
SCORPIONL2_AXI_WRITE_SLVPORT = 0xeb,
SCORPIONL2_AXI_READ_SLVPORT_DATABEAT = 0xec,
SCORPIONL2_AXI_WRITE_SLVPORT_DATABEAT = 0xed,
SCORPIONL2_SNOOPKILL_PREFILTER = 0xee,
SCORPIONL2_SNOOPKILL_FILTEROUT = 0xef,
SCORPIONL2_SNOOPED_IC = 0xf0,
SCORPIONL2_SNOOPED_BP = 0xf1,
SCORPIONL2_SNOOPED_BARRIERS = 0xf2,
SCORPIONL2_SNOOPED_TLB = 0xf3,
SCORPION_L2_MAX_EVT,
};
static const struct scorpion_l2_scorp_evt sc_evt[] = {
{SCORPIONL2_TOTAL_BANK_REQ, 0x80000001, 0, 0x00},
{SCORPIONL2_DSIDE_READ, 0x80000100, 0, 0x01},
{SCORPIONL2_DSIDE_WRITE, 0x80010000, 0, 0x02},
{SCORPIONL2_ISIDE_READ, 0x81000000, 0, 0x03},
{SCORPIONL2_L2CACHE_ISIDE_READ, 0x80000002, 0, 0x00},
{SCORPIONL2_L2CACHE_BANK_REQ, 0x80000200, 0, 0x01},
{SCORPIONL2_L2CACHE_DSIDE_READ, 0x80020000, 0, 0x02},
{SCORPIONL2_L2CACHE_DSIDE_WRITE, 0x82000000, 0, 0x03},
{SCORPIONL2_L2NOCACHE_DSIDE_WRITE, 0x80000003, 0, 0x00},
{SCORPIONL2_L2NOCACHE_ISIDE_READ, 0x80000300, 0, 0x01},
{SCORPIONL2_L2NOCACHE_TOTAL_REQ, 0x80030000, 0, 0x02},
{SCORPIONL2_L2NOCACHE_DSIDE_READ, 0x83000000, 0, 0x03},
{SCORPIONL2_DSIDE_READ_NOL1, 0x80000004, 0, 0x00},
{SCORPIONL2_L2CACHE_WRITETHROUGH, 0x80000400, 0, 0x01},
{SCORPIONL2_BARRIERS, 0x84000000, 0, 0x03},
{SCORPIONL2_HARDWARE_TABLE_WALKS, 0x80000005, 0, 0x00},
{SCORPIONL2_MVA_POC, 0x80000500, 0, 0x01},
{SCORPIONL2_L2CACHE_HW_TABLE_WALKS, 0x80050000, 0, 0x02},
{SCORPIONL2_SETWAY_CACHE_OPS, 0x85000000, 0, 0x03},
{SCORPIONL2_DSIDE_WRITE_HITS, 0x80000006, 0, 0x00},
{SCORPIONL2_ISIDE_READ_HITS, 0x80000600, 0, 0x01},
{SCORPIONL2_CACHE_DSIDE_READ_NOL1, 0x80060000, 0, 0x02},
{SCORPIONL2_TOTAL_CACHE_HITS, 0x86000000, 0, 0x03},
{SCORPIONL2_CACHE_MATCH_MISS, 0x80000007, 0, 0x00},
{SCORPIONL2_DREAD_HIT_L1_DATA, 0x87000000, 0, 0x03},
{SCORPIONL2_L2LINE_LOCKED, 0x80000008, 0, 0x00},
{SCORPIONL2_HW_TABLE_WALK_HIT, 0x80000800, 0, 0x01},
{SCORPIONL2_CACHE_MVA_POC, 0x80080000, 0, 0x02},
{SCORPIONL2_L2ALLOC_DWRITE_MISS, 0x88000000, 0, 0x03},
{SCORPIONL2_CORRECTED_TAG_ARRAY, 0x80001A00, 0, 0x01},
{SCORPIONL2_CORRECTED_DATA_ARRAY, 0x801A0000, 0, 0x02},
{SCORPIONL2_CORRECTED_REPLACEMENT_ARRAY, 0x9A000000, 0, 0x03},
{SCORPIONL2_PMBUS_MPAAF, 0x80001C00, 0, 0x01},
{SCORPIONL2_PMBUS_MPWDAF, 0x801C0000, 0, 0x02},
{SCORPIONL2_PMBUS_MPBRT, 0x9C000000, 0, 0x03},
{SCORPIONL2_CPU0_GRANT, 0x80000001, 1, 0x04},
{SCORPIONL2_CPU1_GRANT, 0x80000100, 1, 0x05},
{SCORPIONL2_CPU0_NOGRANT, 0x80020000, 1, 0x06},
{SCORPIONL2_CPU1_NOGRANT, 0x82000000, 1, 0x07},
{SCORPIONL2_CPU0_LOSING_ARB, 0x80040000, 1, 0x06},
{SCORPIONL2_CPU1_LOSING_ARB, 0x84000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_NOGRANT, 0x80000007, 1, 0x04},
{SCORPIONL2_SLAVEPORT_BPQ_FULL, 0x80000700, 1, 0x05},
{SCORPIONL2_SLAVEPORT_LOSING_ARB, 0x80070000, 1, 0x06},
{SCORPIONL2_SLAVEPORT_GRANT, 0x87000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_GRANTLOCK, 0x80000008, 1, 0x04},
{SCORPIONL2_L2EM_STREX_PASS, 0x80000009, 1, 0x04},
{SCORPIONL2_L2EM_STREX_FAIL, 0x80000900, 1, 0x05},
{SCORPIONL2_LDREX_RESERVE_L2EM, 0x80090000, 1, 0x06},
{SCORPIONL2_SLAVEPORT_LDREX, 0x89000000, 1, 0x07},
{SCORPIONL2_CPU0_L2EM_CLEARED, 0x800A0000, 1, 0x06},
{SCORPIONL2_CPU1_L2EM_CLEARED, 0x8A000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_L2EM_CLEARED, 0x80000B00, 1, 0x05},
{SCORPIONL2_CPU0_CLAMPED, 0x8000000E, 1, 0x04},
{SCORPIONL2_CPU1_CLAMPED, 0x80000E00, 1, 0x05},
{SCORPIONL2_CPU0_WAIT, 0x800F0000, 1, 0x06},
{SCORPIONL2_CPU1_WAIT, 0x8F000000, 1, 0x07},
{SCORPIONL2_CPU0_NONAMBAS_WAIT, 0x80000010, 1, 0x04},
{SCORPIONL2_CPU1_NONAMBAS_WAIT, 0x80001000, 1, 0x05},
{SCORPIONL2_CPU0_DSB_WAIT, 0x80000014, 1, 0x04},
{SCORPIONL2_CPU1_DSB_WAIT, 0x80001400, 1, 0x05},
{SCORPIONL2_AXI_READ, 0x80000001, 2, 0x08},
{SCORPIONL2_AXI_WRITE, 0x80000100, 2, 0x09},
{SCORPIONL2_1BEAT_WRITE, 0x80010000, 2, 0x0a},
{SCORPIONL2_2BEAT_WRITE, 0x80010000, 2, 0x0b},
{SCORPIONL2_4BEAT_WRITE, 0x80000002, 2, 0x08},
{SCORPIONL2_8BEAT_WRITE, 0x80000200, 2, 0x09},
{SCORPIONL2_12BEAT_WRITE, 0x80020000, 2, 0x0a},
{SCORPIONL2_16BEAT_WRITE, 0x82000000, 2, 0x0b},
{SCORPIONL2_1BEAT_DSIDE_READ, 0x80000003, 2, 0x08},
{SCORPIONL2_2BEAT_DSIDE_READ, 0x80000300, 2, 0x09},
{SCORPIONL2_4BEAT_DSIDE_READ, 0x80030000, 2, 0x0a},
{SCORPIONL2_8BEAT_DSIDE_READ, 0x83000000, 2, 0x0b},
{SCORPIONL2_CSYS_READ_1BEAT, 0x80000004, 2, 0x08},
{SCORPIONL2_CSYS_READ_2BEAT, 0x80000400, 2, 0x09},
{SCORPIONL2_CSYS_READ_4BEAT, 0x80040000, 2, 0x0a},
{SCORPIONL2_CSYS_READ_8BEAT, 0x84000000, 2, 0x0b},
{SCORPIONL2_4BEAT_IFETCH_READ, 0x80000005, 2, 0x08},
{SCORPIONL2_8BEAT_IFETCH_READ, 0x80000500, 2, 0x09},
{SCORPIONL2_CSYS_WRITE_1BEAT, 0x80050000, 2, 0x0a},
{SCORPIONL2_CSYS_WRITE_2BEAT, 0x85000000, 2, 0x0b},
{SCORPIONL2_AXI_READ_DATA_BEAT, 0x80000600, 2, 0x09},
{SCORPIONL2_AXI_WRITE_EVT1, 0x80060000, 2, 0x0a},
{SCORPIONL2_AXI_WRITE_EVT2, 0x86000000, 2, 0x0b},
{SCORPIONL2_LDREX_REQ, 0x80000007, 2, 0x08},
{SCORPIONL2_STREX_PASS, 0x80000700, 2, 0x09},
{SCORPIONL2_STREX_FAIL, 0x80070000, 2, 0x0a},
{SCORPIONL2_CPREAD, 0x80000008, 2, 0x08},
{SCORPIONL2_CPWRITE, 0x80000800, 2, 0x09},
{SCORPIONL2_BARRIER_REQ, 0x88000000, 2, 0x0b},
{SCORPIONL2_AXI_READ_SLVPORT, 0x80000001, 3, 0x0c},
{SCORPIONL2_AXI_WRITE_SLVPORT, 0x80000100, 3, 0x0d},
{SCORPIONL2_AXI_READ_SLVPORT_DATABEAT, 0x80010000, 3, 0x0e},
{SCORPIONL2_AXI_WRITE_SLVPORT_DATABEAT, 0x81000000, 3, 0x0f},
{SCORPIONL2_SNOOPKILL_PREFILTER, 0x80000001, 4, 0x10},
{SCORPIONL2_SNOOPKILL_FILTEROUT, 0x80000100, 4, 0x11},
{SCORPIONL2_SNOOPED_IC, 0x80000002, 4, 0x10},
{SCORPIONL2_SNOOPED_BP, 0x80000200, 4, 0x11},
{SCORPIONL2_SNOOPED_BARRIERS, 0x80020000, 4, 0x12},
{SCORPIONL2_SNOOPED_TLB, 0x82000000, 4, 0x13},
};
static struct pmu_hw_events *scorpion_l2_get_hw_events(void)
{
return &scorpion_l2_pmu_hw_events;
}
static u32 scorpion_l2_read_l2pm0(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 0" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm0(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 0" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm1(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 1" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm1(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 1" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm2(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 2" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm2(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 2" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm3(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 3" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm3(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 3" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm4(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 4" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm4(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 4" : : "r" (val));
}
struct scorpion_scorpion_access_funcs {
u32(*read) (void);
void (*write) (u32);
void (*pre) (void);
void (*post) (void);
};
struct scorpion_scorpion_access_funcs scorpion_l2_func[] = {
{scorpion_l2_read_l2pm0, scorpion_l2_write_l2pm0, NULL, NULL},
{scorpion_l2_read_l2pm1, scorpion_l2_write_l2pm1, NULL, NULL},
{scorpion_l2_read_l2pm2, scorpion_l2_write_l2pm2, NULL, NULL},
{scorpion_l2_read_l2pm3, scorpion_l2_write_l2pm3, NULL, NULL},
{scorpion_l2_read_l2pm4, scorpion_l2_write_l2pm4, NULL, NULL},
};
#define COLMN0MASK 0x000000ff
#define COLMN1MASK 0x0000ff00
#define COLMN2MASK 0x00ff0000
static u32 scorpion_l2_get_columnmask(u32 setval)
{
if (setval & COLMN0MASK)
return 0xffffff00;
else if (setval & COLMN1MASK)
return 0xffff00ff;
else if (setval & COLMN2MASK)
return 0xff00ffff;
else
return 0x80ffffff;
}
static void scorpion_l2_evt_setup(u32 gr, u32 setval)
{
u32 val;
if (scorpion_l2_func[gr].pre)
scorpion_l2_func[gr].pre();
val = scorpion_l2_get_columnmask(setval) & scorpion_l2_func[gr].read();
val = val | setval;
scorpion_l2_func[gr].write(val);
if (scorpion_l2_func[gr].post)
scorpion_l2_func[gr].post();
}
#define SCORPION_L2_EVT_START_IDX 0x90
#define SCORPION_L2_INV_EVTYPE 0
static unsigned int get_scorpion_l2_evtinfo(unsigned int evt_type,
struct scorpion_l2_scorp_evt *evtinfo)
{
u32 idx;
u8 prefix;
u8 reg;
u8 code;
u8 group;
prefix = (evt_type & 0xF0000) >> 16;
if (prefix == SCORPION_L2_EVT_PREFIX ||
prefix == L2_SLAVE_EVT_PREFIX) {
reg = (evt_type & 0x0F000) >> 12;
code = (evt_type & 0x00FF0) >> 4;
group = evt_type & 0x0000F;
if ((group > 3) || (reg > SCORPION_MAX_L2_REG))
return SCORPION_L2_INV_EVTYPE;
evtinfo->val = 0x80000000 | (code << (group * 8));
evtinfo->grp = reg;
evtinfo->evt_type_act = group | (reg << 2);
return evtinfo->evt_type_act;
}
if (evt_type < SCORPION_L2_EVT_START_IDX
|| evt_type >= SCORPION_L2_MAX_EVT)
return SCORPION_L2_INV_EVTYPE;
idx = evt_type - SCORPION_L2_EVT_START_IDX;
if (sc_evt[idx].evt_type == evt_type) {
evtinfo->val = sc_evt[idx].val;
evtinfo->grp = sc_evt[idx].grp;
evtinfo->evt_type_act = sc_evt[idx].evt_type_act;
return sc_evt[idx].evt_type_act;
}
return SCORPION_L2_INV_EVTYPE;
}
static inline void scorpion_l2_pmnc_write(unsigned long val)
{
val &= 0xff;
asm volatile ("mcr p15, 3, %0, c15, c4, 0" : : "r" (val));
}
static inline unsigned long scorpion_l2_pmnc_read(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c4, 0" : "=r" (val));
return val;
}
static void scorpion_l2_set_evcntcr(void)
{
u32 val = 0x0;
asm volatile ("mcr p15, 3, %0, c15, c6, 4" : : "r" (val));
}
static inline void scorpion_l2_set_evtyper(int ctr, int val)
{
/* select ctr */
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (ctr));
/* write into EVTYPER */
asm volatile ("mcr p15, 3, %0, c15, c6, 7" : : "r" (val));
}
static void scorpion_l2_set_evfilter_task_mode(unsigned int is_slv)
{
u32 filter_val = l2_orig_filter_prefix | 1 << smp_processor_id();
if (is_slv)
filter_val = l2_slv_filter_prefix;
asm volatile ("mcr p15, 3, %0, c15, c6, 3" : : "r" (filter_val));
}
static void scorpion_l2_set_evfilter_sys_mode(unsigned int is_slv)
{
u32 filter_val = l2_orig_filter_prefix | 0xf;
if (is_slv)
filter_val = l2_slv_filter_prefix;
asm volatile ("mcr p15, 3, %0, c15, c6, 3" : : "r" (filter_val));
}
static void scorpion_l2_enable_intenset(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c5, 1" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c5, 1" : : "r" (1 << idx));
}
}
static void scorpion_l2_disable_intenclr(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c5, 0" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c5, 0" : : "r" (1 << idx));
}
}
static void scorpion_l2_enable_counter(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c4, 3" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c4, 3" : : "r" (1 << idx));
}
}
static void scorpion_l2_disable_counter(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c4, 2" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c4, 2" : : "r" (1 << idx));
}
}
static u32 scorpion_l2_read_counter(int idx)
{
u32 val;
unsigned long iflags;
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mrc p15, 3, %0, c15, c4, 5" : "=r" (val));
} else {
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (idx));
/* read val from counter */
asm volatile ("mrc p15, 3, %0, c15, c6, 5" : "=r" (val));
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
}
return val;
}
static void scorpion_l2_write_counter(int idx, u32 val)
{
unsigned long iflags;
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c4, 5" : : "r" (val));
} else {
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
/* select counter */
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (idx));
/* write val into counter */
asm volatile ("mcr p15, 3, %0, c15, c6, 5" : : "r" (val));
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
}
}
static void scorpion_l2_stop_counter(struct hw_perf_event *hwc, int idx)
{
scorpion_l2_disable_intenclr(idx);
scorpion_l2_disable_counter(idx);
pr_debug("%s: event: %ld ctr: %d stopped\n", __func__,
hwc->config_base, idx);
}
static void scorpion_l2_enable(struct hw_perf_event *hwc, int idx, int cpu)
{
struct scorpion_l2_scorp_evt evtinfo;
int evtype = hwc->config_base;
int ev_typer;
unsigned long iflags;
unsigned int is_slv = 0;
unsigned int evt_prefix;
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
if (hwc->config_base == SCORPION_L2CYCLE_CTR_RAW_CODE)
goto out;
/* Check if user requested any special origin filtering. */
evt_prefix = (hwc->config_base &
L2_EVT_PREFIX_MASK) >> L2_EVT_PREFIX_SHIFT;
if (evt_prefix == L2_SLAVE_EVT_PREFIX)
is_slv = 1;
memset(&evtinfo, 0, sizeof(evtinfo));
ev_typer = get_scorpion_l2_evtinfo(evtype, &evtinfo);
scorpion_l2_set_evtyper(idx, ev_typer);
scorpion_l2_set_evcntcr();
if (cpu < 0)
scorpion_l2_set_evfilter_task_mode(is_slv);
else
scorpion_l2_set_evfilter_sys_mode(is_slv);
scorpion_l2_evt_setup(evtinfo.grp, evtinfo.val);
out:
scorpion_l2_enable_intenset(idx);
scorpion_l2_enable_counter(idx);
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
pr_debug("%s: ctr: %d group: %ld group_code: %lld started from cpu:%d\n",
__func__, idx, hwc->config_base, hwc->config, smp_processor_id());
}
static void scorpion_l2_disable(struct hw_perf_event *hwc, int idx)
{
unsigned long iflags;
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
scorpion_l2_stop_counter(hwc, idx);
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
pr_debug("%s: event: %ld deleted\n", __func__, hwc->config_base);
}
static int scorpion_l2_get_event_idx(struct pmu_hw_events *cpuc,
struct hw_perf_event *hwc)
{
int ctr = 0;
if (hwc->config_base == SCORPION_L2CYCLE_CTR_RAW_CODE) {
if (test_and_set_bit(l2_cycle_ctr_idx,
cpuc->used_mask))
return -EAGAIN;
return l2_cycle_ctr_idx;
}
for (ctr = 0; ctr < total_l2_ctrs - 1; ctr++) {
if (!test_and_set_bit(ctr, cpuc->used_mask))
return ctr;
}
return -EAGAIN;
}
static void scorpion_l2_start(void)
{
isb();
/* Enable all counters */
scorpion_l2_pmnc_write(scorpion_l2_pmnc_read() | SCORPIONL2_PMNC_E);
}
static void scorpion_l2_stop(void)
{
/* Disable all counters */
scorpion_l2_pmnc_write(scorpion_l2_pmnc_read() & ~SCORPIONL2_PMNC_E);
isb();
}
static inline u32 scorpion_l2_get_reset_pmovsr(void)
{
u32 val;
/* Read */
asm volatile ("mrc p15, 3, %0, c15, c4, 1" : "=r" (val));
/* Write to clear flags */
val &= 0xffffffff;
asm volatile ("mcr p15, 3, %0, c15, c4, 1" : : "r" (val));
return val;
}
static irqreturn_t scorpion_l2_handle_irq(int irq_num, void *dev)
{
unsigned long pmovsr;
struct perf_sample_data data;
struct pt_regs *regs;
struct perf_event *event;
struct hw_perf_event *hwc;
int bitp;
int idx = 0;
pmovsr = scorpion_l2_get_reset_pmovsr();
if (!(pmovsr & 0xffffffff))
return IRQ_NONE;
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
while (pmovsr) {
bitp = __ffs(pmovsr);
if (bitp == SCORPION_L2CYCLE_CTR_BIT)
idx = l2_cycle_ctr_idx;
else
idx = bitp;
event = scorpion_l2_pmu_hw_events.events[idx];
if (!event)
goto next;
if (!test_bit(idx, scorpion_l2_pmu_hw_events.used_mask))
goto next;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
goto next;
if (perf_event_overflow(event, &data, regs))
scorpion_l2_disable_counter(hwc->idx);
next:
pmovsr &= (pmovsr - 1);
}
irq_work_run();
return IRQ_HANDLED;
}
static int scorpion_l2_map_event(struct perf_event *event)
{
if (pmu_type > 0 && pmu_type == event->attr.type)
return event->attr.config & L2_EVT_MASK;
else
return -ENOENT;
}
static int
scorpion_l2_pmu_generic_request_irq(int irq, irq_handler_t *handle_irq)
{
return request_irq(irq, *handle_irq,
IRQF_DISABLED | IRQF_NOBALANCING,
"scorpion-l2-armpmu", NULL);
}
static void
scorpion_l2_pmu_generic_free_irq(int irq)
{
if (irq >= 0)
free_irq(irq, NULL);
}
static int msm_l2_test_set_ev_constraint(struct perf_event *event)
{
u32 evt_type = event->attr.config & L2_EVT_MASK;
u8 prefix = (evt_type & 0xF0000) >> 16;
u8 reg = (evt_type & 0x0F000) >> 12;
u8 group = evt_type & 0x0000F;
u8 code = (evt_type & 0x00FF0) >> 4;
unsigned long flags;
u32 err = 0;
u64 bitmap_t;
u32 shift_idx;
if (!prefix)
return 0;
/*
* Cycle counter collision is detected in
* get_event_idx().
*/
if (evt_type == SCORPION_L2CYCLE_CTR_RAW_CODE)
return err;
raw_spin_lock_irqsave(&l2_pmu_constraints.lock, flags);
shift_idx = ((reg * 4) + group);
bitmap_t = 1 << shift_idx;
if (!(l2_pmu_constraints.pmu_bitmap & bitmap_t)) {
l2_pmu_constraints.pmu_bitmap |= bitmap_t;
l2_pmu_constraints.codes[shift_idx] = code;
goto out;
} else {
/*
* If NRCCG's are identical,
* its not column exclusion.
*/
if (l2_pmu_constraints.codes[shift_idx] != code)
err = -EPERM;
else
/*
* If the event is counted in syswide mode
* then we want to count only on one CPU
* and set its filter to count from all.
* This sets the event OFF on all but one
* CPU.
*/
if (!(event->cpu < 0))
event->state = PERF_EVENT_STATE_OFF;
}
out:
raw_spin_unlock_irqrestore(&l2_pmu_constraints.lock, flags);
return err;
}
static int msm_l2_clear_ev_constraint(struct perf_event *event)
{
u32 evt_type = event->attr.config & L2_EVT_MASK;
u8 prefix = (evt_type & 0xF0000) >> 16;
u8 reg = (evt_type & 0x0F000) >> 12;
u8 group = evt_type & 0x0000F;
unsigned long flags;
u64 bitmap_t;
u32 shift_idx;
if (!prefix)
return 0;
raw_spin_lock_irqsave(&l2_pmu_constraints.lock, flags);
shift_idx = ((reg * 4) + group);
bitmap_t = 1 << shift_idx;
/* Clear constraint bit. */
l2_pmu_constraints.pmu_bitmap &= ~bitmap_t;
raw_spin_unlock_irqrestore(&l2_pmu_constraints.lock, flags);
return 1;
}
static int get_num_events(void)
{
int val;
val = scorpion_l2_pmnc_read();
/*
* Read bits 15:11 of the L2PMCR and add 1
* for the cycle counter.
*/
return ((val >> PMCR_NUM_EV_SHIFT) & PMCR_NUM_EV_MASK) + 1;
}
static struct arm_pmu scorpion_l2_pmu = {
.id = ARM_PERF_PMU_ID_SCORPIONMP_L2,
.type = ARM_PMU_DEVICE_L2CC,
.name = "Scorpion L2CC PMU",
.start = scorpion_l2_start,
.stop = scorpion_l2_stop,
.handle_irq = scorpion_l2_handle_irq,
.request_pmu_irq = scorpion_l2_pmu_generic_request_irq,
.free_pmu_irq = scorpion_l2_pmu_generic_free_irq,
.enable = scorpion_l2_enable,
.disable = scorpion_l2_disable,
.read_counter = scorpion_l2_read_counter,
.get_event_idx = scorpion_l2_get_event_idx,
.write_counter = scorpion_l2_write_counter,
.map_event = scorpion_l2_map_event,
.max_period = (1LLU << 32) - 1,
.get_hw_events = scorpion_l2_get_hw_events,
.test_set_event_constraints = msm_l2_test_set_ev_constraint,
.clear_event_constraints = msm_l2_clear_ev_constraint,
.pmu.attr_groups = msm_l2_pmu_attr_grps,
};
static int __devinit scorpion_l2_pmu_device_probe(struct platform_device *pdev)
{
scorpion_l2_pmu.plat_device = pdev;
if (!armpmu_register(&scorpion_l2_pmu, "msm-l2", -1))
pmu_type = scorpion_l2_pmu.pmu.type;
return 0;
}
static struct platform_driver scorpion_l2_pmu_driver = {
.driver = {
.name = "l2-arm-pmu",
},
.probe = scorpion_l2_pmu_device_probe,
};
static int __init register_scorpion_l2_pmu_driver(void)
{
/* Avoid spurious interrupt if any */
scorpion_l2_get_reset_pmovsr();
total_l2_ctrs = get_num_events();
scorpion_l2_pmu.num_events = total_l2_ctrs;
pr_info("Detected %d counters on the L2CC PMU.\n",
total_l2_ctrs);
/*
* The L2 cycle counter index in the used_mask
* bit stream is always after the other counters.
* Counter indexes begin from 0 to keep it consistent
* with the h/w.
*/
l2_cycle_ctr_idx = total_l2_ctrs - 1;
return platform_driver_register(&scorpion_l2_pmu_driver);
}
device_initcall(register_scorpion_l2_pmu_driver);
| gpl-2.0 |
SpiriLiao/linux | drivers/net/wireless/rt2x00/rt2x00firmware.c | 1499 | 3324 | /*
Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com>
Copyright (C) 2004 - 2009 Gertjan van Wingerde <gwingerde@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, see <http://www.gnu.org/licenses/>.
*/
/*
Module: rt2x00lib
Abstract: rt2x00 firmware loading routines.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include "rt2x00.h"
#include "rt2x00lib.h"
static int rt2x00lib_request_firmware(struct rt2x00_dev *rt2x00dev)
{
struct device *device = wiphy_dev(rt2x00dev->hw->wiphy);
const struct firmware *fw;
char *fw_name;
int retval;
/*
* Read correct firmware from harddisk.
*/
fw_name = rt2x00dev->ops->lib->get_firmware_name(rt2x00dev);
if (!fw_name) {
rt2x00_err(rt2x00dev,
"Invalid firmware filename\n"
"Please file bug report to %s\n", DRV_PROJECT);
return -EINVAL;
}
rt2x00_info(rt2x00dev, "Loading firmware file '%s'\n", fw_name);
retval = request_firmware(&fw, fw_name, device);
if (retval) {
rt2x00_err(rt2x00dev, "Failed to request Firmware\n");
return retval;
}
if (!fw || !fw->size || !fw->data) {
rt2x00_err(rt2x00dev, "Failed to read Firmware\n");
release_firmware(fw);
return -ENOENT;
}
rt2x00_info(rt2x00dev, "Firmware detected - version: %d.%d\n",
fw->data[fw->size - 4], fw->data[fw->size - 3]);
snprintf(rt2x00dev->hw->wiphy->fw_version,
sizeof(rt2x00dev->hw->wiphy->fw_version), "%d.%d",
fw->data[fw->size - 4], fw->data[fw->size - 3]);
retval = rt2x00dev->ops->lib->check_firmware(rt2x00dev, fw->data, fw->size);
switch (retval) {
case FW_OK:
break;
case FW_BAD_CRC:
rt2x00_err(rt2x00dev, "Firmware checksum error\n");
goto exit;
case FW_BAD_LENGTH:
rt2x00_err(rt2x00dev, "Invalid firmware file length (len=%zu)\n",
fw->size);
goto exit;
case FW_BAD_VERSION:
rt2x00_err(rt2x00dev, "Current firmware does not support detected chipset\n");
goto exit;
}
rt2x00dev->fw = fw;
return 0;
exit:
release_firmware(fw);
return -ENOENT;
}
int rt2x00lib_load_firmware(struct rt2x00_dev *rt2x00dev)
{
int retval;
if (!rt2x00_has_cap_flag(rt2x00dev, REQUIRE_FIRMWARE))
return 0;
if (!rt2x00dev->fw) {
retval = rt2x00lib_request_firmware(rt2x00dev);
if (retval)
return retval;
}
/*
* Send firmware to the device.
*/
retval = rt2x00dev->ops->lib->load_firmware(rt2x00dev,
rt2x00dev->fw->data,
rt2x00dev->fw->size);
/*
* When the firmware is uploaded to the hardware the LED
* association status might have been triggered, for correct
* LED handling it should now be reset.
*/
rt2x00leds_led_assoc(rt2x00dev, false);
return retval;
}
void rt2x00lib_free_firmware(struct rt2x00_dev *rt2x00dev)
{
release_firmware(rt2x00dev->fw);
rt2x00dev->fw = NULL;
}
| gpl-2.0 |
sub77-twrp/android_kernel_samsung_matissewifi | fs/ext4/ioctl.c | 2523 | 11921 | /*
* linux/fs/ext4/ioctl.c
*
* Copyright (C) 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*/
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/capability.h>
#include <linux/time.h>
#include <linux/compat.h>
#include <linux/mount.h>
#include <linux/file.h>
#include <asm/uaccess.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#define MAX_32_NUM ((((unsigned long long) 1) << 32) - 1)
long ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filp->f_dentry->d_inode;
struct super_block *sb = inode->i_sb;
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned int flags;
ext4_debug("cmd = %u, arg = %lu\n", cmd, arg);
switch (cmd) {
case EXT4_IOC_GETFLAGS:
ext4_get_inode_flags(ei);
flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
return put_user(flags, (int __user *) arg);
case EXT4_IOC_SETFLAGS: {
handle_t *handle = NULL;
int err, migrate = 0;
struct ext4_iloc iloc;
unsigned int oldflags;
unsigned int jflag;
if (!inode_owner_or_capable(inode))
return -EACCES;
if (get_user(flags, (int __user *) arg))
return -EFAULT;
err = mnt_want_write_file(filp);
if (err)
return err;
flags = ext4_mask_flags(inode->i_mode, flags);
err = -EPERM;
mutex_lock(&inode->i_mutex);
/* Is it quota file? Do not allow user to mess with it */
if (IS_NOQUOTA(inode))
goto flags_out;
oldflags = ei->i_flags;
/* The JOURNAL_DATA flag is modifiable only by root */
jflag = flags & EXT4_JOURNAL_DATA_FL;
/*
* The IMMUTABLE and APPEND_ONLY flags can only be changed by
* the relevant capability.
*
* This test looks nicer. Thanks to Pauline Middelink
*/
if ((flags ^ oldflags) & (EXT4_APPEND_FL | EXT4_IMMUTABLE_FL)) {
if (!capable(CAP_LINUX_IMMUTABLE))
goto flags_out;
}
/*
* The JOURNAL_DATA flag can only be changed by
* the relevant capability.
*/
if ((jflag ^ oldflags) & (EXT4_JOURNAL_DATA_FL)) {
if (!capable(CAP_SYS_RESOURCE))
goto flags_out;
}
if (oldflags & EXT4_EXTENTS_FL) {
/* We don't support clearning extent flags */
if (!(flags & EXT4_EXTENTS_FL)) {
err = -EOPNOTSUPP;
goto flags_out;
}
} else if (flags & EXT4_EXTENTS_FL) {
/* migrate the file */
migrate = 1;
flags &= ~EXT4_EXTENTS_FL;
}
if (flags & EXT4_EOFBLOCKS_FL) {
/* we don't support adding EOFBLOCKS flag */
if (!(oldflags & EXT4_EOFBLOCKS_FL)) {
err = -EOPNOTSUPP;
goto flags_out;
}
} else if (oldflags & EXT4_EOFBLOCKS_FL)
ext4_truncate(inode);
handle = ext4_journal_start(inode, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto flags_out;
}
if (IS_SYNC(inode))
ext4_handle_sync(handle);
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto flags_err;
flags = flags & EXT4_FL_USER_MODIFIABLE;
flags |= oldflags & ~EXT4_FL_USER_MODIFIABLE;
ei->i_flags = flags;
ext4_set_inode_flags(inode);
inode->i_ctime = ext4_current_time(inode);
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
flags_err:
ext4_journal_stop(handle);
if (err)
goto flags_out;
if ((jflag ^ oldflags) & (EXT4_JOURNAL_DATA_FL))
err = ext4_change_inode_journal_flag(inode, jflag);
if (err)
goto flags_out;
if (migrate)
err = ext4_ext_migrate(inode);
flags_out:
mutex_unlock(&inode->i_mutex);
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_GETVERSION:
case EXT4_IOC_GETVERSION_OLD:
return put_user(inode->i_generation, (int __user *) arg);
case EXT4_IOC_SETVERSION:
case EXT4_IOC_SETVERSION_OLD: {
handle_t *handle;
struct ext4_iloc iloc;
__u32 generation;
int err;
if (!inode_owner_or_capable(inode))
return -EPERM;
err = mnt_want_write_file(filp);
if (err)
return err;
if (get_user(generation, (int __user *) arg)) {
err = -EFAULT;
goto setversion_out;
}
mutex_lock(&inode->i_mutex);
handle = ext4_journal_start(inode, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto unlock_out;
}
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err == 0) {
inode->i_ctime = ext4_current_time(inode);
inode->i_generation = generation;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
}
ext4_journal_stop(handle);
unlock_out:
mutex_unlock(&inode->i_mutex);
setversion_out:
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_GROUP_EXTEND: {
ext4_fsblk_t n_blocks_count;
int err, err2=0;
err = ext4_resize_begin(sb);
if (err)
return err;
if (get_user(n_blocks_count, (__u32 __user *)arg)) {
err = -EFAULT;
goto group_extend_out;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
ext4_msg(sb, KERN_ERR,
"Online resizing not supported with bigalloc");
err = -EOPNOTSUPP;
goto group_extend_out;
}
err = mnt_want_write_file(filp);
if (err)
goto group_extend_out;
err = ext4_group_extend(sb, EXT4_SB(sb)->s_es, n_blocks_count);
if (EXT4_SB(sb)->s_journal) {
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err2 = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
}
if (err == 0)
err = err2;
mnt_drop_write_file(filp);
group_extend_out:
ext4_resize_end(sb);
return err;
}
case EXT4_IOC_MOVE_EXT: {
struct move_extent me;
struct file *donor_filp;
int err;
if (!(filp->f_mode & FMODE_READ) ||
!(filp->f_mode & FMODE_WRITE))
return -EBADF;
if (copy_from_user(&me,
(struct move_extent __user *)arg, sizeof(me)))
return -EFAULT;
me.moved_len = 0;
donor_filp = fget(me.donor_fd);
if (!donor_filp)
return -EBADF;
if (!(donor_filp->f_mode & FMODE_WRITE)) {
err = -EBADF;
goto mext_out;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
ext4_msg(sb, KERN_ERR,
"Online defrag not supported with bigalloc");
return -EOPNOTSUPP;
}
err = mnt_want_write_file(filp);
if (err)
goto mext_out;
err = ext4_move_extents(filp, donor_filp, me.orig_start,
me.donor_start, me.len, &me.moved_len);
mnt_drop_write_file(filp);
mnt_drop_write(filp->f_path.mnt);
if (copy_to_user((struct move_extent __user *)arg,
&me, sizeof(me)))
err = -EFAULT;
mext_out:
fput(donor_filp);
return err;
}
case EXT4_IOC_GROUP_ADD: {
struct ext4_new_group_data input;
int err, err2=0;
err = ext4_resize_begin(sb);
if (err)
return err;
if (copy_from_user(&input, (struct ext4_new_group_input __user *)arg,
sizeof(input))) {
err = -EFAULT;
goto group_add_out;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
ext4_msg(sb, KERN_ERR,
"Online resizing not supported with bigalloc");
err = -EOPNOTSUPP;
goto group_add_out;
}
err = mnt_want_write_file(filp);
if (err)
goto group_add_out;
err = ext4_group_add(sb, &input);
if (EXT4_SB(sb)->s_journal) {
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err2 = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
}
if (err == 0)
err = err2;
mnt_drop_write_file(filp);
group_add_out:
ext4_resize_end(sb);
return err;
}
case EXT4_IOC_MIGRATE:
{
int err;
if (!inode_owner_or_capable(inode))
return -EACCES;
err = mnt_want_write_file(filp);
if (err)
return err;
/*
* inode_mutex prevent write and truncate on the file.
* Read still goes through. We take i_data_sem in
* ext4_ext_swap_inode_data before we switch the
* inode format to prevent read.
*/
mutex_lock(&(inode->i_mutex));
err = ext4_ext_migrate(inode);
mutex_unlock(&(inode->i_mutex));
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_ALLOC_DA_BLKS:
{
int err;
if (!inode_owner_or_capable(inode))
return -EACCES;
err = mnt_want_write_file(filp);
if (err)
return err;
err = ext4_alloc_da_blocks(inode);
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_RESIZE_FS: {
ext4_fsblk_t n_blocks_count;
struct super_block *sb = inode->i_sb;
int err = 0, err2 = 0;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
ext4_msg(sb, KERN_ERR,
"Online resizing not (yet) supported with bigalloc");
return -EOPNOTSUPP;
}
if (EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_META_BG)) {
ext4_msg(sb, KERN_ERR,
"Online resizing not (yet) supported with meta_bg");
return -EOPNOTSUPP;
}
if (copy_from_user(&n_blocks_count, (__u64 __user *)arg,
sizeof(__u64))) {
return -EFAULT;
}
if (n_blocks_count > MAX_32_NUM &&
!EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR,
"File system only supports 32-bit block numbers");
return -EOPNOTSUPP;
}
err = ext4_resize_begin(sb);
if (err)
return err;
err = mnt_want_write(filp->f_path.mnt);
if (err)
goto resizefs_out;
err = ext4_resize_fs(sb, n_blocks_count);
if (EXT4_SB(sb)->s_journal) {
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err2 = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
}
if (err == 0)
err = err2;
mnt_drop_write(filp->f_path.mnt);
resizefs_out:
ext4_resize_end(sb);
return err;
}
case FITRIM:
{
struct request_queue *q = bdev_get_queue(sb->s_bdev);
struct fstrim_range range;
int ret = 0;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!blk_queue_discard(q))
return -EOPNOTSUPP;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
ext4_msg(sb, KERN_ERR,
"FITRIM not supported with bigalloc");
return -EOPNOTSUPP;
}
if (copy_from_user(&range, (struct fstrim_range __user *)arg,
sizeof(range)))
return -EFAULT;
range.minlen = max((unsigned int)range.minlen,
q->limits.discard_granularity);
ret = ext4_trim_fs(sb, &range);
if (ret < 0)
return ret;
if (copy_to_user((struct fstrim_range __user *)arg, &range,
sizeof(range)))
return -EFAULT;
return 0;
}
default:
return -ENOTTY;
}
}
#ifdef CONFIG_COMPAT
long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
/* These are just misnamed, they actually get/put from/to user an int */
switch (cmd) {
case EXT4_IOC32_GETFLAGS:
cmd = EXT4_IOC_GETFLAGS;
break;
case EXT4_IOC32_SETFLAGS:
cmd = EXT4_IOC_SETFLAGS;
break;
case EXT4_IOC32_GETVERSION:
cmd = EXT4_IOC_GETVERSION;
break;
case EXT4_IOC32_SETVERSION:
cmd = EXT4_IOC_SETVERSION;
break;
case EXT4_IOC32_GROUP_EXTEND:
cmd = EXT4_IOC_GROUP_EXTEND;
break;
case EXT4_IOC32_GETVERSION_OLD:
cmd = EXT4_IOC_GETVERSION_OLD;
break;
case EXT4_IOC32_SETVERSION_OLD:
cmd = EXT4_IOC_SETVERSION_OLD;
break;
case EXT4_IOC32_GETRSVSZ:
cmd = EXT4_IOC_GETRSVSZ;
break;
case EXT4_IOC32_SETRSVSZ:
cmd = EXT4_IOC_SETRSVSZ;
break;
case EXT4_IOC32_GROUP_ADD: {
struct compat_ext4_new_group_input __user *uinput;
struct ext4_new_group_input input;
mm_segment_t old_fs;
int err;
uinput = compat_ptr(arg);
err = get_user(input.group, &uinput->group);
err |= get_user(input.block_bitmap, &uinput->block_bitmap);
err |= get_user(input.inode_bitmap, &uinput->inode_bitmap);
err |= get_user(input.inode_table, &uinput->inode_table);
err |= get_user(input.blocks_count, &uinput->blocks_count);
err |= get_user(input.reserved_blocks,
&uinput->reserved_blocks);
if (err)
return -EFAULT;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = ext4_ioctl(file, EXT4_IOC_GROUP_ADD,
(unsigned long) &input);
set_fs(old_fs);
return err;
}
case EXT4_IOC_MOVE_EXT:
case FITRIM:
case EXT4_IOC_RESIZE_FS:
break;
default:
return -ENOIOCTLCMD;
}
return ext4_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
}
#endif
| gpl-2.0 |
vaginessa/Samsung_STE_Kernel | fs/jfs/jfs_txnmgr.c | 2523 | 77305 | /*
* Copyright (C) International Business Machines Corp., 2000-2005
* Portions Copyright (C) Christoph Hellwig, 2001-2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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
*/
/*
* jfs_txnmgr.c: transaction manager
*
* notes:
* transaction starts with txBegin() and ends with txCommit()
* or txAbort().
*
* tlock is acquired at the time of update;
* (obviate scan at commit time for xtree and dtree)
* tlock and mp points to each other;
* (no hashlist for mp -> tlock).
*
* special cases:
* tlock on in-memory inode:
* in-place tlock in the in-memory inode itself;
* converted to page lock by iWrite() at commit time.
*
* tlock during write()/mmap() under anonymous transaction (tid = 0):
* transferred (?) to transaction at commit time.
*
* use the page itself to update allocation maps
* (obviate intermediate replication of allocation/deallocation data)
* hold on to mp+lock thru update of maps
*/
#include <linux/fs.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/freezer.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kthread.h>
#include <linux/seq_file.h>
#include "jfs_incore.h"
#include "jfs_inode.h"
#include "jfs_filsys.h"
#include "jfs_metapage.h"
#include "jfs_dinode.h"
#include "jfs_imap.h"
#include "jfs_dmap.h"
#include "jfs_superblock.h"
#include "jfs_debug.h"
/*
* transaction management structures
*/
static struct {
int freetid; /* index of a free tid structure */
int freelock; /* index first free lock word */
wait_queue_head_t freewait; /* eventlist of free tblock */
wait_queue_head_t freelockwait; /* eventlist of free tlock */
wait_queue_head_t lowlockwait; /* eventlist of ample tlocks */
int tlocksInUse; /* Number of tlocks in use */
spinlock_t LazyLock; /* synchronize sync_queue & unlock_queue */
/* struct tblock *sync_queue; * Transactions waiting for data sync */
struct list_head unlock_queue; /* Txns waiting to be released */
struct list_head anon_list; /* inodes having anonymous txns */
struct list_head anon_list2; /* inodes having anonymous txns
that couldn't be sync'ed */
} TxAnchor;
int jfs_tlocks_low; /* Indicates low number of available tlocks */
#ifdef CONFIG_JFS_STATISTICS
static struct {
uint txBegin;
uint txBegin_barrier;
uint txBegin_lockslow;
uint txBegin_freetid;
uint txBeginAnon;
uint txBeginAnon_barrier;
uint txBeginAnon_lockslow;
uint txLockAlloc;
uint txLockAlloc_freelock;
} TxStat;
#endif
static int nTxBlock = -1; /* number of transaction blocks */
module_param(nTxBlock, int, 0);
MODULE_PARM_DESC(nTxBlock,
"Number of transaction blocks (max:65536)");
static int nTxLock = -1; /* number of transaction locks */
module_param(nTxLock, int, 0);
MODULE_PARM_DESC(nTxLock,
"Number of transaction locks (max:65536)");
struct tblock *TxBlock; /* transaction block table */
static int TxLockLWM; /* Low water mark for number of txLocks used */
static int TxLockHWM; /* High water mark for number of txLocks used */
static int TxLockVHWM; /* Very High water mark */
struct tlock *TxLock; /* transaction lock table */
/*
* transaction management lock
*/
static DEFINE_SPINLOCK(jfsTxnLock);
#define TXN_LOCK() spin_lock(&jfsTxnLock)
#define TXN_UNLOCK() spin_unlock(&jfsTxnLock)
#define LAZY_LOCK_INIT() spin_lock_init(&TxAnchor.LazyLock);
#define LAZY_LOCK(flags) spin_lock_irqsave(&TxAnchor.LazyLock, flags)
#define LAZY_UNLOCK(flags) spin_unlock_irqrestore(&TxAnchor.LazyLock, flags)
static DECLARE_WAIT_QUEUE_HEAD(jfs_commit_thread_wait);
static int jfs_commit_thread_waking;
/*
* Retry logic exist outside these macros to protect from spurrious wakeups.
*/
static inline void TXN_SLEEP_DROP_LOCK(wait_queue_head_t * event)
{
DECLARE_WAITQUEUE(wait, current);
add_wait_queue(event, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
TXN_UNLOCK();
io_schedule();
__set_current_state(TASK_RUNNING);
remove_wait_queue(event, &wait);
}
#define TXN_SLEEP(event)\
{\
TXN_SLEEP_DROP_LOCK(event);\
TXN_LOCK();\
}
#define TXN_WAKEUP(event) wake_up_all(event)
/*
* statistics
*/
static struct {
tid_t maxtid; /* 4: biggest tid ever used */
lid_t maxlid; /* 4: biggest lid ever used */
int ntid; /* 4: # of transactions performed */
int nlid; /* 4: # of tlocks acquired */
int waitlock; /* 4: # of tlock wait */
} stattx;
/*
* forward references
*/
static int diLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck, struct commit * cd);
static int dataLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void dtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void mapLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void txAllocPMap(struct inode *ip, struct maplock * maplock,
struct tblock * tblk);
static void txForce(struct tblock * tblk);
static int txLog(struct jfs_log * log, struct tblock * tblk,
struct commit * cd);
static void txUpdateMap(struct tblock * tblk);
static void txRelease(struct tblock * tblk);
static void xtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void LogSyncRelease(struct metapage * mp);
/*
* transaction block/lock management
* ---------------------------------
*/
/*
* Get a transaction lock from the free list. If the number in use is
* greater than the high water mark, wake up the sync daemon. This should
* free some anonymous transaction locks. (TXN_LOCK must be held.)
*/
static lid_t txLockAlloc(void)
{
lid_t lid;
INCREMENT(TxStat.txLockAlloc);
if (!TxAnchor.freelock) {
INCREMENT(TxStat.txLockAlloc_freelock);
}
while (!(lid = TxAnchor.freelock))
TXN_SLEEP(&TxAnchor.freelockwait);
TxAnchor.freelock = TxLock[lid].next;
HIGHWATERMARK(stattx.maxlid, lid);
if ((++TxAnchor.tlocksInUse > TxLockHWM) && (jfs_tlocks_low == 0)) {
jfs_info("txLockAlloc tlocks low");
jfs_tlocks_low = 1;
wake_up_process(jfsSyncThread);
}
return lid;
}
static void txLockFree(lid_t lid)
{
TxLock[lid].tid = 0;
TxLock[lid].next = TxAnchor.freelock;
TxAnchor.freelock = lid;
TxAnchor.tlocksInUse--;
if (jfs_tlocks_low && (TxAnchor.tlocksInUse < TxLockLWM)) {
jfs_info("txLockFree jfs_tlocks_low no more");
jfs_tlocks_low = 0;
TXN_WAKEUP(&TxAnchor.lowlockwait);
}
TXN_WAKEUP(&TxAnchor.freelockwait);
}
/*
* NAME: txInit()
*
* FUNCTION: initialize transaction management structures
*
* RETURN:
*
* serialization: single thread at jfs_init()
*/
int txInit(void)
{
int k, size;
struct sysinfo si;
/* Set defaults for nTxLock and nTxBlock if unset */
if (nTxLock == -1) {
if (nTxBlock == -1) {
/* Base default on memory size */
si_meminfo(&si);
if (si.totalram > (256 * 1024)) /* 1 GB */
nTxLock = 64 * 1024;
else
nTxLock = si.totalram >> 2;
} else if (nTxBlock > (8 * 1024))
nTxLock = 64 * 1024;
else
nTxLock = nTxBlock << 3;
}
if (nTxBlock == -1)
nTxBlock = nTxLock >> 3;
/* Verify tunable parameters */
if (nTxBlock < 16)
nTxBlock = 16; /* No one should set it this low */
if (nTxBlock > 65536)
nTxBlock = 65536;
if (nTxLock < 256)
nTxLock = 256; /* No one should set it this low */
if (nTxLock > 65536)
nTxLock = 65536;
printk(KERN_INFO "JFS: nTxBlock = %d, nTxLock = %d\n",
nTxBlock, nTxLock);
/*
* initialize transaction block (tblock) table
*
* transaction id (tid) = tblock index
* tid = 0 is reserved.
*/
TxLockLWM = (nTxLock * 4) / 10;
TxLockHWM = (nTxLock * 7) / 10;
TxLockVHWM = (nTxLock * 8) / 10;
size = sizeof(struct tblock) * nTxBlock;
TxBlock = vmalloc(size);
if (TxBlock == NULL)
return -ENOMEM;
for (k = 1; k < nTxBlock - 1; k++) {
TxBlock[k].next = k + 1;
init_waitqueue_head(&TxBlock[k].gcwait);
init_waitqueue_head(&TxBlock[k].waitor);
}
TxBlock[k].next = 0;
init_waitqueue_head(&TxBlock[k].gcwait);
init_waitqueue_head(&TxBlock[k].waitor);
TxAnchor.freetid = 1;
init_waitqueue_head(&TxAnchor.freewait);
stattx.maxtid = 1; /* statistics */
/*
* initialize transaction lock (tlock) table
*
* transaction lock id = tlock index
* tlock id = 0 is reserved.
*/
size = sizeof(struct tlock) * nTxLock;
TxLock = vmalloc(size);
if (TxLock == NULL) {
vfree(TxBlock);
return -ENOMEM;
}
/* initialize tlock table */
for (k = 1; k < nTxLock - 1; k++)
TxLock[k].next = k + 1;
TxLock[k].next = 0;
init_waitqueue_head(&TxAnchor.freelockwait);
init_waitqueue_head(&TxAnchor.lowlockwait);
TxAnchor.freelock = 1;
TxAnchor.tlocksInUse = 0;
INIT_LIST_HEAD(&TxAnchor.anon_list);
INIT_LIST_HEAD(&TxAnchor.anon_list2);
LAZY_LOCK_INIT();
INIT_LIST_HEAD(&TxAnchor.unlock_queue);
stattx.maxlid = 1; /* statistics */
return 0;
}
/*
* NAME: txExit()
*
* FUNCTION: clean up when module is unloaded
*/
void txExit(void)
{
vfree(TxLock);
TxLock = NULL;
vfree(TxBlock);
TxBlock = NULL;
}
/*
* NAME: txBegin()
*
* FUNCTION: start a transaction.
*
* PARAMETER: sb - superblock
* flag - force for nested tx;
*
* RETURN: tid - transaction id
*
* note: flag force allows to start tx for nested tx
* to prevent deadlock on logsync barrier;
*/
tid_t txBegin(struct super_block *sb, int flag)
{
tid_t t;
struct tblock *tblk;
struct jfs_log *log;
jfs_info("txBegin: flag = 0x%x", flag);
log = JFS_SBI(sb)->log;
TXN_LOCK();
INCREMENT(TxStat.txBegin);
retry:
if (!(flag & COMMIT_FORCE)) {
/*
* synchronize with logsync barrier
*/
if (test_bit(log_SYNCBARRIER, &log->flag) ||
test_bit(log_QUIESCE, &log->flag)) {
INCREMENT(TxStat.txBegin_barrier);
TXN_SLEEP(&log->syncwait);
goto retry;
}
}
if (flag == 0) {
/*
* Don't begin transaction if we're getting starved for tlocks
* unless COMMIT_FORCE or COMMIT_INODE (which may ultimately
* free tlocks)
*/
if (TxAnchor.tlocksInUse > TxLockVHWM) {
INCREMENT(TxStat.txBegin_lockslow);
TXN_SLEEP(&TxAnchor.lowlockwait);
goto retry;
}
}
/*
* allocate transaction id/block
*/
if ((t = TxAnchor.freetid) == 0) {
jfs_info("txBegin: waiting for free tid");
INCREMENT(TxStat.txBegin_freetid);
TXN_SLEEP(&TxAnchor.freewait);
goto retry;
}
tblk = tid_to_tblock(t);
if ((tblk->next == 0) && !(flag & COMMIT_FORCE)) {
/* Don't let a non-forced transaction take the last tblk */
jfs_info("txBegin: waiting for free tid");
INCREMENT(TxStat.txBegin_freetid);
TXN_SLEEP(&TxAnchor.freewait);
goto retry;
}
TxAnchor.freetid = tblk->next;
/*
* initialize transaction
*/
/*
* We can't zero the whole thing or we screw up another thread being
* awakened after sleeping on tblk->waitor
*
* memset(tblk, 0, sizeof(struct tblock));
*/
tblk->next = tblk->last = tblk->xflag = tblk->flag = tblk->lsn = 0;
tblk->sb = sb;
++log->logtid;
tblk->logtid = log->logtid;
++log->active;
HIGHWATERMARK(stattx.maxtid, t); /* statistics */
INCREMENT(stattx.ntid); /* statistics */
TXN_UNLOCK();
jfs_info("txBegin: returning tid = %d", t);
return t;
}
/*
* NAME: txBeginAnon()
*
* FUNCTION: start an anonymous transaction.
* Blocks if logsync or available tlocks are low to prevent
* anonymous tlocks from depleting supply.
*
* PARAMETER: sb - superblock
*
* RETURN: none
*/
void txBeginAnon(struct super_block *sb)
{
struct jfs_log *log;
log = JFS_SBI(sb)->log;
TXN_LOCK();
INCREMENT(TxStat.txBeginAnon);
retry:
/*
* synchronize with logsync barrier
*/
if (test_bit(log_SYNCBARRIER, &log->flag) ||
test_bit(log_QUIESCE, &log->flag)) {
INCREMENT(TxStat.txBeginAnon_barrier);
TXN_SLEEP(&log->syncwait);
goto retry;
}
/*
* Don't begin transaction if we're getting starved for tlocks
*/
if (TxAnchor.tlocksInUse > TxLockVHWM) {
INCREMENT(TxStat.txBeginAnon_lockslow);
TXN_SLEEP(&TxAnchor.lowlockwait);
goto retry;
}
TXN_UNLOCK();
}
/*
* txEnd()
*
* function: free specified transaction block.
*
* logsync barrier processing:
*
* serialization:
*/
void txEnd(tid_t tid)
{
struct tblock *tblk = tid_to_tblock(tid);
struct jfs_log *log;
jfs_info("txEnd: tid = %d", tid);
TXN_LOCK();
/*
* wakeup transactions waiting on the page locked
* by the current transaction
*/
TXN_WAKEUP(&tblk->waitor);
log = JFS_SBI(tblk->sb)->log;
/*
* Lazy commit thread can't free this guy until we mark it UNLOCKED,
* otherwise, we would be left with a transaction that may have been
* reused.
*
* Lazy commit thread will turn off tblkGC_LAZY before calling this
* routine.
*/
if (tblk->flag & tblkGC_LAZY) {
jfs_info("txEnd called w/lazy tid: %d, tblk = 0x%p", tid, tblk);
TXN_UNLOCK();
spin_lock_irq(&log->gclock); // LOGGC_LOCK
tblk->flag |= tblkGC_UNLOCKED;
spin_unlock_irq(&log->gclock); // LOGGC_UNLOCK
return;
}
jfs_info("txEnd: tid: %d, tblk = 0x%p", tid, tblk);
assert(tblk->next == 0);
/*
* insert tblock back on freelist
*/
tblk->next = TxAnchor.freetid;
TxAnchor.freetid = tid;
/*
* mark the tblock not active
*/
if (--log->active == 0) {
clear_bit(log_FLUSH, &log->flag);
/*
* synchronize with logsync barrier
*/
if (test_bit(log_SYNCBARRIER, &log->flag)) {
TXN_UNLOCK();
/* write dirty metadata & forward log syncpt */
jfs_syncpt(log, 1);
jfs_info("log barrier off: 0x%x", log->lsn);
/* enable new transactions start */
clear_bit(log_SYNCBARRIER, &log->flag);
/* wakeup all waitors for logsync barrier */
TXN_WAKEUP(&log->syncwait);
goto wakeup;
}
}
TXN_UNLOCK();
wakeup:
/*
* wakeup all waitors for a free tblock
*/
TXN_WAKEUP(&TxAnchor.freewait);
}
/*
* txLock()
*
* function: acquire a transaction lock on the specified <mp>
*
* parameter:
*
* return: transaction lock id
*
* serialization:
*/
struct tlock *txLock(tid_t tid, struct inode *ip, struct metapage * mp,
int type)
{
struct jfs_inode_info *jfs_ip = JFS_IP(ip);
int dir_xtree = 0;
lid_t lid;
tid_t xtid;
struct tlock *tlck;
struct xtlock *xtlck;
struct linelock *linelock;
xtpage_t *p;
struct tblock *tblk;
TXN_LOCK();
if (S_ISDIR(ip->i_mode) && (type & tlckXTREE) &&
!(mp->xflag & COMMIT_PAGE)) {
/*
* Directory inode is special. It can have both an xtree tlock
* and a dtree tlock associated with it.
*/
dir_xtree = 1;
lid = jfs_ip->xtlid;
} else
lid = mp->lid;
/* is page not locked by a transaction ? */
if (lid == 0)
goto allocateLock;
jfs_info("txLock: tid:%d ip:0x%p mp:0x%p lid:%d", tid, ip, mp, lid);
/* is page locked by the requester transaction ? */
tlck = lid_to_tlock(lid);
if ((xtid = tlck->tid) == tid) {
TXN_UNLOCK();
goto grantLock;
}
/*
* is page locked by anonymous transaction/lock ?
*
* (page update without transaction (i.e., file write) is
* locked under anonymous transaction tid = 0:
* anonymous tlocks maintained on anonymous tlock list of
* the inode of the page and available to all anonymous
* transactions until txCommit() time at which point
* they are transferred to the transaction tlock list of
* the committing transaction of the inode)
*/
if (xtid == 0) {
tlck->tid = tid;
TXN_UNLOCK();
tblk = tid_to_tblock(tid);
/*
* The order of the tlocks in the transaction is important
* (during truncate, child xtree pages must be freed before
* parent's tlocks change the working map).
* Take tlock off anonymous list and add to tail of
* transaction list
*
* Note: We really need to get rid of the tid & lid and
* use list_head's. This code is getting UGLY!
*/
if (jfs_ip->atlhead == lid) {
if (jfs_ip->atltail == lid) {
/* only anonymous txn.
* Remove from anon_list
*/
TXN_LOCK();
list_del_init(&jfs_ip->anon_inode_list);
TXN_UNLOCK();
}
jfs_ip->atlhead = tlck->next;
} else {
lid_t last;
for (last = jfs_ip->atlhead;
lid_to_tlock(last)->next != lid;
last = lid_to_tlock(last)->next) {
assert(last);
}
lid_to_tlock(last)->next = tlck->next;
if (jfs_ip->atltail == lid)
jfs_ip->atltail = last;
}
/* insert the tlock at tail of transaction tlock list */
if (tblk->next)
lid_to_tlock(tblk->last)->next = lid;
else
tblk->next = lid;
tlck->next = 0;
tblk->last = lid;
goto grantLock;
}
goto waitLock;
/*
* allocate a tlock
*/
allocateLock:
lid = txLockAlloc();
tlck = lid_to_tlock(lid);
/*
* initialize tlock
*/
tlck->tid = tid;
TXN_UNLOCK();
/* mark tlock for meta-data page */
if (mp->xflag & COMMIT_PAGE) {
tlck->flag = tlckPAGELOCK;
/* mark the page dirty and nohomeok */
metapage_nohomeok(mp);
jfs_info("locking mp = 0x%p, nohomeok = %d tid = %d tlck = 0x%p",
mp, mp->nohomeok, tid, tlck);
/* if anonymous transaction, and buffer is on the group
* commit synclist, mark inode to show this. This will
* prevent the buffer from being marked nohomeok for too
* long a time.
*/
if ((tid == 0) && mp->lsn)
set_cflag(COMMIT_Synclist, ip);
}
/* mark tlock for in-memory inode */
else
tlck->flag = tlckINODELOCK;
if (S_ISDIR(ip->i_mode))
tlck->flag |= tlckDIRECTORY;
tlck->type = 0;
/* bind the tlock and the page */
tlck->ip = ip;
tlck->mp = mp;
if (dir_xtree)
jfs_ip->xtlid = lid;
else
mp->lid = lid;
/*
* enqueue transaction lock to transaction/inode
*/
/* insert the tlock at tail of transaction tlock list */
if (tid) {
tblk = tid_to_tblock(tid);
if (tblk->next)
lid_to_tlock(tblk->last)->next = lid;
else
tblk->next = lid;
tlck->next = 0;
tblk->last = lid;
}
/* anonymous transaction:
* insert the tlock at head of inode anonymous tlock list
*/
else {
tlck->next = jfs_ip->atlhead;
jfs_ip->atlhead = lid;
if (tlck->next == 0) {
/* This inode's first anonymous transaction */
jfs_ip->atltail = lid;
TXN_LOCK();
list_add_tail(&jfs_ip->anon_inode_list,
&TxAnchor.anon_list);
TXN_UNLOCK();
}
}
/* initialize type dependent area for linelock */
linelock = (struct linelock *) & tlck->lock;
linelock->next = 0;
linelock->flag = tlckLINELOCK;
linelock->maxcnt = TLOCKSHORT;
linelock->index = 0;
switch (type & tlckTYPE) {
case tlckDTREE:
linelock->l2linesize = L2DTSLOTSIZE;
break;
case tlckXTREE:
linelock->l2linesize = L2XTSLOTSIZE;
xtlck = (struct xtlock *) linelock;
xtlck->header.offset = 0;
xtlck->header.length = 2;
if (type & tlckNEW) {
xtlck->lwm.offset = XTENTRYSTART;
} else {
if (mp->xflag & COMMIT_PAGE)
p = (xtpage_t *) mp->data;
else
p = &jfs_ip->i_xtroot;
xtlck->lwm.offset =
le16_to_cpu(p->header.nextindex);
}
xtlck->lwm.length = 0; /* ! */
xtlck->twm.offset = 0;
xtlck->hwm.offset = 0;
xtlck->index = 2;
break;
case tlckINODE:
linelock->l2linesize = L2INODESLOTSIZE;
break;
case tlckDATA:
linelock->l2linesize = L2DATASLOTSIZE;
break;
default:
jfs_err("UFO tlock:0x%p", tlck);
}
/*
* update tlock vector
*/
grantLock:
tlck->type |= type;
return tlck;
/*
* page is being locked by another transaction:
*/
waitLock:
/* Only locks on ipimap or ipaimap should reach here */
/* assert(jfs_ip->fileset == AGGREGATE_I); */
if (jfs_ip->fileset != AGGREGATE_I) {
printk(KERN_ERR "txLock: trying to lock locked page!");
print_hex_dump(KERN_ERR, "ip: ", DUMP_PREFIX_ADDRESS, 16, 4,
ip, sizeof(*ip), 0);
print_hex_dump(KERN_ERR, "mp: ", DUMP_PREFIX_ADDRESS, 16, 4,
mp, sizeof(*mp), 0);
print_hex_dump(KERN_ERR, "Locker's tblock: ",
DUMP_PREFIX_ADDRESS, 16, 4, tid_to_tblock(tid),
sizeof(struct tblock), 0);
print_hex_dump(KERN_ERR, "Tlock: ", DUMP_PREFIX_ADDRESS, 16, 4,
tlck, sizeof(*tlck), 0);
BUG();
}
INCREMENT(stattx.waitlock); /* statistics */
TXN_UNLOCK();
release_metapage(mp);
TXN_LOCK();
xtid = tlck->tid; /* reacquire after dropping TXN_LOCK */
jfs_info("txLock: in waitLock, tid = %d, xtid = %d, lid = %d",
tid, xtid, lid);
/* Recheck everything since dropping TXN_LOCK */
if (xtid && (tlck->mp == mp) && (mp->lid == lid))
TXN_SLEEP_DROP_LOCK(&tid_to_tblock(xtid)->waitor);
else
TXN_UNLOCK();
jfs_info("txLock: awakened tid = %d, lid = %d", tid, lid);
return NULL;
}
/*
* NAME: txRelease()
*
* FUNCTION: Release buffers associated with transaction locks, but don't
* mark homeok yet. The allows other transactions to modify
* buffers, but won't let them go to disk until commit record
* actually gets written.
*
* PARAMETER:
* tblk -
*
* RETURN: Errors from subroutines.
*/
static void txRelease(struct tblock * tblk)
{
struct metapage *mp;
lid_t lid;
struct tlock *tlck;
TXN_LOCK();
for (lid = tblk->next; lid; lid = tlck->next) {
tlck = lid_to_tlock(lid);
if ((mp = tlck->mp) != NULL &&
(tlck->type & tlckBTROOT) == 0) {
assert(mp->xflag & COMMIT_PAGE);
mp->lid = 0;
}
}
/*
* wakeup transactions waiting on a page locked
* by the current transaction
*/
TXN_WAKEUP(&tblk->waitor);
TXN_UNLOCK();
}
/*
* NAME: txUnlock()
*
* FUNCTION: Initiates pageout of pages modified by tid in journalled
* objects and frees their lockwords.
*/
static void txUnlock(struct tblock * tblk)
{
struct tlock *tlck;
struct linelock *linelock;
lid_t lid, next, llid, k;
struct metapage *mp;
struct jfs_log *log;
int difft, diffp;
unsigned long flags;
jfs_info("txUnlock: tblk = 0x%p", tblk);
log = JFS_SBI(tblk->sb)->log;
/*
* mark page under tlock homeok (its log has been written):
*/
for (lid = tblk->next; lid; lid = next) {
tlck = lid_to_tlock(lid);
next = tlck->next;
jfs_info("unlocking lid = %d, tlck = 0x%p", lid, tlck);
/* unbind page from tlock */
if ((mp = tlck->mp) != NULL &&
(tlck->type & tlckBTROOT) == 0) {
assert(mp->xflag & COMMIT_PAGE);
/* hold buffer
*/
hold_metapage(mp);
assert(mp->nohomeok > 0);
_metapage_homeok(mp);
/* inherit younger/larger clsn */
LOGSYNC_LOCK(log, flags);
if (mp->clsn) {
logdiff(difft, tblk->clsn, log);
logdiff(diffp, mp->clsn, log);
if (difft > diffp)
mp->clsn = tblk->clsn;
} else
mp->clsn = tblk->clsn;
LOGSYNC_UNLOCK(log, flags);
assert(!(tlck->flag & tlckFREEPAGE));
put_metapage(mp);
}
/* insert tlock, and linelock(s) of the tlock if any,
* at head of freelist
*/
TXN_LOCK();
llid = ((struct linelock *) & tlck->lock)->next;
while (llid) {
linelock = (struct linelock *) lid_to_tlock(llid);
k = linelock->next;
txLockFree(llid);
llid = k;
}
txLockFree(lid);
TXN_UNLOCK();
}
tblk->next = tblk->last = 0;
/*
* remove tblock from logsynclist
* (allocation map pages inherited lsn of tblk and
* has been inserted in logsync list at txUpdateMap())
*/
if (tblk->lsn) {
LOGSYNC_LOCK(log, flags);
log->count--;
list_del(&tblk->synclist);
LOGSYNC_UNLOCK(log, flags);
}
}
/*
* txMaplock()
*
* function: allocate a transaction lock for freed page/entry;
* for freed page, maplock is used as xtlock/dtlock type;
*/
struct tlock *txMaplock(tid_t tid, struct inode *ip, int type)
{
struct jfs_inode_info *jfs_ip = JFS_IP(ip);
lid_t lid;
struct tblock *tblk;
struct tlock *tlck;
struct maplock *maplock;
TXN_LOCK();
/*
* allocate a tlock
*/
lid = txLockAlloc();
tlck = lid_to_tlock(lid);
/*
* initialize tlock
*/
tlck->tid = tid;
/* bind the tlock and the object */
tlck->flag = tlckINODELOCK;
if (S_ISDIR(ip->i_mode))
tlck->flag |= tlckDIRECTORY;
tlck->ip = ip;
tlck->mp = NULL;
tlck->type = type;
/*
* enqueue transaction lock to transaction/inode
*/
/* insert the tlock at tail of transaction tlock list */
if (tid) {
tblk = tid_to_tblock(tid);
if (tblk->next)
lid_to_tlock(tblk->last)->next = lid;
else
tblk->next = lid;
tlck->next = 0;
tblk->last = lid;
}
/* anonymous transaction:
* insert the tlock at head of inode anonymous tlock list
*/
else {
tlck->next = jfs_ip->atlhead;
jfs_ip->atlhead = lid;
if (tlck->next == 0) {
/* This inode's first anonymous transaction */
jfs_ip->atltail = lid;
list_add_tail(&jfs_ip->anon_inode_list,
&TxAnchor.anon_list);
}
}
TXN_UNLOCK();
/* initialize type dependent area for maplock */
maplock = (struct maplock *) & tlck->lock;
maplock->next = 0;
maplock->maxcnt = 0;
maplock->index = 0;
return tlck;
}
/*
* txLinelock()
*
* function: allocate a transaction lock for log vector list
*/
struct linelock *txLinelock(struct linelock * tlock)
{
lid_t lid;
struct tlock *tlck;
struct linelock *linelock;
TXN_LOCK();
/* allocate a TxLock structure */
lid = txLockAlloc();
tlck = lid_to_tlock(lid);
TXN_UNLOCK();
/* initialize linelock */
linelock = (struct linelock *) tlck;
linelock->next = 0;
linelock->flag = tlckLINELOCK;
linelock->maxcnt = TLOCKLONG;
linelock->index = 0;
if (tlck->flag & tlckDIRECTORY)
linelock->flag |= tlckDIRECTORY;
/* append linelock after tlock */
linelock->next = tlock->next;
tlock->next = lid;
return linelock;
}
/*
* transaction commit management
* -----------------------------
*/
/*
* NAME: txCommit()
*
* FUNCTION: commit the changes to the objects specified in
* clist. For journalled segments only the
* changes of the caller are committed, ie by tid.
* for non-journalled segments the data are flushed to
* disk and then the change to the disk inode and indirect
* blocks committed (so blocks newly allocated to the
* segment will be made a part of the segment atomically).
*
* all of the segments specified in clist must be in
* one file system. no more than 6 segments are needed
* to handle all unix svcs.
*
* if the i_nlink field (i.e. disk inode link count)
* is zero, and the type of inode is a regular file or
* directory, or symbolic link , the inode is truncated
* to zero length. the truncation is committed but the
* VM resources are unaffected until it is closed (see
* iput and iclose).
*
* PARAMETER:
*
* RETURN:
*
* serialization:
* on entry the inode lock on each segment is assumed
* to be held.
*
* i/o error:
*/
int txCommit(tid_t tid, /* transaction identifier */
int nip, /* number of inodes to commit */
struct inode **iplist, /* list of inode to commit */
int flag)
{
int rc = 0;
struct commit cd;
struct jfs_log *log;
struct tblock *tblk;
struct lrd *lrd;
int lsn;
struct inode *ip;
struct jfs_inode_info *jfs_ip;
int k, n;
ino_t top;
struct super_block *sb;
jfs_info("txCommit, tid = %d, flag = %d", tid, flag);
/* is read-only file system ? */
if (isReadOnly(iplist[0])) {
rc = -EROFS;
goto TheEnd;
}
sb = cd.sb = iplist[0]->i_sb;
cd.tid = tid;
if (tid == 0)
tid = txBegin(sb, 0);
tblk = tid_to_tblock(tid);
/*
* initialize commit structure
*/
log = JFS_SBI(sb)->log;
cd.log = log;
/* initialize log record descriptor in commit */
lrd = &cd.lrd;
lrd->logtid = cpu_to_le32(tblk->logtid);
lrd->backchain = 0;
tblk->xflag |= flag;
if ((flag & (COMMIT_FORCE | COMMIT_SYNC)) == 0)
tblk->xflag |= COMMIT_LAZY;
/*
* prepare non-journaled objects for commit
*
* flush data pages of non-journaled file
* to prevent the file getting non-initialized disk blocks
* in case of crash.
* (new blocks - )
*/
cd.iplist = iplist;
cd.nip = nip;
/*
* acquire transaction lock on (on-disk) inodes
*
* update on-disk inode from in-memory inode
* acquiring transaction locks for AFTER records
* on the on-disk inode of file object
*
* sort the inodes array by inode number in descending order
* to prevent deadlock when acquiring transaction lock
* of on-disk inodes on multiple on-disk inode pages by
* multiple concurrent transactions
*/
for (k = 0; k < cd.nip; k++) {
top = (cd.iplist[k])->i_ino;
for (n = k + 1; n < cd.nip; n++) {
ip = cd.iplist[n];
if (ip->i_ino > top) {
top = ip->i_ino;
cd.iplist[n] = cd.iplist[k];
cd.iplist[k] = ip;
}
}
ip = cd.iplist[k];
jfs_ip = JFS_IP(ip);
/*
* BUGBUG - This code has temporarily been removed. The
* intent is to ensure that any file data is written before
* the metadata is committed to the journal. This prevents
* uninitialized data from appearing in a file after the
* journal has been replayed. (The uninitialized data
* could be sensitive data removed by another user.)
*
* The problem now is that we are holding the IWRITELOCK
* on the inode, and calling filemap_fdatawrite on an
* unmapped page will cause a deadlock in jfs_get_block.
*
* The long term solution is to pare down the use of
* IWRITELOCK. We are currently holding it too long.
* We could also be smarter about which data pages need
* to be written before the transaction is committed and
* when we don't need to worry about it at all.
*
* if ((!S_ISDIR(ip->i_mode))
* && (tblk->flag & COMMIT_DELETE) == 0)
* filemap_write_and_wait(ip->i_mapping);
*/
/*
* Mark inode as not dirty. It will still be on the dirty
* inode list, but we'll know not to commit it again unless
* it gets marked dirty again
*/
clear_cflag(COMMIT_Dirty, ip);
/* inherit anonymous tlock(s) of inode */
if (jfs_ip->atlhead) {
lid_to_tlock(jfs_ip->atltail)->next = tblk->next;
tblk->next = jfs_ip->atlhead;
if (!tblk->last)
tblk->last = jfs_ip->atltail;
jfs_ip->atlhead = jfs_ip->atltail = 0;
TXN_LOCK();
list_del_init(&jfs_ip->anon_inode_list);
TXN_UNLOCK();
}
/*
* acquire transaction lock on on-disk inode page
* (become first tlock of the tblk's tlock list)
*/
if (((rc = diWrite(tid, ip))))
goto out;
}
/*
* write log records from transaction locks
*
* txUpdateMap() resets XAD_NEW in XAD.
*/
if ((rc = txLog(log, tblk, &cd)))
goto TheEnd;
/*
* Ensure that inode isn't reused before
* lazy commit thread finishes processing
*/
if (tblk->xflag & COMMIT_DELETE) {
ihold(tblk->u.ip);
/*
* Avoid a rare deadlock
*
* If the inode is locked, we may be blocked in
* jfs_commit_inode. If so, we don't want the
* lazy_commit thread doing the last iput() on the inode
* since that may block on the locked inode. Instead,
* commit the transaction synchronously, so the last iput
* will be done by the calling thread (or later)
*/
/*
* I believe this code is no longer needed. Splitting I_LOCK
* into two bits, I_NEW and I_SYNC should prevent this
* deadlock as well. But since I don't have a JFS testload
* to verify this, only a trivial s/I_LOCK/I_SYNC/ was done.
* Joern
*/
if (tblk->u.ip->i_state & I_SYNC)
tblk->xflag &= ~COMMIT_LAZY;
}
ASSERT((!(tblk->xflag & COMMIT_DELETE)) ||
((tblk->u.ip->i_nlink == 0) &&
!test_cflag(COMMIT_Nolink, tblk->u.ip)));
/*
* write COMMIT log record
*/
lrd->type = cpu_to_le16(LOG_COMMIT);
lrd->length = 0;
lsn = lmLog(log, tblk, lrd, NULL);
lmGroupCommit(log, tblk);
/*
* - transaction is now committed -
*/
/*
* force pages in careful update
* (imap addressing structure update)
*/
if (flag & COMMIT_FORCE)
txForce(tblk);
/*
* update allocation map.
*
* update inode allocation map and inode:
* free pager lock on memory object of inode if any.
* update block allocation map.
*
* txUpdateMap() resets XAD_NEW in XAD.
*/
if (tblk->xflag & COMMIT_FORCE)
txUpdateMap(tblk);
/*
* free transaction locks and pageout/free pages
*/
txRelease(tblk);
if ((tblk->flag & tblkGC_LAZY) == 0)
txUnlock(tblk);
/*
* reset in-memory object state
*/
for (k = 0; k < cd.nip; k++) {
ip = cd.iplist[k];
jfs_ip = JFS_IP(ip);
/*
* reset in-memory inode state
*/
jfs_ip->bxflag = 0;
jfs_ip->blid = 0;
}
out:
if (rc != 0)
txAbort(tid, 1);
TheEnd:
jfs_info("txCommit: tid = %d, returning %d", tid, rc);
return rc;
}
/*
* NAME: txLog()
*
* FUNCTION: Writes AFTER log records for all lines modified
* by tid for segments specified by inodes in comdata.
* Code assumes only WRITELOCKS are recorded in lockwords.
*
* PARAMETERS:
*
* RETURN :
*/
static int txLog(struct jfs_log * log, struct tblock * tblk, struct commit * cd)
{
int rc = 0;
struct inode *ip;
lid_t lid;
struct tlock *tlck;
struct lrd *lrd = &cd->lrd;
/*
* write log record(s) for each tlock of transaction,
*/
for (lid = tblk->next; lid; lid = tlck->next) {
tlck = lid_to_tlock(lid);
tlck->flag |= tlckLOG;
/* initialize lrd common */
ip = tlck->ip;
lrd->aggregate = cpu_to_le32(JFS_SBI(ip->i_sb)->aggregate);
lrd->log.redopage.fileset = cpu_to_le32(JFS_IP(ip)->fileset);
lrd->log.redopage.inode = cpu_to_le32(ip->i_ino);
/* write log record of page from the tlock */
switch (tlck->type & tlckTYPE) {
case tlckXTREE:
xtLog(log, tblk, lrd, tlck);
break;
case tlckDTREE:
dtLog(log, tblk, lrd, tlck);
break;
case tlckINODE:
diLog(log, tblk, lrd, tlck, cd);
break;
case tlckMAP:
mapLog(log, tblk, lrd, tlck);
break;
case tlckDATA:
dataLog(log, tblk, lrd, tlck);
break;
default:
jfs_err("UFO tlock:0x%p", tlck);
}
}
return rc;
}
/*
* diLog()
*
* function: log inode tlock and format maplock to update bmap;
*/
static int diLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck, struct commit * cd)
{
int rc = 0;
struct metapage *mp;
pxd_t *pxd;
struct pxd_lock *pxdlock;
mp = tlck->mp;
/* initialize as REDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_INODE);
lrd->log.redopage.l2linesize = cpu_to_le16(L2INODESLOTSIZE);
pxd = &lrd->log.redopage.pxd;
/*
* inode after image
*/
if (tlck->type & tlckENTRY) {
/* log after-image for logredo(): */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(pxd, mp->index);
PXDlength(pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
} else if (tlck->type & tlckFREE) {
/*
* free inode extent
*
* (pages of the freed inode extent have been invalidated and
* a maplock for free of the extent has been formatted at
* txLock() time);
*
* the tlock had been acquired on the inode allocation map page
* (iag) that specifies the freed extent, even though the map
* page is not itself logged, to prevent pageout of the map
* page before the log;
*/
/* log LOG_NOREDOINOEXT of the freed inode extent for
* logredo() to start NoRedoPage filters, and to update
* imap and bmap for free of the extent;
*/
lrd->type = cpu_to_le16(LOG_NOREDOINOEXT);
/*
* For the LOG_NOREDOINOEXT record, we need
* to pass the IAG number and inode extent
* index (within that IAG) from which the
* the extent being released. These have been
* passed to us in the iplist[1] and iplist[2].
*/
lrd->log.noredoinoext.iagnum =
cpu_to_le32((u32) (size_t) cd->iplist[1]);
lrd->log.noredoinoext.inoext_idx =
cpu_to_le32((u32) (size_t) cd->iplist[2]);
pxdlock = (struct pxd_lock *) & tlck->lock;
*pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* update bmap */
tlck->flag |= tlckUPDATEMAP;
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
} else
jfs_err("diLog: UFO type tlck:0x%p", tlck);
#ifdef _JFS_WIP
/*
* alloc/free external EA extent
*
* a maplock for txUpdateMap() to update bPWMAP for alloc/free
* of the extent has been formatted at txLock() time;
*/
else {
assert(tlck->type & tlckEA);
/* log LOG_UPDATEMAP for logredo() to update bmap for
* alloc of new (and free of old) external EA extent;
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
pxdlock = (struct pxd_lock *) & tlck->lock;
nlock = pxdlock->index;
for (i = 0; i < nlock; i++, pxdlock++) {
if (pxdlock->flag & mlckALLOCPXD)
lrd->log.updatemap.type =
cpu_to_le16(LOG_ALLOCPXD);
else
lrd->log.updatemap.type =
cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
}
/* update bmap */
tlck->flag |= tlckUPDATEMAP;
}
#endif /* _JFS_WIP */
return rc;
}
/*
* dataLog()
*
* function: log data tlock
*/
static int dataLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct metapage *mp;
pxd_t *pxd;
mp = tlck->mp;
/* initialize as REDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_DATA);
lrd->log.redopage.l2linesize = cpu_to_le16(L2DATASLOTSIZE);
pxd = &lrd->log.redopage.pxd;
/* log after-image for logredo(): */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
if (jfs_dirtable_inline(tlck->ip)) {
/*
* The table has been truncated, we've must have deleted
* the last entry, so don't bother logging this
*/
mp->lid = 0;
grab_metapage(mp);
metapage_homeok(mp);
discard_metapage(mp);
tlck->mp = NULL;
return 0;
}
PXDaddress(pxd, mp->index);
PXDlength(pxd, mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return 0;
}
/*
* dtLog()
*
* function: log dtree tlock and format maplock to update bmap;
*/
static void dtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct metapage *mp;
struct pxd_lock *pxdlock;
pxd_t *pxd;
mp = tlck->mp;
/* initialize as REDOPAGE/NOREDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_DTREE);
lrd->log.redopage.l2linesize = cpu_to_le16(L2DTSLOTSIZE);
pxd = &lrd->log.redopage.pxd;
if (tlck->type & tlckBTROOT)
lrd->log.redopage.type |= cpu_to_le16(LOG_BTROOT);
/*
* page extension via relocation: entry insertion;
* page extension in-place: entry insertion;
* new right page from page split, reinitialized in-line
* root from root page split: entry insertion;
*/
if (tlck->type & (tlckNEW | tlckEXTEND)) {
/* log after-image of the new page for logredo():
* mark log (LOG_NEW) for logredo() to initialize
* freelist and update bmap for alloc of the new page;
*/
lrd->type = cpu_to_le16(LOG_REDOPAGE);
if (tlck->type & tlckEXTEND)
lrd->log.redopage.type |= cpu_to_le16(LOG_EXTEND);
else
lrd->log.redopage.type |= cpu_to_le16(LOG_NEW);
PXDaddress(pxd, mp->index);
PXDlength(pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* format a maplock for txUpdateMap() to update bPMAP for
* alloc of the new page;
*/
if (tlck->type & tlckBTROOT)
return;
tlck->flag |= tlckUPDATEMAP;
pxdlock = (struct pxd_lock *) & tlck->lock;
pxdlock->flag = mlckALLOCPXD;
pxdlock->pxd = *pxd;
pxdlock->index = 1;
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return;
}
/*
* entry insertion/deletion,
* sibling page link update (old right page before split);
*/
if (tlck->type & (tlckENTRY | tlckRELINK)) {
/* log after-image for logredo(): */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(pxd, mp->index);
PXDlength(pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return;
}
/*
* page deletion: page has been invalidated
* page relocation: source extent
*
* a maplock for free of the page has been formatted
* at txLock() time);
*/
if (tlck->type & (tlckFREE | tlckRELOCATE)) {
/* log LOG_NOREDOPAGE of the deleted page for logredo()
* to start NoRedoPage filter and to update bmap for free
* of the deletd page
*/
lrd->type = cpu_to_le16(LOG_NOREDOPAGE);
pxdlock = (struct pxd_lock *) & tlck->lock;
*pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* a maplock for txUpdateMap() for free of the page
* has been formatted at txLock() time;
*/
tlck->flag |= tlckUPDATEMAP;
}
return;
}
/*
* xtLog()
*
* function: log xtree tlock and format maplock to update bmap;
*/
static void xtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct inode *ip;
struct metapage *mp;
xtpage_t *p;
struct xtlock *xtlck;
struct maplock *maplock;
struct xdlistlock *xadlock;
struct pxd_lock *pxdlock;
pxd_t *page_pxd;
int next, lwm, hwm;
ip = tlck->ip;
mp = tlck->mp;
/* initialize as REDOPAGE/NOREDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_XTREE);
lrd->log.redopage.l2linesize = cpu_to_le16(L2XTSLOTSIZE);
page_pxd = &lrd->log.redopage.pxd;
if (tlck->type & tlckBTROOT) {
lrd->log.redopage.type |= cpu_to_le16(LOG_BTROOT);
p = &JFS_IP(ip)->i_xtroot;
if (S_ISDIR(ip->i_mode))
lrd->log.redopage.type |=
cpu_to_le16(LOG_DIR_XTREE);
} else
p = (xtpage_t *) mp->data;
next = le16_to_cpu(p->header.nextindex);
xtlck = (struct xtlock *) & tlck->lock;
maplock = (struct maplock *) & tlck->lock;
xadlock = (struct xdlistlock *) maplock;
/*
* entry insertion/extension;
* sibling page link update (old right page before split);
*/
if (tlck->type & (tlckNEW | tlckGROW | tlckRELINK)) {
/* log after-image for logredo():
* logredo() will update bmap for alloc of new/extended
* extents (XAD_NEW|XAD_EXTEND) of XAD[lwm:next) from
* after-image of XADlist;
* logredo() resets (XAD_NEW|XAD_EXTEND) flag when
* applying the after-image to the meta-data page.
*/
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(page_pxd, mp->index);
PXDlength(page_pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* format a maplock for txUpdateMap() to update bPMAP
* for alloc of new/extended extents of XAD[lwm:next)
* from the page itself;
* txUpdateMap() resets (XAD_NEW|XAD_EXTEND) flag.
*/
lwm = xtlck->lwm.offset;
if (lwm == 0)
lwm = XTPAGEMAXSLOT;
if (lwm == next)
goto out;
if (lwm > next) {
jfs_err("xtLog: lwm > next\n");
goto out;
}
tlck->flag |= tlckUPDATEMAP;
xadlock->flag = mlckALLOCXADLIST;
xadlock->count = next - lwm;
if ((xadlock->count <= 4) && (tblk->xflag & COMMIT_LAZY)) {
int i;
pxd_t *pxd;
/*
* Lazy commit may allow xtree to be modified before
* txUpdateMap runs. Copy xad into linelock to
* preserve correct data.
*
* We can fit twice as may pxd's as xads in the lock
*/
xadlock->flag = mlckALLOCPXDLIST;
pxd = xadlock->xdlist = &xtlck->pxdlock;
for (i = 0; i < xadlock->count; i++) {
PXDaddress(pxd, addressXAD(&p->xad[lwm + i]));
PXDlength(pxd, lengthXAD(&p->xad[lwm + i]));
p->xad[lwm + i].flag &=
~(XAD_NEW | XAD_EXTENDED);
pxd++;
}
} else {
/*
* xdlist will point to into inode's xtree, ensure
* that transaction is not committed lazily.
*/
xadlock->flag = mlckALLOCXADLIST;
xadlock->xdlist = &p->xad[lwm];
tblk->xflag &= ~COMMIT_LAZY;
}
jfs_info("xtLog: alloc ip:0x%p mp:0x%p tlck:0x%p lwm:%d "
"count:%d", tlck->ip, mp, tlck, lwm, xadlock->count);
maplock->index = 1;
out:
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return;
}
/*
* page deletion: file deletion/truncation (ref. xtTruncate())
*
* (page will be invalidated after log is written and bmap
* is updated from the page);
*/
if (tlck->type & tlckFREE) {
/* LOG_NOREDOPAGE log for NoRedoPage filter:
* if page free from file delete, NoRedoFile filter from
* inode image of zero link count will subsume NoRedoPage
* filters for each page;
* if page free from file truncattion, write NoRedoPage
* filter;
*
* upadte of block allocation map for the page itself:
* if page free from deletion and truncation, LOG_UPDATEMAP
* log for the page itself is generated from processing
* its parent page xad entries;
*/
/* if page free from file truncation, log LOG_NOREDOPAGE
* of the deleted page for logredo() to start NoRedoPage
* filter for the page;
*/
if (tblk->xflag & COMMIT_TRUNCATE) {
/* write NOREDOPAGE for the page */
lrd->type = cpu_to_le16(LOG_NOREDOPAGE);
PXDaddress(page_pxd, mp->index);
PXDlength(page_pxd,
mp->logical_size >> tblk->sb->
s_blocksize_bits);
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
if (tlck->type & tlckBTROOT) {
/* Empty xtree must be logged */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, tlck));
}
}
/* init LOG_UPDATEMAP of the freed extents
* XAD[XTENTRYSTART:hwm) from the deleted page itself
* for logredo() to update bmap;
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type = cpu_to_le16(LOG_FREEXADLIST);
xtlck = (struct xtlock *) & tlck->lock;
hwm = xtlck->hwm.offset;
lrd->log.updatemap.nxd =
cpu_to_le16(hwm - XTENTRYSTART + 1);
/* reformat linelock for lmLog() */
xtlck->header.offset = XTENTRYSTART;
xtlck->header.length = hwm - XTENTRYSTART + 1;
xtlck->index = 1;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* format a maplock for txUpdateMap() to update bmap
* to free extents of XAD[XTENTRYSTART:hwm) from the
* deleted page itself;
*/
tlck->flag |= tlckUPDATEMAP;
xadlock->count = hwm - XTENTRYSTART + 1;
if ((xadlock->count <= 4) && (tblk->xflag & COMMIT_LAZY)) {
int i;
pxd_t *pxd;
/*
* Lazy commit may allow xtree to be modified before
* txUpdateMap runs. Copy xad into linelock to
* preserve correct data.
*
* We can fit twice as may pxd's as xads in the lock
*/
xadlock->flag = mlckFREEPXDLIST;
pxd = xadlock->xdlist = &xtlck->pxdlock;
for (i = 0; i < xadlock->count; i++) {
PXDaddress(pxd,
addressXAD(&p->xad[XTENTRYSTART + i]));
PXDlength(pxd,
lengthXAD(&p->xad[XTENTRYSTART + i]));
pxd++;
}
} else {
/*
* xdlist will point to into inode's xtree, ensure
* that transaction is not committed lazily.
*/
xadlock->flag = mlckFREEXADLIST;
xadlock->xdlist = &p->xad[XTENTRYSTART];
tblk->xflag &= ~COMMIT_LAZY;
}
jfs_info("xtLog: free ip:0x%p mp:0x%p count:%d lwm:2",
tlck->ip, mp, xadlock->count);
maplock->index = 1;
/* mark page as invalid */
if (((tblk->xflag & COMMIT_PWMAP) || S_ISDIR(ip->i_mode))
&& !(tlck->type & tlckBTROOT))
tlck->flag |= tlckFREEPAGE;
/*
else (tblk->xflag & COMMIT_PMAP)
? release the page;
*/
return;
}
/*
* page/entry truncation: file truncation (ref. xtTruncate())
*
* |----------+------+------+---------------|
* | | |
* | | hwm - hwm before truncation
* | next - truncation point
* lwm - lwm before truncation
* header ?
*/
if (tlck->type & tlckTRUNCATE) {
/* This odd declaration suppresses a bogus gcc warning */
pxd_t pxd = pxd; /* truncated extent of xad */
int twm;
/*
* For truncation the entire linelock may be used, so it would
* be difficult to store xad list in linelock itself.
* Therefore, we'll just force transaction to be committed
* synchronously, so that xtree pages won't be changed before
* txUpdateMap runs.
*/
tblk->xflag &= ~COMMIT_LAZY;
lwm = xtlck->lwm.offset;
if (lwm == 0)
lwm = XTPAGEMAXSLOT;
hwm = xtlck->hwm.offset;
twm = xtlck->twm.offset;
/*
* write log records
*/
/* log after-image for logredo():
*
* logredo() will update bmap for alloc of new/extended
* extents (XAD_NEW|XAD_EXTEND) of XAD[lwm:next) from
* after-image of XADlist;
* logredo() resets (XAD_NEW|XAD_EXTEND) flag when
* applying the after-image to the meta-data page.
*/
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(page_pxd, mp->index);
PXDlength(page_pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/*
* truncate entry XAD[twm == next - 1]:
*/
if (twm == next - 1) {
/* init LOG_UPDATEMAP for logredo() to update bmap for
* free of truncated delta extent of the truncated
* entry XAD[next - 1]:
* (xtlck->pxdlock = truncated delta extent);
*/
pxdlock = (struct pxd_lock *) & xtlck->pxdlock;
/* assert(pxdlock->type & tlckTRUNCATE); */
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type = cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
pxd = pxdlock->pxd; /* save to format maplock */
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
}
/*
* free entries XAD[next:hwm]:
*/
if (hwm >= next) {
/* init LOG_UPDATEMAP of the freed extents
* XAD[next:hwm] from the deleted page itself
* for logredo() to update bmap;
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type =
cpu_to_le16(LOG_FREEXADLIST);
xtlck = (struct xtlock *) & tlck->lock;
hwm = xtlck->hwm.offset;
lrd->log.updatemap.nxd =
cpu_to_le16(hwm - next + 1);
/* reformat linelock for lmLog() */
xtlck->header.offset = next;
xtlck->header.length = hwm - next + 1;
xtlck->index = 1;
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, tlck));
}
/*
* format maplock(s) for txUpdateMap() to update bmap
*/
maplock->index = 0;
/*
* allocate entries XAD[lwm:next):
*/
if (lwm < next) {
/* format a maplock for txUpdateMap() to update bPMAP
* for alloc of new/extended extents of XAD[lwm:next)
* from the page itself;
* txUpdateMap() resets (XAD_NEW|XAD_EXTEND) flag.
*/
tlck->flag |= tlckUPDATEMAP;
xadlock->flag = mlckALLOCXADLIST;
xadlock->count = next - lwm;
xadlock->xdlist = &p->xad[lwm];
jfs_info("xtLog: alloc ip:0x%p mp:0x%p count:%d "
"lwm:%d next:%d",
tlck->ip, mp, xadlock->count, lwm, next);
maplock->index++;
xadlock++;
}
/*
* truncate entry XAD[twm == next - 1]:
*/
if (twm == next - 1) {
/* format a maplock for txUpdateMap() to update bmap
* to free truncated delta extent of the truncated
* entry XAD[next - 1];
* (xtlck->pxdlock = truncated delta extent);
*/
tlck->flag |= tlckUPDATEMAP;
pxdlock = (struct pxd_lock *) xadlock;
pxdlock->flag = mlckFREEPXD;
pxdlock->count = 1;
pxdlock->pxd = pxd;
jfs_info("xtLog: truncate ip:0x%p mp:0x%p count:%d "
"hwm:%d", ip, mp, pxdlock->count, hwm);
maplock->index++;
xadlock++;
}
/*
* free entries XAD[next:hwm]:
*/
if (hwm >= next) {
/* format a maplock for txUpdateMap() to update bmap
* to free extents of XAD[next:hwm] from thedeleted
* page itself;
*/
tlck->flag |= tlckUPDATEMAP;
xadlock->flag = mlckFREEXADLIST;
xadlock->count = hwm - next + 1;
xadlock->xdlist = &p->xad[next];
jfs_info("xtLog: free ip:0x%p mp:0x%p count:%d "
"next:%d hwm:%d",
tlck->ip, mp, xadlock->count, next, hwm);
maplock->index++;
}
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
}
return;
}
/*
* mapLog()
*
* function: log from maplock of freed data extents;
*/
static void mapLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct pxd_lock *pxdlock;
int i, nlock;
pxd_t *pxd;
/*
* page relocation: free the source page extent
*
* a maplock for txUpdateMap() for free of the page
* has been formatted at txLock() time saving the src
* relocated page address;
*/
if (tlck->type & tlckRELOCATE) {
/* log LOG_NOREDOPAGE of the old relocated page
* for logredo() to start NoRedoPage filter;
*/
lrd->type = cpu_to_le16(LOG_NOREDOPAGE);
pxdlock = (struct pxd_lock *) & tlck->lock;
pxd = &lrd->log.redopage.pxd;
*pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* (N.B. currently, logredo() does NOT update bmap
* for free of the page itself for (LOG_XTREE|LOG_NOREDOPAGE);
* if page free from relocation, LOG_UPDATEMAP log is
* specifically generated now for logredo()
* to update bmap for free of src relocated page;
* (new flag LOG_RELOCATE may be introduced which will
* inform logredo() to start NORedoPage filter and also
* update block allocation map at the same time, thus
* avoiding an extra log write);
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type = cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* a maplock for txUpdateMap() for free of the page
* has been formatted at txLock() time;
*/
tlck->flag |= tlckUPDATEMAP;
return;
}
/*
* Otherwise it's not a relocate request
*
*/
else {
/* log LOG_UPDATEMAP for logredo() to update bmap for
* free of truncated/relocated delta extent of the data;
* e.g.: external EA extent, relocated/truncated extent
* from xtTailgate();
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
pxdlock = (struct pxd_lock *) & tlck->lock;
nlock = pxdlock->index;
for (i = 0; i < nlock; i++, pxdlock++) {
if (pxdlock->flag & mlckALLOCPXD)
lrd->log.updatemap.type =
cpu_to_le16(LOG_ALLOCPXD);
else
lrd->log.updatemap.type =
cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
jfs_info("mapLog: xaddr:0x%lx xlen:0x%x",
(ulong) addressPXD(&pxdlock->pxd),
lengthPXD(&pxdlock->pxd));
}
/* update bmap */
tlck->flag |= tlckUPDATEMAP;
}
}
/*
* txEA()
*
* function: acquire maplock for EA/ACL extents or
* set COMMIT_INLINE flag;
*/
void txEA(tid_t tid, struct inode *ip, dxd_t * oldea, dxd_t * newea)
{
struct tlock *tlck = NULL;
struct pxd_lock *maplock = NULL, *pxdlock = NULL;
/*
* format maplock for alloc of new EA extent
*/
if (newea) {
/* Since the newea could be a completely zeroed entry we need to
* check for the two flags which indicate we should actually
* commit new EA data
*/
if (newea->flag & DXD_EXTENT) {
tlck = txMaplock(tid, ip, tlckMAP);
maplock = (struct pxd_lock *) & tlck->lock;
pxdlock = (struct pxd_lock *) maplock;
pxdlock->flag = mlckALLOCPXD;
PXDaddress(&pxdlock->pxd, addressDXD(newea));
PXDlength(&pxdlock->pxd, lengthDXD(newea));
pxdlock++;
maplock->index = 1;
} else if (newea->flag & DXD_INLINE) {
tlck = NULL;
set_cflag(COMMIT_Inlineea, ip);
}
}
/*
* format maplock for free of old EA extent
*/
if (!test_cflag(COMMIT_Nolink, ip) && oldea->flag & DXD_EXTENT) {
if (tlck == NULL) {
tlck = txMaplock(tid, ip, tlckMAP);
maplock = (struct pxd_lock *) & tlck->lock;
pxdlock = (struct pxd_lock *) maplock;
maplock->index = 0;
}
pxdlock->flag = mlckFREEPXD;
PXDaddress(&pxdlock->pxd, addressDXD(oldea));
PXDlength(&pxdlock->pxd, lengthDXD(oldea));
maplock->index++;
}
}
/*
* txForce()
*
* function: synchronously write pages locked by transaction
* after txLog() but before txUpdateMap();
*/
static void txForce(struct tblock * tblk)
{
struct tlock *tlck;
lid_t lid, next;
struct metapage *mp;
/*
* reverse the order of transaction tlocks in
* careful update order of address index pages
* (right to left, bottom up)
*/
tlck = lid_to_tlock(tblk->next);
lid = tlck->next;
tlck->next = 0;
while (lid) {
tlck = lid_to_tlock(lid);
next = tlck->next;
tlck->next = tblk->next;
tblk->next = lid;
lid = next;
}
/*
* synchronously write the page, and
* hold the page for txUpdateMap();
*/
for (lid = tblk->next; lid; lid = next) {
tlck = lid_to_tlock(lid);
next = tlck->next;
if ((mp = tlck->mp) != NULL &&
(tlck->type & tlckBTROOT) == 0) {
assert(mp->xflag & COMMIT_PAGE);
if (tlck->flag & tlckWRITEPAGE) {
tlck->flag &= ~tlckWRITEPAGE;
/* do not release page to freelist */
force_metapage(mp);
#if 0
/*
* The "right" thing to do here is to
* synchronously write the metadata.
* With the current implementation this
* is hard since write_metapage requires
* us to kunmap & remap the page. If we
* have tlocks pointing into the metadata
* pages, we don't want to do this. I think
* we can get by with synchronously writing
* the pages when they are released.
*/
assert(mp->nohomeok);
set_bit(META_dirty, &mp->flag);
set_bit(META_sync, &mp->flag);
#endif
}
}
}
}
/*
* txUpdateMap()
*
* function: update persistent allocation map (and working map
* if appropriate);
*
* parameter:
*/
static void txUpdateMap(struct tblock * tblk)
{
struct inode *ip;
struct inode *ipimap;
lid_t lid;
struct tlock *tlck;
struct maplock *maplock;
struct pxd_lock pxdlock;
int maptype;
int k, nlock;
struct metapage *mp = NULL;
ipimap = JFS_SBI(tblk->sb)->ipimap;
maptype = (tblk->xflag & COMMIT_PMAP) ? COMMIT_PMAP : COMMIT_PWMAP;
/*
* update block allocation map
*
* update allocation state in pmap (and wmap) and
* update lsn of the pmap page;
*/
/*
* scan each tlock/page of transaction for block allocation/free:
*
* for each tlock/page of transaction, update map.
* ? are there tlock for pmap and pwmap at the same time ?
*/
for (lid = tblk->next; lid; lid = tlck->next) {
tlck = lid_to_tlock(lid);
if ((tlck->flag & tlckUPDATEMAP) == 0)
continue;
if (tlck->flag & tlckFREEPAGE) {
/*
* Another thread may attempt to reuse freed space
* immediately, so we want to get rid of the metapage
* before anyone else has a chance to get it.
* Lock metapage, update maps, then invalidate
* the metapage.
*/
mp = tlck->mp;
ASSERT(mp->xflag & COMMIT_PAGE);
grab_metapage(mp);
}
/*
* extent list:
* . in-line PXD list:
* . out-of-line XAD list:
*/
maplock = (struct maplock *) & tlck->lock;
nlock = maplock->index;
for (k = 0; k < nlock; k++, maplock++) {
/*
* allocate blocks in persistent map:
*
* blocks have been allocated from wmap at alloc time;
*/
if (maplock->flag & mlckALLOC) {
txAllocPMap(ipimap, maplock, tblk);
}
/*
* free blocks in persistent and working map:
* blocks will be freed in pmap and then in wmap;
*
* ? tblock specifies the PMAP/PWMAP based upon
* transaction
*
* free blocks in persistent map:
* blocks will be freed from wmap at last reference
* release of the object for regular files;
*
* Alway free blocks from both persistent & working
* maps for directories
*/
else { /* (maplock->flag & mlckFREE) */
if (tlck->flag & tlckDIRECTORY)
txFreeMap(ipimap, maplock,
tblk, COMMIT_PWMAP);
else
txFreeMap(ipimap, maplock,
tblk, maptype);
}
}
if (tlck->flag & tlckFREEPAGE) {
if (!(tblk->flag & tblkGC_LAZY)) {
/* This is equivalent to txRelease */
ASSERT(mp->lid == lid);
tlck->mp->lid = 0;
}
assert(mp->nohomeok == 1);
metapage_homeok(mp);
discard_metapage(mp);
tlck->mp = NULL;
}
}
/*
* update inode allocation map
*
* update allocation state in pmap and
* update lsn of the pmap page;
* update in-memory inode flag/state
*
* unlock mapper/write lock
*/
if (tblk->xflag & COMMIT_CREATE) {
diUpdatePMap(ipimap, tblk->ino, false, tblk);
/* update persistent block allocation map
* for the allocation of inode extent;
*/
pxdlock.flag = mlckALLOCPXD;
pxdlock.pxd = tblk->u.ixpxd;
pxdlock.index = 1;
txAllocPMap(ipimap, (struct maplock *) & pxdlock, tblk);
} else if (tblk->xflag & COMMIT_DELETE) {
ip = tblk->u.ip;
diUpdatePMap(ipimap, ip->i_ino, true, tblk);
iput(ip);
}
}
/*
* txAllocPMap()
*
* function: allocate from persistent map;
*
* parameter:
* ipbmap -
* malock -
* xad list:
* pxd:
*
* maptype -
* allocate from persistent map;
* free from persistent map;
* (e.g., tmp file - free from working map at releae
* of last reference);
* free from persistent and working map;
*
* lsn - log sequence number;
*/
static void txAllocPMap(struct inode *ip, struct maplock * maplock,
struct tblock * tblk)
{
struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
struct xdlistlock *xadlistlock;
xad_t *xad;
s64 xaddr;
int xlen;
struct pxd_lock *pxdlock;
struct xdlistlock *pxdlistlock;
pxd_t *pxd;
int n;
/*
* allocate from persistent map;
*/
if (maplock->flag & mlckALLOCXADLIST) {
xadlistlock = (struct xdlistlock *) maplock;
xad = xadlistlock->xdlist;
for (n = 0; n < xadlistlock->count; n++, xad++) {
if (xad->flag & (XAD_NEW | XAD_EXTENDED)) {
xaddr = addressXAD(xad);
xlen = lengthXAD(xad);
dbUpdatePMap(ipbmap, false, xaddr,
(s64) xlen, tblk);
xad->flag &= ~(XAD_NEW | XAD_EXTENDED);
jfs_info("allocPMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
} else if (maplock->flag & mlckALLOCPXD) {
pxdlock = (struct pxd_lock *) maplock;
xaddr = addressPXD(&pxdlock->pxd);
xlen = lengthPXD(&pxdlock->pxd);
dbUpdatePMap(ipbmap, false, xaddr, (s64) xlen, tblk);
jfs_info("allocPMap: xaddr:0x%lx xlen:%d", (ulong) xaddr, xlen);
} else { /* (maplock->flag & mlckALLOCPXDLIST) */
pxdlistlock = (struct xdlistlock *) maplock;
pxd = pxdlistlock->xdlist;
for (n = 0; n < pxdlistlock->count; n++, pxd++) {
xaddr = addressPXD(pxd);
xlen = lengthPXD(pxd);
dbUpdatePMap(ipbmap, false, xaddr, (s64) xlen,
tblk);
jfs_info("allocPMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
}
/*
* txFreeMap()
*
* function: free from persistent and/or working map;
*
* todo: optimization
*/
void txFreeMap(struct inode *ip,
struct maplock * maplock, struct tblock * tblk, int maptype)
{
struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
struct xdlistlock *xadlistlock;
xad_t *xad;
s64 xaddr;
int xlen;
struct pxd_lock *pxdlock;
struct xdlistlock *pxdlistlock;
pxd_t *pxd;
int n;
jfs_info("txFreeMap: tblk:0x%p maplock:0x%p maptype:0x%x",
tblk, maplock, maptype);
/*
* free from persistent map;
*/
if (maptype == COMMIT_PMAP || maptype == COMMIT_PWMAP) {
if (maplock->flag & mlckFREEXADLIST) {
xadlistlock = (struct xdlistlock *) maplock;
xad = xadlistlock->xdlist;
for (n = 0; n < xadlistlock->count; n++, xad++) {
if (!(xad->flag & XAD_NEW)) {
xaddr = addressXAD(xad);
xlen = lengthXAD(xad);
dbUpdatePMap(ipbmap, true, xaddr,
(s64) xlen, tblk);
jfs_info("freePMap: xaddr:0x%lx "
"xlen:%d",
(ulong) xaddr, xlen);
}
}
} else if (maplock->flag & mlckFREEPXD) {
pxdlock = (struct pxd_lock *) maplock;
xaddr = addressPXD(&pxdlock->pxd);
xlen = lengthPXD(&pxdlock->pxd);
dbUpdatePMap(ipbmap, true, xaddr, (s64) xlen,
tblk);
jfs_info("freePMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
} else { /* (maplock->flag & mlckALLOCPXDLIST) */
pxdlistlock = (struct xdlistlock *) maplock;
pxd = pxdlistlock->xdlist;
for (n = 0; n < pxdlistlock->count; n++, pxd++) {
xaddr = addressPXD(pxd);
xlen = lengthPXD(pxd);
dbUpdatePMap(ipbmap, true, xaddr,
(s64) xlen, tblk);
jfs_info("freePMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
}
/*
* free from working map;
*/
if (maptype == COMMIT_PWMAP || maptype == COMMIT_WMAP) {
if (maplock->flag & mlckFREEXADLIST) {
xadlistlock = (struct xdlistlock *) maplock;
xad = xadlistlock->xdlist;
for (n = 0; n < xadlistlock->count; n++, xad++) {
xaddr = addressXAD(xad);
xlen = lengthXAD(xad);
dbFree(ip, xaddr, (s64) xlen);
xad->flag = 0;
jfs_info("freeWMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
} else if (maplock->flag & mlckFREEPXD) {
pxdlock = (struct pxd_lock *) maplock;
xaddr = addressPXD(&pxdlock->pxd);
xlen = lengthPXD(&pxdlock->pxd);
dbFree(ip, xaddr, (s64) xlen);
jfs_info("freeWMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
} else { /* (maplock->flag & mlckFREEPXDLIST) */
pxdlistlock = (struct xdlistlock *) maplock;
pxd = pxdlistlock->xdlist;
for (n = 0; n < pxdlistlock->count; n++, pxd++) {
xaddr = addressPXD(pxd);
xlen = lengthPXD(pxd);
dbFree(ip, xaddr, (s64) xlen);
jfs_info("freeWMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
}
}
/*
* txFreelock()
*
* function: remove tlock from inode anonymous locklist
*/
void txFreelock(struct inode *ip)
{
struct jfs_inode_info *jfs_ip = JFS_IP(ip);
struct tlock *xtlck, *tlck;
lid_t xlid = 0, lid;
if (!jfs_ip->atlhead)
return;
TXN_LOCK();
xtlck = (struct tlock *) &jfs_ip->atlhead;
while ((lid = xtlck->next) != 0) {
tlck = lid_to_tlock(lid);
if (tlck->flag & tlckFREELOCK) {
xtlck->next = tlck->next;
txLockFree(lid);
} else {
xtlck = tlck;
xlid = lid;
}
}
if (jfs_ip->atlhead)
jfs_ip->atltail = xlid;
else {
jfs_ip->atltail = 0;
/*
* If inode was on anon_list, remove it
*/
list_del_init(&jfs_ip->anon_inode_list);
}
TXN_UNLOCK();
}
/*
* txAbort()
*
* function: abort tx before commit;
*
* frees line-locks and segment locks for all
* segments in comdata structure.
* Optionally sets state of file-system to FM_DIRTY in super-block.
* log age of page-frames in memory for which caller has
* are reset to 0 (to avoid logwarap).
*/
void txAbort(tid_t tid, int dirty)
{
lid_t lid, next;
struct metapage *mp;
struct tblock *tblk = tid_to_tblock(tid);
struct tlock *tlck;
/*
* free tlocks of the transaction
*/
for (lid = tblk->next; lid; lid = next) {
tlck = lid_to_tlock(lid);
next = tlck->next;
mp = tlck->mp;
JFS_IP(tlck->ip)->xtlid = 0;
if (mp) {
mp->lid = 0;
/*
* reset lsn of page to avoid logwarap:
*
* (page may have been previously committed by another
* transaction(s) but has not been paged, i.e.,
* it may be on logsync list even though it has not
* been logged for the current tx.)
*/
if (mp->xflag & COMMIT_PAGE && mp->lsn)
LogSyncRelease(mp);
}
/* insert tlock at head of freelist */
TXN_LOCK();
txLockFree(lid);
TXN_UNLOCK();
}
/* caller will free the transaction block */
tblk->next = tblk->last = 0;
/*
* mark filesystem dirty
*/
if (dirty)
jfs_error(tblk->sb, "txAbort");
return;
}
/*
* txLazyCommit(void)
*
* All transactions except those changing ipimap (COMMIT_FORCE) are
* processed by this routine. This insures that the inode and block
* allocation maps are updated in order. For synchronous transactions,
* let the user thread finish processing after txUpdateMap() is called.
*/
static void txLazyCommit(struct tblock * tblk)
{
struct jfs_log *log;
while (((tblk->flag & tblkGC_READY) == 0) &&
((tblk->flag & tblkGC_UNLOCKED) == 0)) {
/* We must have gotten ahead of the user thread
*/
jfs_info("jfs_lazycommit: tblk 0x%p not unlocked", tblk);
yield();
}
jfs_info("txLazyCommit: processing tblk 0x%p", tblk);
txUpdateMap(tblk);
log = (struct jfs_log *) JFS_SBI(tblk->sb)->log;
spin_lock_irq(&log->gclock); // LOGGC_LOCK
tblk->flag |= tblkGC_COMMITTED;
if (tblk->flag & tblkGC_READY)
log->gcrtc--;
wake_up_all(&tblk->gcwait); // LOGGC_WAKEUP
/*
* Can't release log->gclock until we've tested tblk->flag
*/
if (tblk->flag & tblkGC_LAZY) {
spin_unlock_irq(&log->gclock); // LOGGC_UNLOCK
txUnlock(tblk);
tblk->flag &= ~tblkGC_LAZY;
txEnd(tblk - TxBlock); /* Convert back to tid */
} else
spin_unlock_irq(&log->gclock); // LOGGC_UNLOCK
jfs_info("txLazyCommit: done: tblk = 0x%p", tblk);
}
/*
* jfs_lazycommit(void)
*
* To be run as a kernel daemon. If lbmIODone is called in an interrupt
* context, or where blocking is not wanted, this routine will process
* committed transactions from the unlock queue.
*/
int jfs_lazycommit(void *arg)
{
int WorkDone;
struct tblock *tblk;
unsigned long flags;
struct jfs_sb_info *sbi;
do {
LAZY_LOCK(flags);
jfs_commit_thread_waking = 0; /* OK to wake another thread */
while (!list_empty(&TxAnchor.unlock_queue)) {
WorkDone = 0;
list_for_each_entry(tblk, &TxAnchor.unlock_queue,
cqueue) {
sbi = JFS_SBI(tblk->sb);
/*
* For each volume, the transactions must be
* handled in order. If another commit thread
* is handling a tblk for this superblock,
* skip it
*/
if (sbi->commit_state & IN_LAZYCOMMIT)
continue;
sbi->commit_state |= IN_LAZYCOMMIT;
WorkDone = 1;
/*
* Remove transaction from queue
*/
list_del(&tblk->cqueue);
LAZY_UNLOCK(flags);
txLazyCommit(tblk);
LAZY_LOCK(flags);
sbi->commit_state &= ~IN_LAZYCOMMIT;
/*
* Don't continue in the for loop. (We can't
* anyway, it's unsafe!) We want to go back to
* the beginning of the list.
*/
break;
}
/* If there was nothing to do, don't continue */
if (!WorkDone)
break;
}
/* In case a wakeup came while all threads were active */
jfs_commit_thread_waking = 0;
if (freezing(current)) {
LAZY_UNLOCK(flags);
refrigerator();
} else {
DECLARE_WAITQUEUE(wq, current);
add_wait_queue(&jfs_commit_thread_wait, &wq);
set_current_state(TASK_INTERRUPTIBLE);
LAZY_UNLOCK(flags);
schedule();
__set_current_state(TASK_RUNNING);
remove_wait_queue(&jfs_commit_thread_wait, &wq);
}
} while (!kthread_should_stop());
if (!list_empty(&TxAnchor.unlock_queue))
jfs_err("jfs_lazycommit being killed w/pending transactions!");
else
jfs_info("jfs_lazycommit being killed\n");
return 0;
}
void txLazyUnlock(struct tblock * tblk)
{
unsigned long flags;
LAZY_LOCK(flags);
list_add_tail(&tblk->cqueue, &TxAnchor.unlock_queue);
/*
* Don't wake up a commit thread if there is already one servicing
* this superblock, or if the last one we woke up hasn't started yet.
*/
if (!(JFS_SBI(tblk->sb)->commit_state & IN_LAZYCOMMIT) &&
!jfs_commit_thread_waking) {
jfs_commit_thread_waking = 1;
wake_up(&jfs_commit_thread_wait);
}
LAZY_UNLOCK(flags);
}
static void LogSyncRelease(struct metapage * mp)
{
struct jfs_log *log = mp->log;
assert(mp->nohomeok);
assert(log);
metapage_homeok(mp);
}
/*
* txQuiesce
*
* Block all new transactions and push anonymous transactions to
* completion
*
* This does almost the same thing as jfs_sync below. We don't
* worry about deadlocking when jfs_tlocks_low is set, since we would
* expect jfs_sync to get us out of that jam.
*/
void txQuiesce(struct super_block *sb)
{
struct inode *ip;
struct jfs_inode_info *jfs_ip;
struct jfs_log *log = JFS_SBI(sb)->log;
tid_t tid;
set_bit(log_QUIESCE, &log->flag);
TXN_LOCK();
restart:
while (!list_empty(&TxAnchor.anon_list)) {
jfs_ip = list_entry(TxAnchor.anon_list.next,
struct jfs_inode_info,
anon_inode_list);
ip = &jfs_ip->vfs_inode;
/*
* inode will be removed from anonymous list
* when it is committed
*/
TXN_UNLOCK();
tid = txBegin(ip->i_sb, COMMIT_INODE | COMMIT_FORCE);
mutex_lock(&jfs_ip->commit_mutex);
txCommit(tid, 1, &ip, 0);
txEnd(tid);
mutex_unlock(&jfs_ip->commit_mutex);
/*
* Just to be safe. I don't know how
* long we can run without blocking
*/
cond_resched();
TXN_LOCK();
}
/*
* If jfs_sync is running in parallel, there could be some inodes
* on anon_list2. Let's check.
*/
if (!list_empty(&TxAnchor.anon_list2)) {
list_splice(&TxAnchor.anon_list2, &TxAnchor.anon_list);
INIT_LIST_HEAD(&TxAnchor.anon_list2);
goto restart;
}
TXN_UNLOCK();
/*
* We may need to kick off the group commit
*/
jfs_flush_journal(log, 0);
}
/*
* txResume()
*
* Allows transactions to start again following txQuiesce
*/
void txResume(struct super_block *sb)
{
struct jfs_log *log = JFS_SBI(sb)->log;
clear_bit(log_QUIESCE, &log->flag);
TXN_WAKEUP(&log->syncwait);
}
/*
* jfs_sync(void)
*
* To be run as a kernel daemon. This is awakened when tlocks run low.
* We write any inodes that have anonymous tlocks so they will become
* available.
*/
int jfs_sync(void *arg)
{
struct inode *ip;
struct jfs_inode_info *jfs_ip;
int rc;
tid_t tid;
do {
/*
* write each inode on the anonymous inode list
*/
TXN_LOCK();
while (jfs_tlocks_low && !list_empty(&TxAnchor.anon_list)) {
jfs_ip = list_entry(TxAnchor.anon_list.next,
struct jfs_inode_info,
anon_inode_list);
ip = &jfs_ip->vfs_inode;
if (! igrab(ip)) {
/*
* Inode is being freed
*/
list_del_init(&jfs_ip->anon_inode_list);
} else if (mutex_trylock(&jfs_ip->commit_mutex)) {
/*
* inode will be removed from anonymous list
* when it is committed
*/
TXN_UNLOCK();
tid = txBegin(ip->i_sb, COMMIT_INODE);
rc = txCommit(tid, 1, &ip, 0);
txEnd(tid);
mutex_unlock(&jfs_ip->commit_mutex);
iput(ip);
/*
* Just to be safe. I don't know how
* long we can run without blocking
*/
cond_resched();
TXN_LOCK();
} else {
/* We can't get the commit mutex. It may
* be held by a thread waiting for tlock's
* so let's not block here. Save it to
* put back on the anon_list.
*/
/* Take off anon_list */
list_del(&jfs_ip->anon_inode_list);
/* Put on anon_list2 */
list_add(&jfs_ip->anon_inode_list,
&TxAnchor.anon_list2);
TXN_UNLOCK();
iput(ip);
TXN_LOCK();
}
}
/* Add anon_list2 back to anon_list */
list_splice_init(&TxAnchor.anon_list2, &TxAnchor.anon_list);
if (freezing(current)) {
TXN_UNLOCK();
refrigerator();
} else {
set_current_state(TASK_INTERRUPTIBLE);
TXN_UNLOCK();
schedule();
__set_current_state(TASK_RUNNING);
}
} while (!kthread_should_stop());
jfs_info("jfs_sync being killed");
return 0;
}
#if defined(CONFIG_PROC_FS) && defined(CONFIG_JFS_DEBUG)
static int jfs_txanchor_proc_show(struct seq_file *m, void *v)
{
char *freewait;
char *freelockwait;
char *lowlockwait;
freewait =
waitqueue_active(&TxAnchor.freewait) ? "active" : "empty";
freelockwait =
waitqueue_active(&TxAnchor.freelockwait) ? "active" : "empty";
lowlockwait =
waitqueue_active(&TxAnchor.lowlockwait) ? "active" : "empty";
seq_printf(m,
"JFS TxAnchor\n"
"============\n"
"freetid = %d\n"
"freewait = %s\n"
"freelock = %d\n"
"freelockwait = %s\n"
"lowlockwait = %s\n"
"tlocksInUse = %d\n"
"jfs_tlocks_low = %d\n"
"unlock_queue is %sempty\n",
TxAnchor.freetid,
freewait,
TxAnchor.freelock,
freelockwait,
lowlockwait,
TxAnchor.tlocksInUse,
jfs_tlocks_low,
list_empty(&TxAnchor.unlock_queue) ? "" : "not ");
return 0;
}
static int jfs_txanchor_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, jfs_txanchor_proc_show, NULL);
}
const struct file_operations jfs_txanchor_proc_fops = {
.owner = THIS_MODULE,
.open = jfs_txanchor_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
#if defined(CONFIG_PROC_FS) && defined(CONFIG_JFS_STATISTICS)
static int jfs_txstats_proc_show(struct seq_file *m, void *v)
{
seq_printf(m,
"JFS TxStats\n"
"===========\n"
"calls to txBegin = %d\n"
"txBegin blocked by sync barrier = %d\n"
"txBegin blocked by tlocks low = %d\n"
"txBegin blocked by no free tid = %d\n"
"calls to txBeginAnon = %d\n"
"txBeginAnon blocked by sync barrier = %d\n"
"txBeginAnon blocked by tlocks low = %d\n"
"calls to txLockAlloc = %d\n"
"tLockAlloc blocked by no free lock = %d\n",
TxStat.txBegin,
TxStat.txBegin_barrier,
TxStat.txBegin_lockslow,
TxStat.txBegin_freetid,
TxStat.txBeginAnon,
TxStat.txBeginAnon_barrier,
TxStat.txBeginAnon_lockslow,
TxStat.txLockAlloc,
TxStat.txLockAlloc_freelock);
return 0;
}
static int jfs_txstats_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, jfs_txstats_proc_show, NULL);
}
const struct file_operations jfs_txstats_proc_fops = {
.owner = THIS_MODULE,
.open = jfs_txstats_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.