repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
GabrielCebrianM/android_kernel_bq_bq_Maxwell2Lite | drivers/input/touchscreen/gunze.c | 9892 | 4951 | /*
* Copyright (c) 2000-2001 Vojtech Pavlik
*/
/*
* Gunze AHL-51S touchscreen driver for Linux
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "Gunze AHL-51S touchscreen driver"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define GUNZE_MAX_LENGTH 10
/*
* Per-touchscreen data.
*/
struct gunze {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[GUNZE_MAX_LENGTH];
char phys[32];
};
static void gunze_process_packet(struct gunze* gunze)
{
struct input_dev *dev = gunze->dev;
if (gunze->idx != GUNZE_MAX_LENGTH || gunze->data[5] != ',' ||
(gunze->data[0] != 'T' && gunze->data[0] != 'R')) {
printk(KERN_WARNING "gunze.c: bad packet: >%.*s<\n", GUNZE_MAX_LENGTH, gunze->data);
return;
}
input_report_abs(dev, ABS_X, simple_strtoul(gunze->data + 1, NULL, 10));
input_report_abs(dev, ABS_Y, 1024 - simple_strtoul(gunze->data + 6, NULL, 10));
input_report_key(dev, BTN_TOUCH, gunze->data[0] == 'T');
input_sync(dev);
}
static irqreturn_t gunze_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct gunze* gunze = serio_get_drvdata(serio);
if (data == '\r') {
gunze_process_packet(gunze);
gunze->idx = 0;
} else {
if (gunze->idx < GUNZE_MAX_LENGTH)
gunze->data[gunze->idx++] = data;
}
return IRQ_HANDLED;
}
/*
* gunze_disconnect() is the opposite of gunze_connect()
*/
static void gunze_disconnect(struct serio *serio)
{
struct gunze *gunze = serio_get_drvdata(serio);
input_get_device(gunze->dev);
input_unregister_device(gunze->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(gunze->dev);
kfree(gunze);
}
/*
* gunze_connect() is the routine that is called when someone adds a
* new serio device that supports Gunze protocol and registers it as
* an input device.
*/
static int gunze_connect(struct serio *serio, struct serio_driver *drv)
{
struct gunze *gunze;
struct input_dev *input_dev;
int err;
gunze = kzalloc(sizeof(struct gunze), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gunze || !input_dev) {
err = -ENOMEM;
goto fail1;
}
gunze->serio = serio;
gunze->dev = input_dev;
snprintf(gunze->phys, sizeof(serio->phys), "%s/input0", serio->phys);
input_dev->name = "Gunze AHL-51S TouchScreen";
input_dev->phys = gunze->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_GUNZE;
input_dev->id.product = 0x0051;
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);
input_set_abs_params(input_dev, ABS_X, 24, 1000, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 24, 1000, 0, 0);
serio_set_drvdata(serio, gunze);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(gunze->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(gunze);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id gunze_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_GUNZE,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, gunze_serio_ids);
static struct serio_driver gunze_drv = {
.driver = {
.name = "gunze",
},
.description = DRIVER_DESC,
.id_table = gunze_serio_ids,
.interrupt = gunze_interrupt,
.connect = gunze_connect,
.disconnect = gunze_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init gunze_init(void)
{
return serio_register_driver(&gunze_drv);
}
static void __exit gunze_exit(void)
{
serio_unregister_driver(&gunze_drv);
}
module_init(gunze_init);
module_exit(gunze_exit);
| gpl-2.0 |
davidmueller13/android_kernel_samsung_hlte_arter | drivers/input/touchscreen/touchit213.c | 9892 | 6060 | /*
* Sahara TouchIT-213 serial touchscreen driver
*
* Copyright (c) 2007-2008 Claudio Nieder <private@claudio.ch>
*
* Based on Touchright driver (drivers/input/touchscreen/touchright.c)
* Copyright (c) 2006 Rick Koch <n1gp@hotmail.com>
* Copyright (c) 2004 Vojtech Pavlik
* and Dan Streetman <ddstreet@ieee.org>
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "Sahara TouchIT-213 serial touchscreen driver"
MODULE_AUTHOR("Claudio Nieder <private@claudio.ch>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
/*
* Data is received through COM1 at 9600bit/s,8bit,no parity in packets
* of 5 byte each.
*
* +--------+ +--------+ +--------+ +--------+ +--------+
* |1000000p| |0xxxxxxx| |0xxxxxxx| |0yyyyyyy| |0yyyyyyy|
* +--------+ +--------+ +--------+ +--------+ +--------+
* MSB LSB MSB LSB
*
* The value of p is 1 as long as the screen is touched and 0 when
* reporting the location where touching stopped, e.g. where the pen was
* lifted from the screen.
*
* When holding the screen in landscape mode as the BIOS text output is
* presented, x is the horizontal axis with values growing from left to
* right and y is the vertical axis with values growing from top to
* bottom.
*
* When holding the screen in portrait mode with the Sahara logo in its
* correct position, x ist the vertical axis with values growing from
* top to bottom and y is the horizontal axis with values growing from
* right to left.
*/
#define T213_FORMAT_TOUCH_BIT 0x01
#define T213_FORMAT_STATUS_BYTE 0x80
#define T213_FORMAT_STATUS_MASK ~T213_FORMAT_TOUCH_BIT
/*
* On my Sahara Touch-IT 213 I have observed x values from 0 to 0x7f0
* and y values from 0x1d to 0x7e9, so the actual measurement is
* probably done with an 11 bit precision.
*/
#define T213_MIN_XC 0
#define T213_MAX_XC 0x07ff
#define T213_MIN_YC 0
#define T213_MAX_YC 0x07ff
/*
* Per-touchscreen data.
*/
struct touchit213 {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char csum;
unsigned char data[5];
char phys[32];
};
static irqreturn_t touchit213_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct touchit213 *touchit213 = serio_get_drvdata(serio);
struct input_dev *dev = touchit213->dev;
touchit213->data[touchit213->idx] = data;
switch (touchit213->idx++) {
case 0:
if ((touchit213->data[0] & T213_FORMAT_STATUS_MASK) !=
T213_FORMAT_STATUS_BYTE) {
pr_debug("unsynchronized data: 0x%02x\n", data);
touchit213->idx = 0;
}
break;
case 4:
touchit213->idx = 0;
input_report_abs(dev, ABS_X,
(touchit213->data[1] << 7) | touchit213->data[2]);
input_report_abs(dev, ABS_Y,
(touchit213->data[3] << 7) | touchit213->data[4]);
input_report_key(dev, BTN_TOUCH,
touchit213->data[0] & T213_FORMAT_TOUCH_BIT);
input_sync(dev);
break;
}
return IRQ_HANDLED;
}
/*
* touchit213_disconnect() is the opposite of touchit213_connect()
*/
static void touchit213_disconnect(struct serio *serio)
{
struct touchit213 *touchit213 = serio_get_drvdata(serio);
input_get_device(touchit213->dev);
input_unregister_device(touchit213->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(touchit213->dev);
kfree(touchit213);
}
/*
* touchit213_connect() is the routine that is called when someone adds a
* new serio device that supports the Touchright protocol and registers it as
* an input device.
*/
static int touchit213_connect(struct serio *serio, struct serio_driver *drv)
{
struct touchit213 *touchit213;
struct input_dev *input_dev;
int err;
touchit213 = kzalloc(sizeof(struct touchit213), GFP_KERNEL);
input_dev = input_allocate_device();
if (!touchit213 || !input_dev) {
err = -ENOMEM;
goto fail1;
}
touchit213->serio = serio;
touchit213->dev = input_dev;
snprintf(touchit213->phys, sizeof(touchit213->phys),
"%s/input0", serio->phys);
input_dev->name = "Sahara Touch-iT213 Serial TouchScreen";
input_dev->phys = touchit213->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_TOUCHIT213;
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);
input_set_abs_params(touchit213->dev, ABS_X,
T213_MIN_XC, T213_MAX_XC, 0, 0);
input_set_abs_params(touchit213->dev, ABS_Y,
T213_MIN_YC, T213_MAX_YC, 0, 0);
serio_set_drvdata(serio, touchit213);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(touchit213->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(touchit213);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id touchit213_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_TOUCHIT213,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, touchit213_serio_ids);
static struct serio_driver touchit213_drv = {
.driver = {
.name = "touchit213",
},
.description = DRIVER_DESC,
.id_table = touchit213_serio_ids,
.interrupt = touchit213_interrupt,
.connect = touchit213_connect,
.disconnect = touchit213_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init touchit213_init(void)
{
return serio_register_driver(&touchit213_drv);
}
static void __exit touchit213_exit(void)
{
serio_unregister_driver(&touchit213_drv);
}
module_init(touchit213_init);
module_exit(touchit213_exit);
| gpl-2.0 |
penreturns/AK-OnePone | drivers/input/touchscreen/touchit213.c | 9892 | 6060 | /*
* Sahara TouchIT-213 serial touchscreen driver
*
* Copyright (c) 2007-2008 Claudio Nieder <private@claudio.ch>
*
* Based on Touchright driver (drivers/input/touchscreen/touchright.c)
* Copyright (c) 2006 Rick Koch <n1gp@hotmail.com>
* Copyright (c) 2004 Vojtech Pavlik
* and Dan Streetman <ddstreet@ieee.org>
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "Sahara TouchIT-213 serial touchscreen driver"
MODULE_AUTHOR("Claudio Nieder <private@claudio.ch>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
/*
* Data is received through COM1 at 9600bit/s,8bit,no parity in packets
* of 5 byte each.
*
* +--------+ +--------+ +--------+ +--------+ +--------+
* |1000000p| |0xxxxxxx| |0xxxxxxx| |0yyyyyyy| |0yyyyyyy|
* +--------+ +--------+ +--------+ +--------+ +--------+
* MSB LSB MSB LSB
*
* The value of p is 1 as long as the screen is touched and 0 when
* reporting the location where touching stopped, e.g. where the pen was
* lifted from the screen.
*
* When holding the screen in landscape mode as the BIOS text output is
* presented, x is the horizontal axis with values growing from left to
* right and y is the vertical axis with values growing from top to
* bottom.
*
* When holding the screen in portrait mode with the Sahara logo in its
* correct position, x ist the vertical axis with values growing from
* top to bottom and y is the horizontal axis with values growing from
* right to left.
*/
#define T213_FORMAT_TOUCH_BIT 0x01
#define T213_FORMAT_STATUS_BYTE 0x80
#define T213_FORMAT_STATUS_MASK ~T213_FORMAT_TOUCH_BIT
/*
* On my Sahara Touch-IT 213 I have observed x values from 0 to 0x7f0
* and y values from 0x1d to 0x7e9, so the actual measurement is
* probably done with an 11 bit precision.
*/
#define T213_MIN_XC 0
#define T213_MAX_XC 0x07ff
#define T213_MIN_YC 0
#define T213_MAX_YC 0x07ff
/*
* Per-touchscreen data.
*/
struct touchit213 {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char csum;
unsigned char data[5];
char phys[32];
};
static irqreturn_t touchit213_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct touchit213 *touchit213 = serio_get_drvdata(serio);
struct input_dev *dev = touchit213->dev;
touchit213->data[touchit213->idx] = data;
switch (touchit213->idx++) {
case 0:
if ((touchit213->data[0] & T213_FORMAT_STATUS_MASK) !=
T213_FORMAT_STATUS_BYTE) {
pr_debug("unsynchronized data: 0x%02x\n", data);
touchit213->idx = 0;
}
break;
case 4:
touchit213->idx = 0;
input_report_abs(dev, ABS_X,
(touchit213->data[1] << 7) | touchit213->data[2]);
input_report_abs(dev, ABS_Y,
(touchit213->data[3] << 7) | touchit213->data[4]);
input_report_key(dev, BTN_TOUCH,
touchit213->data[0] & T213_FORMAT_TOUCH_BIT);
input_sync(dev);
break;
}
return IRQ_HANDLED;
}
/*
* touchit213_disconnect() is the opposite of touchit213_connect()
*/
static void touchit213_disconnect(struct serio *serio)
{
struct touchit213 *touchit213 = serio_get_drvdata(serio);
input_get_device(touchit213->dev);
input_unregister_device(touchit213->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(touchit213->dev);
kfree(touchit213);
}
/*
* touchit213_connect() is the routine that is called when someone adds a
* new serio device that supports the Touchright protocol and registers it as
* an input device.
*/
static int touchit213_connect(struct serio *serio, struct serio_driver *drv)
{
struct touchit213 *touchit213;
struct input_dev *input_dev;
int err;
touchit213 = kzalloc(sizeof(struct touchit213), GFP_KERNEL);
input_dev = input_allocate_device();
if (!touchit213 || !input_dev) {
err = -ENOMEM;
goto fail1;
}
touchit213->serio = serio;
touchit213->dev = input_dev;
snprintf(touchit213->phys, sizeof(touchit213->phys),
"%s/input0", serio->phys);
input_dev->name = "Sahara Touch-iT213 Serial TouchScreen";
input_dev->phys = touchit213->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_TOUCHIT213;
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);
input_set_abs_params(touchit213->dev, ABS_X,
T213_MIN_XC, T213_MAX_XC, 0, 0);
input_set_abs_params(touchit213->dev, ABS_Y,
T213_MIN_YC, T213_MAX_YC, 0, 0);
serio_set_drvdata(serio, touchit213);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(touchit213->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(touchit213);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id touchit213_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_TOUCHIT213,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, touchit213_serio_ids);
static struct serio_driver touchit213_drv = {
.driver = {
.name = "touchit213",
},
.description = DRIVER_DESC,
.id_table = touchit213_serio_ids,
.interrupt = touchit213_interrupt,
.connect = touchit213_connect,
.disconnect = touchit213_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init touchit213_init(void)
{
return serio_register_driver(&touchit213_drv);
}
static void __exit touchit213_exit(void)
{
serio_unregister_driver(&touchit213_drv);
}
module_init(touchit213_init);
module_exit(touchit213_exit);
| gpl-2.0 |
Hooks405/kernel_samsung_j3ltespr | drivers/media/usb/gspca/gl860/gl860-mi2020.c | 11172 | 28773 | /* Subdriver for the GL860 chip with the MI2020 sensor
* Author Olivier LORIN, from logs by Iceman/Soro2005 + Fret_saw/Hulkie/Tricid
* with the help of Kytrix/BUGabundo/Blazercist.
* Driver achieved thanks to a webcam gift by Kytrix.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
/* Sensor : MI2020 */
#include "gl860.h"
static u8 dat_wbal1[] = {0x8c, 0xa2, 0x0c};
static u8 dat_bright1[] = {0x8c, 0xa2, 0x06};
static u8 dat_bright3[] = {0x8c, 0xa1, 0x02};
static u8 dat_bright4[] = {0x90, 0x00, 0x0f};
static u8 dat_bright5[] = {0x8c, 0xa1, 0x03};
static u8 dat_bright6[] = {0x90, 0x00, 0x05};
static u8 dat_hvflip1[] = {0x8c, 0x27, 0x19};
static u8 dat_hvflip3[] = {0x8c, 0x27, 0x3b};
static u8 dat_hvflip5[] = {0x8c, 0xa1, 0x03};
static u8 dat_hvflip6[] = {0x90, 0x00, 0x06};
static struct idxdata tbl_middle_hvflip_low[] = {
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
};
static struct idxdata tbl_middle_hvflip_big[] = {
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x01"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x00"},
{102, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
};
static struct idxdata tbl_end_hvflip[] = {
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
{6, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
{6, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
{6, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
};
static u8 dat_freq1[] = { 0x8c, 0xa4, 0x04 };
static u8 dat_multi5[] = { 0x8c, 0xa1, 0x03 };
static u8 dat_multi6[] = { 0x90, 0x00, 0x05 };
static struct validx tbl_init_at_startup[] = {
{0x0000, 0x0000}, {0x0010, 0x0010}, {0x0008, 0x00c0}, {0x0001, 0x00c1},
{0x0001, 0x00c2}, {0x0020, 0x0006}, {0x006a, 0x000d},
{53, 0xffff},
{0x0040, 0x0000}, {0x0063, 0x0006},
};
static struct validx tbl_common_0B[] = {
{0x0002, 0x0004}, {0x006a, 0x0007}, {0x00ef, 0x0006}, {0x006a, 0x000d},
{0x0000, 0x00c0}, {0x0010, 0x0010}, {0x0003, 0x00c1}, {0x0042, 0x00c2},
{0x0004, 0x00d8}, {0x0000, 0x0058}, {0x0041, 0x0000},
};
static struct idxdata tbl_common_3B[] = {
{0x33, "\x86\x25\x01"}, {0x33, "\x86\x25\x00"},
{2, "\xff\xff\xff"},
{0x30, "\x1a\x0a\xcc"}, {0x32, "\x02\x00\x08"}, {0x33, "\xf4\x03\x1d"},
{6, "\xff\xff\xff"}, /* 12 */
{0x34, "\x1e\x8f\x09"}, {0x34, "\x1c\x01\x28"}, {0x34, "\x1e\x8f\x09"},
{2, "\xff\xff\xff"}, /* - */
{0x34, "\x1e\x8f\x09"}, {0x32, "\x14\x06\xe6"}, {0x33, "\x8c\x22\x23"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa2\x0f"}, {0x33, "\x90\x00\x0d"},
{0x33, "\x8c\xa2\x10"}, {0x33, "\x90\x00\x0b"}, {0x33, "\x8c\xa2\x11"},
{0x33, "\x90\x00\x07"}, {0x33, "\xf4\x03\x1d"}, {0x35, "\xa2\x00\xe2"},
{0x33, "\x8c\xab\x05"}, {0x33, "\x90\x00\x01"}, {0x32, "\x6e\x00\x86"},
{0x32, "\x70\x0f\xaa"}, {0x32, "\x72\x0f\xe4"}, {0x33, "\x8c\xa3\x4a"},
{0x33, "\x90\x00\x5a"}, {0x33, "\x8c\xa3\x4b"}, {0x33, "\x90\x00\xa6"},
{0x33, "\x8c\xa3\x61"}, {0x33, "\x90\x00\xc8"}, {0x33, "\x8c\xa3\x62"},
{0x33, "\x90\x00\xe1"}, {0x34, "\xce\x01\xa8"}, {0x34, "\xd0\x66\x33"},
{0x34, "\xd2\x31\x9a"}, {0x34, "\xd4\x94\x63"}, {0x34, "\xd6\x4b\x25"},
{0x34, "\xd8\x26\x70"}, {0x34, "\xda\x72\x4c"}, {0x34, "\xdc\xff\x04"},
{0x34, "\xde\x01\x5b"}, {0x34, "\xe6\x01\x13"}, {0x34, "\xee\x0b\xf0"},
{0x34, "\xf6\x0b\xa4"}, {0x35, "\x00\xf6\xe7"}, {0x35, "\x08\x0d\xfd"},
{0x35, "\x10\x25\x63"}, {0x35, "\x18\x35\x6c"}, {0x35, "\x20\x42\x7e"},
{0x35, "\x28\x19\x44"}, {0x35, "\x30\x39\xd4"}, {0x35, "\x38\xf5\xa8"},
{0x35, "\x4c\x07\x90"}, {0x35, "\x44\x07\xb8"}, {0x35, "\x5c\x06\x88"},
{0x35, "\x54\x07\xff"}, {0x34, "\xe0\x01\x52"}, {0x34, "\xe8\x00\xcc"},
{0x34, "\xf0\x0d\x83"}, {0x34, "\xf8\x0c\xb3"}, {0x35, "\x02\xfe\xba"},
{0x35, "\x0a\x04\xe0"}, {0x35, "\x12\x1c\x63"}, {0x35, "\x1a\x2b\x5a"},
{0x35, "\x22\x32\x5e"}, {0x35, "\x2a\x0d\x28"}, {0x35, "\x32\x2c\x02"},
{0x35, "\x3a\xf4\xfa"}, {0x35, "\x4e\x07\xef"}, {0x35, "\x46\x07\x88"},
{0x35, "\x5e\x07\xc1"}, {0x35, "\x56\x04\x64"}, {0x34, "\xe4\x01\x15"},
{0x34, "\xec\x00\x82"}, {0x34, "\xf4\x0c\xce"}, {0x34, "\xfc\x0c\xba"},
{0x35, "\x06\x1f\x02"}, {0x35, "\x0e\x02\xe3"}, {0x35, "\x16\x1a\x50"},
{0x35, "\x1e\x24\x39"}, {0x35, "\x26\x23\x4c"}, {0x35, "\x2e\xf9\x1b"},
{0x35, "\x36\x23\x19"}, {0x35, "\x3e\x12\x08"}, {0x35, "\x52\x07\x22"},
{0x35, "\x4a\x03\xd3"}, {0x35, "\x62\x06\x54"}, {0x35, "\x5a\x04\x5d"},
{0x34, "\xe2\x01\x04"}, {0x34, "\xea\x00\xa0"}, {0x34, "\xf2\x0c\xbc"},
{0x34, "\xfa\x0c\x5b"}, {0x35, "\x04\x17\xf2"}, {0x35, "\x0c\x02\x08"},
{0x35, "\x14\x28\x43"}, {0x35, "\x1c\x28\x62"}, {0x35, "\x24\x2b\x60"},
{0x35, "\x2c\x07\x33"}, {0x35, "\x34\x1f\xb0"}, {0x35, "\x3c\xed\xcd"},
{0x35, "\x50\x00\x06"}, {0x35, "\x48\x07\xff"}, {0x35, "\x60\x05\x89"},
{0x35, "\x58\x07\xff"}, {0x35, "\x40\x00\xa0"}, {0x35, "\x42\x00\x00"},
{0x32, "\x10\x01\xfc"}, {0x33, "\x8c\xa1\x18"}, {0x33, "\x90\x00\x3c"},
{0x33, "\x78\x00\x00"},
{2, "\xff\xff\xff"},
{0x35, "\xb8\x1f\x20"}, {0x33, "\x8c\xa2\x06"}, {0x33, "\x90\x00\x10"},
{0x33, "\x8c\xa2\x07"}, {0x33, "\x90\x00\x08"}, {0x33, "\x8c\xa2\x42"},
{0x33, "\x90\x00\x0b"}, {0x33, "\x8c\xa2\x4a"}, {0x33, "\x90\x00\x8c"},
{0x35, "\xba\xfa\x08"}, {0x33, "\x8c\xa2\x02"}, {0x33, "\x90\x00\x22"},
{0x33, "\x8c\xa2\x03"}, {0x33, "\x90\x00\xbb"}, {0x33, "\x8c\xa4\x04"},
{0x33, "\x90\x00\x80"}, {0x33, "\x8c\xa7\x9d"}, {0x33, "\x90\x00\x00"},
{0x33, "\x8c\xa7\x9e"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa2\x0c"},
{0x33, "\x90\x00\x17"}, {0x33, "\x8c\xa2\x15"}, {0x33, "\x90\x00\x04"},
{0x33, "\x8c\xa2\x14"}, {0x33, "\x90\x00\x20"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x17"}, {0x33, "\x90\x21\x11"},
{0x33, "\x8c\x27\x1b"}, {0x33, "\x90\x02\x4f"}, {0x33, "\x8c\x27\x25"},
{0x33, "\x90\x06\x0f"}, {0x33, "\x8c\x27\x39"}, {0x33, "\x90\x21\x11"},
{0x33, "\x8c\x27\x3d"}, {0x33, "\x90\x01\x20"}, {0x33, "\x8c\x27\x47"},
{0x33, "\x90\x09\x4c"}, {0x33, "\x8c\x27\x03"}, {0x33, "\x90\x02\x84"},
{0x33, "\x8c\x27\x05"}, {0x33, "\x90\x01\xe2"}, {0x33, "\x8c\x27\x07"},
{0x33, "\x90\x06\x40"}, {0x33, "\x8c\x27\x09"}, {0x33, "\x90\x04\xb0"},
{0x33, "\x8c\x27\x0d"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x0f"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x11"}, {0x33, "\x90\x04\xbd"},
{0x33, "\x8c\x27\x13"}, {0x33, "\x90\x06\x4d"}, {0x33, "\x8c\x27\x15"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x17"}, {0x33, "\x90\x21\x11"},
{0x33, "\x8c\x27\x19"}, {0x33, "\x90\x04\x6c"}, {0x33, "\x8c\x27\x1b"},
{0x33, "\x90\x02\x4f"}, {0x33, "\x8c\x27\x1d"}, {0x33, "\x90\x01\x02"},
{0x33, "\x8c\x27\x1f"}, {0x33, "\x90\x02\x79"}, {0x33, "\x8c\x27\x21"},
{0x33, "\x90\x01\x55"}, {0x33, "\x8c\x27\x23"}, {0x33, "\x90\x02\x85"},
{0x33, "\x8c\x27\x25"}, {0x33, "\x90\x06\x0f"}, {0x33, "\x8c\x27\x27"},
{0x33, "\x90\x20\x20"}, {0x33, "\x8c\x27\x29"}, {0x33, "\x90\x20\x20"},
{0x33, "\x8c\x27\x2b"}, {0x33, "\x90\x10\x20"}, {0x33, "\x8c\x27\x2d"},
{0x33, "\x90\x20\x07"}, {0x33, "\x8c\x27\x2f"}, {0x33, "\x90\x00\x04"},
{0x33, "\x8c\x27\x31"}, {0x33, "\x90\x00\x04"}, {0x33, "\x8c\x27\x33"},
{0x33, "\x90\x04\xbb"}, {0x33, "\x8c\x27\x35"}, {0x33, "\x90\x06\x4b"},
{0x33, "\x8c\x27\x37"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x39"},
{0x33, "\x90\x21\x11"}, {0x33, "\x8c\x27\x3b"}, {0x33, "\x90\x00\x24"},
{0x33, "\x8c\x27\x3d"}, {0x33, "\x90\x01\x20"}, {0x33, "\x8c\x27\x41"},
{0x33, "\x90\x01\x69"}, {0x33, "\x8c\x27\x45"}, {0x33, "\x90\x04\xed"},
{0x33, "\x8c\x27\x47"}, {0x33, "\x90\x09\x4c"}, {0x33, "\x8c\x27\x51"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x53"}, {0x33, "\x90\x03\x20"},
{0x33, "\x8c\x27\x55"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x57"},
{0x33, "\x90\x02\x58"}, {0x33, "\x8c\x27\x5f"}, {0x33, "\x90\x00\x00"},
{0x33, "\x8c\x27\x61"}, {0x33, "\x90\x06\x40"}, {0x33, "\x8c\x27\x63"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x65"}, {0x33, "\x90\x04\xb0"},
{0x33, "\x8c\x22\x2e"}, {0x33, "\x90\x00\xa1"}, {0x33, "\x8c\xa4\x08"},
{0x33, "\x90\x00\x1f"}, {0x33, "\x8c\xa4\x09"}, {0x33, "\x90\x00\x21"},
{0x33, "\x8c\xa4\x0a"}, {0x33, "\x90\x00\x25"}, {0x33, "\x8c\xa4\x0b"},
{0x33, "\x90\x00\x27"}, {0x33, "\x8c\x24\x11"}, {0x33, "\x90\x00\xa1"},
{0x33, "\x8c\x24\x13"}, {0x33, "\x90\x00\xc1"}, {0x33, "\x8c\x24\x15"},
{0x33, "\x90\x00\x6a"}, {0x33, "\x8c\x24\x17"}, {0x33, "\x90\x00\x80"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{3, "\xff\xff\xff"},
};
static struct idxdata tbl_init_post_alt_low1[] = {
{0x33, "\x8c\x27\x15"}, {0x33, "\x90\x00\x25"}, {0x33, "\x8c\x22\x2e"},
{0x33, "\x90\x00\x81"}, {0x33, "\x8c\xa4\x08"}, {0x33, "\x90\x00\x17"},
{0x33, "\x8c\xa4\x09"}, {0x33, "\x90\x00\x1a"}, {0x33, "\x8c\xa4\x0a"},
{0x33, "\x90\x00\x1d"}, {0x33, "\x8c\xa4\x0b"}, {0x33, "\x90\x00\x20"},
{0x33, "\x8c\x24\x11"}, {0x33, "\x90\x00\x81"}, {0x33, "\x8c\x24\x13"},
{0x33, "\x90\x00\x9b"},
};
static struct idxdata tbl_init_post_alt_low2[] = {
{0x33, "\x8c\x27\x03"}, {0x33, "\x90\x03\x24"}, {0x33, "\x8c\x27\x05"},
{0x33, "\x90\x02\x58"}, {0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
};
static struct idxdata tbl_init_post_alt_low3[] = {
{0x34, "\x1e\x8f\x09"}, {0x34, "\x1c\x01\x28"}, {0x34, "\x1e\x8f\x09"},
{2, "\xff\xff\xff"},
{0x34, "\x1e\x8f\x09"}, {0x32, "\x14\x06\xe6"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x01"},
{0x33, "\x2e\x01\x00"}, {0x34, "\x04\x00\x2a"}, {0x33, "\x8c\xa7\x02"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x95"}, {0x33, "\x90\x01\x00"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x01"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x00"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
};
static struct idxdata tbl_init_post_alt_big[] = {
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
{0x34, "\x1e\x8f\x09"}, {0x34, "\x1c\x01\x28"}, {0x34, "\x1e\x8f\x09"},
{2, "\xff\xff\xff"},
{0x34, "\x1e\x8f\x09"}, {0x32, "\x14\x06\xe6"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa1\x30"}, {0x33, "\x90\x00\x03"},
{0x33, "\x8c\xa1\x31"}, {0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa1\x32"},
{0x33, "\x90\x00\x03"}, {0x33, "\x8c\xa1\x34"}, {0x33, "\x90\x00\x03"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x02"}, {0x33, "\x2e\x01\x00"},
{0x34, "\x04\x00\x2a"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
{0x33, "\x8c\x27\x97"}, {0x33, "\x90\x01\x00"},
{51, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x01"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x00"},
{51, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
{51, "\xff\xff\xff"},
};
static struct idxdata tbl_init_post_alt_3B[] = {
{0x32, "\x10\x01\xf8"}, {0x34, "\xce\x01\xa8"}, {0x34, "\xd0\x66\x33"},
{0x34, "\xd2\x31\x9a"}, {0x34, "\xd4\x94\x63"}, {0x34, "\xd6\x4b\x25"},
{0x34, "\xd8\x26\x70"}, {0x34, "\xda\x72\x4c"}, {0x34, "\xdc\xff\x04"},
{0x34, "\xde\x01\x5b"}, {0x34, "\xe6\x01\x13"}, {0x34, "\xee\x0b\xf0"},
{0x34, "\xf6\x0b\xa4"}, {0x35, "\x00\xf6\xe7"}, {0x35, "\x08\x0d\xfd"},
{0x35, "\x10\x25\x63"}, {0x35, "\x18\x35\x6c"}, {0x35, "\x20\x42\x7e"},
{0x35, "\x28\x19\x44"}, {0x35, "\x30\x39\xd4"}, {0x35, "\x38\xf5\xa8"},
{0x35, "\x4c\x07\x90"}, {0x35, "\x44\x07\xb8"}, {0x35, "\x5c\x06\x88"},
{0x35, "\x54\x07\xff"}, {0x34, "\xe0\x01\x52"}, {0x34, "\xe8\x00\xcc"},
{0x34, "\xf0\x0d\x83"}, {0x34, "\xf8\x0c\xb3"}, {0x35, "\x02\xfe\xba"},
{0x35, "\x0a\x04\xe0"}, {0x35, "\x12\x1c\x63"}, {0x35, "\x1a\x2b\x5a"},
{0x35, "\x22\x32\x5e"}, {0x35, "\x2a\x0d\x28"}, {0x35, "\x32\x2c\x02"},
{0x35, "\x3a\xf4\xfa"}, {0x35, "\x4e\x07\xef"}, {0x35, "\x46\x07\x88"},
{0x35, "\x5e\x07\xc1"}, {0x35, "\x56\x04\x64"}, {0x34, "\xe4\x01\x15"},
{0x34, "\xec\x00\x82"}, {0x34, "\xf4\x0c\xce"}, {0x34, "\xfc\x0c\xba"},
{0x35, "\x06\x1f\x02"}, {0x35, "\x0e\x02\xe3"}, {0x35, "\x16\x1a\x50"},
{0x35, "\x1e\x24\x39"}, {0x35, "\x26\x23\x4c"}, {0x35, "\x2e\xf9\x1b"},
{0x35, "\x36\x23\x19"}, {0x35, "\x3e\x12\x08"}, {0x35, "\x52\x07\x22"},
{0x35, "\x4a\x03\xd3"}, {0x35, "\x62\x06\x54"}, {0x35, "\x5a\x04\x5d"},
{0x34, "\xe2\x01\x04"}, {0x34, "\xea\x00\xa0"}, {0x34, "\xf2\x0c\xbc"},
{0x34, "\xfa\x0c\x5b"}, {0x35, "\x04\x17\xf2"}, {0x35, "\x0c\x02\x08"},
{0x35, "\x14\x28\x43"}, {0x35, "\x1c\x28\x62"}, {0x35, "\x24\x2b\x60"},
{0x35, "\x2c\x07\x33"}, {0x35, "\x34\x1f\xb0"}, {0x35, "\x3c\xed\xcd"},
{0x35, "\x50\x00\x06"}, {0x35, "\x48\x07\xff"}, {0x35, "\x60\x05\x89"},
{0x35, "\x58\x07\xff"}, {0x35, "\x40\x00\xa0"}, {0x35, "\x42\x00\x00"},
{0x32, "\x10\x01\xfc"}, {0x33, "\x8c\xa1\x18"}, {0x33, "\x90\x00\x3c"},
};
static u8 *dat_640 = "\xd0\x02\xd1\x08\xd2\xe1\xd3\x02\xd4\x10\xd5\x81";
static u8 *dat_800 = "\xd0\x02\xd1\x10\xd2\x57\xd3\x02\xd4\x18\xd5\x21";
static u8 *dat_1280 = "\xd0\x02\xd1\x20\xd2\x01\xd3\x02\xd4\x28\xd5\x01";
static u8 *dat_1600 = "\xd0\x02\xd1\x20\xd2\xaf\xd3\x02\xd4\x30\xd5\x41";
static int mi2020_init_at_startup(struct gspca_dev *gspca_dev);
static int mi2020_configure_alt(struct gspca_dev *gspca_dev);
static int mi2020_init_pre_alt(struct gspca_dev *gspca_dev);
static int mi2020_init_post_alt(struct gspca_dev *gspca_dev);
static void mi2020_post_unset_alt(struct gspca_dev *gspca_dev);
static int mi2020_camera_settings(struct gspca_dev *gspca_dev);
/*==========================================================================*/
void mi2020_init_settings(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->vcur.backlight = 0;
sd->vcur.brightness = 70;
sd->vcur.sharpness = 20;
sd->vcur.contrast = 0;
sd->vcur.gamma = 0;
sd->vcur.hue = 0;
sd->vcur.saturation = 60;
sd->vcur.whitebal = 0; /* 50, not done by hardware */
sd->vcur.mirror = 0;
sd->vcur.flip = 0;
sd->vcur.AC50Hz = 1;
sd->vmax.backlight = 64;
sd->vmax.brightness = 128;
sd->vmax.sharpness = 40;
sd->vmax.contrast = 3;
sd->vmax.gamma = 2;
sd->vmax.hue = 0 + 1; /* 200, not done by hardware */
sd->vmax.saturation = 0; /* 100, not done by hardware */
sd->vmax.whitebal = 2; /* 100, not done by hardware */
sd->vmax.mirror = 1;
sd->vmax.flip = 1;
sd->vmax.AC50Hz = 1;
sd->dev_camera_settings = mi2020_camera_settings;
sd->dev_init_at_startup = mi2020_init_at_startup;
sd->dev_configure_alt = mi2020_configure_alt;
sd->dev_init_pre_alt = mi2020_init_pre_alt;
sd->dev_post_unset_alt = mi2020_post_unset_alt;
}
/*==========================================================================*/
static void common(struct gspca_dev *gspca_dev)
{
fetch_validx(gspca_dev, tbl_common_0B, ARRAY_SIZE(tbl_common_0B));
fetch_idxdata(gspca_dev, tbl_common_3B, ARRAY_SIZE(tbl_common_3B));
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x0000, 0, NULL);
}
static int mi2020_init_at_startup(struct gspca_dev *gspca_dev)
{
u8 c;
ctrl_in(gspca_dev, 0xc0, 2, 0x0000, 0x0004, 1, &c);
ctrl_in(gspca_dev, 0xc0, 2, 0x0000, 0x0004, 1, &c);
fetch_validx(gspca_dev, tbl_init_at_startup,
ARRAY_SIZE(tbl_init_at_startup));
ctrl_out(gspca_dev, 0x40, 1, 0x7a00, 0x8030, 0, NULL);
ctrl_in(gspca_dev, 0xc0, 2, 0x7a00, 0x8030, 1, &c);
common(gspca_dev);
msleep(61);
/* ctrl_out(gspca_dev, 0x40, 11, 0x0000, 0x0000, 0, NULL); */
/* msleep(36); */
ctrl_out(gspca_dev, 0x40, 1, 0x0001, 0x0000, 0, NULL);
return 0;
}
static int mi2020_init_pre_alt(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->mirrorMask = 0;
sd->vold.hue = -1;
/* These controls need to be reset */
sd->vold.brightness = -1;
sd->vold.sharpness = -1;
/* If not different from default, they do not need to be set */
sd->vold.contrast = 0;
sd->vold.gamma = 0;
sd->vold.backlight = 0;
mi2020_init_post_alt(gspca_dev);
return 0;
}
static int mi2020_init_post_alt(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
s32 mirror = (((sd->vcur.mirror > 0) ^ sd->mirrorMask) > 0);
s32 flip = (((sd->vcur.flip > 0) ^ sd->mirrorMask) > 0);
s32 freq = (sd->vcur.AC50Hz > 0);
s32 wbal = sd->vcur.whitebal;
u8 dat_freq2[] = {0x90, 0x00, 0x80};
u8 dat_multi1[] = {0x8c, 0xa7, 0x00};
u8 dat_multi2[] = {0x90, 0x00, 0x00};
u8 dat_multi3[] = {0x8c, 0xa7, 0x00};
u8 dat_multi4[] = {0x90, 0x00, 0x00};
u8 dat_hvflip2[] = {0x90, 0x04, 0x6c};
u8 dat_hvflip4[] = {0x90, 0x00, 0x24};
u8 dat_wbal2[] = {0x90, 0x00, 0x00};
u8 c;
sd->nbIm = -1;
dat_freq2[2] = freq ? 0xc0 : 0x80;
dat_multi1[2] = 0x9d;
dat_multi3[2] = dat_multi1[2] + 1;
if (wbal == 0) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x17;
} else if (wbal == 1) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x35;
} else if (wbal == 2) {
dat_multi4[2] = dat_multi2[2] = 0x20;
dat_wbal2[2] = 0x17;
}
dat_hvflip2[2] = 0x6c + 2 * (1 - flip) + (1 - mirror);
dat_hvflip4[2] = 0x24 + 2 * (1 - flip) + (1 - mirror);
msleep(200);
ctrl_out(gspca_dev, 0x40, 5, 0x0001, 0x0000, 0, NULL);
msleep(2);
common(gspca_dev);
msleep(142);
ctrl_out(gspca_dev, 0x40, 1, 0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0003, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0042, 0x00c2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x006a, 0x000d, 0, NULL);
switch (reso) {
case IMAGE_640:
case IMAGE_800:
if (reso != IMAGE_800)
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_640);
else
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_800);
fetch_idxdata(gspca_dev, tbl_init_post_alt_low1,
ARRAY_SIZE(tbl_init_post_alt_low1));
if (reso == IMAGE_800)
fetch_idxdata(gspca_dev, tbl_init_post_alt_low2,
ARRAY_SIZE(tbl_init_post_alt_low2));
fetch_idxdata(gspca_dev, tbl_init_post_alt_low3,
ARRAY_SIZE(tbl_init_post_alt_low3));
ctrl_out(gspca_dev, 0x40, 1, 0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0000, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x00c2, 0, NULL);
msleep(120);
break;
case IMAGE_1280:
case IMAGE_1600:
if (reso == IMAGE_1280) {
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_1280);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x07");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x05\x04");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x09");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x04\x02");
} else {
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_1600);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x07");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x06\x40");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x09");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x04\xb0");
}
fetch_idxdata(gspca_dev, tbl_init_post_alt_big,
ARRAY_SIZE(tbl_init_post_alt_big));
ctrl_out(gspca_dev, 0x40, 1, 0x0001, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0000, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x00c2, 0, NULL);
msleep(1850);
}
ctrl_out(gspca_dev, 0x40, 1, 0x0040, 0x0000, 0, NULL);
msleep(40);
/* AC power frequency */
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq2);
msleep(33);
/* light source */
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
msleep(7);
ctrl_in(gspca_dev, 0xc0, 2, 0x0000, 0x0000, 1, &c);
fetch_idxdata(gspca_dev, tbl_init_post_alt_3B,
ARRAY_SIZE(tbl_init_post_alt_3B));
/* hvflip */
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip6);
msleep(250);
if (reso == IMAGE_640 || reso == IMAGE_800)
fetch_idxdata(gspca_dev, tbl_middle_hvflip_low,
ARRAY_SIZE(tbl_middle_hvflip_low));
else
fetch_idxdata(gspca_dev, tbl_middle_hvflip_big,
ARRAY_SIZE(tbl_middle_hvflip_big));
fetch_idxdata(gspca_dev, tbl_end_hvflip,
ARRAY_SIZE(tbl_end_hvflip));
sd->nbIm = 0;
sd->vold.mirror = mirror;
sd->vold.flip = flip;
sd->vold.AC50Hz = freq;
sd->vold.whitebal = wbal;
mi2020_camera_settings(gspca_dev);
return 0;
}
static int mi2020_configure_alt(struct gspca_dev *gspca_dev)
{
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
switch (reso) {
case IMAGE_640:
gspca_dev->alt = 3 + 1;
break;
case IMAGE_800:
case IMAGE_1280:
case IMAGE_1600:
gspca_dev->alt = 1 + 1;
break;
}
return 0;
}
static int mi2020_camera_settings(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
s32 backlight = sd->vcur.backlight;
s32 bright = sd->vcur.brightness;
s32 sharp = sd->vcur.sharpness;
s32 cntr = sd->vcur.contrast;
s32 gam = sd->vcur.gamma;
s32 hue = (sd->vcur.hue > 0);
s32 mirror = (((sd->vcur.mirror > 0) ^ sd->mirrorMask) > 0);
s32 flip = (((sd->vcur.flip > 0) ^ sd->mirrorMask) > 0);
s32 freq = (sd->vcur.AC50Hz > 0);
s32 wbal = sd->vcur.whitebal;
u8 dat_sharp[] = {0x6c, 0x00, 0x08};
u8 dat_bright2[] = {0x90, 0x00, 0x00};
u8 dat_freq2[] = {0x90, 0x00, 0x80};
u8 dat_multi1[] = {0x8c, 0xa7, 0x00};
u8 dat_multi2[] = {0x90, 0x00, 0x00};
u8 dat_multi3[] = {0x8c, 0xa7, 0x00};
u8 dat_multi4[] = {0x90, 0x00, 0x00};
u8 dat_hvflip2[] = {0x90, 0x04, 0x6c};
u8 dat_hvflip4[] = {0x90, 0x00, 0x24};
u8 dat_wbal2[] = {0x90, 0x00, 0x00};
/* Less than 4 images received -> too early to set the settings */
if (sd->nbIm < 4) {
sd->waitSet = 1;
return 0;
}
sd->waitSet = 0;
if (freq != sd->vold.AC50Hz) {
sd->vold.AC50Hz = freq;
dat_freq2[2] = freq ? 0xc0 : 0x80;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq2);
msleep(20);
}
if (wbal != sd->vold.whitebal) {
sd->vold.whitebal = wbal;
if (wbal < 0 || wbal > sd->vmax.whitebal)
wbal = 0;
dat_multi1[2] = 0x9d;
dat_multi3[2] = dat_multi1[2] + 1;
if (wbal == 0) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x17;
} else if (wbal == 1) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x35;
} else if (wbal == 2) {
dat_multi4[2] = dat_multi2[2] = 0x20;
dat_wbal2[2] = 0x17;
}
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
}
if (mirror != sd->vold.mirror || flip != sd->vold.flip) {
sd->vold.mirror = mirror;
sd->vold.flip = flip;
dat_hvflip2[2] = 0x6c + 2 * (1 - flip) + (1 - mirror);
dat_hvflip4[2] = 0x24 + 2 * (1 - flip) + (1 - mirror);
fetch_idxdata(gspca_dev, tbl_init_post_alt_3B,
ARRAY_SIZE(tbl_init_post_alt_3B));
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip6);
msleep(40);
if (reso == IMAGE_640 || reso == IMAGE_800)
fetch_idxdata(gspca_dev, tbl_middle_hvflip_low,
ARRAY_SIZE(tbl_middle_hvflip_low));
else
fetch_idxdata(gspca_dev, tbl_middle_hvflip_big,
ARRAY_SIZE(tbl_middle_hvflip_big));
fetch_idxdata(gspca_dev, tbl_end_hvflip,
ARRAY_SIZE(tbl_end_hvflip));
}
if (bright != sd->vold.brightness) {
sd->vold.brightness = bright;
if (bright < 0 || bright > sd->vmax.brightness)
bright = 0;
dat_bright2[2] = bright;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright6);
}
if (cntr != sd->vold.contrast || gam != sd->vold.gamma) {
sd->vold.contrast = cntr;
if (cntr < 0 || cntr > sd->vmax.contrast)
cntr = 0;
sd->vold.gamma = gam;
if (gam < 0 || gam > sd->vmax.gamma)
gam = 0;
dat_multi1[2] = 0x6d;
dat_multi3[2] = dat_multi1[2] + 1;
if (cntr == 0)
cntr = 4;
dat_multi4[2] = dat_multi2[2] = cntr * 0x10 + 2 - gam;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
}
if (backlight != sd->vold.backlight) {
sd->vold.backlight = backlight;
if (backlight < 0 || backlight > sd->vmax.backlight)
backlight = 0;
dat_multi1[2] = 0x9d;
dat_multi3[2] = dat_multi1[2] + 1;
dat_multi4[2] = dat_multi2[2] = backlight;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
}
if (sharp != sd->vold.sharpness) {
sd->vold.sharpness = sharp;
if (sharp < 0 || sharp > sd->vmax.sharpness)
sharp = 0;
dat_sharp[1] = sharp;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0032, 3, dat_sharp);
}
if (hue != sd->vold.hue) {
sd->swapRB = hue;
sd->vold.hue = hue;
}
return 0;
}
static void mi2020_post_unset_alt(struct gspca_dev *gspca_dev)
{
ctrl_out(gspca_dev, 0x40, 5, 0x0000, 0x0000, 0, NULL);
msleep(40);
ctrl_out(gspca_dev, 0x40, 1, 0x0001, 0x0000, 0, NULL);
}
| gpl-2.0 |
mythos234/SimplKernel-LL-N910F | drivers/media/usb/gspca/gl860/gl860-mi2020.c | 11172 | 28773 | /* Subdriver for the GL860 chip with the MI2020 sensor
* Author Olivier LORIN, from logs by Iceman/Soro2005 + Fret_saw/Hulkie/Tricid
* with the help of Kytrix/BUGabundo/Blazercist.
* Driver achieved thanks to a webcam gift by Kytrix.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
/* Sensor : MI2020 */
#include "gl860.h"
static u8 dat_wbal1[] = {0x8c, 0xa2, 0x0c};
static u8 dat_bright1[] = {0x8c, 0xa2, 0x06};
static u8 dat_bright3[] = {0x8c, 0xa1, 0x02};
static u8 dat_bright4[] = {0x90, 0x00, 0x0f};
static u8 dat_bright5[] = {0x8c, 0xa1, 0x03};
static u8 dat_bright6[] = {0x90, 0x00, 0x05};
static u8 dat_hvflip1[] = {0x8c, 0x27, 0x19};
static u8 dat_hvflip3[] = {0x8c, 0x27, 0x3b};
static u8 dat_hvflip5[] = {0x8c, 0xa1, 0x03};
static u8 dat_hvflip6[] = {0x90, 0x00, 0x06};
static struct idxdata tbl_middle_hvflip_low[] = {
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
{0x33, "\x90\x00\x06"},
{6, "\xff\xff\xff"},
};
static struct idxdata tbl_middle_hvflip_big[] = {
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x01"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x00"},
{102, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
};
static struct idxdata tbl_end_hvflip[] = {
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
{6, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
{6, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
{6, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x02"}, {0x33, "\x90\x00\x1f"},
};
static u8 dat_freq1[] = { 0x8c, 0xa4, 0x04 };
static u8 dat_multi5[] = { 0x8c, 0xa1, 0x03 };
static u8 dat_multi6[] = { 0x90, 0x00, 0x05 };
static struct validx tbl_init_at_startup[] = {
{0x0000, 0x0000}, {0x0010, 0x0010}, {0x0008, 0x00c0}, {0x0001, 0x00c1},
{0x0001, 0x00c2}, {0x0020, 0x0006}, {0x006a, 0x000d},
{53, 0xffff},
{0x0040, 0x0000}, {0x0063, 0x0006},
};
static struct validx tbl_common_0B[] = {
{0x0002, 0x0004}, {0x006a, 0x0007}, {0x00ef, 0x0006}, {0x006a, 0x000d},
{0x0000, 0x00c0}, {0x0010, 0x0010}, {0x0003, 0x00c1}, {0x0042, 0x00c2},
{0x0004, 0x00d8}, {0x0000, 0x0058}, {0x0041, 0x0000},
};
static struct idxdata tbl_common_3B[] = {
{0x33, "\x86\x25\x01"}, {0x33, "\x86\x25\x00"},
{2, "\xff\xff\xff"},
{0x30, "\x1a\x0a\xcc"}, {0x32, "\x02\x00\x08"}, {0x33, "\xf4\x03\x1d"},
{6, "\xff\xff\xff"}, /* 12 */
{0x34, "\x1e\x8f\x09"}, {0x34, "\x1c\x01\x28"}, {0x34, "\x1e\x8f\x09"},
{2, "\xff\xff\xff"}, /* - */
{0x34, "\x1e\x8f\x09"}, {0x32, "\x14\x06\xe6"}, {0x33, "\x8c\x22\x23"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa2\x0f"}, {0x33, "\x90\x00\x0d"},
{0x33, "\x8c\xa2\x10"}, {0x33, "\x90\x00\x0b"}, {0x33, "\x8c\xa2\x11"},
{0x33, "\x90\x00\x07"}, {0x33, "\xf4\x03\x1d"}, {0x35, "\xa2\x00\xe2"},
{0x33, "\x8c\xab\x05"}, {0x33, "\x90\x00\x01"}, {0x32, "\x6e\x00\x86"},
{0x32, "\x70\x0f\xaa"}, {0x32, "\x72\x0f\xe4"}, {0x33, "\x8c\xa3\x4a"},
{0x33, "\x90\x00\x5a"}, {0x33, "\x8c\xa3\x4b"}, {0x33, "\x90\x00\xa6"},
{0x33, "\x8c\xa3\x61"}, {0x33, "\x90\x00\xc8"}, {0x33, "\x8c\xa3\x62"},
{0x33, "\x90\x00\xe1"}, {0x34, "\xce\x01\xa8"}, {0x34, "\xd0\x66\x33"},
{0x34, "\xd2\x31\x9a"}, {0x34, "\xd4\x94\x63"}, {0x34, "\xd6\x4b\x25"},
{0x34, "\xd8\x26\x70"}, {0x34, "\xda\x72\x4c"}, {0x34, "\xdc\xff\x04"},
{0x34, "\xde\x01\x5b"}, {0x34, "\xe6\x01\x13"}, {0x34, "\xee\x0b\xf0"},
{0x34, "\xf6\x0b\xa4"}, {0x35, "\x00\xf6\xe7"}, {0x35, "\x08\x0d\xfd"},
{0x35, "\x10\x25\x63"}, {0x35, "\x18\x35\x6c"}, {0x35, "\x20\x42\x7e"},
{0x35, "\x28\x19\x44"}, {0x35, "\x30\x39\xd4"}, {0x35, "\x38\xf5\xa8"},
{0x35, "\x4c\x07\x90"}, {0x35, "\x44\x07\xb8"}, {0x35, "\x5c\x06\x88"},
{0x35, "\x54\x07\xff"}, {0x34, "\xe0\x01\x52"}, {0x34, "\xe8\x00\xcc"},
{0x34, "\xf0\x0d\x83"}, {0x34, "\xf8\x0c\xb3"}, {0x35, "\x02\xfe\xba"},
{0x35, "\x0a\x04\xe0"}, {0x35, "\x12\x1c\x63"}, {0x35, "\x1a\x2b\x5a"},
{0x35, "\x22\x32\x5e"}, {0x35, "\x2a\x0d\x28"}, {0x35, "\x32\x2c\x02"},
{0x35, "\x3a\xf4\xfa"}, {0x35, "\x4e\x07\xef"}, {0x35, "\x46\x07\x88"},
{0x35, "\x5e\x07\xc1"}, {0x35, "\x56\x04\x64"}, {0x34, "\xe4\x01\x15"},
{0x34, "\xec\x00\x82"}, {0x34, "\xf4\x0c\xce"}, {0x34, "\xfc\x0c\xba"},
{0x35, "\x06\x1f\x02"}, {0x35, "\x0e\x02\xe3"}, {0x35, "\x16\x1a\x50"},
{0x35, "\x1e\x24\x39"}, {0x35, "\x26\x23\x4c"}, {0x35, "\x2e\xf9\x1b"},
{0x35, "\x36\x23\x19"}, {0x35, "\x3e\x12\x08"}, {0x35, "\x52\x07\x22"},
{0x35, "\x4a\x03\xd3"}, {0x35, "\x62\x06\x54"}, {0x35, "\x5a\x04\x5d"},
{0x34, "\xe2\x01\x04"}, {0x34, "\xea\x00\xa0"}, {0x34, "\xf2\x0c\xbc"},
{0x34, "\xfa\x0c\x5b"}, {0x35, "\x04\x17\xf2"}, {0x35, "\x0c\x02\x08"},
{0x35, "\x14\x28\x43"}, {0x35, "\x1c\x28\x62"}, {0x35, "\x24\x2b\x60"},
{0x35, "\x2c\x07\x33"}, {0x35, "\x34\x1f\xb0"}, {0x35, "\x3c\xed\xcd"},
{0x35, "\x50\x00\x06"}, {0x35, "\x48\x07\xff"}, {0x35, "\x60\x05\x89"},
{0x35, "\x58\x07\xff"}, {0x35, "\x40\x00\xa0"}, {0x35, "\x42\x00\x00"},
{0x32, "\x10\x01\xfc"}, {0x33, "\x8c\xa1\x18"}, {0x33, "\x90\x00\x3c"},
{0x33, "\x78\x00\x00"},
{2, "\xff\xff\xff"},
{0x35, "\xb8\x1f\x20"}, {0x33, "\x8c\xa2\x06"}, {0x33, "\x90\x00\x10"},
{0x33, "\x8c\xa2\x07"}, {0x33, "\x90\x00\x08"}, {0x33, "\x8c\xa2\x42"},
{0x33, "\x90\x00\x0b"}, {0x33, "\x8c\xa2\x4a"}, {0x33, "\x90\x00\x8c"},
{0x35, "\xba\xfa\x08"}, {0x33, "\x8c\xa2\x02"}, {0x33, "\x90\x00\x22"},
{0x33, "\x8c\xa2\x03"}, {0x33, "\x90\x00\xbb"}, {0x33, "\x8c\xa4\x04"},
{0x33, "\x90\x00\x80"}, {0x33, "\x8c\xa7\x9d"}, {0x33, "\x90\x00\x00"},
{0x33, "\x8c\xa7\x9e"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa2\x0c"},
{0x33, "\x90\x00\x17"}, {0x33, "\x8c\xa2\x15"}, {0x33, "\x90\x00\x04"},
{0x33, "\x8c\xa2\x14"}, {0x33, "\x90\x00\x20"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x17"}, {0x33, "\x90\x21\x11"},
{0x33, "\x8c\x27\x1b"}, {0x33, "\x90\x02\x4f"}, {0x33, "\x8c\x27\x25"},
{0x33, "\x90\x06\x0f"}, {0x33, "\x8c\x27\x39"}, {0x33, "\x90\x21\x11"},
{0x33, "\x8c\x27\x3d"}, {0x33, "\x90\x01\x20"}, {0x33, "\x8c\x27\x47"},
{0x33, "\x90\x09\x4c"}, {0x33, "\x8c\x27\x03"}, {0x33, "\x90\x02\x84"},
{0x33, "\x8c\x27\x05"}, {0x33, "\x90\x01\xe2"}, {0x33, "\x8c\x27\x07"},
{0x33, "\x90\x06\x40"}, {0x33, "\x8c\x27\x09"}, {0x33, "\x90\x04\xb0"},
{0x33, "\x8c\x27\x0d"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x0f"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x11"}, {0x33, "\x90\x04\xbd"},
{0x33, "\x8c\x27\x13"}, {0x33, "\x90\x06\x4d"}, {0x33, "\x8c\x27\x15"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x17"}, {0x33, "\x90\x21\x11"},
{0x33, "\x8c\x27\x19"}, {0x33, "\x90\x04\x6c"}, {0x33, "\x8c\x27\x1b"},
{0x33, "\x90\x02\x4f"}, {0x33, "\x8c\x27\x1d"}, {0x33, "\x90\x01\x02"},
{0x33, "\x8c\x27\x1f"}, {0x33, "\x90\x02\x79"}, {0x33, "\x8c\x27\x21"},
{0x33, "\x90\x01\x55"}, {0x33, "\x8c\x27\x23"}, {0x33, "\x90\x02\x85"},
{0x33, "\x8c\x27\x25"}, {0x33, "\x90\x06\x0f"}, {0x33, "\x8c\x27\x27"},
{0x33, "\x90\x20\x20"}, {0x33, "\x8c\x27\x29"}, {0x33, "\x90\x20\x20"},
{0x33, "\x8c\x27\x2b"}, {0x33, "\x90\x10\x20"}, {0x33, "\x8c\x27\x2d"},
{0x33, "\x90\x20\x07"}, {0x33, "\x8c\x27\x2f"}, {0x33, "\x90\x00\x04"},
{0x33, "\x8c\x27\x31"}, {0x33, "\x90\x00\x04"}, {0x33, "\x8c\x27\x33"},
{0x33, "\x90\x04\xbb"}, {0x33, "\x8c\x27\x35"}, {0x33, "\x90\x06\x4b"},
{0x33, "\x8c\x27\x37"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x39"},
{0x33, "\x90\x21\x11"}, {0x33, "\x8c\x27\x3b"}, {0x33, "\x90\x00\x24"},
{0x33, "\x8c\x27\x3d"}, {0x33, "\x90\x01\x20"}, {0x33, "\x8c\x27\x41"},
{0x33, "\x90\x01\x69"}, {0x33, "\x8c\x27\x45"}, {0x33, "\x90\x04\xed"},
{0x33, "\x8c\x27\x47"}, {0x33, "\x90\x09\x4c"}, {0x33, "\x8c\x27\x51"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x53"}, {0x33, "\x90\x03\x20"},
{0x33, "\x8c\x27\x55"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x57"},
{0x33, "\x90\x02\x58"}, {0x33, "\x8c\x27\x5f"}, {0x33, "\x90\x00\x00"},
{0x33, "\x8c\x27\x61"}, {0x33, "\x90\x06\x40"}, {0x33, "\x8c\x27\x63"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x65"}, {0x33, "\x90\x04\xb0"},
{0x33, "\x8c\x22\x2e"}, {0x33, "\x90\x00\xa1"}, {0x33, "\x8c\xa4\x08"},
{0x33, "\x90\x00\x1f"}, {0x33, "\x8c\xa4\x09"}, {0x33, "\x90\x00\x21"},
{0x33, "\x8c\xa4\x0a"}, {0x33, "\x90\x00\x25"}, {0x33, "\x8c\xa4\x0b"},
{0x33, "\x90\x00\x27"}, {0x33, "\x8c\x24\x11"}, {0x33, "\x90\x00\xa1"},
{0x33, "\x8c\x24\x13"}, {0x33, "\x90\x00\xc1"}, {0x33, "\x8c\x24\x15"},
{0x33, "\x90\x00\x6a"}, {0x33, "\x8c\x24\x17"}, {0x33, "\x90\x00\x80"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{3, "\xff\xff\xff"},
};
static struct idxdata tbl_init_post_alt_low1[] = {
{0x33, "\x8c\x27\x15"}, {0x33, "\x90\x00\x25"}, {0x33, "\x8c\x22\x2e"},
{0x33, "\x90\x00\x81"}, {0x33, "\x8c\xa4\x08"}, {0x33, "\x90\x00\x17"},
{0x33, "\x8c\xa4\x09"}, {0x33, "\x90\x00\x1a"}, {0x33, "\x8c\xa4\x0a"},
{0x33, "\x90\x00\x1d"}, {0x33, "\x8c\xa4\x0b"}, {0x33, "\x90\x00\x20"},
{0x33, "\x8c\x24\x11"}, {0x33, "\x90\x00\x81"}, {0x33, "\x8c\x24\x13"},
{0x33, "\x90\x00\x9b"},
};
static struct idxdata tbl_init_post_alt_low2[] = {
{0x33, "\x8c\x27\x03"}, {0x33, "\x90\x03\x24"}, {0x33, "\x8c\x27\x05"},
{0x33, "\x90\x02\x58"}, {0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
};
static struct idxdata tbl_init_post_alt_low3[] = {
{0x34, "\x1e\x8f\x09"}, {0x34, "\x1c\x01\x28"}, {0x34, "\x1e\x8f\x09"},
{2, "\xff\xff\xff"},
{0x34, "\x1e\x8f\x09"}, {0x32, "\x14\x06\xe6"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x01"},
{0x33, "\x2e\x01\x00"}, {0x34, "\x04\x00\x2a"}, {0x33, "\x8c\xa7\x02"},
{0x33, "\x90\x00\x00"}, {0x33, "\x8c\x27\x95"}, {0x33, "\x90\x01\x00"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x01"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x00"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
};
static struct idxdata tbl_init_post_alt_big[] = {
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
{0x34, "\x1e\x8f\x09"}, {0x34, "\x1c\x01\x28"}, {0x34, "\x1e\x8f\x09"},
{2, "\xff\xff\xff"},
{0x34, "\x1e\x8f\x09"}, {0x32, "\x14\x06\xe6"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x05"},
{2, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x06"}, {0x33, "\x8c\xa1\x20"},
{0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa1\x30"}, {0x33, "\x90\x00\x03"},
{0x33, "\x8c\xa1\x31"}, {0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa1\x32"},
{0x33, "\x90\x00\x03"}, {0x33, "\x8c\xa1\x34"}, {0x33, "\x90\x00\x03"},
{0x33, "\x8c\xa1\x03"}, {0x33, "\x90\x00\x02"}, {0x33, "\x2e\x01\x00"},
{0x34, "\x04\x00\x2a"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
{0x33, "\x8c\x27\x97"}, {0x33, "\x90\x01\x00"},
{51, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x00"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x01"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x00"},
{51, "\xff\xff\xff"},
{0x33, "\x8c\xa1\x20"}, {0x33, "\x90\x00\x72"}, {0x33, "\x8c\xa1\x03"},
{0x33, "\x90\x00\x02"}, {0x33, "\x8c\xa7\x02"}, {0x33, "\x90\x00\x01"},
{51, "\xff\xff\xff"},
};
static struct idxdata tbl_init_post_alt_3B[] = {
{0x32, "\x10\x01\xf8"}, {0x34, "\xce\x01\xa8"}, {0x34, "\xd0\x66\x33"},
{0x34, "\xd2\x31\x9a"}, {0x34, "\xd4\x94\x63"}, {0x34, "\xd6\x4b\x25"},
{0x34, "\xd8\x26\x70"}, {0x34, "\xda\x72\x4c"}, {0x34, "\xdc\xff\x04"},
{0x34, "\xde\x01\x5b"}, {0x34, "\xe6\x01\x13"}, {0x34, "\xee\x0b\xf0"},
{0x34, "\xf6\x0b\xa4"}, {0x35, "\x00\xf6\xe7"}, {0x35, "\x08\x0d\xfd"},
{0x35, "\x10\x25\x63"}, {0x35, "\x18\x35\x6c"}, {0x35, "\x20\x42\x7e"},
{0x35, "\x28\x19\x44"}, {0x35, "\x30\x39\xd4"}, {0x35, "\x38\xf5\xa8"},
{0x35, "\x4c\x07\x90"}, {0x35, "\x44\x07\xb8"}, {0x35, "\x5c\x06\x88"},
{0x35, "\x54\x07\xff"}, {0x34, "\xe0\x01\x52"}, {0x34, "\xe8\x00\xcc"},
{0x34, "\xf0\x0d\x83"}, {0x34, "\xf8\x0c\xb3"}, {0x35, "\x02\xfe\xba"},
{0x35, "\x0a\x04\xe0"}, {0x35, "\x12\x1c\x63"}, {0x35, "\x1a\x2b\x5a"},
{0x35, "\x22\x32\x5e"}, {0x35, "\x2a\x0d\x28"}, {0x35, "\x32\x2c\x02"},
{0x35, "\x3a\xf4\xfa"}, {0x35, "\x4e\x07\xef"}, {0x35, "\x46\x07\x88"},
{0x35, "\x5e\x07\xc1"}, {0x35, "\x56\x04\x64"}, {0x34, "\xe4\x01\x15"},
{0x34, "\xec\x00\x82"}, {0x34, "\xf4\x0c\xce"}, {0x34, "\xfc\x0c\xba"},
{0x35, "\x06\x1f\x02"}, {0x35, "\x0e\x02\xe3"}, {0x35, "\x16\x1a\x50"},
{0x35, "\x1e\x24\x39"}, {0x35, "\x26\x23\x4c"}, {0x35, "\x2e\xf9\x1b"},
{0x35, "\x36\x23\x19"}, {0x35, "\x3e\x12\x08"}, {0x35, "\x52\x07\x22"},
{0x35, "\x4a\x03\xd3"}, {0x35, "\x62\x06\x54"}, {0x35, "\x5a\x04\x5d"},
{0x34, "\xe2\x01\x04"}, {0x34, "\xea\x00\xa0"}, {0x34, "\xf2\x0c\xbc"},
{0x34, "\xfa\x0c\x5b"}, {0x35, "\x04\x17\xf2"}, {0x35, "\x0c\x02\x08"},
{0x35, "\x14\x28\x43"}, {0x35, "\x1c\x28\x62"}, {0x35, "\x24\x2b\x60"},
{0x35, "\x2c\x07\x33"}, {0x35, "\x34\x1f\xb0"}, {0x35, "\x3c\xed\xcd"},
{0x35, "\x50\x00\x06"}, {0x35, "\x48\x07\xff"}, {0x35, "\x60\x05\x89"},
{0x35, "\x58\x07\xff"}, {0x35, "\x40\x00\xa0"}, {0x35, "\x42\x00\x00"},
{0x32, "\x10\x01\xfc"}, {0x33, "\x8c\xa1\x18"}, {0x33, "\x90\x00\x3c"},
};
static u8 *dat_640 = "\xd0\x02\xd1\x08\xd2\xe1\xd3\x02\xd4\x10\xd5\x81";
static u8 *dat_800 = "\xd0\x02\xd1\x10\xd2\x57\xd3\x02\xd4\x18\xd5\x21";
static u8 *dat_1280 = "\xd0\x02\xd1\x20\xd2\x01\xd3\x02\xd4\x28\xd5\x01";
static u8 *dat_1600 = "\xd0\x02\xd1\x20\xd2\xaf\xd3\x02\xd4\x30\xd5\x41";
static int mi2020_init_at_startup(struct gspca_dev *gspca_dev);
static int mi2020_configure_alt(struct gspca_dev *gspca_dev);
static int mi2020_init_pre_alt(struct gspca_dev *gspca_dev);
static int mi2020_init_post_alt(struct gspca_dev *gspca_dev);
static void mi2020_post_unset_alt(struct gspca_dev *gspca_dev);
static int mi2020_camera_settings(struct gspca_dev *gspca_dev);
/*==========================================================================*/
void mi2020_init_settings(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->vcur.backlight = 0;
sd->vcur.brightness = 70;
sd->vcur.sharpness = 20;
sd->vcur.contrast = 0;
sd->vcur.gamma = 0;
sd->vcur.hue = 0;
sd->vcur.saturation = 60;
sd->vcur.whitebal = 0; /* 50, not done by hardware */
sd->vcur.mirror = 0;
sd->vcur.flip = 0;
sd->vcur.AC50Hz = 1;
sd->vmax.backlight = 64;
sd->vmax.brightness = 128;
sd->vmax.sharpness = 40;
sd->vmax.contrast = 3;
sd->vmax.gamma = 2;
sd->vmax.hue = 0 + 1; /* 200, not done by hardware */
sd->vmax.saturation = 0; /* 100, not done by hardware */
sd->vmax.whitebal = 2; /* 100, not done by hardware */
sd->vmax.mirror = 1;
sd->vmax.flip = 1;
sd->vmax.AC50Hz = 1;
sd->dev_camera_settings = mi2020_camera_settings;
sd->dev_init_at_startup = mi2020_init_at_startup;
sd->dev_configure_alt = mi2020_configure_alt;
sd->dev_init_pre_alt = mi2020_init_pre_alt;
sd->dev_post_unset_alt = mi2020_post_unset_alt;
}
/*==========================================================================*/
static void common(struct gspca_dev *gspca_dev)
{
fetch_validx(gspca_dev, tbl_common_0B, ARRAY_SIZE(tbl_common_0B));
fetch_idxdata(gspca_dev, tbl_common_3B, ARRAY_SIZE(tbl_common_3B));
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x0000, 0, NULL);
}
static int mi2020_init_at_startup(struct gspca_dev *gspca_dev)
{
u8 c;
ctrl_in(gspca_dev, 0xc0, 2, 0x0000, 0x0004, 1, &c);
ctrl_in(gspca_dev, 0xc0, 2, 0x0000, 0x0004, 1, &c);
fetch_validx(gspca_dev, tbl_init_at_startup,
ARRAY_SIZE(tbl_init_at_startup));
ctrl_out(gspca_dev, 0x40, 1, 0x7a00, 0x8030, 0, NULL);
ctrl_in(gspca_dev, 0xc0, 2, 0x7a00, 0x8030, 1, &c);
common(gspca_dev);
msleep(61);
/* ctrl_out(gspca_dev, 0x40, 11, 0x0000, 0x0000, 0, NULL); */
/* msleep(36); */
ctrl_out(gspca_dev, 0x40, 1, 0x0001, 0x0000, 0, NULL);
return 0;
}
static int mi2020_init_pre_alt(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->mirrorMask = 0;
sd->vold.hue = -1;
/* These controls need to be reset */
sd->vold.brightness = -1;
sd->vold.sharpness = -1;
/* If not different from default, they do not need to be set */
sd->vold.contrast = 0;
sd->vold.gamma = 0;
sd->vold.backlight = 0;
mi2020_init_post_alt(gspca_dev);
return 0;
}
static int mi2020_init_post_alt(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
s32 mirror = (((sd->vcur.mirror > 0) ^ sd->mirrorMask) > 0);
s32 flip = (((sd->vcur.flip > 0) ^ sd->mirrorMask) > 0);
s32 freq = (sd->vcur.AC50Hz > 0);
s32 wbal = sd->vcur.whitebal;
u8 dat_freq2[] = {0x90, 0x00, 0x80};
u8 dat_multi1[] = {0x8c, 0xa7, 0x00};
u8 dat_multi2[] = {0x90, 0x00, 0x00};
u8 dat_multi3[] = {0x8c, 0xa7, 0x00};
u8 dat_multi4[] = {0x90, 0x00, 0x00};
u8 dat_hvflip2[] = {0x90, 0x04, 0x6c};
u8 dat_hvflip4[] = {0x90, 0x00, 0x24};
u8 dat_wbal2[] = {0x90, 0x00, 0x00};
u8 c;
sd->nbIm = -1;
dat_freq2[2] = freq ? 0xc0 : 0x80;
dat_multi1[2] = 0x9d;
dat_multi3[2] = dat_multi1[2] + 1;
if (wbal == 0) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x17;
} else if (wbal == 1) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x35;
} else if (wbal == 2) {
dat_multi4[2] = dat_multi2[2] = 0x20;
dat_wbal2[2] = 0x17;
}
dat_hvflip2[2] = 0x6c + 2 * (1 - flip) + (1 - mirror);
dat_hvflip4[2] = 0x24 + 2 * (1 - flip) + (1 - mirror);
msleep(200);
ctrl_out(gspca_dev, 0x40, 5, 0x0001, 0x0000, 0, NULL);
msleep(2);
common(gspca_dev);
msleep(142);
ctrl_out(gspca_dev, 0x40, 1, 0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0003, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0042, 0x00c2, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x006a, 0x000d, 0, NULL);
switch (reso) {
case IMAGE_640:
case IMAGE_800:
if (reso != IMAGE_800)
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_640);
else
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_800);
fetch_idxdata(gspca_dev, tbl_init_post_alt_low1,
ARRAY_SIZE(tbl_init_post_alt_low1));
if (reso == IMAGE_800)
fetch_idxdata(gspca_dev, tbl_init_post_alt_low2,
ARRAY_SIZE(tbl_init_post_alt_low2));
fetch_idxdata(gspca_dev, tbl_init_post_alt_low3,
ARRAY_SIZE(tbl_init_post_alt_low3));
ctrl_out(gspca_dev, 0x40, 1, 0x0010, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0000, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x00c2, 0, NULL);
msleep(120);
break;
case IMAGE_1280:
case IMAGE_1600:
if (reso == IMAGE_1280) {
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_1280);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x07");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x05\x04");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x09");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x04\x02");
} else {
ctrl_out(gspca_dev, 0x40, 3, 0x0000, 0x0200,
12, dat_1600);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x07");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x06\x40");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x8c\x27\x09");
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033,
3, "\x90\x04\xb0");
}
fetch_idxdata(gspca_dev, tbl_init_post_alt_big,
ARRAY_SIZE(tbl_init_post_alt_big));
ctrl_out(gspca_dev, 0x40, 1, 0x0001, 0x0010, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0000, 0x00c1, 0, NULL);
ctrl_out(gspca_dev, 0x40, 1, 0x0041, 0x00c2, 0, NULL);
msleep(1850);
}
ctrl_out(gspca_dev, 0x40, 1, 0x0040, 0x0000, 0, NULL);
msleep(40);
/* AC power frequency */
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq2);
msleep(33);
/* light source */
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
msleep(7);
ctrl_in(gspca_dev, 0xc0, 2, 0x0000, 0x0000, 1, &c);
fetch_idxdata(gspca_dev, tbl_init_post_alt_3B,
ARRAY_SIZE(tbl_init_post_alt_3B));
/* hvflip */
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip6);
msleep(250);
if (reso == IMAGE_640 || reso == IMAGE_800)
fetch_idxdata(gspca_dev, tbl_middle_hvflip_low,
ARRAY_SIZE(tbl_middle_hvflip_low));
else
fetch_idxdata(gspca_dev, tbl_middle_hvflip_big,
ARRAY_SIZE(tbl_middle_hvflip_big));
fetch_idxdata(gspca_dev, tbl_end_hvflip,
ARRAY_SIZE(tbl_end_hvflip));
sd->nbIm = 0;
sd->vold.mirror = mirror;
sd->vold.flip = flip;
sd->vold.AC50Hz = freq;
sd->vold.whitebal = wbal;
mi2020_camera_settings(gspca_dev);
return 0;
}
static int mi2020_configure_alt(struct gspca_dev *gspca_dev)
{
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
switch (reso) {
case IMAGE_640:
gspca_dev->alt = 3 + 1;
break;
case IMAGE_800:
case IMAGE_1280:
case IMAGE_1600:
gspca_dev->alt = 1 + 1;
break;
}
return 0;
}
static int mi2020_camera_settings(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 reso = gspca_dev->cam.cam_mode[(s32) gspca_dev->curr_mode].priv;
s32 backlight = sd->vcur.backlight;
s32 bright = sd->vcur.brightness;
s32 sharp = sd->vcur.sharpness;
s32 cntr = sd->vcur.contrast;
s32 gam = sd->vcur.gamma;
s32 hue = (sd->vcur.hue > 0);
s32 mirror = (((sd->vcur.mirror > 0) ^ sd->mirrorMask) > 0);
s32 flip = (((sd->vcur.flip > 0) ^ sd->mirrorMask) > 0);
s32 freq = (sd->vcur.AC50Hz > 0);
s32 wbal = sd->vcur.whitebal;
u8 dat_sharp[] = {0x6c, 0x00, 0x08};
u8 dat_bright2[] = {0x90, 0x00, 0x00};
u8 dat_freq2[] = {0x90, 0x00, 0x80};
u8 dat_multi1[] = {0x8c, 0xa7, 0x00};
u8 dat_multi2[] = {0x90, 0x00, 0x00};
u8 dat_multi3[] = {0x8c, 0xa7, 0x00};
u8 dat_multi4[] = {0x90, 0x00, 0x00};
u8 dat_hvflip2[] = {0x90, 0x04, 0x6c};
u8 dat_hvflip4[] = {0x90, 0x00, 0x24};
u8 dat_wbal2[] = {0x90, 0x00, 0x00};
/* Less than 4 images received -> too early to set the settings */
if (sd->nbIm < 4) {
sd->waitSet = 1;
return 0;
}
sd->waitSet = 0;
if (freq != sd->vold.AC50Hz) {
sd->vold.AC50Hz = freq;
dat_freq2[2] = freq ? 0xc0 : 0x80;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_freq2);
msleep(20);
}
if (wbal != sd->vold.whitebal) {
sd->vold.whitebal = wbal;
if (wbal < 0 || wbal > sd->vmax.whitebal)
wbal = 0;
dat_multi1[2] = 0x9d;
dat_multi3[2] = dat_multi1[2] + 1;
if (wbal == 0) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x17;
} else if (wbal == 1) {
dat_multi4[2] = dat_multi2[2] = 0;
dat_wbal2[2] = 0x35;
} else if (wbal == 2) {
dat_multi4[2] = dat_multi2[2] = 0x20;
dat_wbal2[2] = 0x17;
}
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_wbal2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
}
if (mirror != sd->vold.mirror || flip != sd->vold.flip) {
sd->vold.mirror = mirror;
sd->vold.flip = flip;
dat_hvflip2[2] = 0x6c + 2 * (1 - flip) + (1 - mirror);
dat_hvflip4[2] = 0x24 + 2 * (1 - flip) + (1 - mirror);
fetch_idxdata(gspca_dev, tbl_init_post_alt_3B,
ARRAY_SIZE(tbl_init_post_alt_3B));
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_hvflip6);
msleep(40);
if (reso == IMAGE_640 || reso == IMAGE_800)
fetch_idxdata(gspca_dev, tbl_middle_hvflip_low,
ARRAY_SIZE(tbl_middle_hvflip_low));
else
fetch_idxdata(gspca_dev, tbl_middle_hvflip_big,
ARRAY_SIZE(tbl_middle_hvflip_big));
fetch_idxdata(gspca_dev, tbl_end_hvflip,
ARRAY_SIZE(tbl_end_hvflip));
}
if (bright != sd->vold.brightness) {
sd->vold.brightness = bright;
if (bright < 0 || bright > sd->vmax.brightness)
bright = 0;
dat_bright2[2] = bright;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_bright6);
}
if (cntr != sd->vold.contrast || gam != sd->vold.gamma) {
sd->vold.contrast = cntr;
if (cntr < 0 || cntr > sd->vmax.contrast)
cntr = 0;
sd->vold.gamma = gam;
if (gam < 0 || gam > sd->vmax.gamma)
gam = 0;
dat_multi1[2] = 0x6d;
dat_multi3[2] = dat_multi1[2] + 1;
if (cntr == 0)
cntr = 4;
dat_multi4[2] = dat_multi2[2] = cntr * 0x10 + 2 - gam;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
}
if (backlight != sd->vold.backlight) {
sd->vold.backlight = backlight;
if (backlight < 0 || backlight > sd->vmax.backlight)
backlight = 0;
dat_multi1[2] = 0x9d;
dat_multi3[2] = dat_multi1[2] + 1;
dat_multi4[2] = dat_multi2[2] = backlight;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi1);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi2);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi3);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi4);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi5);
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0033, 3, dat_multi6);
}
if (sharp != sd->vold.sharpness) {
sd->vold.sharpness = sharp;
if (sharp < 0 || sharp > sd->vmax.sharpness)
sharp = 0;
dat_sharp[1] = sharp;
ctrl_out(gspca_dev, 0x40, 3, 0x7a00, 0x0032, 3, dat_sharp);
}
if (hue != sd->vold.hue) {
sd->swapRB = hue;
sd->vold.hue = hue;
}
return 0;
}
static void mi2020_post_unset_alt(struct gspca_dev *gspca_dev)
{
ctrl_out(gspca_dev, 0x40, 5, 0x0000, 0x0000, 0, NULL);
msleep(40);
ctrl_out(gspca_dev, 0x40, 1, 0x0001, 0x0000, 0, NULL);
}
| gpl-2.0 |
KaijunTang/linux-kernel | sound/synth/emux/emux_hwdep.c | 11940 | 3731 | /*
* Interface for hwdep device
*
* Copyright (C) 2004 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/hwdep.h>
#include <asm/uaccess.h>
#include "emux_voice.h"
#define TMP_CLIENT_ID 0x1001
/*
* load patch
*/
static int
snd_emux_hwdep_load_patch(struct snd_emux *emu, void __user *arg)
{
int err;
struct soundfont_patch_info patch;
if (copy_from_user(&patch, arg, sizeof(patch)))
return -EFAULT;
if (patch.type >= SNDRV_SFNT_LOAD_INFO &&
patch.type <= SNDRV_SFNT_PROBE_DATA) {
err = snd_soundfont_load(emu->sflist, arg, patch.len + sizeof(patch), TMP_CLIENT_ID);
if (err < 0)
return err;
} else {
if (emu->ops.load_fx)
return emu->ops.load_fx(emu, patch.type, patch.optarg, arg, patch.len + sizeof(patch));
else
return -EINVAL;
}
return 0;
}
/*
* set misc mode
*/
static int
snd_emux_hwdep_misc_mode(struct snd_emux *emu, void __user *arg)
{
struct snd_emux_misc_mode info;
int i;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.mode < 0 || info.mode >= EMUX_MD_END)
return -EINVAL;
if (info.port < 0) {
for (i = 0; i < emu->num_ports; i++)
emu->portptrs[i]->ctrls[info.mode] = info.value;
} else {
if (info.port < emu->num_ports)
emu->portptrs[info.port]->ctrls[info.mode] = info.value;
}
return 0;
}
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct snd_emux *emu = hw->private_data;
switch (cmd) {
case SNDRV_EMUX_IOCTL_VERSION:
return put_user(SNDRV_EMUX_VERSION, (unsigned int __user *)arg);
case SNDRV_EMUX_IOCTL_LOAD_PATCH:
return snd_emux_hwdep_load_patch(emu, (void __user *)arg);
case SNDRV_EMUX_IOCTL_RESET_SAMPLES:
snd_soundfont_remove_samples(emu->sflist);
break;
case SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES:
snd_soundfont_remove_unlocked(emu->sflist);
break;
case SNDRV_EMUX_IOCTL_MEM_AVAIL:
if (emu->memhdr) {
int size = snd_util_mem_avail(emu->memhdr);
return put_user(size, (unsigned int __user *)arg);
}
break;
case SNDRV_EMUX_IOCTL_MISC_MODE:
return snd_emux_hwdep_misc_mode(emu, (void __user *)arg);
}
return 0;
}
/*
* register hwdep device
*/
int
snd_emux_init_hwdep(struct snd_emux *emu)
{
struct snd_hwdep *hw;
int err;
if ((err = snd_hwdep_new(emu->card, SNDRV_EMUX_HWDEP_NAME, emu->hwdep_idx, &hw)) < 0)
return err;
emu->hwdep = hw;
strcpy(hw->name, SNDRV_EMUX_HWDEP_NAME);
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
hw->exclusive = 1;
hw->private_data = emu;
if ((err = snd_card_register(emu->card)) < 0)
return err;
return 0;
}
/*
* unregister
*/
void
snd_emux_delete_hwdep(struct snd_emux *emu)
{
if (emu->hwdep) {
snd_device_free(emu->card, emu->hwdep);
emu->hwdep = NULL;
}
}
| gpl-2.0 |
CyanogenMod/htc-kernel-supersonic | sound/pci/ctxfi/ctamixer.c | 12708 | 9927 | /**
* Copyright (C) 2008, Creative Technology Ltd. All Rights Reserved.
*
* This source file is released under GPL v2 license (no other versions).
* See the COPYING file included in the main directory of this source
* distribution for the license terms and conditions.
*
* @File ctamixer.c
*
* @Brief
* This file contains the implementation of the Audio Mixer
* resource management object.
*
* @Author Liu Chun
* @Date May 21 2008
*
*/
#include "ctamixer.h"
#include "cthardware.h"
#include <linux/slab.h>
#define AMIXER_RESOURCE_NUM 256
#define SUM_RESOURCE_NUM 256
#define AMIXER_Y_IMMEDIATE 1
#define BLANK_SLOT 4094
static int amixer_master(struct rsc *rsc)
{
rsc->conj = 0;
return rsc->idx = container_of(rsc, struct amixer, rsc)->idx[0];
}
static int amixer_next_conj(struct rsc *rsc)
{
rsc->conj++;
return container_of(rsc, struct amixer, rsc)->idx[rsc->conj];
}
static int amixer_index(const struct rsc *rsc)
{
return container_of(rsc, struct amixer, rsc)->idx[rsc->conj];
}
static int amixer_output_slot(const struct rsc *rsc)
{
return (amixer_index(rsc) << 4) + 0x4;
}
static struct rsc_ops amixer_basic_rsc_ops = {
.master = amixer_master,
.next_conj = amixer_next_conj,
.index = amixer_index,
.output_slot = amixer_output_slot,
};
static int amixer_set_input(struct amixer *amixer, struct rsc *rsc)
{
struct hw *hw;
hw = amixer->rsc.hw;
hw->amixer_set_mode(amixer->rsc.ctrl_blk, AMIXER_Y_IMMEDIATE);
amixer->input = rsc;
if (!rsc)
hw->amixer_set_x(amixer->rsc.ctrl_blk, BLANK_SLOT);
else
hw->amixer_set_x(amixer->rsc.ctrl_blk,
rsc->ops->output_slot(rsc));
return 0;
}
/* y is a 14-bit immediate constant */
static int amixer_set_y(struct amixer *amixer, unsigned int y)
{
struct hw *hw;
hw = amixer->rsc.hw;
hw->amixer_set_y(amixer->rsc.ctrl_blk, y);
return 0;
}
static int amixer_set_invalid_squash(struct amixer *amixer, unsigned int iv)
{
struct hw *hw;
hw = amixer->rsc.hw;
hw->amixer_set_iv(amixer->rsc.ctrl_blk, iv);
return 0;
}
static int amixer_set_sum(struct amixer *amixer, struct sum *sum)
{
struct hw *hw;
hw = amixer->rsc.hw;
amixer->sum = sum;
if (!sum) {
hw->amixer_set_se(amixer->rsc.ctrl_blk, 0);
} else {
hw->amixer_set_se(amixer->rsc.ctrl_blk, 1);
hw->amixer_set_sadr(amixer->rsc.ctrl_blk,
sum->rsc.ops->index(&sum->rsc));
}
return 0;
}
static int amixer_commit_write(struct amixer *amixer)
{
struct hw *hw;
unsigned int index;
int i;
struct rsc *input;
struct sum *sum;
hw = amixer->rsc.hw;
input = amixer->input;
sum = amixer->sum;
/* Program master and conjugate resources */
amixer->rsc.ops->master(&amixer->rsc);
if (input)
input->ops->master(input);
if (sum)
sum->rsc.ops->master(&sum->rsc);
for (i = 0; i < amixer->rsc.msr; i++) {
hw->amixer_set_dirty_all(amixer->rsc.ctrl_blk);
if (input) {
hw->amixer_set_x(amixer->rsc.ctrl_blk,
input->ops->output_slot(input));
input->ops->next_conj(input);
}
if (sum) {
hw->amixer_set_sadr(amixer->rsc.ctrl_blk,
sum->rsc.ops->index(&sum->rsc));
sum->rsc.ops->next_conj(&sum->rsc);
}
index = amixer->rsc.ops->output_slot(&amixer->rsc);
hw->amixer_commit_write(hw, index, amixer->rsc.ctrl_blk);
amixer->rsc.ops->next_conj(&amixer->rsc);
}
amixer->rsc.ops->master(&amixer->rsc);
if (input)
input->ops->master(input);
if (sum)
sum->rsc.ops->master(&sum->rsc);
return 0;
}
static int amixer_commit_raw_write(struct amixer *amixer)
{
struct hw *hw;
unsigned int index;
hw = amixer->rsc.hw;
index = amixer->rsc.ops->output_slot(&amixer->rsc);
hw->amixer_commit_write(hw, index, amixer->rsc.ctrl_blk);
return 0;
}
static int amixer_get_y(struct amixer *amixer)
{
struct hw *hw;
hw = amixer->rsc.hw;
return hw->amixer_get_y(amixer->rsc.ctrl_blk);
}
static int amixer_setup(struct amixer *amixer, struct rsc *input,
unsigned int scale, struct sum *sum)
{
amixer_set_input(amixer, input);
amixer_set_y(amixer, scale);
amixer_set_sum(amixer, sum);
amixer_commit_write(amixer);
return 0;
}
static struct amixer_rsc_ops amixer_ops = {
.set_input = amixer_set_input,
.set_invalid_squash = amixer_set_invalid_squash,
.set_scale = amixer_set_y,
.set_sum = amixer_set_sum,
.commit_write = amixer_commit_write,
.commit_raw_write = amixer_commit_raw_write,
.setup = amixer_setup,
.get_scale = amixer_get_y,
};
static int amixer_rsc_init(struct amixer *amixer,
const struct amixer_desc *desc,
struct amixer_mgr *mgr)
{
int err;
err = rsc_init(&amixer->rsc, amixer->idx[0],
AMIXER, desc->msr, mgr->mgr.hw);
if (err)
return err;
/* Set amixer specific operations */
amixer->rsc.ops = &amixer_basic_rsc_ops;
amixer->ops = &amixer_ops;
amixer->input = NULL;
amixer->sum = NULL;
amixer_setup(amixer, NULL, 0, NULL);
return 0;
}
static int amixer_rsc_uninit(struct amixer *amixer)
{
amixer_setup(amixer, NULL, 0, NULL);
rsc_uninit(&amixer->rsc);
amixer->ops = NULL;
amixer->input = NULL;
amixer->sum = NULL;
return 0;
}
static int get_amixer_rsc(struct amixer_mgr *mgr,
const struct amixer_desc *desc,
struct amixer **ramixer)
{
int err, i;
unsigned int idx;
struct amixer *amixer;
unsigned long flags;
*ramixer = NULL;
/* Allocate mem for amixer resource */
amixer = kzalloc(sizeof(*amixer), GFP_KERNEL);
if (!amixer)
return -ENOMEM;
/* Check whether there are sufficient
* amixer resources to meet request. */
err = 0;
spin_lock_irqsave(&mgr->mgr_lock, flags);
for (i = 0; i < desc->msr; i++) {
err = mgr_get_resource(&mgr->mgr, 1, &idx);
if (err)
break;
amixer->idx[i] = idx;
}
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
if (err) {
printk(KERN_ERR "ctxfi: Can't meet AMIXER resource request!\n");
goto error;
}
err = amixer_rsc_init(amixer, desc, mgr);
if (err)
goto error;
*ramixer = amixer;
return 0;
error:
spin_lock_irqsave(&mgr->mgr_lock, flags);
for (i--; i >= 0; i--)
mgr_put_resource(&mgr->mgr, 1, amixer->idx[i]);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
kfree(amixer);
return err;
}
static int put_amixer_rsc(struct amixer_mgr *mgr, struct amixer *amixer)
{
unsigned long flags;
int i;
spin_lock_irqsave(&mgr->mgr_lock, flags);
for (i = 0; i < amixer->rsc.msr; i++)
mgr_put_resource(&mgr->mgr, 1, amixer->idx[i]);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
amixer_rsc_uninit(amixer);
kfree(amixer);
return 0;
}
int amixer_mgr_create(void *hw, struct amixer_mgr **ramixer_mgr)
{
int err;
struct amixer_mgr *amixer_mgr;
*ramixer_mgr = NULL;
amixer_mgr = kzalloc(sizeof(*amixer_mgr), GFP_KERNEL);
if (!amixer_mgr)
return -ENOMEM;
err = rsc_mgr_init(&amixer_mgr->mgr, AMIXER, AMIXER_RESOURCE_NUM, hw);
if (err)
goto error;
spin_lock_init(&amixer_mgr->mgr_lock);
amixer_mgr->get_amixer = get_amixer_rsc;
amixer_mgr->put_amixer = put_amixer_rsc;
*ramixer_mgr = amixer_mgr;
return 0;
error:
kfree(amixer_mgr);
return err;
}
int amixer_mgr_destroy(struct amixer_mgr *amixer_mgr)
{
rsc_mgr_uninit(&amixer_mgr->mgr);
kfree(amixer_mgr);
return 0;
}
/* SUM resource management */
static int sum_master(struct rsc *rsc)
{
rsc->conj = 0;
return rsc->idx = container_of(rsc, struct sum, rsc)->idx[0];
}
static int sum_next_conj(struct rsc *rsc)
{
rsc->conj++;
return container_of(rsc, struct sum, rsc)->idx[rsc->conj];
}
static int sum_index(const struct rsc *rsc)
{
return container_of(rsc, struct sum, rsc)->idx[rsc->conj];
}
static int sum_output_slot(const struct rsc *rsc)
{
return (sum_index(rsc) << 4) + 0xc;
}
static struct rsc_ops sum_basic_rsc_ops = {
.master = sum_master,
.next_conj = sum_next_conj,
.index = sum_index,
.output_slot = sum_output_slot,
};
static int sum_rsc_init(struct sum *sum,
const struct sum_desc *desc,
struct sum_mgr *mgr)
{
int err;
err = rsc_init(&sum->rsc, sum->idx[0], SUM, desc->msr, mgr->mgr.hw);
if (err)
return err;
sum->rsc.ops = &sum_basic_rsc_ops;
return 0;
}
static int sum_rsc_uninit(struct sum *sum)
{
rsc_uninit(&sum->rsc);
return 0;
}
static int get_sum_rsc(struct sum_mgr *mgr,
const struct sum_desc *desc,
struct sum **rsum)
{
int err, i;
unsigned int idx;
struct sum *sum;
unsigned long flags;
*rsum = NULL;
/* Allocate mem for sum resource */
sum = kzalloc(sizeof(*sum), GFP_KERNEL);
if (!sum)
return -ENOMEM;
/* Check whether there are sufficient sum resources to meet request. */
err = 0;
spin_lock_irqsave(&mgr->mgr_lock, flags);
for (i = 0; i < desc->msr; i++) {
err = mgr_get_resource(&mgr->mgr, 1, &idx);
if (err)
break;
sum->idx[i] = idx;
}
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
if (err) {
printk(KERN_ERR "ctxfi: Can't meet SUM resource request!\n");
goto error;
}
err = sum_rsc_init(sum, desc, mgr);
if (err)
goto error;
*rsum = sum;
return 0;
error:
spin_lock_irqsave(&mgr->mgr_lock, flags);
for (i--; i >= 0; i--)
mgr_put_resource(&mgr->mgr, 1, sum->idx[i]);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
kfree(sum);
return err;
}
static int put_sum_rsc(struct sum_mgr *mgr, struct sum *sum)
{
unsigned long flags;
int i;
spin_lock_irqsave(&mgr->mgr_lock, flags);
for (i = 0; i < sum->rsc.msr; i++)
mgr_put_resource(&mgr->mgr, 1, sum->idx[i]);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
sum_rsc_uninit(sum);
kfree(sum);
return 0;
}
int sum_mgr_create(void *hw, struct sum_mgr **rsum_mgr)
{
int err;
struct sum_mgr *sum_mgr;
*rsum_mgr = NULL;
sum_mgr = kzalloc(sizeof(*sum_mgr), GFP_KERNEL);
if (!sum_mgr)
return -ENOMEM;
err = rsc_mgr_init(&sum_mgr->mgr, SUM, SUM_RESOURCE_NUM, hw);
if (err)
goto error;
spin_lock_init(&sum_mgr->mgr_lock);
sum_mgr->get_sum = get_sum_rsc;
sum_mgr->put_sum = put_sum_rsc;
*rsum_mgr = sum_mgr;
return 0;
error:
kfree(sum_mgr);
return err;
}
int sum_mgr_destroy(struct sum_mgr *sum_mgr)
{
rsc_mgr_uninit(&sum_mgr->mgr);
kfree(sum_mgr);
return 0;
}
| gpl-2.0 |
toastido/N900TUVUDNF4 | fs/sdcardfs/super.c | 165 | 5613 | /*
* fs/sdcardfs/super.c
*
* Copyright (c) 2013 Samsung Electronics Co. Ltd
* Authors: Daeho Jeong, Woojoong Lee, Seunghwan Hyun,
* Sunghwan Yun, Sungjong Seo
*
* This program has been developed as a stackable file system based on
* the WrapFS which written by
*
* Copyright (c) 1998-2011 Erez Zadok
* Copyright (c) 2009 Shrikar Archak
* Copyright (c) 2003-2011 Stony Brook University
* Copyright (c) 2003-2011 The Research Foundation of SUNY
*
* This file is dual licensed. It may be redistributed and/or modified
* under the terms of the Apache 2.0 License OR version 2 of the GNU
* General Public License.
*/
#include "sdcardfs.h"
/*
* The inode cache is used with alloc_inode for both our inode info and the
* vfs inode.
*/
static struct kmem_cache *sdcardfs_inode_cachep;
/* final actions when unmounting a file system */
static void sdcardfs_put_super(struct super_block *sb)
{
struct sdcardfs_sb_info *spd;
struct super_block *s;
spd = SDCARDFS_SB(sb);
if (!spd)
return;
if(spd->obbpath_s) {
kfree(spd->obbpath_s);
path_put(&spd->obbpath);
}
/* decrement lower super references */
s = sdcardfs_lower_super(sb);
sdcardfs_set_lower_super(sb, NULL);
atomic_dec(&s->s_active);
if(spd->pkgl_id)
packagelist_destroy(spd->pkgl_id);
kfree(spd);
sb->s_fs_info = NULL;
}
static int sdcardfs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
int err;
struct path lower_path;
u32 min_blocks;
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb);
sdcardfs_get_lower_path(dentry, &lower_path);
err = vfs_statfs(&lower_path, buf);
sdcardfs_put_lower_path(dentry, &lower_path);
if (sbi->options.reserved_mb) {
/* Invalid statfs informations. */
if (buf->f_bsize == 0) {
printk(KERN_ERR "Returned block size is zero.\n");
return -EINVAL;
}
min_blocks = ((sbi->options.reserved_mb * 1024 * 1024)/buf->f_bsize);
buf->f_blocks -= min_blocks;
if (buf->f_bavail > min_blocks)
buf->f_bavail -= min_blocks;
else
buf->f_bavail = 0;
/* Make reserved blocks invisiable to media storage */
buf->f_bfree = buf->f_bavail;
}
/* set return buf to our f/s to avoid confusing user-level utils */
buf->f_type = SDCARDFS_SUPER_MAGIC;
return err;
}
/*
* @flags: numeric mount options
* @options: mount options string
*/
static int sdcardfs_remount_fs(struct super_block *sb, int *flags, char *options)
{
int err = 0;
/*
* The VFS will take care of "ro" and "rw" flags among others. We
* can safely accept a few flags (RDONLY, MANDLOCK), and honor
* SILENT, but anything else left over is an error.
*/
if ((*flags & ~(MS_RDONLY | MS_MANDLOCK | MS_SILENT)) != 0) {
printk(KERN_ERR
"sdcardfs: remount flags 0x%x unsupported\n", *flags);
err = -EINVAL;
}
return err;
}
/*
* Called by iput() when the inode reference count reached zero
* and the inode is not hashed anywhere. Used to clear anything
* that needs to be, before the inode is completely destroyed and put
* on the inode free list.
*/
static void sdcardfs_evict_inode(struct inode *inode)
{
struct inode *lower_inode;
truncate_inode_pages(&inode->i_data, 0);
end_writeback(inode);
/*
* Decrement a reference to a lower_inode, which was incremented
* by our read_inode when it was created initially.
*/
lower_inode = sdcardfs_lower_inode(inode);
sdcardfs_set_lower_inode(inode, NULL);
iput(lower_inode);
}
static struct inode *sdcardfs_alloc_inode(struct super_block *sb)
{
struct sdcardfs_inode_info *i;
i = kmem_cache_alloc(sdcardfs_inode_cachep, GFP_KERNEL);
if (!i)
return NULL;
/* memset everything up to the inode to 0 */
memset(i, 0, offsetof(struct sdcardfs_inode_info, vfs_inode));
i->vfs_inode.i_version = 1;
return &i->vfs_inode;
}
static void sdcardfs_destroy_inode(struct inode *inode)
{
kmem_cache_free(sdcardfs_inode_cachep, SDCARDFS_I(inode));
}
/* sdcardfs inode cache constructor */
static void init_once(void *obj)
{
struct sdcardfs_inode_info *i = obj;
inode_init_once(&i->vfs_inode);
}
int sdcardfs_init_inode_cache(void)
{
int err = 0;
sdcardfs_inode_cachep =
kmem_cache_create("sdcardfs_inode_cache",
sizeof(struct sdcardfs_inode_info), 0,
SLAB_RECLAIM_ACCOUNT, init_once);
if (!sdcardfs_inode_cachep)
err = -ENOMEM;
return err;
}
/* sdcardfs inode cache destructor */
void sdcardfs_destroy_inode_cache(void)
{
if (sdcardfs_inode_cachep)
kmem_cache_destroy(sdcardfs_inode_cachep);
}
/*
* Used only in nfs, to kill any pending RPC tasks, so that subsequent
* code can actually succeed and won't leave tasks that need handling.
*/
static void sdcardfs_umount_begin(struct super_block *sb)
{
struct super_block *lower_sb;
lower_sb = sdcardfs_lower_super(sb);
if (lower_sb && lower_sb->s_op && lower_sb->s_op->umount_begin)
lower_sb->s_op->umount_begin(lower_sb);
}
static int sdcardfs_show_options(struct seq_file *m, struct dentry *root)
{
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(root->d_sb);
struct sdcardfs_mount_options *opts = &sbi->options;
if (opts->fs_low_uid != 0)
seq_printf(m, ",uid=%u", opts->fs_low_uid);
if (opts->fs_low_gid != 0)
seq_printf(m, ",gid=%u", opts->fs_low_gid);
return 0;
};
const struct super_operations sdcardfs_sops = {
.put_super = sdcardfs_put_super,
.statfs = sdcardfs_statfs,
.remount_fs = sdcardfs_remount_fs,
.evict_inode = sdcardfs_evict_inode,
.umount_begin = sdcardfs_umount_begin,
.show_options = sdcardfs_show_options,
.alloc_inode = sdcardfs_alloc_inode,
.destroy_inode = sdcardfs_destroy_inode,
.drop_inode = generic_delete_inode,
};
| gpl-2.0 |
dohclude/android_kernel_htc_msm8960 | drivers/mtd/devices/lart.c | 165 | 19218 |
/*
* MTD driver for the 28F160F3 Flash Memory (non-CFI) on LART.
*
* Author: Abraham vd Merwe <abraham@2d3d.co.za>
*
* Copyright (c) 2001, 2d3D, Inc.
*
* This code 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.
*
* References:
*
* [1] 3 Volt Fast Boot Block Flash Memory" Intel Datasheet
* - Order Number: 290644-005
* - January 2000
*
* [2] MTD internal API documentation
* - http://www.linux-mtd.infradead.org/
*
* Limitations:
*
* Even though this driver is written for 3 Volt Fast Boot
* Block Flash Memory, it is rather specific to LART. With
* Minor modifications, notably the without data/address line
* mangling and different bus settings, etc. it should be
* trivial to adapt to other platforms.
*
* If somebody would sponsor me a different board, I'll
* adapt the driver (:
*/
/* debugging */
//#define LART_DEBUG
/* partition support */
#define HAVE_PARTITIONS
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mtd/mtd.h>
#ifdef HAVE_PARTITIONS
#include <linux/mtd/partitions.h>
#endif
#ifndef CONFIG_SA1100_LART
#error This is for LART architecture only
#endif
static char module_name[] = "lart";
/*
* These values is specific to 28Fxxxx3 flash memory.
* See section 2.3.1 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet
*/
#define FLASH_BLOCKSIZE_PARAM (4096 * BUSWIDTH)
#define FLASH_NUMBLOCKS_16m_PARAM 8
#define FLASH_NUMBLOCKS_8m_PARAM 8
/*
* These values is specific to 28Fxxxx3 flash memory.
* See section 2.3.2 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet
*/
#define FLASH_BLOCKSIZE_MAIN (32768 * BUSWIDTH)
#define FLASH_NUMBLOCKS_16m_MAIN 31
#define FLASH_NUMBLOCKS_8m_MAIN 15
/*
* These values are specific to LART
*/
/* general */
#define BUSWIDTH 4 /* don't change this - a lot of the code _will_ break if you change this */
#define FLASH_OFFSET 0xe8000000 /* see linux/arch/arm/mach-sa1100/lart.c */
/* blob */
#define NUM_BLOB_BLOCKS FLASH_NUMBLOCKS_16m_PARAM
#define BLOB_START 0x00000000
#define BLOB_LEN (NUM_BLOB_BLOCKS * FLASH_BLOCKSIZE_PARAM)
/* kernel */
#define NUM_KERNEL_BLOCKS 7
#define KERNEL_START (BLOB_START + BLOB_LEN)
#define KERNEL_LEN (NUM_KERNEL_BLOCKS * FLASH_BLOCKSIZE_MAIN)
/* initial ramdisk */
#define NUM_INITRD_BLOCKS 24
#define INITRD_START (KERNEL_START + KERNEL_LEN)
#define INITRD_LEN (NUM_INITRD_BLOCKS * FLASH_BLOCKSIZE_MAIN)
/*
* See section 4.0 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet
*/
#define READ_ARRAY 0x00FF00FF /* Read Array/Reset */
#define READ_ID_CODES 0x00900090 /* Read Identifier Codes */
#define ERASE_SETUP 0x00200020 /* Block Erase */
#define ERASE_CONFIRM 0x00D000D0 /* Block Erase and Program Resume */
#define PGM_SETUP 0x00400040 /* Program */
#define STATUS_READ 0x00700070 /* Read Status Register */
#define STATUS_CLEAR 0x00500050 /* Clear Status Register */
#define STATUS_BUSY 0x00800080 /* Write State Machine Status (WSMS) */
#define STATUS_ERASE_ERR 0x00200020 /* Erase Status (ES) */
#define STATUS_PGM_ERR 0x00100010 /* Program Status (PS) */
/*
* See section 4.2 in "3 Volt Fast Boot Block Flash Memory" Intel Datasheet
*/
#define FLASH_MANUFACTURER 0x00890089
#define FLASH_DEVICE_8mbit_TOP 0x88f188f1
#define FLASH_DEVICE_8mbit_BOTTOM 0x88f288f2
#define FLASH_DEVICE_16mbit_TOP 0x88f388f3
#define FLASH_DEVICE_16mbit_BOTTOM 0x88f488f4
/***************************************************************************************************/
/*
* The data line mapping on LART is as follows:
*
* U2 CPU | U3 CPU
* -------------------
* 0 20 | 0 12
* 1 22 | 1 14
* 2 19 | 2 11
* 3 17 | 3 9
* 4 24 | 4 0
* 5 26 | 5 2
* 6 31 | 6 7
* 7 29 | 7 5
* 8 21 | 8 13
* 9 23 | 9 15
* 10 18 | 10 10
* 11 16 | 11 8
* 12 25 | 12 1
* 13 27 | 13 3
* 14 30 | 14 6
* 15 28 | 15 4
*/
/* Mangle data (x) */
#define DATA_TO_FLASH(x) \
( \
(((x) & 0x08009000) >> 11) + \
(((x) & 0x00002000) >> 10) + \
(((x) & 0x04004000) >> 8) + \
(((x) & 0x00000010) >> 4) + \
(((x) & 0x91000820) >> 3) + \
(((x) & 0x22080080) >> 2) + \
((x) & 0x40000400) + \
(((x) & 0x00040040) << 1) + \
(((x) & 0x00110000) << 4) + \
(((x) & 0x00220100) << 5) + \
(((x) & 0x00800208) << 6) + \
(((x) & 0x00400004) << 9) + \
(((x) & 0x00000001) << 12) + \
(((x) & 0x00000002) << 13) \
)
/* Unmangle data (x) */
#define FLASH_TO_DATA(x) \
( \
(((x) & 0x00010012) << 11) + \
(((x) & 0x00000008) << 10) + \
(((x) & 0x00040040) << 8) + \
(((x) & 0x00000001) << 4) + \
(((x) & 0x12200104) << 3) + \
(((x) & 0x08820020) << 2) + \
((x) & 0x40000400) + \
(((x) & 0x00080080) >> 1) + \
(((x) & 0x01100000) >> 4) + \
(((x) & 0x04402000) >> 5) + \
(((x) & 0x20008200) >> 6) + \
(((x) & 0x80000800) >> 9) + \
(((x) & 0x00001000) >> 12) + \
(((x) & 0x00004000) >> 13) \
)
/*
* The address line mapping on LART is as follows:
*
* U3 CPU | U2 CPU
* -------------------
* 0 2 | 0 2
* 1 3 | 1 3
* 2 9 | 2 9
* 3 13 | 3 8
* 4 8 | 4 7
* 5 12 | 5 6
* 6 11 | 6 5
* 7 10 | 7 4
* 8 4 | 8 10
* 9 5 | 9 11
* 10 6 | 10 12
* 11 7 | 11 13
*
* BOOT BLOCK BOUNDARY
*
* 12 15 | 12 15
* 13 14 | 13 14
* 14 16 | 14 16
*
* MAIN BLOCK BOUNDARY
*
* 15 17 | 15 18
* 16 18 | 16 17
* 17 20 | 17 20
* 18 19 | 18 19
* 19 21 | 19 21
*
* As we can see from above, the addresses aren't mangled across
* block boundaries, so we don't need to worry about address
* translations except for sending/reading commands during
* initialization
*/
/* Mangle address (x) on chip U2 */
#define ADDR_TO_FLASH_U2(x) \
( \
(((x) & 0x00000f00) >> 4) + \
(((x) & 0x00042000) << 1) + \
(((x) & 0x0009c003) << 2) + \
(((x) & 0x00021080) << 3) + \
(((x) & 0x00000010) << 4) + \
(((x) & 0x00000040) << 5) + \
(((x) & 0x00000024) << 7) + \
(((x) & 0x00000008) << 10) \
)
/* Unmangle address (x) on chip U2 */
#define FLASH_U2_TO_ADDR(x) \
( \
(((x) << 4) & 0x00000f00) + \
(((x) >> 1) & 0x00042000) + \
(((x) >> 2) & 0x0009c003) + \
(((x) >> 3) & 0x00021080) + \
(((x) >> 4) & 0x00000010) + \
(((x) >> 5) & 0x00000040) + \
(((x) >> 7) & 0x00000024) + \
(((x) >> 10) & 0x00000008) \
)
/* Mangle address (x) on chip U3 */
#define ADDR_TO_FLASH_U3(x) \
( \
(((x) & 0x00000080) >> 3) + \
(((x) & 0x00000040) >> 1) + \
(((x) & 0x00052020) << 1) + \
(((x) & 0x00084f03) << 2) + \
(((x) & 0x00029010) << 3) + \
(((x) & 0x00000008) << 5) + \
(((x) & 0x00000004) << 7) \
)
/* Unmangle address (x) on chip U3 */
#define FLASH_U3_TO_ADDR(x) \
( \
(((x) << 3) & 0x00000080) + \
(((x) << 1) & 0x00000040) + \
(((x) >> 1) & 0x00052020) + \
(((x) >> 2) & 0x00084f03) + \
(((x) >> 3) & 0x00029010) + \
(((x) >> 5) & 0x00000008) + \
(((x) >> 7) & 0x00000004) \
)
/***************************************************************************************************/
static __u8 read8 (__u32 offset)
{
volatile __u8 *data = (__u8 *) (FLASH_OFFSET + offset);
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(): 0x%.8x -> 0x%.2x\n", __func__, offset, *data);
#endif
return (*data);
}
static __u32 read32 (__u32 offset)
{
volatile __u32 *data = (__u32 *) (FLASH_OFFSET + offset);
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(): 0x%.8x -> 0x%.8x\n", __func__, offset, *data);
#endif
return (*data);
}
static void write32 (__u32 x,__u32 offset)
{
volatile __u32 *data = (__u32 *) (FLASH_OFFSET + offset);
*data = x;
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(): 0x%.8x <- 0x%.8x\n", __func__, offset, *data);
#endif
}
/***************************************************************************************************/
/*
* Probe for 16mbit flash memory on a LART board without doing
* too much damage. Since we need to write 1 dword to memory,
* we're f**cked if this happens to be DRAM since we can't
* restore the memory (otherwise we might exit Read Array mode).
*
* Returns 1 if we found 16mbit flash memory on LART, 0 otherwise.
*/
static int flash_probe (void)
{
__u32 manufacturer,devtype;
/* setup "Read Identifier Codes" mode */
write32 (DATA_TO_FLASH (READ_ID_CODES),0x00000000);
/* probe U2. U2/U3 returns the same data since the first 3
* address lines is mangled in the same way */
manufacturer = FLASH_TO_DATA (read32 (ADDR_TO_FLASH_U2 (0x00000000)));
devtype = FLASH_TO_DATA (read32 (ADDR_TO_FLASH_U2 (0x00000001)));
/* put the flash back into command mode */
write32 (DATA_TO_FLASH (READ_ARRAY),0x00000000);
return (manufacturer == FLASH_MANUFACTURER && (devtype == FLASH_DEVICE_16mbit_TOP || devtype == FLASH_DEVICE_16mbit_BOTTOM));
}
/*
* Erase one block of flash memory at offset ``offset'' which is any
* address within the block which should be erased.
*
* Returns 1 if successful, 0 otherwise.
*/
static inline int erase_block (__u32 offset)
{
__u32 status;
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(): 0x%.8x\n", __func__, offset);
#endif
/* erase and confirm */
write32 (DATA_TO_FLASH (ERASE_SETUP),offset);
write32 (DATA_TO_FLASH (ERASE_CONFIRM),offset);
/* wait for block erase to finish */
do
{
write32 (DATA_TO_FLASH (STATUS_READ),offset);
status = FLASH_TO_DATA (read32 (offset));
}
while ((~status & STATUS_BUSY) != 0);
/* put the flash back into command mode */
write32 (DATA_TO_FLASH (READ_ARRAY),offset);
/* was the erase successfull? */
if ((status & STATUS_ERASE_ERR))
{
printk (KERN_WARNING "%s: erase error at address 0x%.8x.\n",module_name,offset);
return (0);
}
return (1);
}
static int flash_erase (struct mtd_info *mtd,struct erase_info *instr)
{
__u32 addr,len;
int i,first;
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(addr = 0x%.8x, len = %d)\n", __func__, instr->addr, instr->len);
#endif
/* sanity checks */
if (instr->addr + instr->len > mtd->size) return (-EINVAL);
/*
* check that both start and end of the requested erase are
* aligned with the erasesize at the appropriate addresses.
*
* skip all erase regions which are ended before the start of
* the requested erase. Actually, to save on the calculations,
* we skip to the first erase region which starts after the
* start of the requested erase, and then go back one.
*/
for (i = 0; i < mtd->numeraseregions && instr->addr >= mtd->eraseregions[i].offset; i++) ;
i--;
/*
* ok, now i is pointing at the erase region in which this
* erase request starts. Check the start of the requested
* erase range is aligned with the erase size which is in
* effect here.
*/
if (i < 0 || (instr->addr & (mtd->eraseregions[i].erasesize - 1)))
return -EINVAL;
/* Remember the erase region we start on */
first = i;
/*
* next, check that the end of the requested erase is aligned
* with the erase region at that address.
*
* as before, drop back one to point at the region in which
* the address actually falls
*/
for (; i < mtd->numeraseregions && instr->addr + instr->len >= mtd->eraseregions[i].offset; i++) ;
i--;
/* is the end aligned on a block boundary? */
if (i < 0 || ((instr->addr + instr->len) & (mtd->eraseregions[i].erasesize - 1)))
return -EINVAL;
addr = instr->addr;
len = instr->len;
i = first;
/* now erase those blocks */
while (len)
{
if (!erase_block (addr))
{
instr->state = MTD_ERASE_FAILED;
return (-EIO);
}
addr += mtd->eraseregions[i].erasesize;
len -= mtd->eraseregions[i].erasesize;
if (addr == mtd->eraseregions[i].offset + (mtd->eraseregions[i].erasesize * mtd->eraseregions[i].numblocks)) i++;
}
instr->state = MTD_ERASE_DONE;
mtd_erase_callback(instr);
return (0);
}
static int flash_read (struct mtd_info *mtd,loff_t from,size_t len,size_t *retlen,u_char *buf)
{
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(from = 0x%.8x, len = %d)\n", __func__, (__u32)from, len);
#endif
/* sanity checks */
if (!len) return (0);
if (from + len > mtd->size) return (-EINVAL);
/* we always read len bytes */
*retlen = len;
/* first, we read bytes until we reach a dword boundary */
if (from & (BUSWIDTH - 1))
{
int gap = BUSWIDTH - (from & (BUSWIDTH - 1));
while (len && gap--) *buf++ = read8 (from++), len--;
}
/* now we read dwords until we reach a non-dword boundary */
while (len >= BUSWIDTH)
{
*((__u32 *) buf) = read32 (from);
buf += BUSWIDTH;
from += BUSWIDTH;
len -= BUSWIDTH;
}
/* top up the last unaligned bytes */
if (len & (BUSWIDTH - 1))
while (len--) *buf++ = read8 (from++);
return (0);
}
/*
* Write one dword ``x'' to flash memory at offset ``offset''. ``offset''
* must be 32 bits, i.e. it must be on a dword boundary.
*
* Returns 1 if successful, 0 otherwise.
*/
static inline int write_dword (__u32 offset,__u32 x)
{
__u32 status;
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(): 0x%.8x <- 0x%.8x\n", __func__, offset, x);
#endif
/* setup writing */
write32 (DATA_TO_FLASH (PGM_SETUP),offset);
/* write the data */
write32 (x,offset);
/* wait for the write to finish */
do
{
write32 (DATA_TO_FLASH (STATUS_READ),offset);
status = FLASH_TO_DATA (read32 (offset));
}
while ((~status & STATUS_BUSY) != 0);
/* put the flash back into command mode */
write32 (DATA_TO_FLASH (READ_ARRAY),offset);
/* was the write successfull? */
if ((status & STATUS_PGM_ERR) || read32 (offset) != x)
{
printk (KERN_WARNING "%s: write error at address 0x%.8x.\n",module_name,offset);
return (0);
}
return (1);
}
static int flash_write (struct mtd_info *mtd,loff_t to,size_t len,size_t *retlen,const u_char *buf)
{
__u8 tmp[4];
int i,n;
#ifdef LART_DEBUG
printk (KERN_DEBUG "%s(to = 0x%.8x, len = %d)\n", __func__, (__u32)to, len);
#endif
*retlen = 0;
/* sanity checks */
if (!len) return (0);
if (to + len > mtd->size) return (-EINVAL);
/* first, we write a 0xFF.... padded byte until we reach a dword boundary */
if (to & (BUSWIDTH - 1))
{
__u32 aligned = to & ~(BUSWIDTH - 1);
int gap = to - aligned;
i = n = 0;
while (gap--) tmp[i++] = 0xFF;
while (len && i < BUSWIDTH) tmp[i++] = buf[n++], len--;
while (i < BUSWIDTH) tmp[i++] = 0xFF;
if (!write_dword (aligned,*((__u32 *) tmp))) return (-EIO);
to += n;
buf += n;
*retlen += n;
}
/* now we write dwords until we reach a non-dword boundary */
while (len >= BUSWIDTH)
{
if (!write_dword (to,*((__u32 *) buf))) return (-EIO);
to += BUSWIDTH;
buf += BUSWIDTH;
*retlen += BUSWIDTH;
len -= BUSWIDTH;
}
/* top up the last unaligned bytes, padded with 0xFF.... */
if (len & (BUSWIDTH - 1))
{
i = n = 0;
while (len--) tmp[i++] = buf[n++];
while (i < BUSWIDTH) tmp[i++] = 0xFF;
if (!write_dword (to,*((__u32 *) tmp))) return (-EIO);
*retlen += n;
}
return (0);
}
/***************************************************************************************************/
static struct mtd_info mtd;
static struct mtd_erase_region_info erase_regions[] = {
/* parameter blocks */
{
.offset = 0x00000000,
.erasesize = FLASH_BLOCKSIZE_PARAM,
.numblocks = FLASH_NUMBLOCKS_16m_PARAM,
},
/* main blocks */
{
.offset = FLASH_BLOCKSIZE_PARAM * FLASH_NUMBLOCKS_16m_PARAM,
.erasesize = FLASH_BLOCKSIZE_MAIN,
.numblocks = FLASH_NUMBLOCKS_16m_MAIN,
}
};
#ifdef HAVE_PARTITIONS
static struct mtd_partition lart_partitions[] = {
/* blob */
{
.name = "blob",
.offset = BLOB_START,
.size = BLOB_LEN,
},
/* kernel */
{
.name = "kernel",
.offset = KERNEL_START, /* MTDPART_OFS_APPEND */
.size = KERNEL_LEN,
},
/* initial ramdisk / file system */
{
.name = "file system",
.offset = INITRD_START, /* MTDPART_OFS_APPEND */
.size = INITRD_LEN, /* MTDPART_SIZ_FULL */
}
};
#endif
static int __init lart_flash_init (void)
{
int result;
memset (&mtd,0,sizeof (mtd));
printk ("MTD driver for LART. Written by Abraham vd Merwe <abraham@2d3d.co.za>\n");
printk ("%s: Probing for 28F160x3 flash on LART...\n",module_name);
if (!flash_probe ())
{
printk (KERN_WARNING "%s: Found no LART compatible flash device\n",module_name);
return (-ENXIO);
}
printk ("%s: This looks like a LART board to me.\n",module_name);
mtd.name = module_name;
mtd.type = MTD_NORFLASH;
mtd.writesize = 1;
mtd.flags = MTD_CAP_NORFLASH;
mtd.size = FLASH_BLOCKSIZE_PARAM * FLASH_NUMBLOCKS_16m_PARAM + FLASH_BLOCKSIZE_MAIN * FLASH_NUMBLOCKS_16m_MAIN;
mtd.erasesize = FLASH_BLOCKSIZE_MAIN;
mtd.numeraseregions = ARRAY_SIZE(erase_regions);
mtd.eraseregions = erase_regions;
mtd.erase = flash_erase;
mtd.read = flash_read;
mtd.write = flash_write;
mtd.owner = THIS_MODULE;
#ifdef LART_DEBUG
printk (KERN_DEBUG
"mtd.name = %s\n"
"mtd.size = 0x%.8x (%uM)\n"
"mtd.erasesize = 0x%.8x (%uK)\n"
"mtd.numeraseregions = %d\n",
mtd.name,
mtd.size,mtd.size / (1024*1024),
mtd.erasesize,mtd.erasesize / 1024,
mtd.numeraseregions);
if (mtd.numeraseregions)
for (result = 0; result < mtd.numeraseregions; result++)
printk (KERN_DEBUG
"\n\n"
"mtd.eraseregions[%d].offset = 0x%.8x\n"
"mtd.eraseregions[%d].erasesize = 0x%.8x (%uK)\n"
"mtd.eraseregions[%d].numblocks = %d\n",
result,mtd.eraseregions[result].offset,
result,mtd.eraseregions[result].erasesize,mtd.eraseregions[result].erasesize / 1024,
result,mtd.eraseregions[result].numblocks);
#ifdef HAVE_PARTITIONS
printk ("\npartitions = %d\n", ARRAY_SIZE(lart_partitions));
for (result = 0; result < ARRAY_SIZE(lart_partitions); result++)
printk (KERN_DEBUG
"\n\n"
"lart_partitions[%d].name = %s\n"
"lart_partitions[%d].offset = 0x%.8x\n"
"lart_partitions[%d].size = 0x%.8x (%uK)\n",
result,lart_partitions[result].name,
result,lart_partitions[result].offset,
result,lart_partitions[result].size,lart_partitions[result].size / 1024);
#endif
#endif
#ifndef HAVE_PARTITIONS
result = add_mtd_device (&mtd);
#else
result = add_mtd_partitions (&mtd,lart_partitions, ARRAY_SIZE(lart_partitions));
#endif
return (result);
}
static void __exit lart_flash_exit (void)
{
#ifndef HAVE_PARTITIONS
del_mtd_device (&mtd);
#else
del_mtd_partitions (&mtd);
#endif
}
module_init (lart_flash_init);
module_exit (lart_flash_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Abraham vd Merwe <abraham@2d3d.co.za>");
MODULE_DESCRIPTION("MTD driver for Intel 28F160F3 on LART board");
| gpl-2.0 |
cedrichu/kernel_tcp_stack_14.04LTS | net/sctp/tsnmap.c | 165 | 9751 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions manipulate sctp tsn mapping array.
*
* 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 <linux-sctp@vger.kernel.org>
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Jon Grimm <jgrimm@us.ibm.com>
* Karl Knutson <karl@athena.chicago.il.us>
* Sridhar Samudrala <sri@us.ibm.com>
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/bitmap.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
static void sctp_tsnmap_update(struct sctp_tsnmap *map);
static void sctp_tsnmap_find_gap_ack(unsigned long *map, __u16 off,
__u16 len, __u16 *start, __u16 *end);
static int sctp_tsnmap_grow(struct sctp_tsnmap *map, u16 size);
/* Initialize a block of memory as a tsnmap. */
struct sctp_tsnmap *sctp_tsnmap_init(struct sctp_tsnmap *map, __u16 len,
__u32 initial_tsn, gfp_t gfp)
{
if (!map->tsn_map) {
map->tsn_map = kzalloc(len>>3, gfp);
if (map->tsn_map == NULL)
return NULL;
map->len = len;
} else {
bitmap_zero(map->tsn_map, map->len);
}
/* Keep track of TSNs represented by tsn_map. */
map->base_tsn = initial_tsn;
map->cumulative_tsn_ack_point = initial_tsn - 1;
map->max_tsn_seen = map->cumulative_tsn_ack_point;
map->num_dup_tsns = 0;
return map;
}
void sctp_tsnmap_free(struct sctp_tsnmap *map)
{
map->len = 0;
kfree(map->tsn_map);
}
/* Test the tracking state of this TSN.
* Returns:
* 0 if the TSN has not yet been seen
* >0 if the TSN has been seen (duplicate)
* <0 if the TSN is invalid (too large to track)
*/
int sctp_tsnmap_check(const struct sctp_tsnmap *map, __u32 tsn)
{
u32 gap;
/* Check to see if this is an old TSN */
if (TSN_lte(tsn, map->cumulative_tsn_ack_point))
return 1;
/* Verify that we can hold this TSN and that it will not
* overlfow our map
*/
if (!TSN_lt(tsn, map->base_tsn + SCTP_TSN_MAP_SIZE))
return -1;
/* Calculate the index into the mapping arrays. */
gap = tsn - map->base_tsn;
/* Check to see if TSN has already been recorded. */
if (gap < map->len && test_bit(gap, map->tsn_map))
return 1;
else
return 0;
}
/* Mark this TSN as seen. */
int sctp_tsnmap_mark(struct sctp_tsnmap *map, __u32 tsn,
struct sctp_transport *trans)
{
u16 gap;
if (TSN_lt(tsn, map->base_tsn))
return 0;
gap = tsn - map->base_tsn;
if (gap >= map->len && !sctp_tsnmap_grow(map, gap + 1))
return -ENOMEM;
if (!sctp_tsnmap_has_gap(map) && gap == 0) {
/* In this case the map has no gaps and the tsn we are
* recording is the next expected tsn. We don't touch
* the map but simply bump the values.
*/
map->max_tsn_seen++;
map->cumulative_tsn_ack_point++;
if (trans)
trans->sack_generation =
trans->asoc->peer.sack_generation;
map->base_tsn++;
} else {
/* Either we already have a gap, or about to record a gap, so
* have work to do.
*
* Bump the max.
*/
if (TSN_lt(map->max_tsn_seen, tsn))
map->max_tsn_seen = tsn;
/* Mark the TSN as received. */
set_bit(gap, map->tsn_map);
/* Go fixup any internal TSN mapping variables including
* cumulative_tsn_ack_point.
*/
sctp_tsnmap_update(map);
}
return 0;
}
/* Initialize a Gap Ack Block iterator from memory being provided. */
static void sctp_tsnmap_iter_init(const struct sctp_tsnmap *map,
struct sctp_tsnmap_iter *iter)
{
/* Only start looking one past the Cumulative TSN Ack Point. */
iter->start = map->cumulative_tsn_ack_point + 1;
}
/* Get the next Gap Ack Blocks. Returns 0 if there was not another block
* to get.
*/
static int sctp_tsnmap_next_gap_ack(const struct sctp_tsnmap *map,
struct sctp_tsnmap_iter *iter,
__u16 *start, __u16 *end)
{
int ended = 0;
__u16 start_ = 0, end_ = 0, offset;
/* If there are no more gap acks possible, get out fast. */
if (TSN_lte(map->max_tsn_seen, iter->start))
return 0;
offset = iter->start - map->base_tsn;
sctp_tsnmap_find_gap_ack(map->tsn_map, offset, map->len,
&start_, &end_);
/* The Gap Ack Block happens to end at the end of the map. */
if (start_ && !end_)
end_ = map->len - 1;
/* If we found a Gap Ack Block, return the start and end and
* bump the iterator forward.
*/
if (end_) {
/* Fix up the start and end based on the
* Cumulative TSN Ack which is always 1 behind base.
*/
*start = start_ + 1;
*end = end_ + 1;
/* Move the iterator forward. */
iter->start = map->cumulative_tsn_ack_point + *end + 1;
ended = 1;
}
return ended;
}
/* Mark this and any lower TSN as seen. */
void sctp_tsnmap_skip(struct sctp_tsnmap *map, __u32 tsn)
{
u32 gap;
if (TSN_lt(tsn, map->base_tsn))
return;
if (!TSN_lt(tsn, map->base_tsn + SCTP_TSN_MAP_SIZE))
return;
/* Bump the max. */
if (TSN_lt(map->max_tsn_seen, tsn))
map->max_tsn_seen = tsn;
gap = tsn - map->base_tsn + 1;
map->base_tsn += gap;
map->cumulative_tsn_ack_point += gap;
if (gap >= map->len) {
/* If our gap is larger then the map size, just
* zero out the map.
*/
bitmap_zero(map->tsn_map, map->len);
} else {
/* If the gap is smaller than the map size,
* shift the map by 'gap' bits and update further.
*/
bitmap_shift_right(map->tsn_map, map->tsn_map, gap, map->len);
sctp_tsnmap_update(map);
}
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* This private helper function updates the tsnmap buffers and
* the Cumulative TSN Ack Point.
*/
static void sctp_tsnmap_update(struct sctp_tsnmap *map)
{
u16 len;
unsigned long zero_bit;
len = map->max_tsn_seen - map->cumulative_tsn_ack_point;
zero_bit = find_first_zero_bit(map->tsn_map, len);
if (!zero_bit)
return; /* The first 0-bit is bit 0. nothing to do */
map->base_tsn += zero_bit;
map->cumulative_tsn_ack_point += zero_bit;
bitmap_shift_right(map->tsn_map, map->tsn_map, zero_bit, map->len);
}
/* How many data chunks are we missing from our peer?
*/
__u16 sctp_tsnmap_pending(struct sctp_tsnmap *map)
{
__u32 cum_tsn = map->cumulative_tsn_ack_point;
__u32 max_tsn = map->max_tsn_seen;
__u32 base_tsn = map->base_tsn;
__u16 pending_data;
u32 gap;
pending_data = max_tsn - cum_tsn;
gap = max_tsn - base_tsn;
if (gap == 0 || gap >= map->len)
goto out;
pending_data -= bitmap_weight(map->tsn_map, gap + 1);
out:
return pending_data;
}
/* This is a private helper for finding Gap Ack Blocks. It searches a
* single array for the start and end of a Gap Ack Block.
*
* The flags "started" and "ended" tell is if we found the beginning
* or (respectively) the end of a Gap Ack Block.
*/
static void sctp_tsnmap_find_gap_ack(unsigned long *map, __u16 off,
__u16 len, __u16 *start, __u16 *end)
{
int i = off;
/* Look through the entire array, but break out
* early if we have found the end of the Gap Ack Block.
*/
/* Also, stop looking past the maximum TSN seen. */
/* Look for the start. */
i = find_next_bit(map, len, off);
if (i < len)
*start = i;
/* Look for the end. */
if (*start) {
/* We have found the start, let's find the
* end. If we find the end, break out.
*/
i = find_next_zero_bit(map, len, i);
if (i < len)
*end = i - 1;
}
}
/* Renege that we have seen a TSN. */
void sctp_tsnmap_renege(struct sctp_tsnmap *map, __u32 tsn)
{
u32 gap;
if (TSN_lt(tsn, map->base_tsn))
return;
/* Assert: TSN is in range. */
if (!TSN_lt(tsn, map->base_tsn + map->len))
return;
gap = tsn - map->base_tsn;
/* Pretend we never saw the TSN. */
clear_bit(gap, map->tsn_map);
}
/* How many gap ack blocks do we have recorded? */
__u16 sctp_tsnmap_num_gabs(struct sctp_tsnmap *map,
struct sctp_gap_ack_block *gabs)
{
struct sctp_tsnmap_iter iter;
int ngaps = 0;
/* Refresh the gap ack information. */
if (sctp_tsnmap_has_gap(map)) {
__u16 start = 0, end = 0;
sctp_tsnmap_iter_init(map, &iter);
while (sctp_tsnmap_next_gap_ack(map, &iter,
&start,
&end)) {
gabs[ngaps].start = htons(start);
gabs[ngaps].end = htons(end);
ngaps++;
if (ngaps >= SCTP_MAX_GABS)
break;
}
}
return ngaps;
}
static int sctp_tsnmap_grow(struct sctp_tsnmap *map, u16 size)
{
unsigned long *new;
unsigned long inc;
u16 len;
if (size > SCTP_TSN_MAP_SIZE)
return 0;
inc = ALIGN((size - map->len), BITS_PER_LONG) + SCTP_TSN_MAP_INCREMENT;
len = min_t(u16, map->len + inc, SCTP_TSN_MAP_SIZE);
new = kzalloc(len>>3, GFP_ATOMIC);
if (!new)
return 0;
bitmap_copy(new, map->tsn_map,
map->max_tsn_seen - map->cumulative_tsn_ack_point);
kfree(map->tsn_map);
map->tsn_map = new;
map->len = len;
return 1;
}
| gpl-2.0 |
TeamICS/heroc-kernel-2.6.35-ics | drivers/usb/gadget/at91_udc.c | 165 | 48571 | /*
* at91_udc -- driver for at91-series USB peripheral controller
*
* Copyright (C) 2004 by Thomas Rathbone
* Copyright (C) 2005 by HP Labs
* Copyright (C) 2005 by David Brownell
*
* 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.
*/
#undef VERBOSE_DEBUG
#undef PACKET_TRACE
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/clk.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <asm/byteorder.h>
#include <mach/hardware.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/system.h>
#include <asm/gpio.h>
#include <mach/board.h>
#include <mach/cpu.h>
#include <mach/at91sam9261_matrix.h>
#include "at91_udc.h"
/*
* This controller is simple and PIO-only. It's used in many AT91-series
* full speed USB controllers, including the at91rm9200 (arm920T, with MMU),
* at91sam926x (arm926ejs, with MMU), and several no-mmu versions.
*
* This driver expects the board has been wired with two GPIOs suppporting
* a VBUS sensing IRQ, and a D+ pullup. (They may be omitted, but the
* testing hasn't covered such cases.)
*
* The pullup is most important (so it's integrated on sam926x parts). It
* provides software control over whether the host enumerates the device.
*
* The VBUS sensing helps during enumeration, and allows both USB clocks
* (and the transceiver) to stay gated off until they're necessary, saving
* power. During USB suspend, the 48 MHz clock is gated off in hardware;
* it may also be gated off by software during some Linux sleep states.
*/
#define DRIVER_VERSION "3 May 2006"
static const char driver_name [] = "at91_udc";
static const char ep0name[] = "ep0";
#define at91_udp_read(dev, reg) \
__raw_readl((dev)->udp_baseaddr + (reg))
#define at91_udp_write(dev, reg, val) \
__raw_writel((val), (dev)->udp_baseaddr + (reg))
/*-------------------------------------------------------------------------*/
#ifdef CONFIG_USB_GADGET_DEBUG_FILES
#include <linux/seq_file.h>
static const char debug_filename[] = "driver/udc";
#define FOURBITS "%s%s%s%s"
#define EIGHTBITS FOURBITS FOURBITS
static void proc_ep_show(struct seq_file *s, struct at91_ep *ep)
{
static char *types[] = {
"control", "out-iso", "out-bulk", "out-int",
"BOGUS", "in-iso", "in-bulk", "in-int"};
u32 csr;
struct at91_request *req;
unsigned long flags;
local_irq_save(flags);
csr = __raw_readl(ep->creg);
/* NOTE: not collecting per-endpoint irq statistics... */
seq_printf(s, "\n");
seq_printf(s, "%s, maxpacket %d %s%s %s%s\n",
ep->ep.name, ep->ep.maxpacket,
ep->is_in ? "in" : "out",
ep->is_iso ? " iso" : "",
ep->is_pingpong
? (ep->fifo_bank ? "pong" : "ping")
: "",
ep->stopped ? " stopped" : "");
seq_printf(s, "csr %08x rxbytes=%d %s %s %s" EIGHTBITS "\n",
csr,
(csr & 0x07ff0000) >> 16,
(csr & (1 << 15)) ? "enabled" : "disabled",
(csr & (1 << 11)) ? "DATA1" : "DATA0",
types[(csr & 0x700) >> 8],
/* iff type is control then print current direction */
(!(csr & 0x700))
? ((csr & (1 << 7)) ? " IN" : " OUT")
: "",
(csr & (1 << 6)) ? " rxdatabk1" : "",
(csr & (1 << 5)) ? " forcestall" : "",
(csr & (1 << 4)) ? " txpktrdy" : "",
(csr & (1 << 3)) ? " stallsent" : "",
(csr & (1 << 2)) ? " rxsetup" : "",
(csr & (1 << 1)) ? " rxdatabk0" : "",
(csr & (1 << 0)) ? " txcomp" : "");
if (list_empty (&ep->queue))
seq_printf(s, "\t(queue empty)\n");
else list_for_each_entry (req, &ep->queue, queue) {
unsigned length = req->req.actual;
seq_printf(s, "\treq %p len %d/%d buf %p\n",
&req->req, length,
req->req.length, req->req.buf);
}
local_irq_restore(flags);
}
static void proc_irq_show(struct seq_file *s, const char *label, u32 mask)
{
int i;
seq_printf(s, "%s %04x:%s%s" FOURBITS, label, mask,
(mask & (1 << 13)) ? " wakeup" : "",
(mask & (1 << 12)) ? " endbusres" : "",
(mask & (1 << 11)) ? " sofint" : "",
(mask & (1 << 10)) ? " extrsm" : "",
(mask & (1 << 9)) ? " rxrsm" : "",
(mask & (1 << 8)) ? " rxsusp" : "");
for (i = 0; i < 8; i++) {
if (mask & (1 << i))
seq_printf(s, " ep%d", i);
}
seq_printf(s, "\n");
}
static int proc_udc_show(struct seq_file *s, void *unused)
{
struct at91_udc *udc = s->private;
struct at91_ep *ep;
u32 tmp;
seq_printf(s, "%s: version %s\n", driver_name, DRIVER_VERSION);
seq_printf(s, "vbus %s, pullup %s, %s powered%s, gadget %s\n\n",
udc->vbus ? "present" : "off",
udc->enabled
? (udc->vbus ? "active" : "enabled")
: "disabled",
udc->selfpowered ? "self" : "VBUS",
udc->suspended ? ", suspended" : "",
udc->driver ? udc->driver->driver.name : "(none)");
/* don't access registers when interface isn't clocked */
if (!udc->clocked) {
seq_printf(s, "(not clocked)\n");
return 0;
}
tmp = at91_udp_read(udc, AT91_UDP_FRM_NUM);
seq_printf(s, "frame %05x:%s%s frame=%d\n", tmp,
(tmp & AT91_UDP_FRM_OK) ? " ok" : "",
(tmp & AT91_UDP_FRM_ERR) ? " err" : "",
(tmp & AT91_UDP_NUM));
tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
seq_printf(s, "glbstate %02x:%s" FOURBITS "\n", tmp,
(tmp & AT91_UDP_RMWUPE) ? " rmwupe" : "",
(tmp & AT91_UDP_RSMINPR) ? " rsminpr" : "",
(tmp & AT91_UDP_ESR) ? " esr" : "",
(tmp & AT91_UDP_CONFG) ? " confg" : "",
(tmp & AT91_UDP_FADDEN) ? " fadden" : "");
tmp = at91_udp_read(udc, AT91_UDP_FADDR);
seq_printf(s, "faddr %03x:%s fadd=%d\n", tmp,
(tmp & AT91_UDP_FEN) ? " fen" : "",
(tmp & AT91_UDP_FADD));
proc_irq_show(s, "imr ", at91_udp_read(udc, AT91_UDP_IMR));
proc_irq_show(s, "isr ", at91_udp_read(udc, AT91_UDP_ISR));
if (udc->enabled && udc->vbus) {
proc_ep_show(s, &udc->ep[0]);
list_for_each_entry (ep, &udc->gadget.ep_list, ep.ep_list) {
if (ep->desc)
proc_ep_show(s, ep);
}
}
return 0;
}
static int proc_udc_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_udc_show, PDE(inode)->data);
}
static const struct file_operations proc_ops = {
.owner = THIS_MODULE,
.open = proc_udc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void create_debug_file(struct at91_udc *udc)
{
udc->pde = proc_create_data(debug_filename, 0, NULL, &proc_ops, udc);
}
static void remove_debug_file(struct at91_udc *udc)
{
if (udc->pde)
remove_proc_entry(debug_filename, NULL);
}
#else
static inline void create_debug_file(struct at91_udc *udc) {}
static inline void remove_debug_file(struct at91_udc *udc) {}
#endif
/*-------------------------------------------------------------------------*/
static void done(struct at91_ep *ep, struct at91_request *req, int status)
{
unsigned stopped = ep->stopped;
struct at91_udc *udc = ep->udc;
list_del_init(&req->queue);
if (req->req.status == -EINPROGRESS)
req->req.status = status;
else
status = req->req.status;
if (status && status != -ESHUTDOWN)
VDBG("%s done %p, status %d\n", ep->ep.name, req, status);
ep->stopped = 1;
req->req.complete(&ep->ep, &req->req);
ep->stopped = stopped;
/* ep0 is always ready; other endpoints need a non-empty queue */
if (list_empty(&ep->queue) && ep->int_mask != (1 << 0))
at91_udp_write(udc, AT91_UDP_IDR, ep->int_mask);
}
/*-------------------------------------------------------------------------*/
/* bits indicating OUT fifo has data ready */
#define RX_DATA_READY (AT91_UDP_RX_DATA_BK0 | AT91_UDP_RX_DATA_BK1)
/*
* Endpoint FIFO CSR bits have a mix of bits, making it unsafe to just write
* back most of the value you just read (because of side effects, including
* bits that may change after reading and before writing).
*
* Except when changing a specific bit, always write values which:
* - clear SET_FX bits (setting them could change something)
* - set CLR_FX bits (clearing them could change something)
*
* There are also state bits like FORCESTALL, EPEDS, DIR, and EPTYPE
* that shouldn't normally be changed.
*
* NOTE at91sam9260 docs mention synch between UDPCK and MCK clock domains,
* implying a need to wait for one write to complete (test relevant bits)
* before starting the next write. This shouldn't be an issue given how
* infrequently we write, except maybe for write-then-read idioms.
*/
#define SET_FX (AT91_UDP_TXPKTRDY)
#define CLR_FX (RX_DATA_READY | AT91_UDP_RXSETUP \
| AT91_UDP_STALLSENT | AT91_UDP_TXCOMP)
/* pull OUT packet data from the endpoint's fifo */
static int read_fifo (struct at91_ep *ep, struct at91_request *req)
{
u32 __iomem *creg = ep->creg;
u8 __iomem *dreg = ep->creg + (AT91_UDP_FDR(0) - AT91_UDP_CSR(0));
u32 csr;
u8 *buf;
unsigned int count, bufferspace, is_done;
buf = req->req.buf + req->req.actual;
bufferspace = req->req.length - req->req.actual;
/*
* there might be nothing to read if ep_queue() calls us,
* or if we already emptied both pingpong buffers
*/
rescan:
csr = __raw_readl(creg);
if ((csr & RX_DATA_READY) == 0)
return 0;
count = (csr & AT91_UDP_RXBYTECNT) >> 16;
if (count > ep->ep.maxpacket)
count = ep->ep.maxpacket;
if (count > bufferspace) {
DBG("%s buffer overflow\n", ep->ep.name);
req->req.status = -EOVERFLOW;
count = bufferspace;
}
__raw_readsb(dreg, buf, count);
/* release and swap pingpong mem bank */
csr |= CLR_FX;
if (ep->is_pingpong) {
if (ep->fifo_bank == 0) {
csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK0);
ep->fifo_bank = 1;
} else {
csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK1);
ep->fifo_bank = 0;
}
} else
csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK0);
__raw_writel(csr, creg);
req->req.actual += count;
is_done = (count < ep->ep.maxpacket);
if (count == bufferspace)
is_done = 1;
PACKET("%s %p out/%d%s\n", ep->ep.name, &req->req, count,
is_done ? " (done)" : "");
/*
* avoid extra trips through IRQ logic for packets already in
* the fifo ... maybe preventing an extra (expensive) OUT-NAK
*/
if (is_done)
done(ep, req, 0);
else if (ep->is_pingpong) {
/*
* One dummy read to delay the code because of a HW glitch:
* CSR returns bad RXCOUNT when read too soon after updating
* RX_DATA_BK flags.
*/
csr = __raw_readl(creg);
bufferspace -= count;
buf += count;
goto rescan;
}
return is_done;
}
/* load fifo for an IN packet */
static int write_fifo(struct at91_ep *ep, struct at91_request *req)
{
u32 __iomem *creg = ep->creg;
u32 csr = __raw_readl(creg);
u8 __iomem *dreg = ep->creg + (AT91_UDP_FDR(0) - AT91_UDP_CSR(0));
unsigned total, count, is_last;
u8 *buf;
/*
* TODO: allow for writing two packets to the fifo ... that'll
* reduce the amount of IN-NAKing, but probably won't affect
* throughput much. (Unlike preventing OUT-NAKing!)
*/
/*
* If ep_queue() calls us, the queue is empty and possibly in
* odd states like TXCOMP not yet cleared (we do it, saving at
* least one IRQ) or the fifo not yet being free. Those aren't
* issues normally (IRQ handler fast path).
*/
if (unlikely(csr & (AT91_UDP_TXCOMP | AT91_UDP_TXPKTRDY))) {
if (csr & AT91_UDP_TXCOMP) {
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_TXCOMP);
__raw_writel(csr, creg);
csr = __raw_readl(creg);
}
if (csr & AT91_UDP_TXPKTRDY)
return 0;
}
buf = req->req.buf + req->req.actual;
prefetch(buf);
total = req->req.length - req->req.actual;
if (ep->ep.maxpacket < total) {
count = ep->ep.maxpacket;
is_last = 0;
} else {
count = total;
is_last = (count < ep->ep.maxpacket) || !req->req.zero;
}
/*
* Write the packet, maybe it's a ZLP.
*
* NOTE: incrementing req->actual before we receive the ACK means
* gadget driver IN bytecounts can be wrong in fault cases. That's
* fixable with PIO drivers like this one (save "count" here, and
* do the increment later on TX irq), but not for most DMA hardware.
*
* So all gadget drivers must accept that potential error. Some
* hardware supports precise fifo status reporting, letting them
* recover when the actual bytecount matters (e.g. for USB Test
* and Measurement Class devices).
*/
__raw_writesb(dreg, buf, count);
csr &= ~SET_FX;
csr |= CLR_FX | AT91_UDP_TXPKTRDY;
__raw_writel(csr, creg);
req->req.actual += count;
PACKET("%s %p in/%d%s\n", ep->ep.name, &req->req, count,
is_last ? " (done)" : "");
if (is_last)
done(ep, req, 0);
return is_last;
}
static void nuke(struct at91_ep *ep, int status)
{
struct at91_request *req;
// terminer chaque requete dans la queue
ep->stopped = 1;
if (list_empty(&ep->queue))
return;
VDBG("%s %s\n", __func__, ep->ep.name);
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct at91_request, queue);
done(ep, req, status);
}
}
/*-------------------------------------------------------------------------*/
static int at91_ep_enable(struct usb_ep *_ep,
const struct usb_endpoint_descriptor *desc)
{
struct at91_ep *ep = container_of(_ep, struct at91_ep, ep);
struct at91_udc *dev = ep->udc;
u16 maxpacket;
u32 tmp;
unsigned long flags;
if (!_ep || !ep
|| !desc || ep->desc
|| _ep->name == ep0name
|| desc->bDescriptorType != USB_DT_ENDPOINT
|| (maxpacket = le16_to_cpu(desc->wMaxPacketSize)) == 0
|| maxpacket > ep->maxpacket) {
DBG("bad ep or descriptor\n");
return -EINVAL;
}
if (!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN) {
DBG("bogus device state\n");
return -ESHUTDOWN;
}
tmp = usb_endpoint_type(desc);
switch (tmp) {
case USB_ENDPOINT_XFER_CONTROL:
DBG("only one control endpoint\n");
return -EINVAL;
case USB_ENDPOINT_XFER_INT:
if (maxpacket > 64)
goto bogus_max;
break;
case USB_ENDPOINT_XFER_BULK:
switch (maxpacket) {
case 8:
case 16:
case 32:
case 64:
goto ok;
}
bogus_max:
DBG("bogus maxpacket %d\n", maxpacket);
return -EINVAL;
case USB_ENDPOINT_XFER_ISOC:
if (!ep->is_pingpong) {
DBG("iso requires double buffering\n");
return -EINVAL;
}
break;
}
ok:
local_irq_save(flags);
/* initialize endpoint to match this descriptor */
ep->is_in = usb_endpoint_dir_in(desc);
ep->is_iso = (tmp == USB_ENDPOINT_XFER_ISOC);
ep->stopped = 0;
if (ep->is_in)
tmp |= 0x04;
tmp <<= 8;
tmp |= AT91_UDP_EPEDS;
__raw_writel(tmp, ep->creg);
ep->desc = desc;
ep->ep.maxpacket = maxpacket;
/*
* reset/init endpoint fifo. NOTE: leaves fifo_bank alone,
* since endpoint resets don't reset hw pingpong state.
*/
at91_udp_write(dev, AT91_UDP_RST_EP, ep->int_mask);
at91_udp_write(dev, AT91_UDP_RST_EP, 0);
local_irq_restore(flags);
return 0;
}
static int at91_ep_disable (struct usb_ep * _ep)
{
struct at91_ep *ep = container_of(_ep, struct at91_ep, ep);
struct at91_udc *udc = ep->udc;
unsigned long flags;
if (ep == &ep->udc->ep[0])
return -EINVAL;
local_irq_save(flags);
nuke(ep, -ESHUTDOWN);
/* restore the endpoint's pristine config */
ep->desc = NULL;
ep->ep.maxpacket = ep->maxpacket;
/* reset fifos and endpoint */
if (ep->udc->clocked) {
at91_udp_write(udc, AT91_UDP_RST_EP, ep->int_mask);
at91_udp_write(udc, AT91_UDP_RST_EP, 0);
__raw_writel(0, ep->creg);
}
local_irq_restore(flags);
return 0;
}
/*
* this is a PIO-only driver, so there's nothing
* interesting for request or buffer allocation.
*/
static struct usb_request *
at91_ep_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags)
{
struct at91_request *req;
req = kzalloc(sizeof (struct at91_request), gfp_flags);
if (!req)
return NULL;
INIT_LIST_HEAD(&req->queue);
return &req->req;
}
static void at91_ep_free_request(struct usb_ep *_ep, struct usb_request *_req)
{
struct at91_request *req;
req = container_of(_req, struct at91_request, req);
BUG_ON(!list_empty(&req->queue));
kfree(req);
}
static int at91_ep_queue(struct usb_ep *_ep,
struct usb_request *_req, gfp_t gfp_flags)
{
struct at91_request *req;
struct at91_ep *ep;
struct at91_udc *dev;
int status;
unsigned long flags;
req = container_of(_req, struct at91_request, req);
ep = container_of(_ep, struct at91_ep, ep);
if (!_req || !_req->complete
|| !_req->buf || !list_empty(&req->queue)) {
DBG("invalid request\n");
return -EINVAL;
}
if (!_ep || (!ep->desc && ep->ep.name != ep0name)) {
DBG("invalid ep\n");
return -EINVAL;
}
dev = ep->udc;
if (!dev || !dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN) {
DBG("invalid device\n");
return -EINVAL;
}
_req->status = -EINPROGRESS;
_req->actual = 0;
local_irq_save(flags);
/* try to kickstart any empty and idle queue */
if (list_empty(&ep->queue) && !ep->stopped) {
int is_ep0;
/*
* If this control request has a non-empty DATA stage, this
* will start that stage. It works just like a non-control
* request (until the status stage starts, maybe early).
*
* If the data stage is empty, then this starts a successful
* IN/STATUS stage. (Unsuccessful ones use set_halt.)
*/
is_ep0 = (ep->ep.name == ep0name);
if (is_ep0) {
u32 tmp;
if (!dev->req_pending) {
status = -EINVAL;
goto done;
}
/*
* defer changing CONFG until after the gadget driver
* reconfigures the endpoints.
*/
if (dev->wait_for_config_ack) {
tmp = at91_udp_read(dev, AT91_UDP_GLB_STAT);
tmp ^= AT91_UDP_CONFG;
VDBG("toggle config\n");
at91_udp_write(dev, AT91_UDP_GLB_STAT, tmp);
}
if (req->req.length == 0) {
ep0_in_status:
PACKET("ep0 in/status\n");
status = 0;
tmp = __raw_readl(ep->creg);
tmp &= ~SET_FX;
tmp |= CLR_FX | AT91_UDP_TXPKTRDY;
__raw_writel(tmp, ep->creg);
dev->req_pending = 0;
goto done;
}
}
if (ep->is_in)
status = write_fifo(ep, req);
else {
status = read_fifo(ep, req);
/* IN/STATUS stage is otherwise triggered by irq */
if (status && is_ep0)
goto ep0_in_status;
}
} else
status = 0;
if (req && !status) {
list_add_tail (&req->queue, &ep->queue);
at91_udp_write(dev, AT91_UDP_IER, ep->int_mask);
}
done:
local_irq_restore(flags);
return (status < 0) ? status : 0;
}
static int at91_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
{
struct at91_ep *ep;
struct at91_request *req;
ep = container_of(_ep, struct at91_ep, ep);
if (!_ep || ep->ep.name == ep0name)
return -EINVAL;
/* make sure it's actually queued on this endpoint */
list_for_each_entry (req, &ep->queue, queue) {
if (&req->req == _req)
break;
}
if (&req->req != _req)
return -EINVAL;
done(ep, req, -ECONNRESET);
return 0;
}
static int at91_ep_set_halt(struct usb_ep *_ep, int value)
{
struct at91_ep *ep = container_of(_ep, struct at91_ep, ep);
struct at91_udc *udc = ep->udc;
u32 __iomem *creg;
u32 csr;
unsigned long flags;
int status = 0;
if (!_ep || ep->is_iso || !ep->udc->clocked)
return -EINVAL;
creg = ep->creg;
local_irq_save(flags);
csr = __raw_readl(creg);
/*
* fail with still-busy IN endpoints, ensuring correct sequencing
* of data tx then stall. note that the fifo rx bytecount isn't
* completely accurate as a tx bytecount.
*/
if (ep->is_in && (!list_empty(&ep->queue) || (csr >> 16) != 0))
status = -EAGAIN;
else {
csr |= CLR_FX;
csr &= ~SET_FX;
if (value) {
csr |= AT91_UDP_FORCESTALL;
VDBG("halt %s\n", ep->ep.name);
} else {
at91_udp_write(udc, AT91_UDP_RST_EP, ep->int_mask);
at91_udp_write(udc, AT91_UDP_RST_EP, 0);
csr &= ~AT91_UDP_FORCESTALL;
}
__raw_writel(csr, creg);
}
local_irq_restore(flags);
return status;
}
static const struct usb_ep_ops at91_ep_ops = {
.enable = at91_ep_enable,
.disable = at91_ep_disable,
.alloc_request = at91_ep_alloc_request,
.free_request = at91_ep_free_request,
.queue = at91_ep_queue,
.dequeue = at91_ep_dequeue,
.set_halt = at91_ep_set_halt,
// there's only imprecise fifo status reporting
};
/*-------------------------------------------------------------------------*/
static int at91_get_frame(struct usb_gadget *gadget)
{
struct at91_udc *udc = to_udc(gadget);
if (!to_udc(gadget)->clocked)
return -EINVAL;
return at91_udp_read(udc, AT91_UDP_FRM_NUM) & AT91_UDP_NUM;
}
static int at91_wakeup(struct usb_gadget *gadget)
{
struct at91_udc *udc = to_udc(gadget);
u32 glbstate;
int status = -EINVAL;
unsigned long flags;
DBG("%s\n", __func__ );
local_irq_save(flags);
if (!udc->clocked || !udc->suspended)
goto done;
/* NOTE: some "early versions" handle ESR differently ... */
glbstate = at91_udp_read(udc, AT91_UDP_GLB_STAT);
if (!(glbstate & AT91_UDP_ESR))
goto done;
glbstate |= AT91_UDP_ESR;
at91_udp_write(udc, AT91_UDP_GLB_STAT, glbstate);
done:
local_irq_restore(flags);
return status;
}
/* reinit == restore inital software state */
static void udc_reinit(struct at91_udc *udc)
{
u32 i;
INIT_LIST_HEAD(&udc->gadget.ep_list);
INIT_LIST_HEAD(&udc->gadget.ep0->ep_list);
for (i = 0; i < NUM_ENDPOINTS; i++) {
struct at91_ep *ep = &udc->ep[i];
if (i != 0)
list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list);
ep->desc = NULL;
ep->stopped = 0;
ep->fifo_bank = 0;
ep->ep.maxpacket = ep->maxpacket;
ep->creg = (void __iomem *) udc->udp_baseaddr + AT91_UDP_CSR(i);
// initialiser une queue par endpoint
INIT_LIST_HEAD(&ep->queue);
}
}
static void stop_activity(struct at91_udc *udc)
{
struct usb_gadget_driver *driver = udc->driver;
int i;
if (udc->gadget.speed == USB_SPEED_UNKNOWN)
driver = NULL;
udc->gadget.speed = USB_SPEED_UNKNOWN;
udc->suspended = 0;
for (i = 0; i < NUM_ENDPOINTS; i++) {
struct at91_ep *ep = &udc->ep[i];
ep->stopped = 1;
nuke(ep, -ESHUTDOWN);
}
if (driver)
driver->disconnect(&udc->gadget);
udc_reinit(udc);
}
static void clk_on(struct at91_udc *udc)
{
if (udc->clocked)
return;
udc->clocked = 1;
clk_enable(udc->iclk);
clk_enable(udc->fclk);
}
static void clk_off(struct at91_udc *udc)
{
if (!udc->clocked)
return;
udc->clocked = 0;
udc->gadget.speed = USB_SPEED_UNKNOWN;
clk_disable(udc->fclk);
clk_disable(udc->iclk);
}
/*
* activate/deactivate link with host; minimize power usage for
* inactive links by cutting clocks and transceiver power.
*/
static void pullup(struct at91_udc *udc, int is_on)
{
int active = !udc->board.pullup_active_low;
if (!udc->enabled || !udc->vbus)
is_on = 0;
DBG("%sactive\n", is_on ? "" : "in");
if (is_on) {
clk_on(udc);
at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_RXRSM);
at91_udp_write(udc, AT91_UDP_TXVC, 0);
if (cpu_is_at91rm9200())
gpio_set_value(udc->board.pullup_pin, active);
else if (cpu_is_at91sam9260() || cpu_is_at91sam9263() || cpu_is_at91sam9g20()) {
u32 txvc = at91_udp_read(udc, AT91_UDP_TXVC);
txvc |= AT91_UDP_TXVC_PUON;
at91_udp_write(udc, AT91_UDP_TXVC, txvc);
} else if (cpu_is_at91sam9261() || cpu_is_at91sam9g10()) {
u32 usbpucr;
usbpucr = at91_sys_read(AT91_MATRIX_USBPUCR);
usbpucr |= AT91_MATRIX_USBPUCR_PUON;
at91_sys_write(AT91_MATRIX_USBPUCR, usbpucr);
}
} else {
stop_activity(udc);
at91_udp_write(udc, AT91_UDP_IDR, AT91_UDP_RXRSM);
at91_udp_write(udc, AT91_UDP_TXVC, AT91_UDP_TXVC_TXVDIS);
if (cpu_is_at91rm9200())
gpio_set_value(udc->board.pullup_pin, !active);
else if (cpu_is_at91sam9260() || cpu_is_at91sam9263() || cpu_is_at91sam9g20()) {
u32 txvc = at91_udp_read(udc, AT91_UDP_TXVC);
txvc &= ~AT91_UDP_TXVC_PUON;
at91_udp_write(udc, AT91_UDP_TXVC, txvc);
} else if (cpu_is_at91sam9261() || cpu_is_at91sam9g10()) {
u32 usbpucr;
usbpucr = at91_sys_read(AT91_MATRIX_USBPUCR);
usbpucr &= ~AT91_MATRIX_USBPUCR_PUON;
at91_sys_write(AT91_MATRIX_USBPUCR, usbpucr);
}
clk_off(udc);
}
}
/* vbus is here! turn everything on that's ready */
static int at91_vbus_session(struct usb_gadget *gadget, int is_active)
{
struct at91_udc *udc = to_udc(gadget);
unsigned long flags;
// VDBG("vbus %s\n", is_active ? "on" : "off");
local_irq_save(flags);
udc->vbus = (is_active != 0);
if (udc->driver)
pullup(udc, is_active);
else
pullup(udc, 0);
local_irq_restore(flags);
return 0;
}
static int at91_pullup(struct usb_gadget *gadget, int is_on)
{
struct at91_udc *udc = to_udc(gadget);
unsigned long flags;
local_irq_save(flags);
udc->enabled = is_on = !!is_on;
pullup(udc, is_on);
local_irq_restore(flags);
return 0;
}
static int at91_set_selfpowered(struct usb_gadget *gadget, int is_on)
{
struct at91_udc *udc = to_udc(gadget);
unsigned long flags;
local_irq_save(flags);
udc->selfpowered = (is_on != 0);
local_irq_restore(flags);
return 0;
}
static const struct usb_gadget_ops at91_udc_ops = {
.get_frame = at91_get_frame,
.wakeup = at91_wakeup,
.set_selfpowered = at91_set_selfpowered,
.vbus_session = at91_vbus_session,
.pullup = at91_pullup,
/*
* VBUS-powered devices may also also want to support bigger
* power budgets after an appropriate SET_CONFIGURATION.
*/
// .vbus_power = at91_vbus_power,
};
/*-------------------------------------------------------------------------*/
static int handle_ep(struct at91_ep *ep)
{
struct at91_request *req;
u32 __iomem *creg = ep->creg;
u32 csr = __raw_readl(creg);
if (!list_empty(&ep->queue))
req = list_entry(ep->queue.next,
struct at91_request, queue);
else
req = NULL;
if (ep->is_in) {
if (csr & (AT91_UDP_STALLSENT | AT91_UDP_TXCOMP)) {
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_STALLSENT | AT91_UDP_TXCOMP);
__raw_writel(csr, creg);
}
if (req)
return write_fifo(ep, req);
} else {
if (csr & AT91_UDP_STALLSENT) {
/* STALLSENT bit == ISOERR */
if (ep->is_iso && req)
req->req.status = -EILSEQ;
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_STALLSENT);
__raw_writel(csr, creg);
csr = __raw_readl(creg);
}
if (req && (csr & RX_DATA_READY))
return read_fifo(ep, req);
}
return 0;
}
union setup {
u8 raw[8];
struct usb_ctrlrequest r;
};
static void handle_setup(struct at91_udc *udc, struct at91_ep *ep, u32 csr)
{
u32 __iomem *creg = ep->creg;
u8 __iomem *dreg = ep->creg + (AT91_UDP_FDR(0) - AT91_UDP_CSR(0));
unsigned rxcount, i = 0;
u32 tmp;
union setup pkt;
int status = 0;
/* read and ack SETUP; hard-fail for bogus packets */
rxcount = (csr & AT91_UDP_RXBYTECNT) >> 16;
if (likely(rxcount == 8)) {
while (rxcount--)
pkt.raw[i++] = __raw_readb(dreg);
if (pkt.r.bRequestType & USB_DIR_IN) {
csr |= AT91_UDP_DIR;
ep->is_in = 1;
} else {
csr &= ~AT91_UDP_DIR;
ep->is_in = 0;
}
} else {
// REVISIT this happens sometimes under load; why??
ERR("SETUP len %d, csr %08x\n", rxcount, csr);
status = -EINVAL;
}
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_RXSETUP);
__raw_writel(csr, creg);
udc->wait_for_addr_ack = 0;
udc->wait_for_config_ack = 0;
ep->stopped = 0;
if (unlikely(status != 0))
goto stall;
#define w_index le16_to_cpu(pkt.r.wIndex)
#define w_value le16_to_cpu(pkt.r.wValue)
#define w_length le16_to_cpu(pkt.r.wLength)
VDBG("SETUP %02x.%02x v%04x i%04x l%04x\n",
pkt.r.bRequestType, pkt.r.bRequest,
w_value, w_index, w_length);
/*
* A few standard requests get handled here, ones that touch
* hardware ... notably for device and endpoint features.
*/
udc->req_pending = 1;
csr = __raw_readl(creg);
csr |= CLR_FX;
csr &= ~SET_FX;
switch ((pkt.r.bRequestType << 8) | pkt.r.bRequest) {
case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
| USB_REQ_SET_ADDRESS:
__raw_writel(csr | AT91_UDP_TXPKTRDY, creg);
udc->addr = w_value;
udc->wait_for_addr_ack = 1;
udc->req_pending = 0;
/* FADDR is set later, when we ack host STATUS */
return;
case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
| USB_REQ_SET_CONFIGURATION:
tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT) & AT91_UDP_CONFG;
if (pkt.r.wValue)
udc->wait_for_config_ack = (tmp == 0);
else
udc->wait_for_config_ack = (tmp != 0);
if (udc->wait_for_config_ack)
VDBG("wait for config\n");
/* CONFG is toggled later, if gadget driver succeeds */
break;
/*
* Hosts may set or clear remote wakeup status, and
* devices may report they're VBUS powered.
*/
case ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
| USB_REQ_GET_STATUS:
tmp = (udc->selfpowered << USB_DEVICE_SELF_POWERED);
if (at91_udp_read(udc, AT91_UDP_GLB_STAT) & AT91_UDP_ESR)
tmp |= (1 << USB_DEVICE_REMOTE_WAKEUP);
PACKET("get device status\n");
__raw_writeb(tmp, dreg);
__raw_writeb(0, dreg);
goto write_in;
/* then STATUS starts later, automatically */
case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
| USB_REQ_SET_FEATURE:
if (w_value != USB_DEVICE_REMOTE_WAKEUP)
goto stall;
tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
tmp |= AT91_UDP_ESR;
at91_udp_write(udc, AT91_UDP_GLB_STAT, tmp);
goto succeed;
case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
| USB_REQ_CLEAR_FEATURE:
if (w_value != USB_DEVICE_REMOTE_WAKEUP)
goto stall;
tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
tmp &= ~AT91_UDP_ESR;
at91_udp_write(udc, AT91_UDP_GLB_STAT, tmp);
goto succeed;
/*
* Interfaces have no feature settings; this is pretty useless.
* we won't even insist the interface exists...
*/
case ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE) << 8)
| USB_REQ_GET_STATUS:
PACKET("get interface status\n");
__raw_writeb(0, dreg);
__raw_writeb(0, dreg);
goto write_in;
/* then STATUS starts later, automatically */
case ((USB_TYPE_STANDARD|USB_RECIP_INTERFACE) << 8)
| USB_REQ_SET_FEATURE:
case ((USB_TYPE_STANDARD|USB_RECIP_INTERFACE) << 8)
| USB_REQ_CLEAR_FEATURE:
goto stall;
/*
* Hosts may clear bulk/intr endpoint halt after the gadget
* driver sets it (not widely used); or set it (for testing)
*/
case ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_ENDPOINT) << 8)
| USB_REQ_GET_STATUS:
tmp = w_index & USB_ENDPOINT_NUMBER_MASK;
ep = &udc->ep[tmp];
if (tmp >= NUM_ENDPOINTS || (tmp && !ep->desc))
goto stall;
if (tmp) {
if ((w_index & USB_DIR_IN)) {
if (!ep->is_in)
goto stall;
} else if (ep->is_in)
goto stall;
}
PACKET("get %s status\n", ep->ep.name);
if (__raw_readl(ep->creg) & AT91_UDP_FORCESTALL)
tmp = (1 << USB_ENDPOINT_HALT);
else
tmp = 0;
__raw_writeb(tmp, dreg);
__raw_writeb(0, dreg);
goto write_in;
/* then STATUS starts later, automatically */
case ((USB_TYPE_STANDARD|USB_RECIP_ENDPOINT) << 8)
| USB_REQ_SET_FEATURE:
tmp = w_index & USB_ENDPOINT_NUMBER_MASK;
ep = &udc->ep[tmp];
if (w_value != USB_ENDPOINT_HALT || tmp >= NUM_ENDPOINTS)
goto stall;
if (!ep->desc || ep->is_iso)
goto stall;
if ((w_index & USB_DIR_IN)) {
if (!ep->is_in)
goto stall;
} else if (ep->is_in)
goto stall;
tmp = __raw_readl(ep->creg);
tmp &= ~SET_FX;
tmp |= CLR_FX | AT91_UDP_FORCESTALL;
__raw_writel(tmp, ep->creg);
goto succeed;
case ((USB_TYPE_STANDARD|USB_RECIP_ENDPOINT) << 8)
| USB_REQ_CLEAR_FEATURE:
tmp = w_index & USB_ENDPOINT_NUMBER_MASK;
ep = &udc->ep[tmp];
if (w_value != USB_ENDPOINT_HALT || tmp >= NUM_ENDPOINTS)
goto stall;
if (tmp == 0)
goto succeed;
if (!ep->desc || ep->is_iso)
goto stall;
if ((w_index & USB_DIR_IN)) {
if (!ep->is_in)
goto stall;
} else if (ep->is_in)
goto stall;
at91_udp_write(udc, AT91_UDP_RST_EP, ep->int_mask);
at91_udp_write(udc, AT91_UDP_RST_EP, 0);
tmp = __raw_readl(ep->creg);
tmp |= CLR_FX;
tmp &= ~(SET_FX | AT91_UDP_FORCESTALL);
__raw_writel(tmp, ep->creg);
if (!list_empty(&ep->queue))
handle_ep(ep);
goto succeed;
}
#undef w_value
#undef w_index
#undef w_length
/* pass request up to the gadget driver */
if (udc->driver)
status = udc->driver->setup(&udc->gadget, &pkt.r);
else
status = -ENODEV;
if (status < 0) {
stall:
VDBG("req %02x.%02x protocol STALL; stat %d\n",
pkt.r.bRequestType, pkt.r.bRequest, status);
csr |= AT91_UDP_FORCESTALL;
__raw_writel(csr, creg);
udc->req_pending = 0;
}
return;
succeed:
/* immediate successful (IN) STATUS after zero length DATA */
PACKET("ep0 in/status\n");
write_in:
csr |= AT91_UDP_TXPKTRDY;
__raw_writel(csr, creg);
udc->req_pending = 0;
return;
}
static void handle_ep0(struct at91_udc *udc)
{
struct at91_ep *ep0 = &udc->ep[0];
u32 __iomem *creg = ep0->creg;
u32 csr = __raw_readl(creg);
struct at91_request *req;
if (unlikely(csr & AT91_UDP_STALLSENT)) {
nuke(ep0, -EPROTO);
udc->req_pending = 0;
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_STALLSENT | AT91_UDP_FORCESTALL);
__raw_writel(csr, creg);
VDBG("ep0 stalled\n");
csr = __raw_readl(creg);
}
if (csr & AT91_UDP_RXSETUP) {
nuke(ep0, 0);
udc->req_pending = 0;
handle_setup(udc, ep0, csr);
return;
}
if (list_empty(&ep0->queue))
req = NULL;
else
req = list_entry(ep0->queue.next, struct at91_request, queue);
/* host ACKed an IN packet that we sent */
if (csr & AT91_UDP_TXCOMP) {
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_TXCOMP);
/* write more IN DATA? */
if (req && ep0->is_in) {
if (handle_ep(ep0))
udc->req_pending = 0;
/*
* Ack after:
* - last IN DATA packet (including GET_STATUS)
* - IN/STATUS for OUT DATA
* - IN/STATUS for any zero-length DATA stage
* except for the IN DATA case, the host should send
* an OUT status later, which we'll ack.
*/
} else {
udc->req_pending = 0;
__raw_writel(csr, creg);
/*
* SET_ADDRESS takes effect only after the STATUS
* (to the original address) gets acked.
*/
if (udc->wait_for_addr_ack) {
u32 tmp;
at91_udp_write(udc, AT91_UDP_FADDR,
AT91_UDP_FEN | udc->addr);
tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
tmp &= ~AT91_UDP_FADDEN;
if (udc->addr)
tmp |= AT91_UDP_FADDEN;
at91_udp_write(udc, AT91_UDP_GLB_STAT, tmp);
udc->wait_for_addr_ack = 0;
VDBG("address %d\n", udc->addr);
}
}
}
/* OUT packet arrived ... */
else if (csr & AT91_UDP_RX_DATA_BK0) {
csr |= CLR_FX;
csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK0);
/* OUT DATA stage */
if (!ep0->is_in) {
if (req) {
if (handle_ep(ep0)) {
/* send IN/STATUS */
PACKET("ep0 in/status\n");
csr = __raw_readl(creg);
csr &= ~SET_FX;
csr |= CLR_FX | AT91_UDP_TXPKTRDY;
__raw_writel(csr, creg);
udc->req_pending = 0;
}
} else if (udc->req_pending) {
/*
* AT91 hardware has a hard time with this
* "deferred response" mode for control-OUT
* transfers. (For control-IN it's fine.)
*
* The normal solution leaves OUT data in the
* fifo until the gadget driver is ready.
* We couldn't do that here without disabling
* the IRQ that tells about SETUP packets,
* e.g. when the host gets impatient...
*
* Working around it by copying into a buffer
* would almost be a non-deferred response,
* except that it wouldn't permit reliable
* stalling of the request. Instead, demand
* that gadget drivers not use this mode.
*/
DBG("no control-OUT deferred responses!\n");
__raw_writel(csr | AT91_UDP_FORCESTALL, creg);
udc->req_pending = 0;
}
/* STATUS stage for control-IN; ack. */
} else {
PACKET("ep0 out/status ACK\n");
__raw_writel(csr, creg);
/* "early" status stage */
if (req)
done(ep0, req, 0);
}
}
}
static irqreturn_t at91_udc_irq (int irq, void *_udc)
{
struct at91_udc *udc = _udc;
u32 rescans = 5;
int disable_clock = 0;
if (!udc->clocked) {
clk_on(udc);
disable_clock = 1;
}
while (rescans--) {
u32 status;
status = at91_udp_read(udc, AT91_UDP_ISR)
& at91_udp_read(udc, AT91_UDP_IMR);
if (!status)
break;
/* USB reset irq: not maskable */
if (status & AT91_UDP_ENDBUSRES) {
at91_udp_write(udc, AT91_UDP_IDR, ~MINIMUS_INTERRUPTUS);
at91_udp_write(udc, AT91_UDP_IER, MINIMUS_INTERRUPTUS);
/* Atmel code clears this irq twice */
at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_ENDBUSRES);
at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_ENDBUSRES);
VDBG("end bus reset\n");
udc->addr = 0;
stop_activity(udc);
/* enable ep0 */
at91_udp_write(udc, AT91_UDP_CSR(0),
AT91_UDP_EPEDS | AT91_UDP_EPTYPE_CTRL);
udc->gadget.speed = USB_SPEED_FULL;
udc->suspended = 0;
at91_udp_write(udc, AT91_UDP_IER, AT91_UDP_EP(0));
/*
* NOTE: this driver keeps clocks off unless the
* USB host is present. That saves power, but for
* boards that don't support VBUS detection, both
* clocks need to be active most of the time.
*/
/* host initiated suspend (3+ms bus idle) */
} else if (status & AT91_UDP_RXSUSP) {
at91_udp_write(udc, AT91_UDP_IDR, AT91_UDP_RXSUSP);
at91_udp_write(udc, AT91_UDP_IER, AT91_UDP_RXRSM);
at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_RXSUSP);
// VDBG("bus suspend\n");
if (udc->suspended)
continue;
udc->suspended = 1;
/*
* NOTE: when suspending a VBUS-powered device, the
* gadget driver should switch into slow clock mode
* and then into standby to avoid drawing more than
* 500uA power (2500uA for some high-power configs).
*/
if (udc->driver && udc->driver->suspend)
udc->driver->suspend(&udc->gadget);
/* host initiated resume */
} else if (status & AT91_UDP_RXRSM) {
at91_udp_write(udc, AT91_UDP_IDR, AT91_UDP_RXRSM);
at91_udp_write(udc, AT91_UDP_IER, AT91_UDP_RXSUSP);
at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_RXRSM);
// VDBG("bus resume\n");
if (!udc->suspended)
continue;
udc->suspended = 0;
/*
* NOTE: for a VBUS-powered device, the gadget driver
* would normally want to switch out of slow clock
* mode into normal mode.
*/
if (udc->driver && udc->driver->resume)
udc->driver->resume(&udc->gadget);
/* endpoint IRQs are cleared by handling them */
} else {
int i;
unsigned mask = 1;
struct at91_ep *ep = &udc->ep[1];
if (status & mask)
handle_ep0(udc);
for (i = 1; i < NUM_ENDPOINTS; i++) {
mask <<= 1;
if (status & mask)
handle_ep(ep);
ep++;
}
}
}
if (disable_clock)
clk_off(udc);
return IRQ_HANDLED;
}
/*-------------------------------------------------------------------------*/
static void nop_release(struct device *dev)
{
/* nothing to free */
}
static struct at91_udc controller = {
.gadget = {
.ops = &at91_udc_ops,
.ep0 = &controller.ep[0].ep,
.name = driver_name,
.dev = {
.init_name = "gadget",
.release = nop_release,
}
},
.ep[0] = {
.ep = {
.name = ep0name,
.ops = &at91_ep_ops,
},
.udc = &controller,
.maxpacket = 8,
.int_mask = 1 << 0,
},
.ep[1] = {
.ep = {
.name = "ep1",
.ops = &at91_ep_ops,
},
.udc = &controller,
.is_pingpong = 1,
.maxpacket = 64,
.int_mask = 1 << 1,
},
.ep[2] = {
.ep = {
.name = "ep2",
.ops = &at91_ep_ops,
},
.udc = &controller,
.is_pingpong = 1,
.maxpacket = 64,
.int_mask = 1 << 2,
},
.ep[3] = {
.ep = {
/* could actually do bulk too */
.name = "ep3-int",
.ops = &at91_ep_ops,
},
.udc = &controller,
.maxpacket = 8,
.int_mask = 1 << 3,
},
.ep[4] = {
.ep = {
.name = "ep4",
.ops = &at91_ep_ops,
},
.udc = &controller,
.is_pingpong = 1,
.maxpacket = 256,
.int_mask = 1 << 4,
},
.ep[5] = {
.ep = {
.name = "ep5",
.ops = &at91_ep_ops,
},
.udc = &controller,
.is_pingpong = 1,
.maxpacket = 256,
.int_mask = 1 << 5,
},
/* ep6 and ep7 are also reserved (custom silicon might use them) */
};
static irqreturn_t at91_vbus_irq(int irq, void *_udc)
{
struct at91_udc *udc = _udc;
unsigned value;
/* vbus needs at least brief debouncing */
udelay(10);
value = gpio_get_value(udc->board.vbus_pin);
if (value != udc->vbus)
at91_vbus_session(&udc->gadget, value);
return IRQ_HANDLED;
}
int usb_gadget_register_driver (struct usb_gadget_driver *driver)
{
struct at91_udc *udc = &controller;
int retval;
if (!driver
|| driver->speed < USB_SPEED_FULL
|| !driver->bind
|| !driver->setup) {
DBG("bad parameter.\n");
return -EINVAL;
}
if (udc->driver) {
DBG("UDC already has a gadget driver\n");
return -EBUSY;
}
udc->driver = driver;
udc->gadget.dev.driver = &driver->driver;
dev_set_drvdata(&udc->gadget.dev, &driver->driver);
udc->enabled = 1;
udc->selfpowered = 1;
retval = driver->bind(&udc->gadget);
if (retval) {
DBG("driver->bind() returned %d\n", retval);
udc->driver = NULL;
udc->gadget.dev.driver = NULL;
dev_set_drvdata(&udc->gadget.dev, NULL);
udc->enabled = 0;
udc->selfpowered = 0;
return retval;
}
local_irq_disable();
pullup(udc, 1);
local_irq_enable();
DBG("bound to %s\n", driver->driver.name);
return 0;
}
EXPORT_SYMBOL (usb_gadget_register_driver);
int usb_gadget_unregister_driver (struct usb_gadget_driver *driver)
{
struct at91_udc *udc = &controller;
if (!driver || driver != udc->driver || !driver->unbind)
return -EINVAL;
local_irq_disable();
udc->enabled = 0;
at91_udp_write(udc, AT91_UDP_IDR, ~0);
pullup(udc, 0);
local_irq_enable();
driver->unbind(&udc->gadget);
udc->gadget.dev.driver = NULL;
dev_set_drvdata(&udc->gadget.dev, NULL);
udc->driver = NULL;
DBG("unbound from %s\n", driver->driver.name);
return 0;
}
EXPORT_SYMBOL (usb_gadget_unregister_driver);
/*-------------------------------------------------------------------------*/
static void at91udc_shutdown(struct platform_device *dev)
{
/* force disconnect on reboot */
pullup(platform_get_drvdata(dev), 0);
}
static int __init at91udc_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct at91_udc *udc;
int retval;
struct resource *res;
if (!dev->platform_data) {
/* small (so we copy it) but critical! */
DBG("missing platform_data\n");
return -ENODEV;
}
if (pdev->num_resources != 2) {
DBG("invalid num_resources\n");
return -ENODEV;
}
if ((pdev->resource[0].flags != IORESOURCE_MEM)
|| (pdev->resource[1].flags != IORESOURCE_IRQ)) {
DBG("invalid resource type\n");
return -ENODEV;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENXIO;
if (!request_mem_region(res->start, resource_size(res), driver_name)) {
DBG("someone's using UDC memory\n");
return -EBUSY;
}
/* init software state */
udc = &controller;
udc->gadget.dev.parent = dev;
udc->board = *(struct at91_udc_data *) dev->platform_data;
udc->pdev = pdev;
udc->enabled = 0;
/* rm9200 needs manual D+ pullup; off by default */
if (cpu_is_at91rm9200()) {
if (udc->board.pullup_pin <= 0) {
DBG("no D+ pullup?\n");
retval = -ENODEV;
goto fail0;
}
retval = gpio_request(udc->board.pullup_pin, "udc_pullup");
if (retval) {
DBG("D+ pullup is busy\n");
goto fail0;
}
gpio_direction_output(udc->board.pullup_pin,
udc->board.pullup_active_low);
}
/* newer chips have more FIFO memory than rm9200 */
if (cpu_is_at91sam9260() || cpu_is_at91sam9g20()) {
udc->ep[0].maxpacket = 64;
udc->ep[3].maxpacket = 64;
udc->ep[4].maxpacket = 512;
udc->ep[5].maxpacket = 512;
} else if (cpu_is_at91sam9261() || cpu_is_at91sam9g10()) {
udc->ep[3].maxpacket = 64;
} else if (cpu_is_at91sam9263()) {
udc->ep[0].maxpacket = 64;
udc->ep[3].maxpacket = 64;
}
udc->udp_baseaddr = ioremap(res->start, resource_size(res));
if (!udc->udp_baseaddr) {
retval = -ENOMEM;
goto fail0a;
}
udc_reinit(udc);
/* get interface and function clocks */
udc->iclk = clk_get(dev, "udc_clk");
udc->fclk = clk_get(dev, "udpck");
if (IS_ERR(udc->iclk) || IS_ERR(udc->fclk)) {
DBG("clocks missing\n");
retval = -ENODEV;
/* NOTE: we "know" here that refcounts on these are NOPs */
goto fail0b;
}
retval = device_register(&udc->gadget.dev);
if (retval < 0)
goto fail0b;
/* don't do anything until we have both gadget driver and VBUS */
clk_enable(udc->iclk);
at91_udp_write(udc, AT91_UDP_TXVC, AT91_UDP_TXVC_TXVDIS);
at91_udp_write(udc, AT91_UDP_IDR, 0xffffffff);
/* Clear all pending interrupts - UDP may be used by bootloader. */
at91_udp_write(udc, AT91_UDP_ICR, 0xffffffff);
clk_disable(udc->iclk);
/* request UDC and maybe VBUS irqs */
udc->udp_irq = platform_get_irq(pdev, 0);
retval = request_irq(udc->udp_irq, at91_udc_irq,
IRQF_DISABLED, driver_name, udc);
if (retval < 0) {
DBG("request irq %d failed\n", udc->udp_irq);
goto fail1;
}
if (udc->board.vbus_pin > 0) {
retval = gpio_request(udc->board.vbus_pin, "udc_vbus");
if (retval < 0) {
DBG("request vbus pin failed\n");
goto fail2;
}
gpio_direction_input(udc->board.vbus_pin);
/*
* Get the initial state of VBUS - we cannot expect
* a pending interrupt.
*/
udc->vbus = gpio_get_value(udc->board.vbus_pin);
if (request_irq(udc->board.vbus_pin, at91_vbus_irq,
IRQF_DISABLED, driver_name, udc)) {
DBG("request vbus irq %d failed\n",
udc->board.vbus_pin);
retval = -EBUSY;
goto fail3;
}
} else {
DBG("no VBUS detection, assuming always-on\n");
udc->vbus = 1;
}
dev_set_drvdata(dev, udc);
device_init_wakeup(dev, 1);
create_debug_file(udc);
INFO("%s version %s\n", driver_name, DRIVER_VERSION);
return 0;
fail3:
if (udc->board.vbus_pin > 0)
gpio_free(udc->board.vbus_pin);
fail2:
free_irq(udc->udp_irq, udc);
fail1:
device_unregister(&udc->gadget.dev);
fail0b:
iounmap(udc->udp_baseaddr);
fail0a:
if (cpu_is_at91rm9200())
gpio_free(udc->board.pullup_pin);
fail0:
release_mem_region(res->start, resource_size(res));
DBG("%s probe failed, %d\n", driver_name, retval);
return retval;
}
static int __exit at91udc_remove(struct platform_device *pdev)
{
struct at91_udc *udc = platform_get_drvdata(pdev);
struct resource *res;
DBG("remove\n");
if (udc->driver)
return -EBUSY;
pullup(udc, 0);
device_init_wakeup(&pdev->dev, 0);
remove_debug_file(udc);
if (udc->board.vbus_pin > 0) {
free_irq(udc->board.vbus_pin, udc);
gpio_free(udc->board.vbus_pin);
}
free_irq(udc->udp_irq, udc);
device_unregister(&udc->gadget.dev);
iounmap(udc->udp_baseaddr);
if (cpu_is_at91rm9200())
gpio_free(udc->board.pullup_pin);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
clk_put(udc->iclk);
clk_put(udc->fclk);
return 0;
}
#ifdef CONFIG_PM
static int at91udc_suspend(struct platform_device *pdev, pm_message_t mesg)
{
struct at91_udc *udc = platform_get_drvdata(pdev);
int wake = udc->driver && device_may_wakeup(&pdev->dev);
/* Unless we can act normally to the host (letting it wake us up
* whenever it has work for us) force disconnect. Wakeup requires
* PLLB for USB events (signaling for reset, wakeup, or incoming
* tokens) and VBUS irqs (on systems which support them).
*/
if ((!udc->suspended && udc->addr)
|| !wake
|| at91_suspend_entering_slow_clock()) {
pullup(udc, 0);
wake = 0;
} else
enable_irq_wake(udc->udp_irq);
udc->active_suspend = wake;
if (udc->board.vbus_pin > 0 && wake)
enable_irq_wake(udc->board.vbus_pin);
return 0;
}
static int at91udc_resume(struct platform_device *pdev)
{
struct at91_udc *udc = platform_get_drvdata(pdev);
if (udc->board.vbus_pin > 0 && udc->active_suspend)
disable_irq_wake(udc->board.vbus_pin);
/* maybe reconnect to host; if so, clocks on */
if (udc->active_suspend)
disable_irq_wake(udc->udp_irq);
else
pullup(udc, 1);
return 0;
}
#else
#define at91udc_suspend NULL
#define at91udc_resume NULL
#endif
static struct platform_driver at91_udc_driver = {
.remove = __exit_p(at91udc_remove),
.shutdown = at91udc_shutdown,
.suspend = at91udc_suspend,
.resume = at91udc_resume,
.driver = {
.name = (char *) driver_name,
.owner = THIS_MODULE,
},
};
static int __init udc_init_module(void)
{
return platform_driver_probe(&at91_udc_driver, at91udc_probe);
}
module_init(udc_init_module);
static void __exit udc_exit_module(void)
{
platform_driver_unregister(&at91_udc_driver);
}
module_exit(udc_exit_module);
MODULE_DESCRIPTION("AT91 udc driver");
MODULE_AUTHOR("Thomas Rathbone, David Brownell");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:at91_udc");
| gpl-2.0 |
Pingmin/linux | drivers/platform/x86/msi-laptop.c | 421 | 28101 | // SPDX-License-Identifier: GPL-2.0-or-later
/*-*-linux-c-*-*/
/*
Copyright (C) 2006 Lennart Poettering <mzxreary (at) 0pointer (dot) de>
*/
/*
* msi-laptop.c - MSI S270 laptop support. This laptop is sold under
* various brands, including "Cytron/TCM/Medion/Tchibo MD96100".
*
* Driver also supports S271, S420 models.
*
* This driver exports a few files in /sys/devices/platform/msi-laptop-pf/:
*
* lcd_level - Screen brightness: contains a single integer in the
* range 0..8. (rw)
*
* auto_brightness - Enable automatic brightness control: contains
* either 0 or 1. If set to 1 the hardware adjusts the screen
* brightness automatically when the power cord is
* plugged/unplugged. (rw)
*
* wlan - WLAN subsystem enabled: contains either 0 or 1. (ro)
*
* bluetooth - Bluetooth subsystem enabled: contains either 0 or 1
* Please note that this file is constantly 0 if no Bluetooth
* hardware is available. (ro)
*
* In addition to these platform device attributes the driver
* registers itself in the Linux backlight control subsystem and is
* available to userspace under /sys/class/backlight/msi-laptop-bl/.
*
* This driver might work on other laptops produced by MSI. If you
* want to try it you can pass force=1 as argument to the module which
* will force it to load even when the DMI data doesn't identify the
* laptop as MSI S270. YMMV.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/dmi.h>
#include <linux/backlight.h>
#include <linux/platform_device.h>
#include <linux/rfkill.h>
#include <linux/i8042.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <acpi/video.h>
#define MSI_DRIVER_VERSION "0.5"
#define MSI_LCD_LEVEL_MAX 9
#define MSI_EC_COMMAND_WIRELESS 0x10
#define MSI_EC_COMMAND_LCD_LEVEL 0x11
#define MSI_STANDARD_EC_COMMAND_ADDRESS 0x2e
#define MSI_STANDARD_EC_BLUETOOTH_MASK (1 << 0)
#define MSI_STANDARD_EC_WEBCAM_MASK (1 << 1)
#define MSI_STANDARD_EC_WLAN_MASK (1 << 3)
#define MSI_STANDARD_EC_3G_MASK (1 << 4)
/* For set SCM load flag to disable BIOS fn key */
#define MSI_STANDARD_EC_SCM_LOAD_ADDRESS 0x2d
#define MSI_STANDARD_EC_SCM_LOAD_MASK (1 << 0)
#define MSI_STANDARD_EC_FUNCTIONS_ADDRESS 0xe4
/* Power LED is orange - Turbo mode */
#define MSI_STANDARD_EC_TURBO_MASK (1 << 1)
/* Power LED is green - ECO mode */
#define MSI_STANDARD_EC_ECO_MASK (1 << 3)
/* Touchpad is turned on */
#define MSI_STANDARD_EC_TOUCHPAD_MASK (1 << 4)
/* If this bit != bit 1, turbo mode can't be toggled */
#define MSI_STANDARD_EC_TURBO_COOLDOWN_MASK (1 << 7)
#define MSI_STANDARD_EC_FAN_ADDRESS 0x33
/* If zero, fan rotates at maximal speed */
#define MSI_STANDARD_EC_AUTOFAN_MASK (1 << 0)
#ifdef CONFIG_PM_SLEEP
static int msi_laptop_resume(struct device *device);
#endif
static SIMPLE_DEV_PM_OPS(msi_laptop_pm, NULL, msi_laptop_resume);
#define MSI_STANDARD_EC_DEVICES_EXISTS_ADDRESS 0x2f
static bool force;
module_param(force, bool, 0);
MODULE_PARM_DESC(force, "Force driver load, ignore DMI data");
static int auto_brightness;
module_param(auto_brightness, int, 0);
MODULE_PARM_DESC(auto_brightness, "Enable automatic brightness control (0: disabled; 1: enabled; 2: don't touch)");
static const struct key_entry msi_laptop_keymap[] = {
{KE_KEY, KEY_TOUCHPAD_ON, {KEY_TOUCHPAD_ON} }, /* Touch Pad On */
{KE_KEY, KEY_TOUCHPAD_OFF, {KEY_TOUCHPAD_OFF} },/* Touch Pad On */
{KE_END, 0}
};
static struct input_dev *msi_laptop_input_dev;
static int wlan_s, bluetooth_s, threeg_s;
static int threeg_exists;
static struct rfkill *rfk_wlan, *rfk_bluetooth, *rfk_threeg;
/* MSI laptop quirks */
struct quirk_entry {
bool old_ec_model;
/* Some MSI 3G netbook only have one fn key to control
* Wlan/Bluetooth/3G, those netbook will load the SCM (windows app) to
* disable the original Wlan/Bluetooth control by BIOS when user press
* fn key, then control Wlan/Bluetooth/3G by SCM (software control by
* OS). Without SCM, user cann't on/off 3G module on those 3G netbook.
* On Linux, msi-laptop driver will do the same thing to disable the
* original BIOS control, then might need use HAL or other userland
* application to do the software control that simulate with SCM.
* e.g. MSI N034 netbook
*/
bool load_scm_model;
/* Some MSI laptops need delay before reading from EC */
bool ec_delay;
/* Some MSI Wind netbooks (e.g. MSI Wind U100) need loading SCM to get
* some features working (e.g. ECO mode), but we cannot change
* Wlan/Bluetooth state in software and we can only read its state.
*/
bool ec_read_only;
};
static struct quirk_entry *quirks;
/* Hardware access */
static int set_lcd_level(int level)
{
u8 buf[2];
if (level < 0 || level >= MSI_LCD_LEVEL_MAX)
return -EINVAL;
buf[0] = 0x80;
buf[1] = (u8) (level*31);
return ec_transaction(MSI_EC_COMMAND_LCD_LEVEL, buf, sizeof(buf),
NULL, 0);
}
static int get_lcd_level(void)
{
u8 wdata = 0, rdata;
int result;
result = ec_transaction(MSI_EC_COMMAND_LCD_LEVEL, &wdata, 1,
&rdata, 1);
if (result < 0)
return result;
return (int) rdata / 31;
}
static int get_auto_brightness(void)
{
u8 wdata = 4, rdata;
int result;
result = ec_transaction(MSI_EC_COMMAND_LCD_LEVEL, &wdata, 1,
&rdata, 1);
if (result < 0)
return result;
return !!(rdata & 8);
}
static int set_auto_brightness(int enable)
{
u8 wdata[2], rdata;
int result;
wdata[0] = 4;
result = ec_transaction(MSI_EC_COMMAND_LCD_LEVEL, wdata, 1,
&rdata, 1);
if (result < 0)
return result;
wdata[0] = 0x84;
wdata[1] = (rdata & 0xF7) | (enable ? 8 : 0);
return ec_transaction(MSI_EC_COMMAND_LCD_LEVEL, wdata, 2,
NULL, 0);
}
static ssize_t set_device_state(const char *buf, size_t count, u8 mask)
{
int status;
u8 wdata = 0, rdata;
int result;
if (sscanf(buf, "%i", &status) != 1 || (status < 0 || status > 1))
return -EINVAL;
if (quirks->ec_read_only)
return -EOPNOTSUPP;
/* read current device state */
result = ec_read(MSI_STANDARD_EC_COMMAND_ADDRESS, &rdata);
if (result < 0)
return result;
if (!!(rdata & mask) != status) {
/* reverse device bit */
if (rdata & mask)
wdata = rdata & ~mask;
else
wdata = rdata | mask;
result = ec_write(MSI_STANDARD_EC_COMMAND_ADDRESS, wdata);
if (result < 0)
return result;
}
return count;
}
static int get_wireless_state(int *wlan, int *bluetooth)
{
u8 wdata = 0, rdata;
int result;
result = ec_transaction(MSI_EC_COMMAND_WIRELESS, &wdata, 1, &rdata, 1);
if (result < 0)
return result;
if (wlan)
*wlan = !!(rdata & 8);
if (bluetooth)
*bluetooth = !!(rdata & 128);
return 0;
}
static int get_wireless_state_ec_standard(void)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_COMMAND_ADDRESS, &rdata);
if (result < 0)
return result;
wlan_s = !!(rdata & MSI_STANDARD_EC_WLAN_MASK);
bluetooth_s = !!(rdata & MSI_STANDARD_EC_BLUETOOTH_MASK);
threeg_s = !!(rdata & MSI_STANDARD_EC_3G_MASK);
return 0;
}
static int get_threeg_exists(void)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_DEVICES_EXISTS_ADDRESS, &rdata);
if (result < 0)
return result;
threeg_exists = !!(rdata & MSI_STANDARD_EC_3G_MASK);
return 0;
}
/* Backlight device stuff */
static int bl_get_brightness(struct backlight_device *b)
{
return get_lcd_level();
}
static int bl_update_status(struct backlight_device *b)
{
return set_lcd_level(b->props.brightness);
}
static const struct backlight_ops msibl_ops = {
.get_brightness = bl_get_brightness,
.update_status = bl_update_status,
};
static struct backlight_device *msibl_device;
/* Platform device */
static ssize_t show_wlan(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret, enabled = 0;
if (quirks->old_ec_model) {
ret = get_wireless_state(&enabled, NULL);
} else {
ret = get_wireless_state_ec_standard();
enabled = wlan_s;
}
if (ret < 0)
return ret;
return sprintf(buf, "%i\n", enabled);
}
static ssize_t store_wlan(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
return set_device_state(buf, count, MSI_STANDARD_EC_WLAN_MASK);
}
static ssize_t show_bluetooth(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret, enabled = 0;
if (quirks->old_ec_model) {
ret = get_wireless_state(NULL, &enabled);
} else {
ret = get_wireless_state_ec_standard();
enabled = bluetooth_s;
}
if (ret < 0)
return ret;
return sprintf(buf, "%i\n", enabled);
}
static ssize_t store_bluetooth(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
return set_device_state(buf, count, MSI_STANDARD_EC_BLUETOOTH_MASK);
}
static ssize_t show_threeg(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
/* old msi ec not support 3G */
if (quirks->old_ec_model)
return -ENODEV;
ret = get_wireless_state_ec_standard();
if (ret < 0)
return ret;
return sprintf(buf, "%i\n", threeg_s);
}
static ssize_t store_threeg(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
return set_device_state(buf, count, MSI_STANDARD_EC_3G_MASK);
}
static ssize_t show_lcd_level(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
ret = get_lcd_level();
if (ret < 0)
return ret;
return sprintf(buf, "%i\n", ret);
}
static ssize_t store_lcd_level(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int level, ret;
if (sscanf(buf, "%i", &level) != 1 ||
(level < 0 || level >= MSI_LCD_LEVEL_MAX))
return -EINVAL;
ret = set_lcd_level(level);
if (ret < 0)
return ret;
return count;
}
static ssize_t show_auto_brightness(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
ret = get_auto_brightness();
if (ret < 0)
return ret;
return sprintf(buf, "%i\n", ret);
}
static ssize_t store_auto_brightness(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int enable, ret;
if (sscanf(buf, "%i", &enable) != 1 || (enable != (enable & 1)))
return -EINVAL;
ret = set_auto_brightness(enable);
if (ret < 0)
return ret;
return count;
}
static ssize_t show_touchpad(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_FUNCTIONS_ADDRESS, &rdata);
if (result < 0)
return result;
return sprintf(buf, "%i\n", !!(rdata & MSI_STANDARD_EC_TOUCHPAD_MASK));
}
static ssize_t show_turbo(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_FUNCTIONS_ADDRESS, &rdata);
if (result < 0)
return result;
return sprintf(buf, "%i\n", !!(rdata & MSI_STANDARD_EC_TURBO_MASK));
}
static ssize_t show_eco(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_FUNCTIONS_ADDRESS, &rdata);
if (result < 0)
return result;
return sprintf(buf, "%i\n", !!(rdata & MSI_STANDARD_EC_ECO_MASK));
}
static ssize_t show_turbo_cooldown(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_FUNCTIONS_ADDRESS, &rdata);
if (result < 0)
return result;
return sprintf(buf, "%i\n", (!!(rdata & MSI_STANDARD_EC_TURBO_MASK)) |
(!!(rdata & MSI_STANDARD_EC_TURBO_COOLDOWN_MASK) << 1));
}
static ssize_t show_auto_fan(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_FAN_ADDRESS, &rdata);
if (result < 0)
return result;
return sprintf(buf, "%i\n", !!(rdata & MSI_STANDARD_EC_AUTOFAN_MASK));
}
static ssize_t store_auto_fan(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int enable, result;
if (sscanf(buf, "%i", &enable) != 1 || (enable != (enable & 1)))
return -EINVAL;
result = ec_write(MSI_STANDARD_EC_FAN_ADDRESS, enable);
if (result < 0)
return result;
return count;
}
static DEVICE_ATTR(lcd_level, 0644, show_lcd_level, store_lcd_level);
static DEVICE_ATTR(auto_brightness, 0644, show_auto_brightness,
store_auto_brightness);
static DEVICE_ATTR(bluetooth, 0444, show_bluetooth, NULL);
static DEVICE_ATTR(wlan, 0444, show_wlan, NULL);
static DEVICE_ATTR(threeg, 0444, show_threeg, NULL);
static DEVICE_ATTR(touchpad, 0444, show_touchpad, NULL);
static DEVICE_ATTR(turbo_mode, 0444, show_turbo, NULL);
static DEVICE_ATTR(eco_mode, 0444, show_eco, NULL);
static DEVICE_ATTR(turbo_cooldown, 0444, show_turbo_cooldown, NULL);
static DEVICE_ATTR(auto_fan, 0644, show_auto_fan, store_auto_fan);
static struct attribute *msipf_attributes[] = {
&dev_attr_bluetooth.attr,
&dev_attr_wlan.attr,
&dev_attr_touchpad.attr,
&dev_attr_turbo_mode.attr,
&dev_attr_eco_mode.attr,
&dev_attr_turbo_cooldown.attr,
&dev_attr_auto_fan.attr,
NULL
};
static struct attribute *msipf_old_attributes[] = {
&dev_attr_lcd_level.attr,
&dev_attr_auto_brightness.attr,
NULL
};
static const struct attribute_group msipf_attribute_group = {
.attrs = msipf_attributes
};
static const struct attribute_group msipf_old_attribute_group = {
.attrs = msipf_old_attributes
};
static struct platform_driver msipf_driver = {
.driver = {
.name = "msi-laptop-pf",
.pm = &msi_laptop_pm,
},
};
static struct platform_device *msipf_device;
/* Initialization */
static struct quirk_entry quirk_old_ec_model = {
.old_ec_model = true,
};
static struct quirk_entry quirk_load_scm_model = {
.load_scm_model = true,
.ec_delay = true,
};
static struct quirk_entry quirk_load_scm_ro_model = {
.load_scm_model = true,
.ec_read_only = true,
};
static int dmi_check_cb(const struct dmi_system_id *dmi)
{
pr_info("Identified laptop model '%s'\n", dmi->ident);
quirks = dmi->driver_data;
return 1;
}
static const struct dmi_system_id msi_dmi_table[] __initconst = {
{
.ident = "MSI S270",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "MICRO-STAR INT'L CO.,LTD"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-1013"),
DMI_MATCH(DMI_PRODUCT_VERSION, "0131"),
DMI_MATCH(DMI_CHASSIS_VENDOR,
"MICRO-STAR INT'L CO.,LTD")
},
.driver_data = &quirk_old_ec_model,
.callback = dmi_check_cb
},
{
.ident = "MSI S271",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-1058"),
DMI_MATCH(DMI_PRODUCT_VERSION, "0581"),
DMI_MATCH(DMI_BOARD_NAME, "MS-1058")
},
.driver_data = &quirk_old_ec_model,
.callback = dmi_check_cb
},
{
.ident = "MSI S420",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-1412"),
DMI_MATCH(DMI_BOARD_VENDOR, "MSI"),
DMI_MATCH(DMI_BOARD_NAME, "MS-1412")
},
.driver_data = &quirk_old_ec_model,
.callback = dmi_check_cb
},
{
.ident = "Medion MD96100",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "NOTEBOOK"),
DMI_MATCH(DMI_PRODUCT_NAME, "SAM2000"),
DMI_MATCH(DMI_PRODUCT_VERSION, "0131"),
DMI_MATCH(DMI_CHASSIS_VENDOR,
"MICRO-STAR INT'L CO.,LTD")
},
.driver_data = &quirk_old_ec_model,
.callback = dmi_check_cb
},
{
.ident = "MSI N034",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR,
"MICRO-STAR INTERNATIONAL CO., LTD"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-N034"),
DMI_MATCH(DMI_CHASSIS_VENDOR,
"MICRO-STAR INTERNATIONAL CO., LTD")
},
.driver_data = &quirk_load_scm_model,
.callback = dmi_check_cb
},
{
.ident = "MSI N051",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR,
"MICRO-STAR INTERNATIONAL CO., LTD"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-N051"),
DMI_MATCH(DMI_CHASSIS_VENDOR,
"MICRO-STAR INTERNATIONAL CO., LTD")
},
.driver_data = &quirk_load_scm_model,
.callback = dmi_check_cb
},
{
.ident = "MSI N014",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR,
"MICRO-STAR INTERNATIONAL CO., LTD"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-N014"),
},
.driver_data = &quirk_load_scm_model,
.callback = dmi_check_cb
},
{
.ident = "MSI CR620",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR,
"Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "CR620"),
},
.driver_data = &quirk_load_scm_model,
.callback = dmi_check_cb
},
{
.ident = "MSI U270",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR,
"Micro-Star International Co., Ltd."),
DMI_MATCH(DMI_PRODUCT_NAME, "U270 series"),
},
.driver_data = &quirk_load_scm_model,
.callback = dmi_check_cb
},
{
.ident = "MSI U90/U100",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR,
"MICRO-STAR INTERNATIONAL CO., LTD"),
DMI_MATCH(DMI_PRODUCT_NAME, "U90/U100"),
},
.driver_data = &quirk_load_scm_ro_model,
.callback = dmi_check_cb
},
{ }
};
static int rfkill_bluetooth_set(void *data, bool blocked)
{
/* Do something with blocked...*/
/*
* blocked == false is on
* blocked == true is off
*/
int result = set_device_state(blocked ? "0" : "1", 0,
MSI_STANDARD_EC_BLUETOOTH_MASK);
return min(result, 0);
}
static int rfkill_wlan_set(void *data, bool blocked)
{
int result = set_device_state(blocked ? "0" : "1", 0,
MSI_STANDARD_EC_WLAN_MASK);
return min(result, 0);
}
static int rfkill_threeg_set(void *data, bool blocked)
{
int result = set_device_state(blocked ? "0" : "1", 0,
MSI_STANDARD_EC_3G_MASK);
return min(result, 0);
}
static const struct rfkill_ops rfkill_bluetooth_ops = {
.set_block = rfkill_bluetooth_set
};
static const struct rfkill_ops rfkill_wlan_ops = {
.set_block = rfkill_wlan_set
};
static const struct rfkill_ops rfkill_threeg_ops = {
.set_block = rfkill_threeg_set
};
static void rfkill_cleanup(void)
{
if (rfk_bluetooth) {
rfkill_unregister(rfk_bluetooth);
rfkill_destroy(rfk_bluetooth);
}
if (rfk_threeg) {
rfkill_unregister(rfk_threeg);
rfkill_destroy(rfk_threeg);
}
if (rfk_wlan) {
rfkill_unregister(rfk_wlan);
rfkill_destroy(rfk_wlan);
}
}
static bool msi_rfkill_set_state(struct rfkill *rfkill, bool blocked)
{
if (quirks->ec_read_only)
return rfkill_set_hw_state(rfkill, blocked);
else
return rfkill_set_sw_state(rfkill, blocked);
}
static void msi_update_rfkill(struct work_struct *ignored)
{
get_wireless_state_ec_standard();
if (rfk_wlan)
msi_rfkill_set_state(rfk_wlan, !wlan_s);
if (rfk_bluetooth)
msi_rfkill_set_state(rfk_bluetooth, !bluetooth_s);
if (rfk_threeg)
msi_rfkill_set_state(rfk_threeg, !threeg_s);
}
static DECLARE_DELAYED_WORK(msi_rfkill_dwork, msi_update_rfkill);
static DECLARE_WORK(msi_rfkill_work, msi_update_rfkill);
static void msi_send_touchpad_key(struct work_struct *ignored)
{
u8 rdata;
int result;
result = ec_read(MSI_STANDARD_EC_FUNCTIONS_ADDRESS, &rdata);
if (result < 0)
return;
sparse_keymap_report_event(msi_laptop_input_dev,
(rdata & MSI_STANDARD_EC_TOUCHPAD_MASK) ?
KEY_TOUCHPAD_ON : KEY_TOUCHPAD_OFF, 1, true);
}
static DECLARE_DELAYED_WORK(msi_touchpad_dwork, msi_send_touchpad_key);
static DECLARE_WORK(msi_touchpad_work, msi_send_touchpad_key);
static bool msi_laptop_i8042_filter(unsigned char data, unsigned char str,
struct serio *port)
{
static bool extended;
if (str & I8042_STR_AUXDATA)
return false;
/* 0x54 wwan, 0x62 bluetooth, 0x76 wlan, 0xE4 touchpad toggle*/
if (unlikely(data == 0xe0)) {
extended = true;
return false;
} else if (unlikely(extended)) {
extended = false;
switch (data) {
case 0xE4:
if (quirks->ec_delay) {
schedule_delayed_work(&msi_touchpad_dwork,
round_jiffies_relative(0.5 * HZ));
} else
schedule_work(&msi_touchpad_work);
break;
case 0x54:
case 0x62:
case 0x76:
if (quirks->ec_delay) {
schedule_delayed_work(&msi_rfkill_dwork,
round_jiffies_relative(0.5 * HZ));
} else
schedule_work(&msi_rfkill_work);
break;
}
}
return false;
}
static void msi_init_rfkill(struct work_struct *ignored)
{
if (rfk_wlan) {
rfkill_set_sw_state(rfk_wlan, !wlan_s);
rfkill_wlan_set(NULL, !wlan_s);
}
if (rfk_bluetooth) {
rfkill_set_sw_state(rfk_bluetooth, !bluetooth_s);
rfkill_bluetooth_set(NULL, !bluetooth_s);
}
if (rfk_threeg) {
rfkill_set_sw_state(rfk_threeg, !threeg_s);
rfkill_threeg_set(NULL, !threeg_s);
}
}
static DECLARE_DELAYED_WORK(msi_rfkill_init, msi_init_rfkill);
static int rfkill_init(struct platform_device *sdev)
{
/* add rfkill */
int retval;
/* keep the hardware wireless state */
get_wireless_state_ec_standard();
rfk_bluetooth = rfkill_alloc("msi-bluetooth", &sdev->dev,
RFKILL_TYPE_BLUETOOTH,
&rfkill_bluetooth_ops, NULL);
if (!rfk_bluetooth) {
retval = -ENOMEM;
goto err_bluetooth;
}
retval = rfkill_register(rfk_bluetooth);
if (retval)
goto err_bluetooth;
rfk_wlan = rfkill_alloc("msi-wlan", &sdev->dev, RFKILL_TYPE_WLAN,
&rfkill_wlan_ops, NULL);
if (!rfk_wlan) {
retval = -ENOMEM;
goto err_wlan;
}
retval = rfkill_register(rfk_wlan);
if (retval)
goto err_wlan;
if (threeg_exists) {
rfk_threeg = rfkill_alloc("msi-threeg", &sdev->dev,
RFKILL_TYPE_WWAN, &rfkill_threeg_ops, NULL);
if (!rfk_threeg) {
retval = -ENOMEM;
goto err_threeg;
}
retval = rfkill_register(rfk_threeg);
if (retval)
goto err_threeg;
}
/* schedule to run rfkill state initial */
if (quirks->ec_delay) {
schedule_delayed_work(&msi_rfkill_init,
round_jiffies_relative(1 * HZ));
} else
schedule_work(&msi_rfkill_work);
return 0;
err_threeg:
rfkill_destroy(rfk_threeg);
if (rfk_wlan)
rfkill_unregister(rfk_wlan);
err_wlan:
rfkill_destroy(rfk_wlan);
if (rfk_bluetooth)
rfkill_unregister(rfk_bluetooth);
err_bluetooth:
rfkill_destroy(rfk_bluetooth);
return retval;
}
#ifdef CONFIG_PM_SLEEP
static int msi_laptop_resume(struct device *device)
{
u8 data;
int result;
if (!quirks->load_scm_model)
return 0;
/* set load SCM to disable hardware control by fn key */
result = ec_read(MSI_STANDARD_EC_SCM_LOAD_ADDRESS, &data);
if (result < 0)
return result;
result = ec_write(MSI_STANDARD_EC_SCM_LOAD_ADDRESS,
data | MSI_STANDARD_EC_SCM_LOAD_MASK);
if (result < 0)
return result;
return 0;
}
#endif
static int __init msi_laptop_input_setup(void)
{
int err;
msi_laptop_input_dev = input_allocate_device();
if (!msi_laptop_input_dev)
return -ENOMEM;
msi_laptop_input_dev->name = "MSI Laptop hotkeys";
msi_laptop_input_dev->phys = "msi-laptop/input0";
msi_laptop_input_dev->id.bustype = BUS_HOST;
err = sparse_keymap_setup(msi_laptop_input_dev,
msi_laptop_keymap, NULL);
if (err)
goto err_free_dev;
err = input_register_device(msi_laptop_input_dev);
if (err)
goto err_free_dev;
return 0;
err_free_dev:
input_free_device(msi_laptop_input_dev);
return err;
}
static int __init load_scm_model_init(struct platform_device *sdev)
{
u8 data;
int result;
if (!quirks->ec_read_only) {
/* allow userland write sysfs file */
dev_attr_bluetooth.store = store_bluetooth;
dev_attr_wlan.store = store_wlan;
dev_attr_threeg.store = store_threeg;
dev_attr_bluetooth.attr.mode |= S_IWUSR;
dev_attr_wlan.attr.mode |= S_IWUSR;
dev_attr_threeg.attr.mode |= S_IWUSR;
}
/* disable hardware control by fn key */
result = ec_read(MSI_STANDARD_EC_SCM_LOAD_ADDRESS, &data);
if (result < 0)
return result;
result = ec_write(MSI_STANDARD_EC_SCM_LOAD_ADDRESS,
data | MSI_STANDARD_EC_SCM_LOAD_MASK);
if (result < 0)
return result;
/* initial rfkill */
result = rfkill_init(sdev);
if (result < 0)
goto fail_rfkill;
/* setup input device */
result = msi_laptop_input_setup();
if (result)
goto fail_input;
result = i8042_install_filter(msi_laptop_i8042_filter);
if (result) {
pr_err("Unable to install key filter\n");
goto fail_filter;
}
return 0;
fail_filter:
input_unregister_device(msi_laptop_input_dev);
fail_input:
rfkill_cleanup();
fail_rfkill:
return result;
}
static int __init msi_init(void)
{
int ret;
if (acpi_disabled)
return -ENODEV;
dmi_check_system(msi_dmi_table);
if (!quirks)
/* quirks may be NULL if no match in DMI table */
quirks = &quirk_load_scm_model;
if (force)
quirks = &quirk_old_ec_model;
if (!quirks->old_ec_model)
get_threeg_exists();
if (auto_brightness < 0 || auto_brightness > 2)
return -EINVAL;
/* Register backlight stuff */
if (quirks->old_ec_model ||
acpi_video_get_backlight_type() == acpi_backlight_vendor) {
struct backlight_properties props;
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = MSI_LCD_LEVEL_MAX - 1;
msibl_device = backlight_device_register("msi-laptop-bl", NULL,
NULL, &msibl_ops,
&props);
if (IS_ERR(msibl_device))
return PTR_ERR(msibl_device);
}
ret = platform_driver_register(&msipf_driver);
if (ret)
goto fail_backlight;
/* Register platform stuff */
msipf_device = platform_device_alloc("msi-laptop-pf", -1);
if (!msipf_device) {
ret = -ENOMEM;
goto fail_platform_driver;
}
ret = platform_device_add(msipf_device);
if (ret)
goto fail_device_add;
if (quirks->load_scm_model && (load_scm_model_init(msipf_device) < 0)) {
ret = -EINVAL;
goto fail_scm_model_init;
}
ret = sysfs_create_group(&msipf_device->dev.kobj,
&msipf_attribute_group);
if (ret)
goto fail_create_group;
if (!quirks->old_ec_model) {
if (threeg_exists)
ret = device_create_file(&msipf_device->dev,
&dev_attr_threeg);
if (ret)
goto fail_create_attr;
} else {
ret = sysfs_create_group(&msipf_device->dev.kobj,
&msipf_old_attribute_group);
if (ret)
goto fail_create_attr;
/* Disable automatic brightness control by default because
* this module was probably loaded to do brightness control in
* software. */
if (auto_brightness != 2)
set_auto_brightness(auto_brightness);
}
pr_info("driver " MSI_DRIVER_VERSION " successfully loaded\n");
return 0;
fail_create_attr:
sysfs_remove_group(&msipf_device->dev.kobj, &msipf_attribute_group);
fail_create_group:
if (quirks->load_scm_model) {
i8042_remove_filter(msi_laptop_i8042_filter);
cancel_delayed_work_sync(&msi_rfkill_dwork);
cancel_work_sync(&msi_rfkill_work);
rfkill_cleanup();
}
fail_scm_model_init:
platform_device_del(msipf_device);
fail_device_add:
platform_device_put(msipf_device);
fail_platform_driver:
platform_driver_unregister(&msipf_driver);
fail_backlight:
backlight_device_unregister(msibl_device);
return ret;
}
static void __exit msi_cleanup(void)
{
if (quirks->load_scm_model) {
i8042_remove_filter(msi_laptop_i8042_filter);
input_unregister_device(msi_laptop_input_dev);
cancel_delayed_work_sync(&msi_rfkill_dwork);
cancel_work_sync(&msi_rfkill_work);
rfkill_cleanup();
}
sysfs_remove_group(&msipf_device->dev.kobj, &msipf_attribute_group);
if (!quirks->old_ec_model && threeg_exists)
device_remove_file(&msipf_device->dev, &dev_attr_threeg);
platform_device_unregister(msipf_device);
platform_driver_unregister(&msipf_driver);
backlight_device_unregister(msibl_device);
if (quirks->old_ec_model) {
/* Enable automatic brightness control again */
if (auto_brightness != 2)
set_auto_brightness(1);
}
pr_info("driver unloaded\n");
}
module_init(msi_init);
module_exit(msi_cleanup);
MODULE_AUTHOR("Lennart Poettering");
MODULE_DESCRIPTION("MSI Laptop Support");
MODULE_VERSION(MSI_DRIVER_VERSION);
MODULE_LICENSE("GPL");
MODULE_ALIAS("dmi:*:svnMICRO-STARINT'LCO.,LTD:pnMS-1013:pvr0131*:cvnMICRO-STARINT'LCO.,LTD:ct10:*");
MODULE_ALIAS("dmi:*:svnMicro-StarInternational:pnMS-1058:pvr0581:rvnMSI:rnMS-1058:*:ct10:*");
MODULE_ALIAS("dmi:*:svnMicro-StarInternational:pnMS-1412:*:rvnMSI:rnMS-1412:*:cvnMICRO-STARINT'LCO.,LTD:ct10:*");
MODULE_ALIAS("dmi:*:svnNOTEBOOK:pnSAM2000:pvr0131*:cvnMICRO-STARINT'LCO.,LTD:ct10:*");
MODULE_ALIAS("dmi:*:svnMICRO-STARINTERNATIONAL*:pnMS-N034:*");
MODULE_ALIAS("dmi:*:svnMICRO-STARINTERNATIONAL*:pnMS-N051:*");
MODULE_ALIAS("dmi:*:svnMICRO-STARINTERNATIONAL*:pnMS-N014:*");
MODULE_ALIAS("dmi:*:svnMicro-StarInternational*:pnCR620:*");
MODULE_ALIAS("dmi:*:svnMicro-StarInternational*:pnU270series:*");
MODULE_ALIAS("dmi:*:svnMICRO-STARINTERNATIONAL*:pnU90/U100:*");
| gpl-2.0 |
dewadg/mako-kernel | drivers/staging/prima/CORE/TL/src/wlan_qct_tl_ba.c | 421 | 67630 | /*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by 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.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by 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.
*/
/*===========================================================================
W L A N _ Q C T _ T L _ B A. C
OVERVIEW:
This software unit holds the implementation of the WLAN Transport Layer
Block Ack session support. Also included are the AMSDU de-aggregation
completion and MSDU re-ordering functionality.
The functions externalized by this module are to be called ONLY by the main
TL module or the HAL layer.
DEPENDENCIES:
Are listed for each API below.
Copyright (c) 2008 QUALCOMM Incorporated.
All Rights Reserved.
Qualcomm Confidential and Proprietary
===========================================================================*/
/*===========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
$Header$$DateTime$$Author$
when who what, where, why
---------- --- --------------------------------------------------------
2010-10-xx dli Change ucCIndex to point to the slot the next frame to be expected to fwd
2008-08-22 sch Update based on unit test
2008-07-31 lti Created module
===========================================================================*/
/*----------------------------------------------------------------------------
* Include Files
* -------------------------------------------------------------------------*/
#include "wlan_qct_tl.h"
#include "wlan_qct_wda.h"
#include "wlan_qct_tli.h"
#include "wlan_qct_tli_ba.h"
#include "wlan_qct_hal.h"
#include "vos_list.h"
#include "vos_lock.h"
#include "tlDebug.h"
/*----------------------------------------------------------------------------
* Preprocessor Definitions and Constants
* -------------------------------------------------------------------------*/
//#define WLANTL_REORDER_DEBUG_MSG_ENABLE
#define WLANTL_BA_REORDERING_AGING_TIMER 30 /* 30 millisec */
#define WLANTL_BA_MIN_FREE_RX_VOS_BUFFER 0 /* RX VOS buffer low threshold */
/*==========================================================================
FUNCTION tlReorderingAgingTimerExpierCB
DESCRIPTION
After aging timer expiered, all Qed frames have to be routed to upper
layer. Otherwise, there is possibilitied that ahng some frames
PARAMETERS
v_PVOID_t timerUdata Timer callback user data
Has information about where frames should be
routed
RETURN VALUE
VOS_STATUS_SUCCESS General success
VOS_STATUS_E_INVAL Invalid frame handle
============================================================================*/
v_VOID_t WLANTL_ReorderingAgingTimerExpierCB
(
v_PVOID_t timerUdata
)
{
WLANTL_TIMER_EXPIER_UDATA_T *expireHandle;
WLANTL_BAReorderType *ReorderInfo;
WLANTL_CbType *pTLHandle;
WLANTL_STAClientType* pClientSTA = NULL;
vos_pkt_t *vosDataBuff;
VOS_STATUS status = VOS_STATUS_SUCCESS;
v_U8_t ucSTAID;
v_U8_t ucTID;
v_U8_t opCode;
WLANTL_RxMetaInfoType wRxMetaInfo;
v_U32_t fwIdx = 0;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
if(NULL == timerUdata)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Timer Callback User data NULL"));
return;
}
expireHandle = (WLANTL_TIMER_EXPIER_UDATA_T *)timerUdata;
ucSTAID = (v_U8_t)expireHandle->STAID;
ucTID = expireHandle->TID;
if(WLANTL_STA_ID_INVALID(ucSTAID) || WLANTL_TID_INVALID(ucTID))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"SID %d or TID %d is not valid",
ucSTAID, ucTID));
return;
}
pTLHandle = (WLANTL_CbType *)expireHandle->pTLHandle;
if(NULL == pTLHandle)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"TL Control block NULL"));
return;
}
pClientSTA = pTLHandle->atlSTAClients[ucSTAID];
if( NULL == pClientSTA ){
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"TL:STA Memory not allocated STA ID: %d, %s", ucSTAID, __func__));
return;
}
ReorderInfo = &pClientSTA->atlBAReorderInfo[ucTID];
if(NULL == ReorderInfo)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Reorder data NULL, this could not happen SID %d, TID %d",
ucSTAID, ucTID));
return;
}
if(0 == pClientSTA->atlBAReorderInfo[ucTID].ucExists)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Reorder session doesn't exist SID %d, TID %d",
ucSTAID, ucTID));
return;
}
if(!VOS_IS_STATUS_SUCCESS(vos_lock_acquire(&ReorderInfo->reorderLock)))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_ReorderingAgingTimerExpierCB, Get LOCK Fail"));
return;
}
if( 0 == pClientSTA->atlBAReorderInfo[ucTID].ucExists )
{
vos_lock_release(&ReorderInfo->reorderLock);
return;
}
opCode = WLANTL_OPCODE_FWDALL_DROPCUR;
vosDataBuff = NULL;
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO,"BA timeout with %d pending frames, curIdx %d", ReorderInfo->pendingFramesCount, ReorderInfo->ucCIndex));
if(ReorderInfo->pendingFramesCount == 0)
{
if(!VOS_IS_STATUS_SUCCESS(vos_lock_release(&ReorderInfo->reorderLock)))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_ReorderingAgingTimerExpierCB, Release LOCK Fail"));
}
return;
}
if(0 == ReorderInfo->ucCIndex)
{
fwIdx = ReorderInfo->winSize;
}
else
{
fwIdx = ReorderInfo->ucCIndex - 1;
}
/* Do replay check before giving packets to upper layer
replay check code : check whether replay check is needed or not */
if(VOS_TRUE == pClientSTA->ucIsReplayCheckValid)
{
v_U64_t ullpreviousReplayCounter = 0;
v_U64_t ullcurrentReplayCounter = 0;
v_U8_t ucloopCounter = 0;
v_BOOL_t status = 0;
/*Do replay check for all packets which are in Reorder buffer */
for(ucloopCounter = 0; ucloopCounter < WLANTL_MAX_WINSIZE; ucloopCounter++)
{
/*Get previous reply counter*/
ullpreviousReplayCounter = pClientSTA->ullReplayCounter[ucTID];
/*Get current replay counter of packet in reorder buffer*/
ullcurrentReplayCounter = ReorderInfo->reorderBuffer->ullReplayCounter[ucloopCounter];
/*Check for holes, if a hole is found in Reorder buffer then
no need to do replay check on it, skip the current
hole and do replay check on other packets*/
if(NULL != (ReorderInfo->reorderBuffer->arrayBuffer[ucloopCounter]))
{
status = WLANTL_IsReplayPacket(ullcurrentReplayCounter, ullpreviousReplayCounter);
if(VOS_TRUE == status)
{
/*Increment the debug counter*/
pClientSTA->ulTotalReplayPacketsDetected++;
/*A replay packet found*/
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLANTL_ReorderingAgingTimerExpierCB: total dropped replay packets on STA ID %X is [0x%lX]\n",
ucSTAID, pClientSTA->ulTotalReplayPacketsDetected);
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLANTL_ReorderingAgingTimerExpierCB: replay packet found with PN : [0x%llX]\n",
ullcurrentReplayCounter);
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLANTL_ReorderingAgingTimerExpierCB: Drop the replay packet with PN : [0x%llX]\n",
ullcurrentReplayCounter);
ReorderInfo->reorderBuffer->arrayBuffer[ucloopCounter] = NULL;
ReorderInfo->reorderBuffer->ullReplayCounter[ucloopCounter] = 0;
}
else
{
/*Not a replay packet update previous replay counter*/
pClientSTA->ullReplayCounter[ucTID] = ullcurrentReplayCounter;
}
}
else
{
/* A hole detected in Reorder buffer*/
//BAMSGERROR("WLANTL_ReorderingAgingTimerExpierCB,hole detected\n",0,0,0);
}
}
}
status = WLANTL_ChainFrontPkts(fwIdx, opCode,
&vosDataBuff, ReorderInfo, NULL);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make packet chain fail with Qed frames %d", status));
if(!VOS_IS_STATUS_SUCCESS(vos_lock_release(&ReorderInfo->reorderLock)))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_ReorderingAgingTimerExpierCB, Release LOCK Fail"));
}
return;
}
if(NULL == pClientSTA->pfnSTARx)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Callback function NULL with STAID %d", ucSTAID));
if(!VOS_IS_STATUS_SUCCESS(vos_lock_release(&ReorderInfo->reorderLock)))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_ReorderingAgingTimerExpierCB, Release LOCK Fail"));
}
return;
}
if(NULL == vosDataBuff)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"No pending frames, why triggered timer? "));
if(!VOS_IS_STATUS_SUCCESS(vos_lock_release(&ReorderInfo->reorderLock)))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_ReorderingAgingTimerExpierCB, Release LOCK Fail"));
}
return;
}
if( WLAN_STA_SOFTAP == pClientSTA->wSTADesc.wSTAType)
{
WLANTL_FwdPktToHDD( expireHandle->pAdapter, vosDataBuff, ucSTAID);
}
else
{
wRxMetaInfo.ucUP = ucTID;
pClientSTA->pfnSTARx(expireHandle->pAdapter,
vosDataBuff, ucSTAID, &wRxMetaInfo);
}
if(!VOS_IS_STATUS_SUCCESS(vos_lock_release(&ReorderInfo->reorderLock)))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_ReorderingAgingTimerExpierCB, Release LOCK Fail"));
}
return;
}/*WLANTL_ReorderingAgingTimerExpierCB*/
/*----------------------------------------------------------------------------
INTERACTION WITH TL Main
---------------------------------------------------------------------------*/
/*==========================================================================
FUNCTION WLANTL_InitBAReorderBuffer
DESCRIPTION
Init Reorder buffer array
PARAMETERS
v_PVOID_t pvosGCtx Global context
RETURN VALUE
NONE
============================================================================*/
void WLANTL_InitBAReorderBuffer
(
v_PVOID_t pvosGCtx
)
{
WLANTL_CbType *pTLCb;
v_U32_t idx;
v_U32_t pIdx;
pTLCb = VOS_GET_TL_CB(pvosGCtx);
if (NULL == pTLCb)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid TL Control Block", __func__));
return;
}
for(idx = 0; idx < WLANTL_MAX_BA_SESSION; idx++)
{
pTLCb->reorderBufferPool[idx].isAvailable = VOS_TRUE;
for(pIdx = 0; pIdx < WLANTL_MAX_WINSIZE; pIdx++)
{
pTLCb->reorderBufferPool[idx].arrayBuffer[pIdx] = NULL;
pTLCb->reorderBufferPool[idx].ullReplayCounter[pIdx] = 0;
}
}
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"BA reorder buffer init"));
return;
}
/*==========================================================================
FUNCTION WLANTL_BaSessionAdd
DESCRIPTION
HAL notifies TL when a new Block Ack session is being added.
DEPENDENCIES
A BA session on Rx needs to be added in TL before the response is
being sent out
PARAMETERS
IN
pvosGCtx: pointer to the global vos context; a handle to TL's
control block can be extracted from its context
ucSTAId: identifier of the station for which requested the BA
session
ucTid: Tspec ID for the new BA session
uSize: size of the reordering window
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_E_INVAL: Input parameters are invalid
VOS_STATUS_E_FAULT: Station ID is outside array boundaries or pointer
to TL cb is NULL ; access would cause a page fault
VOS_STATUS_E_EXISTS: Station was not registered or BA session already
exists
VOS_STATUS_E_NOSUPPORT: Not yet supported
SIDE EFFECTS
============================================================================*/
VOS_STATUS
WLANTL_BaSessionAdd
(
v_PVOID_t pvosGCtx,
v_U16_t sessionID,
v_U32_t ucSTAId,
v_U8_t ucTid,
v_U32_t uBufferSize,
v_U32_t winSize,
v_U32_t SSN
)
{
WLANTL_CbType *pTLCb = NULL;
WLANTL_STAClientType *pClientSTA = NULL;
WLANTL_BAReorderType *reorderInfo;
v_U32_t idx;
VOS_STATUS status = VOS_STATUS_SUCCESS;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/*------------------------------------------------------------------------
Sanity check
------------------------------------------------------------------------*/
if ( WLANTL_TID_INVALID(ucTid))
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid parameter sent on WLANTL_BaSessionAdd");
return VOS_STATUS_E_INVAL;
}
if ( WLANTL_STA_ID_INVALID( ucSTAId ) )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid station id requested on WLANTL_BaSessionAdd");
return VOS_STATUS_E_FAULT;
}
/*------------------------------------------------------------------------
Extract TL control block and check existance
------------------------------------------------------------------------*/
pTLCb = VOS_GET_TL_CB(pvosGCtx);
if ( NULL == pTLCb )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid TL pointer from pvosGCtx on WLANTL_BaSessionAdd");
return VOS_STATUS_E_FAULT;
}
pClientSTA = pTLCb->atlSTAClients[ucSTAId];
if ( NULL == pClientSTA )
{
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Client Memory was not allocated on %s", __func__));
return VOS_STATUS_E_FAILURE;
}
if ( 0 == pClientSTA->ucExists )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Station was not yet registered on WLANTL_BaSessionAdd");
return VOS_STATUS_E_EXISTS;
}
/*------------------------------------------------------------------------
Verify that BA session was not already added
------------------------------------------------------------------------*/
if ( 0 != pClientSTA->atlBAReorderInfo[ucTid].ucExists )
{
pClientSTA->atlBAReorderInfo[ucTid].ucExists++;
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:BA session already exists on WLANTL_BaSessionAdd");
return VOS_STATUS_E_EXISTS;
}
/*------------------------------------------------------------------------
Initialize new BA session
------------------------------------------------------------------------*/
reorderInfo = &pClientSTA->atlBAReorderInfo[ucTid];
for(idx = 0; idx < WLANTL_MAX_BA_SESSION; idx++)
{
if(VOS_TRUE == pTLCb->reorderBufferPool[idx].isAvailable)
{
pClientSTA->atlBAReorderInfo[ucTid].reorderBuffer =
&(pTLCb->reorderBufferPool[idx]);
pTLCb->reorderBufferPool[idx].isAvailable = VOS_FALSE;
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"%dth buffer available, buffer PTR 0x%p",
idx,
pClientSTA->atlBAReorderInfo[ucTid].reorderBuffer
));
break;
}
}
if( WLAN_STA_SOFTAP == pClientSTA->wSTADesc.wSTAType)
{
if( WLANTL_MAX_BA_SESSION == idx)
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"Number of Add BA request received more than allowed \n");
return VOS_STATUS_E_NOSUPPORT;
}
}
reorderInfo->timerUdata.pAdapter = pvosGCtx;
reorderInfo->timerUdata.pTLHandle = (v_PVOID_t)pTLCb;
reorderInfo->timerUdata.STAID = ucSTAId;
reorderInfo->timerUdata.TID = ucTid;
/* BA aging timer */
status = vos_timer_init(&reorderInfo->agingTimer,
VOS_TIMER_TYPE_SW,
WLANTL_ReorderingAgingTimerExpierCB,
(v_PVOID_t)(&reorderInfo->timerUdata));
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Timer Init Fail"));
return status;
}
/* Reorder LOCK
* During handle normal RX frame, if timer sxpier, abnormal race condition happen
* Frames should be protected from double handle */
status = vos_lock_init(&reorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Lock Init Fail"));
return status;
}
pClientSTA->atlBAReorderInfo[ucTid].ucExists++;
pClientSTA->atlBAReorderInfo[ucTid].usCount = 0;
pClientSTA->atlBAReorderInfo[ucTid].ucCIndex = 0;
if(0 == winSize)
{
pClientSTA->atlBAReorderInfo[ucTid].winSize = WLANTL_MAX_WINSIZE;
}
else
{
pClientSTA->atlBAReorderInfo[ucTid].winSize = winSize;
}
pClientSTA->atlBAReorderInfo[ucTid].SSN = SSN;
pClientSTA->atlBAReorderInfo[ucTid].sessionID = sessionID;
pClientSTA->atlBAReorderInfo[ucTid].pendingFramesCount = 0;
TLLOG2(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_HIGH,
"WLAN TL:New BA session added for STA: %d TID: %d",
ucSTAId, ucTid));
return VOS_STATUS_SUCCESS;
}/* WLANTL_BaSessionAdd */
/*==========================================================================
FUNCTION WLANTL_BaSessionDel
DESCRIPTION
HAL notifies TL when a new Block Ack session is being deleted.
DEPENDENCIES
PARAMETERS
IN
pvosGCtx: pointer to the global vos context; a handle to TL's
control block can be extracted from its context
ucSTAId: identifier of the station for which requested the BA
session
ucTid: Tspec ID for the new BA session
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_E_INVAL: Input parameters are invalid
VOS_STATUS_E_FAULT: Station ID is outside array boundaries or pointer
to TL cb is NULL ; access would cause a page fault
VOS_STATUS_E_EXISTS: Station was not registered or BA session already
exists
VOS_STATUS_E_NOSUPPORT: Not yet supported
SIDE EFFECTS
============================================================================*/
VOS_STATUS
WLANTL_BaSessionDel
(
v_PVOID_t pvosGCtx,
v_U16_t ucSTAId,
v_U8_t ucTid
)
{
WLANTL_CbType* pTLCb = NULL;
WLANTL_STAClientType *pClientSTA = NULL;
vos_pkt_t* vosDataBuff = NULL;
VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE;
VOS_STATUS lockStatus = VOS_STATUS_E_FAILURE;
WLANTL_BAReorderType* reOrderInfo = NULL;
WLANTL_RxMetaInfoType wRxMetaInfo;
v_U32_t fwIdx = 0;
tANI_U8 lockRetryCnt = 0;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*------------------------------------------------------------------------
Sanity check
------------------------------------------------------------------------*/
if ( WLANTL_TID_INVALID(ucTid))
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid parameter sent on WLANTL_BaSessionDel");
return VOS_STATUS_E_INVAL;
}
if ( WLANTL_STA_ID_INVALID( ucSTAId ) )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid station id requested on WLANTL_BaSessionDel");
return VOS_STATUS_E_FAULT;
}
/*------------------------------------------------------------------------
Extract TL control block and check existance
------------------------------------------------------------------------*/
pTLCb = VOS_GET_TL_CB(pvosGCtx);
if ( NULL == pTLCb )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid TL pointer from pvosGCtx on WLANTL_BaSessionDel");
return VOS_STATUS_E_FAULT;
}
pClientSTA = pTLCb->atlSTAClients[ucSTAId];
if ( NULL == pClientSTA )
{
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Client Memory was not allocated on %s", __func__));
return VOS_STATUS_E_FAILURE;
}
if (( 0 == pClientSTA->ucExists ) &&
( 0 == pClientSTA->atlBAReorderInfo[ucTid].ucExists ))
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_WARN,
"WLAN TL:Station was not yet registered on WLANTL_BaSessionDel");
return VOS_STATUS_E_EXISTS;
}
else if(( 0 == pClientSTA->ucExists ) &&
( 0 != pClientSTA->atlBAReorderInfo[ucTid].ucExists ))
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_WARN,
"STA was deleted but BA info is still there, just remove BA info");
reOrderInfo = &pClientSTA->atlBAReorderInfo[ucTid];
reOrderInfo->reorderBuffer->isAvailable = VOS_TRUE;
memset(&reOrderInfo->reorderBuffer->arrayBuffer[0],
0,
WLANTL_MAX_WINSIZE * sizeof(v_PVOID_t));
vos_timer_destroy(&reOrderInfo->agingTimer);
memset(reOrderInfo, 0, sizeof(WLANTL_BAReorderType));
return VOS_STATUS_SUCCESS;
}
/*------------------------------------------------------------------------
Verify that BA session was added
------------------------------------------------------------------------*/
if ( 0 == pClientSTA->atlBAReorderInfo[ucTid].ucExists )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_HIGH,
"WLAN TL:BA session does not exists on WLANTL_BaSessionDel");
return VOS_STATUS_E_EXISTS;
}
/*------------------------------------------------------------------------
Send all pending packets to HDD
------------------------------------------------------------------------*/
reOrderInfo = &pClientSTA->atlBAReorderInfo[ucTid];
/*------------------------------------------------------------------------
Invalidate reorder info here. This ensures that no packets are
bufferd after reorder buffer is cleaned.
*/
lockStatus = vos_lock_acquire(&reOrderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"Unable to acquire reorder vos lock in %s\n", __func__));
return lockStatus;
}
pClientSTA->atlBAReorderInfo[ucTid].ucExists = 0;
TLLOG2(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_HIGH,
"WLAN TL: Fwd all packets to HDD on WLANTL_BaSessionDel"));
if(0 == reOrderInfo->ucCIndex)
{
fwIdx = reOrderInfo->winSize;
}
else
{
fwIdx = reOrderInfo->ucCIndex - 1;
}
if(0 != reOrderInfo->pendingFramesCount)
{
vosStatus = WLANTL_ChainFrontPkts(fwIdx,
WLANTL_OPCODE_FWDALL_DROPCUR,
&vosDataBuff, reOrderInfo, pTLCb);
}
if ((VOS_STATUS_SUCCESS == vosStatus) && (NULL != vosDataBuff))
{
TLLOG2(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_HIGH,
"WLAN TL: Chaining was successful sending all pkts to HDD : %x",
vosDataBuff ));
if ( WLAN_STA_SOFTAP == pClientSTA->wSTADesc.wSTAType )
{
WLANTL_FwdPktToHDD( pvosGCtx, vosDataBuff, ucSTAId);
}
else
{
wRxMetaInfo.ucUP = ucTid;
pClientSTA->pfnSTARx( pvosGCtx, vosDataBuff, ucSTAId,
&wRxMetaInfo );
}
}
vos_lock_release(&reOrderInfo->reorderLock);
/*------------------------------------------------------------------------
Delete reordering timer
------------------------------------------------------------------------*/
if(VOS_TIMER_STATE_RUNNING == vos_timer_getCurrentState(&reOrderInfo->agingTimer))
{
vosStatus = vos_timer_stop(&reOrderInfo->agingTimer);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Timer stop fail: %d", vosStatus));
return vosStatus;
}
}
if(VOS_TIMER_STATE_STOPPED == vos_timer_getCurrentState(&reOrderInfo->agingTimer))
{
vosStatus = vos_timer_destroy(&reOrderInfo->agingTimer);
}
else
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Timer is not stopped state current state is %d",
vos_timer_getCurrentState(&reOrderInfo->agingTimer)));
}
if ( VOS_STATUS_SUCCESS != vosStatus )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_WARN,
"WLAN TL:Failed to destroy reorder timer on WLANTL_BaSessionAdd");
}
/*------------------------------------------------------------------------
Delete session
------------------------------------------------------------------------*/
pClientSTA->atlBAReorderInfo[ucTid].usCount = 0;
pClientSTA->atlBAReorderInfo[ucTid].ucCIndex = 0;
reOrderInfo->winSize = 0;
reOrderInfo->SSN = 0;
reOrderInfo->sessionID = 0;
while (vos_lock_destroy(&reOrderInfo->reorderLock) == VOS_STATUS_E_BUSY)
{
if( lockRetryCnt > 2)
{
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"Unable to destroy reorderLock\n"));
break;
}
vos_sleep(1);
lockRetryCnt++;
}
TLLOG2(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_HIGH,
"WLAN TL: BA session deleted for STA: %d TID: %d",
ucSTAId, ucTid));
memset((v_U8_t *)(&reOrderInfo->reorderBuffer->arrayBuffer[0]),
0,
WLANTL_MAX_WINSIZE * sizeof(v_PVOID_t));
reOrderInfo->reorderBuffer->isAvailable = VOS_TRUE;
return VOS_STATUS_SUCCESS;
}/* WLANTL_BaSessionDel */
/*----------------------------------------------------------------------------
INTERACTION WITH TL main module
---------------------------------------------------------------------------*/
/*==========================================================================
AMSDU sub-frame processing module
==========================================================================*/
/*==========================================================================
FUNCTION WLANTL_AMSDUProcess
DESCRIPTION
Process A-MSDU sub-frame. Start of chain if marked as first frame.
Linked at the end of the existing AMSDU chain.
DEPENDENCIES
PARAMETERS
IN/OUT:
vosDataBuff: vos packet for the received data
outgoing contains the root of the chain for the rx
aggregated MSDU if the frame is marked as last; otherwise
NULL
IN
pvosGCtx: pointer to the global vos context; a handle to TL's
control block can be extracted from its context
pvBDHeader: pointer to the BD header
ucSTAId: Station ID
ucMPDUHLen: length of the MPDU header
usMPDULen: length of the MPDU
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_E_INVAL: invalid input parameters
VOS_STATUS_E_FAULT: pointer to TL cb is NULL ; access would cause a
page fault
VOS_STATUS_SUCCESS: Everything is good :)
Other values can be returned as a result of a function call, please check
corresponding API for more info.
SIDE EFFECTS
============================================================================*/
VOS_STATUS
WLANTL_AMSDUProcess
(
v_PVOID_t pvosGCtx,
vos_pkt_t** ppVosDataBuff,
v_PVOID_t pvBDHeader,
v_U8_t ucSTAId,
v_U8_t ucMPDUHLen,
v_U16_t usMPDULen
)
{
v_U8_t ucFsf; /* First AMSDU sub frame */
v_U8_t ucAef; /* Error in AMSDU sub frame */
WLANTL_CbType* pTLCb = NULL;
WLANTL_STAClientType *pClientSTA = NULL;
v_U8_t MPDUHeaderAMSDUHeader[WLANTL_MPDU_HEADER_LEN + TL_AMSDU_SUBFRM_HEADER_LEN];
v_U16_t subFrameLength;
v_U16_t paddingSize;
VOS_STATUS vStatus = VOS_STATUS_SUCCESS;
v_U16_t MPDUDataOffset;
v_U16_t packetLength;
static v_U32_t numAMSDUFrames;
vos_pkt_t* vosDataBuff;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/*------------------------------------------------------------------------
Sanity check
------------------------------------------------------------------------*/
if (( NULL == ppVosDataBuff ) || (NULL == *ppVosDataBuff) || ( NULL == pvBDHeader ) ||
( WLANTL_STA_ID_INVALID(ucSTAId)) )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid parameter sent on WLANTL_AMSDUProcess");
return VOS_STATUS_E_INVAL;
}
vosDataBuff = *ppVosDataBuff;
/*------------------------------------------------------------------------
Extract TL control block
------------------------------------------------------------------------*/
pTLCb = VOS_GET_TL_CB(pvosGCtx);
if ( NULL == pTLCb )
{
VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Invalid TL pointer from pvosGCtx on WLANTL_AMSDUProcess");
return VOS_STATUS_E_FAULT;
}
pClientSTA = pTLCb->atlSTAClients[ucSTAId];
if ( NULL == pClientSTA )
{
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Client Memory was not allocated on %s", __func__));
return VOS_STATUS_E_FAILURE;
}
/*------------------------------------------------------------------------
Check frame
------------------------------------------------------------------------*/
ucAef = (v_U8_t)WDA_GET_RX_AEF( pvBDHeader );
ucFsf = (v_U8_t)WDA_GET_RX_ESF( pvBDHeader );
/* On Prima, MPDU data offset not includes BD header size */
MPDUDataOffset = (v_U16_t)WDA_GET_RX_MPDU_DATA_OFFSET(pvBDHeader);
if ( WLANHAL_RX_BD_AEF_SET == ucAef )
{
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Error in AMSDU - dropping entire chain"));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
if((0 != ucMPDUHLen) && ucFsf)
{
/*
* This is first AMSDU sub frame
* AMSDU Header should be removed
* MPDU header should be stored into context to recover next frames
*/
/* Assumed here Address4 is never part of AMSDU received at TL */
if (ucMPDUHLen > WLANTL_MPDU_HEADER_LEN)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"MPDU Header length (%d) is greater",ucMPDUHLen));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
vStatus = vos_pkt_pop_head(vosDataBuff, MPDUHeaderAMSDUHeader, ucMPDUHLen + TL_AMSDU_SUBFRM_HEADER_LEN);
if(!VOS_IS_STATUS_SUCCESS(vStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Pop MPDU AMSDU Header fail"));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
pClientSTA->ucMPDUHeaderLen = ucMPDUHLen;
memcpy(pClientSTA->aucMPDUHeader, MPDUHeaderAMSDUHeader, ucMPDUHLen);
/* AMSDU header stored to handle garbage data within next frame */
}
else
{
/* Trim garbage, size is frameLoop */
if(MPDUDataOffset > 0)
{
vStatus = vos_pkt_trim_head(vosDataBuff, MPDUDataOffset);
}
if(!VOS_IS_STATUS_SUCCESS(vStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Trim Garbage Data fail"));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
/* Remove MPDU header and AMSDU header from the packet */
vStatus = vos_pkt_pop_head(vosDataBuff, MPDUHeaderAMSDUHeader, ucMPDUHLen + TL_AMSDU_SUBFRM_HEADER_LEN);
if(!VOS_IS_STATUS_SUCCESS(vStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"AMSDU Header Pop fail"));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
} /* End of henalding not first sub frame specific */
/* Put in MPDU header into all the frame */
vStatus = vos_pkt_push_head(vosDataBuff, pClientSTA->aucMPDUHeader, pClientSTA->ucMPDUHeaderLen);
if(!VOS_IS_STATUS_SUCCESS(vStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"MPDU Header Push back fail"));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
/* Find Padding and remove */
memcpy(&subFrameLength, MPDUHeaderAMSDUHeader + ucMPDUHLen + WLANTL_AMSDU_SUBFRAME_LEN_OFFSET, sizeof(v_U16_t));
subFrameLength = vos_be16_to_cpu(subFrameLength);
paddingSize = usMPDULen - ucMPDUHLen - subFrameLength - TL_AMSDU_SUBFRM_HEADER_LEN;
vos_pkt_get_packet_length(vosDataBuff, &packetLength);
if((paddingSize > 0) && (paddingSize < packetLength))
{
/* There is padding bits, remove it */
vos_pkt_trim_tail(vosDataBuff, paddingSize);
}
else if(0 == paddingSize)
{
/* No Padding bits */
/* Do Nothing */
}
else
{
/* Padding size is larger than Frame size, Actually negative */
/* Not a valid case, not a valid frame, drop it */
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Padding Size is negative, no possible %d", paddingSize));
vos_pkt_return_packet(vosDataBuff);
*ppVosDataBuff = NULL;
return VOS_STATUS_SUCCESS; /*Not a transport error*/
}
numAMSDUFrames++;
if(0 == (numAMSDUFrames % 5000))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"%lu AMSDU frames arrived", numAMSDUFrames));
}
return VOS_STATUS_SUCCESS;
}/* WLANTL_AMSDUProcess */
/*==========================================================================
Re-ordering module
==========================================================================*/
/*==========================================================================
FUNCTION WLANTL_MSDUReorder
DESCRIPTION
MSDU reordering
DEPENDENCIES
PARAMETERS
IN
vosDataBuff: vos packet for the received data
pvBDHeader: pointer to the BD header
ucSTAId: Station ID
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_SUCCESS: Everything is good :)
SIDE EFFECTS
============================================================================*/
VOS_STATUS WLANTL_MSDUReorder
(
WLANTL_CbType *pTLCb,
vos_pkt_t **vosDataBuff,
v_PVOID_t pvBDHeader,
v_U8_t ucSTAId,
v_U8_t ucTid
)
{
WLANTL_BAReorderType *currentReorderInfo;
WLANTL_STAClientType *pClientSTA = NULL;
vos_pkt_t *vosPktIdx;
v_U8_t ucOpCode;
v_U8_t ucSlotIdx;
v_U8_t ucFwdIdx;
v_U16_t CSN;
v_U32_t ucCIndexOrig;
VOS_STATUS status = VOS_STATUS_SUCCESS;
VOS_STATUS lockStatus = VOS_STATUS_SUCCESS;
VOS_STATUS timerStatus = VOS_STATUS_SUCCESS;
VOS_TIMER_STATE timerState;
v_SIZE_t rxFree;
v_U64_t ullreplayCounter = 0; /* 48-bit replay counter */
if((NULL == pTLCb) || (*vosDataBuff == NULL))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Invalid ARG pTLCb 0x%p, vosDataBuff 0x%p",
pTLCb, *vosDataBuff));
return VOS_STATUS_E_INVAL;
}
pClientSTA = pTLCb->atlSTAClients[ucSTAId];
if ( NULL == pClientSTA )
{
TLLOGE(VOS_TRACE( VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,
"WLAN TL:Client Memory was not allocated on %s", __func__));
return VOS_STATUS_E_FAILURE;
}
currentReorderInfo = &pClientSTA->atlBAReorderInfo[ucTid];
lockStatus = vos_lock_acquire(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
if( pClientSTA->atlBAReorderInfo[ucTid].ucExists == 0 )
{
vos_lock_release(¤tReorderInfo->reorderLock);
return VOS_STATUS_E_INVAL;
}
ucOpCode = (v_U8_t)WDA_GET_RX_REORDER_OPCODE(pvBDHeader);
ucSlotIdx = (v_U8_t)WDA_GET_RX_REORDER_SLOT_IDX(pvBDHeader);
ucFwdIdx = (v_U8_t)WDA_GET_RX_REORDER_FWD_IDX(pvBDHeader);
CSN = (v_U16_t)WDA_GET_RX_REORDER_CUR_PKT_SEQ_NO(pvBDHeader);
#ifdef WLANTL_HAL_VOLANS
/* Replay check code : check whether replay check is needed or not */
if(VOS_TRUE == pClientSTA->ucIsReplayCheckValid)
{
/* Getting 48-bit replay counter from the RX BD */
ullreplayCounter = WDA_DS_GetReplayCounter(aucBDHeader);
}
#endif
#ifdef WLANTL_REORDER_DEBUG_MSG_ENABLE
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"opCode %d SI %d, FI %d, CI %d seqNo %d", ucOpCode, ucSlotIdx, ucFwdIdx, currentReorderInfo->ucCIndex, CSN));
#else
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"opCode %d SI %d, FI %d, CI %d seqNo %d", ucOpCode, ucSlotIdx, ucFwdIdx, currentReorderInfo->ucCIndex, CSN));
#endif
// remember our current CI so that later we can tell if it advanced
ucCIndexOrig = currentReorderInfo->ucCIndex;
switch(ucOpCode)
{
case WLANTL_OPCODE_INVALID:
/* Do nothing just pass through current frame */
break;
case WLANTL_OPCODE_QCUR_FWDBUF:
if(0 == currentReorderInfo->pendingFramesCount)
{
//This frame will be fwd'ed to the OS. The next slot is the one we expect next
currentReorderInfo->ucCIndex = (ucSlotIdx + 1) % currentReorderInfo->winSize;
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
status = WLANTL_QueueCurrent(currentReorderInfo,
vosDataBuff,
ucSlotIdx);
if(VOS_TRUE == pClientSTA->ucIsReplayCheckValid)
{
WLANTL_FillReplayCounter(currentReorderInfo,
ullreplayCounter, ucSlotIdx);
}
if(VOS_STATUS_E_RESOURCES == status)
{
/* This is the case slot index is already cycle one route, route all the frames Qed */
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDALL_QCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain fail %d", status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
status = vos_pkt_chain_packet(vosPktIdx, *vosDataBuff, 1);
*vosDataBuff = vosPktIdx;
currentReorderInfo->pendingFramesCount = 0;
}
else
{
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_QCUR_FWDBUF,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain fail %d", status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
*vosDataBuff = vosPktIdx;
}
break;
case WLANTL_OPCODE_FWDBUF_FWDCUR:
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDBUF_FWDCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain fail %d", status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
if(NULL == vosPktIdx)
{
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Nothing to chain, just send current frame\n"));
}
else
{
status = vos_pkt_chain_packet(vosPktIdx, *vosDataBuff, 1);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain with CUR frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
*vosDataBuff = vosPktIdx;
}
//ucFwdIdx is the slot this packet supposes to take but there is a hole there
//It looks that the chip will put the next packet into the slot ucFwdIdx.
currentReorderInfo->ucCIndex = ucFwdIdx;
break;
case WLANTL_OPCODE_QCUR:
status = WLANTL_QueueCurrent(currentReorderInfo,
vosDataBuff,
ucSlotIdx);
if(VOS_TRUE == pClientSTA->ucIsReplayCheckValid)
{
WLANTL_FillReplayCounter(currentReorderInfo,
ullreplayCounter, ucSlotIdx);
}
if(VOS_STATUS_E_RESOURCES == status)
{
/* This is the case slot index is already cycle one route, route all the frames Qed */
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDALL_QCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain fail %d", status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
status = vos_pkt_chain_packet(vosPktIdx, *vosDataBuff, 1);
*vosDataBuff = vosPktIdx;
currentReorderInfo->pendingFramesCount = 0;
}
else
{
/* Since current Frame is Qed, no frame will be routed */
*vosDataBuff = NULL;
}
break;
case WLANTL_OPCODE_FWDBUF_QUEUECUR:
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDBUF_QUEUECUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make chain with buffered frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
//This opCode means the window shift. Enforce the current Index
currentReorderInfo->ucCIndex = ucFwdIdx;
status = WLANTL_QueueCurrent(currentReorderInfo,
vosDataBuff,
ucSlotIdx);
if(VOS_TRUE == pClientSTA->ucIsReplayCheckValid)
{
WLANTL_FillReplayCounter(currentReorderInfo,
ullreplayCounter, ucSlotIdx);
}
if(VOS_STATUS_E_RESOURCES == status)
{
vos_pkt_return_packet(vosPktIdx);
/* This is the case slot index is already cycle one route, route all the frames Qed */
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDALL_QCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain fail %d", status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
status = vos_pkt_chain_packet(vosPktIdx, *vosDataBuff, 1);
*vosDataBuff = vosPktIdx;
currentReorderInfo->pendingFramesCount = 0;
}
*vosDataBuff = vosPktIdx;
break;
case WLANTL_OPCODE_FWDBUF_DROPCUR:
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDBUF_DROPCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make chain with buffered frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
//Since BAR frame received, set the index to the right location
currentReorderInfo->ucCIndex = ucFwdIdx;
/* Current frame has to be dropped, BAR frame */
status = vos_pkt_return_packet(*vosDataBuff);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Drop BAR frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
*vosDataBuff = vosPktIdx;
break;
case WLANTL_OPCODE_FWDALL_DROPCUR:
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDALL_DROPCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make chain with buffered frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
//Since BAR frame received and beyond cur window, set the index to the right location
currentReorderInfo->ucCIndex = 0;
status = vos_pkt_return_packet(*vosDataBuff);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Drop BAR frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
*vosDataBuff = vosPktIdx;
break;
case WLANTL_OPCODE_FWDALL_QCUR:
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(currentReorderInfo->winSize,
WLANTL_OPCODE_FWDALL_DROPCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make chain with buffered frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
status = WLANTL_QueueCurrent(currentReorderInfo,
vosDataBuff,
ucSlotIdx);
if(VOS_TRUE == pClientSTA->ucIsReplayCheckValid)
{
WLANTL_FillReplayCounter(currentReorderInfo,
ullreplayCounter, ucSlotIdx);
}
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Q Current frame fail %d",
status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
currentReorderInfo->ucCIndex = ucSlotIdx;
*vosDataBuff = vosPktIdx;
break;
case WLANTL_OPCODE_TEARDOWN:
// do we have a procedure in place to teardown BA?
// fall through to drop the current packet
case WLANTL_OPCODE_DROPCUR:
vos_pkt_return_packet(*vosDataBuff);
*vosDataBuff = NULL;
break;
default:
break;
}
/* Check the available VOS RX buffer size
* If remaining VOS RX buffer is too few, have to make space
* Route all the Qed frames upper layer
* Otherwise, RX thread could be stall */
vos_pkt_get_available_buffer_pool(VOS_PKT_TYPE_RX_RAW, &rxFree);
if(WLANTL_BA_MIN_FREE_RX_VOS_BUFFER >= rxFree)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO, "RX Free: %d", rxFree));
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO, "RX free buffer count is too low, Pending frame count is %d",
currentReorderInfo->pendingFramesCount));
vosPktIdx = NULL;
status = WLANTL_ChainFrontPkts(ucFwdIdx,
WLANTL_OPCODE_FWDALL_DROPCUR,
&vosPktIdx,
currentReorderInfo,
pTLCb);
if(!VOS_IS_STATUS_SUCCESS(status))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Make frame chain fail %d", status));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return status;
}
if(NULL != *vosDataBuff)
{
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Already something, Chain it"));
vos_pkt_chain_packet(*vosDataBuff, vosPktIdx, 1);
}
else
{
*vosDataBuff = vosPktIdx;
}
currentReorderInfo->pendingFramesCount = 0;
}
/*
* Current aging timer logic:
* 1) if we forwarded any packets and the timer is running:
* stop the timer
* 2) if there are packets queued and the timer is not running:
* start the timer
*/
timerState = vos_timer_getCurrentState(¤tReorderInfo->agingTimer);
if ((VOS_TIMER_STATE_RUNNING == timerState) &&
(ucCIndexOrig != currentReorderInfo->ucCIndex))
{
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"HOLE filled, Pending Frames Count %d",
currentReorderInfo->pendingFramesCount));
// we forwarded some packets so stop aging the current hole
timerStatus = vos_timer_stop(¤tReorderInfo->agingTimer);
timerState = VOS_TIMER_STATE_STOPPED;
// ignore the returned status since there is a race condition
// whereby between the time we called getCurrentState() and the
// time we call stop() the timer could have fired. In that case
// stop() will return an error, but we don't care since the
// timer has stopped
}
if (currentReorderInfo->pendingFramesCount > 0)
{
if (VOS_TIMER_STATE_STOPPED == timerState)
{
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"There is a new HOLE, Pending Frames Count %d",
currentReorderInfo->pendingFramesCount));
timerStatus = vos_timer_start(¤tReorderInfo->agingTimer,
WLANTL_BA_REORDERING_AGING_TIMER);
if(!VOS_IS_STATUS_SUCCESS(timerStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Timer start fail: %d", timerStatus));
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return timerStatus;
}
}
else
{
// we didn't forward any packets and the timer was already
// running so we're still aging the same hole
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Still HOLE, Pending Frames Count %d",
currentReorderInfo->pendingFramesCount));
}
}
lockStatus = vos_lock_release(¤tReorderInfo->reorderLock);
if(!VOS_IS_STATUS_SUCCESS(lockStatus))
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"WLANTL_MSDUReorder, Release LOCK Fail"));
return lockStatus;
}
return VOS_STATUS_SUCCESS;
}/* WLANTL_MSDUReorder */
/*==========================================================================
Utility functions
==========================================================================*/
/*==========================================================================
FUNCTION WLANTL_QueueCurrent
DESCRIPTION
It will queue a packet at a given slot index in the MSDU reordering list.
DEPENDENCIES
PARAMETERS
IN
pwBaReorder: pointer to the BA reordering session info
vosDataBuff: data buffer to be queued
ucSlotIndex: slot index
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_SUCCESS: Everything is OK
SIDE EFFECTS
============================================================================*/
VOS_STATUS WLANTL_QueueCurrent
(
WLANTL_BAReorderType* pwBaReorder,
vos_pkt_t** vosDataBuff,
v_U8_t ucSlotIndex
)
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"vos Packet has to be Qed 0x%p",
*vosDataBuff));
if(NULL != pwBaReorder->reorderBuffer->arrayBuffer[ucSlotIndex])
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"One Cycle rounded, lost many frames already, not in Q %d\n",
pwBaReorder->pendingFramesCount));
return VOS_STATUS_E_RESOURCES;
}
pwBaReorder->reorderBuffer->arrayBuffer[ucSlotIndex] =
(v_PVOID_t)(*vosDataBuff);
pwBaReorder->pendingFramesCount++;
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Assigned, Pending Frames %d at slot %d, dataPtr 0x%x",
pwBaReorder->pendingFramesCount,
ucSlotIndex,
pwBaReorder->reorderBuffer->arrayBuffer[ucSlotIndex]));
return status;
}/*WLANTL_QueueCurrent*/
/*==========================================================================
FUNCTION WLANTL_ChainFrontPkts
DESCRIPTION
It will remove all the packets from the front of a vos list and chain
them to a vos pkt .
DEPENDENCIES
PARAMETERS
IN
ucCount: number of packets to extract
pwBaReorder: pointer to the BA reordering session info
OUT
vosDataBuff: data buffer containing the extracted chain of packets
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_SUCCESS: Everything is OK
SIDE EFFECTS
============================================================================*/
VOS_STATUS WLANTL_ChainFrontPkts
(
v_U32_t fwdIndex,
v_U8_t opCode,
vos_pkt_t **vosDataBuff,
WLANTL_BAReorderType *pwBaReorder,
WLANTL_CbType *pTLCb
)
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
v_U32_t idx;
v_PVOID_t currentDataPtr = NULL;
int negDetect;
#ifdef WLANTL_REORDER_DEBUG_MSG_ENABLE
#define WLANTL_OUT_OF_WINDOW_IDX 65
v_U32_t frameIdx[2] = {0, 0}, ffidx = fwdIndex, idx2 = WLANTL_OUT_OF_WINDOW_IDX;
int pending = pwBaReorder->pendingFramesCount, start = WLANTL_OUT_OF_WINDOW_IDX, end;
#endif
if(pwBaReorder->ucCIndex >= fwdIndex)
{
fwdIndex += pwBaReorder->winSize;
}
if((WLANTL_OPCODE_FWDALL_DROPCUR == opCode) ||
(WLANTL_OPCODE_FWDALL_QCUR == opCode))
{
fwdIndex = pwBaReorder->ucCIndex + pwBaReorder->winSize;
}
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Current Index %d, FWD Index %d, reorderBuffer 0x%p",
pwBaReorder->ucCIndex % pwBaReorder->winSize,
fwdIndex % pwBaReorder->winSize,
pwBaReorder->reorderBuffer));
negDetect = pwBaReorder->pendingFramesCount;
for(idx = pwBaReorder->ucCIndex; idx <= fwdIndex; idx++)
{
currentDataPtr =
pwBaReorder->reorderBuffer->arrayBuffer[idx % pwBaReorder->winSize];
if(NULL != currentDataPtr)
{
#ifdef WLANTL_REORDER_DEBUG_MSG_ENABLE
idx2 = (idx >= pwBaReorder->winSize) ? (idx - pwBaReorder->winSize) : idx;
frameIdx[idx2 / 32] |= 1 << (idx2 % 32);
if(start == WLANTL_OUT_OF_WINDOW_IDX) start = idx2;
#endif
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"There is buffered frame %d",
idx % pwBaReorder->winSize));
if(NULL == *vosDataBuff)
{
*vosDataBuff = (vos_pkt_t *)currentDataPtr;
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"This is new head %d",
idx % pwBaReorder->winSize));
}
else
{
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"There is bufered Just add %d",
idx % pwBaReorder->winSize));
vos_pkt_chain_packet(*vosDataBuff,
(vos_pkt_t *)currentDataPtr,
VOS_TRUE);
}
pwBaReorder->reorderBuffer->arrayBuffer[idx % pwBaReorder->winSize]
= NULL;
pwBaReorder->pendingFramesCount--;
negDetect--;
if(negDetect < 0)
{
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"This is not possible, some balance has problem\n"));
VOS_ASSERT(0);
return VOS_STATUS_E_FAULT;
}
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Slot Index %d, set as NULL, Pending Frames %d",
idx % pwBaReorder->winSize,
pwBaReorder->pendingFramesCount
));
pwBaReorder->ucCIndex = (idx + 1) % pwBaReorder->winSize;
}
else
{
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Empty Array %d",
idx % pwBaReorder->winSize));
}
TLLOG4(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_INFO_LOW,"Current Index %d, winSize %d",
pwBaReorder->ucCIndex,
pwBaReorder->winSize
));
}
#ifdef WLANTL_REORDER_DEBUG_MSG_ENABLE
end = idx2;
TLLOGE(VOS_TRACE(VOS_MODULE_ID_TL, VOS_TRACE_LEVEL_ERROR,"Fwd 0x%08X-%08X opCode %d fwdIdx %d windowSize %d pending frame %d fw no. %d from idx %d to %d",
frameIdx[1], frameIdx[0], opCode, ffidx, pwBaReorder->winSize, pending, pending - negDetect, start, end));
#endif
return status;
}/*WLANTL_ChainFrontPkts*/
/*==========================================================================
FUNCTION WLANTL_FillReplayCounter
DESCRIPTION
It will fill repaly counter at a given slot index in the MSDU reordering list.
DEPENDENCIES
PARAMETERS
IN
pwBaReorder : pointer to the BA reordering session info
replayCounter: replay counter to be filled
ucSlotIndex : slot index
RETURN VALUE
NONE
SIDE EFFECTS
NONE
============================================================================*/
void WLANTL_FillReplayCounter
(
WLANTL_BAReorderType* pwBaReorder,
v_U64_t ullreplayCounter,
v_U8_t ucSlotIndex
)
{
//BAMSGDEBUG("replay counter to be filled in Qed frames %llu",
//replayCounter, 0, 0);
pwBaReorder->reorderBuffer->ullReplayCounter[ucSlotIndex] = ullreplayCounter;
//BAMSGDEBUG("Assigned, replay counter Pending Frames %d at slot %d, replay counter[0x%llX]\n",
//pwBaReorder->pendingFramesCount,
//ucSlotIndex,
//pwBaReorder->reorderBuffer->ullReplayCounter);
return;
}/*WLANTL_FillReplayCounter*/
| gpl-2.0 |
venkatkamesh/android_kernel_sonyz_msm8974 | net/core/pktgen.c | 677 | 92826 | /*
* Authors:
* Copyright 2001, 2002 by Robert Olsson <robert.olsson@its.uu.se>
* Uppsala University and
* Swedish University of Agricultural Sciences
*
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Ben Greear <greearb@candelatech.com>
* Jens Låås <jens.laas@data.slu.se>
*
* 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.
*
*
* A tool for loading the network with preconfigurated packets.
* The tool is implemented as a linux module. Parameters are output
* device, delay (to hard_xmit), number of packets, and whether
* to use multiple SKBs or just the same one.
* pktgen uses the installed interface's output routine.
*
* Additional hacking by:
*
* Jens.Laas@data.slu.se
* Improved by ANK. 010120.
* Improved by ANK even more. 010212.
* MAC address typo fixed. 010417 --ro
* Integrated. 020301 --DaveM
* Added multiskb option 020301 --DaveM
* Scaling of results. 020417--sigurdur@linpro.no
* Significant re-work of the module:
* * Convert to threaded model to more efficiently be able to transmit
* and receive on multiple interfaces at once.
* * Converted many counters to __u64 to allow longer runs.
* * Allow configuration of ranges, like min/max IP address, MACs,
* and UDP-ports, for both source and destination, and can
* set to use a random distribution or sequentially walk the range.
* * Can now change most values after starting.
* * Place 12-byte packet in UDP payload with magic number,
* sequence number, and timestamp.
* * Add receiver code that detects dropped pkts, re-ordered pkts, and
* latencies (with micro-second) precision.
* * Add IOCTL interface to easily get counters & configuration.
* --Ben Greear <greearb@candelatech.com>
*
* Renamed multiskb to clone_skb and cleaned up sending core for two distinct
* skb modes. A clone_skb=0 mode for Ben "ranges" work and a clone_skb != 0
* as a "fastpath" with a configurable number of clones after alloc's.
* clone_skb=0 means all packets are allocated this also means ranges time
* stamps etc can be used. clone_skb=100 means 1 malloc is followed by 100
* clones.
*
* Also moved to /proc/net/pktgen/
* --ro
*
* Sept 10: Fixed threading/locking. Lots of bone-headed and more clever
* mistakes. Also merged in DaveM's patch in the -pre6 patch.
* --Ben Greear <greearb@candelatech.com>
*
* Integrated to 2.5.x 021029 --Lucio Maciel (luciomaciel@zipmail.com.br)
*
*
* 021124 Finished major redesign and rewrite for new functionality.
* See Documentation/networking/pktgen.txt for how to use this.
*
* The new operation:
* For each CPU one thread/process is created at start. This process checks
* for running devices in the if_list and sends packets until count is 0 it
* also the thread checks the thread->control which is used for inter-process
* communication. controlling process "posts" operations to the threads this
* way. The if_lock should be possible to remove when add/rem_device is merged
* into this too.
*
* By design there should only be *one* "controlling" process. In practice
* multiple write accesses gives unpredictable result. Understood by "write"
* to /proc gives result code thats should be read be the "writer".
* For practical use this should be no problem.
*
* Note when adding devices to a specific CPU there good idea to also assign
* /proc/irq/XX/smp_affinity so TX-interrupts gets bound to the same CPU.
* --ro
*
* Fix refcount off by one if first packet fails, potential null deref,
* memleak 030710- KJP
*
* First "ranges" functionality for ipv6 030726 --ro
*
* Included flow support. 030802 ANK.
*
* Fixed unaligned access on IA-64 Grant Grundler <grundler@parisc-linux.org>
*
* Remove if fix from added Harald Welte <laforge@netfilter.org> 040419
* ia64 compilation fix from Aron Griffis <aron@hp.com> 040604
*
* New xmit() return, do_div and misc clean up by Stephen Hemminger
* <shemminger@osdl.org> 040923
*
* Randy Dunlap fixed u64 printk compiler waring
*
* Remove FCS from BW calculation. Lennert Buytenhek <buytenh@wantstofly.org>
* New time handling. Lennert Buytenhek <buytenh@wantstofly.org> 041213
*
* Corrections from Nikolai Malykh (nmalykh@bilim.com)
* Removed unused flags F_SET_SRCMAC & F_SET_SRCIP 041230
*
* interruptible_sleep_on_timeout() replaced Nishanth Aravamudan <nacc@us.ibm.com>
* 050103
*
* MPLS support by Steven Whitehouse <steve@chygwyn.com>
*
* 802.1Q/Q-in-Q support by Francesco Fondelli (FF) <francesco.fondelli@gmail.com>
*
* Fixed src_mac command to set source mac of packet to value specified in
* command by Adit Ranadive <adit.262@gmail.com>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sys.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/unistd.h>
#include <linux/string.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/hrtimer.h>
#include <linux/freezer.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/rtnetlink.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/udp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/wait.h>
#include <linux/etherdevice.h>
#include <linux/kthread.h>
#include <linux/prefetch.h>
#include <net/net_namespace.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
#ifdef CONFIG_XFRM
#include <net/xfrm.h>
#endif
#include <asm/byteorder.h>
#include <linux/rcupdate.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <linux/timex.h>
#include <linux/uaccess.h>
#include <asm/dma.h>
#include <asm/div64.h> /* do_div */
#define VERSION "2.74"
#define IP_NAME_SZ 32
#define MAX_MPLS_LABELS 16 /* This is the max label stack depth */
#define MPLS_STACK_BOTTOM htonl(0x00000100)
#define func_enter() pr_debug("entering %s\n", __func__);
/* Device flag bits */
#define F_IPSRC_RND (1<<0) /* IP-Src Random */
#define F_IPDST_RND (1<<1) /* IP-Dst Random */
#define F_UDPSRC_RND (1<<2) /* UDP-Src Random */
#define F_UDPDST_RND (1<<3) /* UDP-Dst Random */
#define F_MACSRC_RND (1<<4) /* MAC-Src Random */
#define F_MACDST_RND (1<<5) /* MAC-Dst Random */
#define F_TXSIZE_RND (1<<6) /* Transmit size is random */
#define F_IPV6 (1<<7) /* Interface in IPV6 Mode */
#define F_MPLS_RND (1<<8) /* Random MPLS labels */
#define F_VID_RND (1<<9) /* Random VLAN ID */
#define F_SVID_RND (1<<10) /* Random SVLAN ID */
#define F_FLOW_SEQ (1<<11) /* Sequential flows */
#define F_IPSEC_ON (1<<12) /* ipsec on for flows */
#define F_QUEUE_MAP_RND (1<<13) /* queue map Random */
#define F_QUEUE_MAP_CPU (1<<14) /* queue map mirrors smp_processor_id() */
#define F_NODE (1<<15) /* Node memory alloc*/
/* Thread control flag bits */
#define T_STOP (1<<0) /* Stop run */
#define T_RUN (1<<1) /* Start run */
#define T_REMDEVALL (1<<2) /* Remove all devs */
#define T_REMDEV (1<<3) /* Remove one dev */
/* If lock -- can be removed after some work */
#define if_lock(t) spin_lock(&(t->if_lock));
#define if_unlock(t) spin_unlock(&(t->if_lock));
/* Used to help with determining the pkts on receive */
#define PKTGEN_MAGIC 0xbe9be955
#define PG_PROC_DIR "pktgen"
#define PGCTRL "pgctrl"
static struct proc_dir_entry *pg_proc_dir;
#define MAX_CFLOWS 65536
#define VLAN_TAG_SIZE(x) ((x)->vlan_id == 0xffff ? 0 : 4)
#define SVLAN_TAG_SIZE(x) ((x)->svlan_id == 0xffff ? 0 : 4)
struct flow_state {
__be32 cur_daddr;
int count;
#ifdef CONFIG_XFRM
struct xfrm_state *x;
#endif
__u32 flags;
};
/* flow flag bits */
#define F_INIT (1<<0) /* flow has been initialized */
struct pktgen_dev {
/*
* Try to keep frequent/infrequent used vars. separated.
*/
struct proc_dir_entry *entry; /* proc file */
struct pktgen_thread *pg_thread;/* the owner */
struct list_head list; /* chaining in the thread's run-queue */
int running; /* if false, the test will stop */
/* If min != max, then we will either do a linear iteration, or
* we will do a random selection from within the range.
*/
__u32 flags;
int removal_mark; /* non-zero => the device is marked for
* removal by worker thread */
int min_pkt_size; /* = ETH_ZLEN; */
int max_pkt_size; /* = ETH_ZLEN; */
int pkt_overhead; /* overhead for MPLS, VLANs, IPSEC etc */
int nfrags;
struct page *page;
u64 delay; /* nano-seconds */
__u64 count; /* Default No packets to send */
__u64 sofar; /* How many pkts we've sent so far */
__u64 tx_bytes; /* How many bytes we've transmitted */
__u64 errors; /* Errors when trying to transmit, */
/* runtime counters relating to clone_skb */
__u64 allocated_skbs;
__u32 clone_count;
int last_ok; /* Was last skb sent?
* Or a failed transmit of some sort?
* This will keep sequence numbers in order
*/
ktime_t next_tx;
ktime_t started_at;
ktime_t stopped_at;
u64 idle_acc; /* nano-seconds */
__u32 seq_num;
int clone_skb; /*
* Use multiple SKBs during packet gen.
* If this number is greater than 1, then
* that many copies of the same packet will be
* sent before a new packet is allocated.
* If you want to send 1024 identical packets
* before creating a new packet,
* set clone_skb to 1024.
*/
char dst_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char dst_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
struct in6_addr in6_saddr;
struct in6_addr in6_daddr;
struct in6_addr cur_in6_daddr;
struct in6_addr cur_in6_saddr;
/* For ranges */
struct in6_addr min_in6_daddr;
struct in6_addr max_in6_daddr;
struct in6_addr min_in6_saddr;
struct in6_addr max_in6_saddr;
/* If we're doing ranges, random or incremental, then this
* defines the min/max for those ranges.
*/
__be32 saddr_min; /* inclusive, source IP address */
__be32 saddr_max; /* exclusive, source IP address */
__be32 daddr_min; /* inclusive, dest IP address */
__be32 daddr_max; /* exclusive, dest IP address */
__u16 udp_src_min; /* inclusive, source UDP port */
__u16 udp_src_max; /* exclusive, source UDP port */
__u16 udp_dst_min; /* inclusive, dest UDP port */
__u16 udp_dst_max; /* exclusive, dest UDP port */
/* DSCP + ECN */
__u8 tos; /* six MSB of (former) IPv4 TOS
are for dscp codepoint */
__u8 traffic_class; /* ditto for the (former) Traffic Class in IPv6
(see RFC 3260, sec. 4) */
/* MPLS */
unsigned nr_labels; /* Depth of stack, 0 = no MPLS */
__be32 labels[MAX_MPLS_LABELS];
/* VLAN/SVLAN (802.1Q/Q-in-Q) */
__u8 vlan_p;
__u8 vlan_cfi;
__u16 vlan_id; /* 0xffff means no vlan tag */
__u8 svlan_p;
__u8 svlan_cfi;
__u16 svlan_id; /* 0xffff means no svlan tag */
__u32 src_mac_count; /* How many MACs to iterate through */
__u32 dst_mac_count; /* How many MACs to iterate through */
unsigned char dst_mac[ETH_ALEN];
unsigned char src_mac[ETH_ALEN];
__u32 cur_dst_mac_offset;
__u32 cur_src_mac_offset;
__be32 cur_saddr;
__be32 cur_daddr;
__u16 ip_id;
__u16 cur_udp_dst;
__u16 cur_udp_src;
__u16 cur_queue_map;
__u32 cur_pkt_size;
__u32 last_pkt_size;
__u8 hh[14];
/* = {
0x00, 0x80, 0xC8, 0x79, 0xB3, 0xCB,
We fill in SRC address later
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00
};
*/
__u16 pad; /* pad out the hh struct to an even 16 bytes */
struct sk_buff *skb; /* skb we are to transmit next, used for when we
* are transmitting the same one multiple times
*/
struct net_device *odev; /* The out-going device.
* Note that the device should have it's
* pg_info pointer pointing back to this
* device.
* Set when the user specifies the out-going
* device name (not when the inject is
* started as it used to do.)
*/
char odevname[32];
struct flow_state *flows;
unsigned cflows; /* Concurrent flows (config) */
unsigned lflow; /* Flow length (config) */
unsigned nflows; /* accumulated flows (stats) */
unsigned curfl; /* current sequenced flow (state)*/
u16 queue_map_min;
u16 queue_map_max;
__u32 skb_priority; /* skb priority field */
int node; /* Memory node */
#ifdef CONFIG_XFRM
__u8 ipsmode; /* IPSEC mode (config) */
__u8 ipsproto; /* IPSEC type (config) */
#endif
char result[512];
};
struct pktgen_hdr {
__be32 pgh_magic;
__be32 seq_num;
__be32 tv_sec;
__be32 tv_usec;
};
static bool pktgen_exiting __read_mostly;
struct pktgen_thread {
spinlock_t if_lock; /* for list of devices */
struct list_head if_list; /* All device here */
struct list_head th_list;
struct task_struct *tsk;
char result[512];
/* Field for thread to receive "posted" events terminate,
stop ifs etc. */
u32 control;
int cpu;
wait_queue_head_t queue;
struct completion start_done;
};
#define REMOVE 1
#define FIND 0
static const char version[] =
"Packet Generator for packet performance testing. "
"Version: " VERSION "\n";
static int pktgen_remove_device(struct pktgen_thread *t, struct pktgen_dev *i);
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname);
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact);
static int pktgen_device_event(struct notifier_block *, unsigned long, void *);
static void pktgen_run_all_threads(void);
static void pktgen_reset_all_threads(void);
static void pktgen_stop_all_threads_ifs(void);
static void pktgen_stop(struct pktgen_thread *t);
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev);
static unsigned int scan_ip6(const char *s, char ip[16]);
/* Module parameters, defaults. */
static int pg_count_d __read_mostly = 1000;
static int pg_delay_d __read_mostly;
static int pg_clone_skb_d __read_mostly;
static int debug __read_mostly;
static DEFINE_MUTEX(pktgen_thread_lock);
static LIST_HEAD(pktgen_threads);
static struct notifier_block pktgen_notifier_block = {
.notifier_call = pktgen_device_event,
};
/*
* /proc handling functions
*
*/
static int pgctrl_show(struct seq_file *seq, void *v)
{
seq_puts(seq, version);
return 0;
}
static ssize_t pgctrl_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int err = 0;
char data[128];
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto out;
}
if (count > sizeof(data))
count = sizeof(data);
if (copy_from_user(data, buf, count)) {
err = -EFAULT;
goto out;
}
data[count - 1] = 0; /* Make string */
if (!strcmp(data, "stop"))
pktgen_stop_all_threads_ifs();
else if (!strcmp(data, "start"))
pktgen_run_all_threads();
else if (!strcmp(data, "reset"))
pktgen_reset_all_threads();
else
pr_warning("Unknown command: %s\n", data);
err = count;
out:
return err;
}
static int pgctrl_open(struct inode *inode, struct file *file)
{
return single_open(file, pgctrl_show, PDE(inode)->data);
}
static const struct file_operations pktgen_fops = {
.owner = THIS_MODULE,
.open = pgctrl_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pgctrl_write,
.release = single_release,
};
static int pktgen_if_show(struct seq_file *seq, void *v)
{
const struct pktgen_dev *pkt_dev = seq->private;
ktime_t stopped;
u64 idle;
seq_printf(seq,
"Params: count %llu min_pkt_size: %u max_pkt_size: %u\n",
(unsigned long long)pkt_dev->count, pkt_dev->min_pkt_size,
pkt_dev->max_pkt_size);
seq_printf(seq,
" frags: %d delay: %llu clone_skb: %d ifname: %s\n",
pkt_dev->nfrags, (unsigned long long) pkt_dev->delay,
pkt_dev->clone_skb, pkt_dev->odevname);
seq_printf(seq, " flows: %u flowlen: %u\n", pkt_dev->cflows,
pkt_dev->lflow);
seq_printf(seq,
" queue_map_min: %u queue_map_max: %u\n",
pkt_dev->queue_map_min,
pkt_dev->queue_map_max);
if (pkt_dev->skb_priority)
seq_printf(seq, " skb_priority: %u\n",
pkt_dev->skb_priority);
if (pkt_dev->flags & F_IPV6) {
seq_printf(seq,
" saddr: %pI6c min_saddr: %pI6c max_saddr: %pI6c\n"
" daddr: %pI6c min_daddr: %pI6c max_daddr: %pI6c\n",
&pkt_dev->in6_saddr,
&pkt_dev->min_in6_saddr, &pkt_dev->max_in6_saddr,
&pkt_dev->in6_daddr,
&pkt_dev->min_in6_daddr, &pkt_dev->max_in6_daddr);
} else {
seq_printf(seq,
" dst_min: %s dst_max: %s\n",
pkt_dev->dst_min, pkt_dev->dst_max);
seq_printf(seq,
" src_min: %s src_max: %s\n",
pkt_dev->src_min, pkt_dev->src_max);
}
seq_puts(seq, " src_mac: ");
seq_printf(seq, "%pM ",
is_zero_ether_addr(pkt_dev->src_mac) ?
pkt_dev->odev->dev_addr : pkt_dev->src_mac);
seq_printf(seq, "dst_mac: ");
seq_printf(seq, "%pM\n", pkt_dev->dst_mac);
seq_printf(seq,
" udp_src_min: %d udp_src_max: %d"
" udp_dst_min: %d udp_dst_max: %d\n",
pkt_dev->udp_src_min, pkt_dev->udp_src_max,
pkt_dev->udp_dst_min, pkt_dev->udp_dst_max);
seq_printf(seq,
" src_mac_count: %d dst_mac_count: %d\n",
pkt_dev->src_mac_count, pkt_dev->dst_mac_count);
if (pkt_dev->nr_labels) {
unsigned i;
seq_printf(seq, " mpls: ");
for (i = 0; i < pkt_dev->nr_labels; i++)
seq_printf(seq, "%08x%s", ntohl(pkt_dev->labels[i]),
i == pkt_dev->nr_labels-1 ? "\n" : ", ");
}
if (pkt_dev->vlan_id != 0xffff)
seq_printf(seq, " vlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->vlan_id, pkt_dev->vlan_p,
pkt_dev->vlan_cfi);
if (pkt_dev->svlan_id != 0xffff)
seq_printf(seq, " svlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->svlan_id, pkt_dev->svlan_p,
pkt_dev->svlan_cfi);
if (pkt_dev->tos)
seq_printf(seq, " tos: 0x%02x\n", pkt_dev->tos);
if (pkt_dev->traffic_class)
seq_printf(seq, " traffic_class: 0x%02x\n", pkt_dev->traffic_class);
if (pkt_dev->node >= 0)
seq_printf(seq, " node: %d\n", pkt_dev->node);
seq_printf(seq, " Flags: ");
if (pkt_dev->flags & F_IPV6)
seq_printf(seq, "IPV6 ");
if (pkt_dev->flags & F_IPSRC_RND)
seq_printf(seq, "IPSRC_RND ");
if (pkt_dev->flags & F_IPDST_RND)
seq_printf(seq, "IPDST_RND ");
if (pkt_dev->flags & F_TXSIZE_RND)
seq_printf(seq, "TXSIZE_RND ");
if (pkt_dev->flags & F_UDPSRC_RND)
seq_printf(seq, "UDPSRC_RND ");
if (pkt_dev->flags & F_UDPDST_RND)
seq_printf(seq, "UDPDST_RND ");
if (pkt_dev->flags & F_MPLS_RND)
seq_printf(seq, "MPLS_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_RND)
seq_printf(seq, "QUEUE_MAP_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
seq_printf(seq, "QUEUE_MAP_CPU ");
if (pkt_dev->cflows) {
if (pkt_dev->flags & F_FLOW_SEQ)
seq_printf(seq, "FLOW_SEQ "); /*in sequence flows*/
else
seq_printf(seq, "FLOW_RND ");
}
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
seq_printf(seq, "IPSEC ");
#endif
if (pkt_dev->flags & F_MACSRC_RND)
seq_printf(seq, "MACSRC_RND ");
if (pkt_dev->flags & F_MACDST_RND)
seq_printf(seq, "MACDST_RND ");
if (pkt_dev->flags & F_VID_RND)
seq_printf(seq, "VID_RND ");
if (pkt_dev->flags & F_SVID_RND)
seq_printf(seq, "SVID_RND ");
if (pkt_dev->flags & F_NODE)
seq_printf(seq, "NODE_ALLOC ");
seq_puts(seq, "\n");
/* not really stopped, more like last-running-at */
stopped = pkt_dev->running ? ktime_get() : pkt_dev->stopped_at;
idle = pkt_dev->idle_acc;
do_div(idle, NSEC_PER_USEC);
seq_printf(seq,
"Current:\n pkts-sofar: %llu errors: %llu\n",
(unsigned long long)pkt_dev->sofar,
(unsigned long long)pkt_dev->errors);
seq_printf(seq,
" started: %lluus stopped: %lluus idle: %lluus\n",
(unsigned long long) ktime_to_us(pkt_dev->started_at),
(unsigned long long) ktime_to_us(stopped),
(unsigned long long) idle);
seq_printf(seq,
" seq_num: %d cur_dst_mac_offset: %d cur_src_mac_offset: %d\n",
pkt_dev->seq_num, pkt_dev->cur_dst_mac_offset,
pkt_dev->cur_src_mac_offset);
if (pkt_dev->flags & F_IPV6) {
seq_printf(seq, " cur_saddr: %pI6c cur_daddr: %pI6c\n",
&pkt_dev->cur_in6_saddr,
&pkt_dev->cur_in6_daddr);
} else
seq_printf(seq, " cur_saddr: 0x%x cur_daddr: 0x%x\n",
pkt_dev->cur_saddr, pkt_dev->cur_daddr);
seq_printf(seq, " cur_udp_dst: %d cur_udp_src: %d\n",
pkt_dev->cur_udp_dst, pkt_dev->cur_udp_src);
seq_printf(seq, " cur_queue_map: %u\n", pkt_dev->cur_queue_map);
seq_printf(seq, " flows: %u\n", pkt_dev->nflows);
if (pkt_dev->result[0])
seq_printf(seq, "Result: %s\n", pkt_dev->result);
else
seq_printf(seq, "Result: Idle\n");
return 0;
}
static int hex32_arg(const char __user *user_buffer, unsigned long maxlen,
__u32 *num)
{
int i = 0;
*num = 0;
for (; i < maxlen; i++) {
int value;
char c;
*num <<= 4;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
value = hex_to_bin(c);
if (value >= 0)
*num |= value;
else
break;
}
return i;
}
static int count_trail_chars(const char __user * user_buffer,
unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
case '=':
break;
default:
goto done;
}
}
done:
return i;
}
static long num_arg(const char __user *user_buffer, unsigned long maxlen,
unsigned long *num)
{
int i;
*num = 0;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
if ((c >= '0') && (c <= '9')) {
*num *= 10;
*num += c - '0';
} else
break;
}
return i;
}
static int strn_len(const char __user * user_buffer, unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
goto done_str;
break;
default:
break;
}
}
done_str:
return i;
}
static ssize_t get_labels(const char __user *buffer, struct pktgen_dev *pkt_dev)
{
unsigned n = 0;
char c;
ssize_t i = 0;
int len;
pkt_dev->nr_labels = 0;
do {
__u32 tmp;
len = hex32_arg(&buffer[i], 8, &tmp);
if (len <= 0)
return len;
pkt_dev->labels[n] = htonl(tmp);
if (pkt_dev->labels[n] & MPLS_STACK_BOTTOM)
pkt_dev->flags |= F_MPLS_RND;
i += len;
if (get_user(c, &buffer[i]))
return -EFAULT;
i++;
n++;
if (n >= MAX_MPLS_LABELS)
return -E2BIG;
} while (c == ',');
pkt_dev->nr_labels = n;
return i;
}
static ssize_t pktgen_if_write(struct file *file,
const char __user * user_buffer, size_t count,
loff_t * offset)
{
struct seq_file *seq = file->private_data;
struct pktgen_dev *pkt_dev = seq->private;
int i, max, len;
char name[16], valstr[32];
unsigned long value = 0;
char *pg_result = NULL;
int tmp = 0;
char buf[128];
pg_result = &(pkt_dev->result[0]);
if (count < 1) {
pr_warning("wrong command format\n");
return -EINVAL;
}
max = count;
tmp = count_trail_chars(user_buffer, max);
if (tmp < 0) {
pr_warning("illegal format\n");
return tmp;
}
i = tmp;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug) {
size_t copy = min_t(size_t, count, 1023);
char tb[copy + 1];
if (copy_from_user(tb, user_buffer, copy))
return -EFAULT;
tb[copy] = 0;
printk(KERN_DEBUG "pktgen: %s,%lu buffer -:%s:-\n", name,
(unsigned long)count, tb);
}
if (!strcmp(name, "min_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: min_pkt_size=%u",
pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "max_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->max_pkt_size) {
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: max_pkt_size=%u",
pkt_dev->max_pkt_size);
return count;
}
/* Shortcut for min = max */
if (!strcmp(name, "pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: pkt_size=%u", pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "debug")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
debug = value;
sprintf(pg_result, "OK: debug=%u", debug);
return count;
}
if (!strcmp(name, "frags")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->nfrags = value;
sprintf(pg_result, "OK: frags=%u", pkt_dev->nfrags);
return count;
}
if (!strcmp(name, "delay")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value == 0x7FFFFFFF)
pkt_dev->delay = ULLONG_MAX;
else
pkt_dev->delay = (u64)value;
sprintf(pg_result, "OK: delay=%llu",
(unsigned long long) pkt_dev->delay);
return count;
}
if (!strcmp(name, "rate")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (!value)
return len;
pkt_dev->delay = pkt_dev->min_pkt_size*8*NSEC_PER_USEC/value;
if (debug)
pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
sprintf(pg_result, "OK: rate=%lu", value);
return count;
}
if (!strcmp(name, "ratep")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (!value)
return len;
pkt_dev->delay = NSEC_PER_SEC/value;
if (debug)
pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
sprintf(pg_result, "OK: rate=%lu", value);
return count;
}
if (!strcmp(name, "udp_src_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_min) {
pkt_dev->udp_src_min = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_min=%u", pkt_dev->udp_src_min);
return count;
}
if (!strcmp(name, "udp_dst_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_min) {
pkt_dev->udp_dst_min = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_min=%u", pkt_dev->udp_dst_min);
return count;
}
if (!strcmp(name, "udp_src_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_max) {
pkt_dev->udp_src_max = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_max=%u", pkt_dev->udp_src_max);
return count;
}
if (!strcmp(name, "udp_dst_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_max) {
pkt_dev->udp_dst_max = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_max=%u", pkt_dev->udp_dst_max);
return count;
}
if (!strcmp(name, "clone_skb")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
if ((value > 0) &&
(!(pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)))
return -ENOTSUPP;
i += len;
pkt_dev->clone_skb = value;
sprintf(pg_result, "OK: clone_skb=%d", pkt_dev->clone_skb);
return count;
}
if (!strcmp(name, "count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->count = value;
sprintf(pg_result, "OK: count=%llu",
(unsigned long long)pkt_dev->count);
return count;
}
if (!strcmp(name, "src_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->src_mac_count != value) {
pkt_dev->src_mac_count = value;
pkt_dev->cur_src_mac_offset = 0;
}
sprintf(pg_result, "OK: src_mac_count=%d",
pkt_dev->src_mac_count);
return count;
}
if (!strcmp(name, "dst_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->dst_mac_count != value) {
pkt_dev->dst_mac_count = value;
pkt_dev->cur_dst_mac_offset = 0;
}
sprintf(pg_result, "OK: dst_mac_count=%d",
pkt_dev->dst_mac_count);
return count;
}
if (!strcmp(name, "node")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (node_possible(value)) {
pkt_dev->node = value;
sprintf(pg_result, "OK: node=%d", pkt_dev->node);
if (pkt_dev->page) {
put_page(pkt_dev->page);
pkt_dev->page = NULL;
}
}
else
sprintf(pg_result, "ERROR: node not possible");
return count;
}
if (!strcmp(name, "flag")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0)
return len;
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
if (strcmp(f, "IPSRC_RND") == 0)
pkt_dev->flags |= F_IPSRC_RND;
else if (strcmp(f, "!IPSRC_RND") == 0)
pkt_dev->flags &= ~F_IPSRC_RND;
else if (strcmp(f, "TXSIZE_RND") == 0)
pkt_dev->flags |= F_TXSIZE_RND;
else if (strcmp(f, "!TXSIZE_RND") == 0)
pkt_dev->flags &= ~F_TXSIZE_RND;
else if (strcmp(f, "IPDST_RND") == 0)
pkt_dev->flags |= F_IPDST_RND;
else if (strcmp(f, "!IPDST_RND") == 0)
pkt_dev->flags &= ~F_IPDST_RND;
else if (strcmp(f, "UDPSRC_RND") == 0)
pkt_dev->flags |= F_UDPSRC_RND;
else if (strcmp(f, "!UDPSRC_RND") == 0)
pkt_dev->flags &= ~F_UDPSRC_RND;
else if (strcmp(f, "UDPDST_RND") == 0)
pkt_dev->flags |= F_UDPDST_RND;
else if (strcmp(f, "!UDPDST_RND") == 0)
pkt_dev->flags &= ~F_UDPDST_RND;
else if (strcmp(f, "MACSRC_RND") == 0)
pkt_dev->flags |= F_MACSRC_RND;
else if (strcmp(f, "!MACSRC_RND") == 0)
pkt_dev->flags &= ~F_MACSRC_RND;
else if (strcmp(f, "MACDST_RND") == 0)
pkt_dev->flags |= F_MACDST_RND;
else if (strcmp(f, "!MACDST_RND") == 0)
pkt_dev->flags &= ~F_MACDST_RND;
else if (strcmp(f, "MPLS_RND") == 0)
pkt_dev->flags |= F_MPLS_RND;
else if (strcmp(f, "!MPLS_RND") == 0)
pkt_dev->flags &= ~F_MPLS_RND;
else if (strcmp(f, "VID_RND") == 0)
pkt_dev->flags |= F_VID_RND;
else if (strcmp(f, "!VID_RND") == 0)
pkt_dev->flags &= ~F_VID_RND;
else if (strcmp(f, "SVID_RND") == 0)
pkt_dev->flags |= F_SVID_RND;
else if (strcmp(f, "!SVID_RND") == 0)
pkt_dev->flags &= ~F_SVID_RND;
else if (strcmp(f, "FLOW_SEQ") == 0)
pkt_dev->flags |= F_FLOW_SEQ;
else if (strcmp(f, "QUEUE_MAP_RND") == 0)
pkt_dev->flags |= F_QUEUE_MAP_RND;
else if (strcmp(f, "!QUEUE_MAP_RND") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_RND;
else if (strcmp(f, "QUEUE_MAP_CPU") == 0)
pkt_dev->flags |= F_QUEUE_MAP_CPU;
else if (strcmp(f, "!QUEUE_MAP_CPU") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_CPU;
#ifdef CONFIG_XFRM
else if (strcmp(f, "IPSEC") == 0)
pkt_dev->flags |= F_IPSEC_ON;
#endif
else if (strcmp(f, "!IPV6") == 0)
pkt_dev->flags &= ~F_IPV6;
else if (strcmp(f, "NODE_ALLOC") == 0)
pkt_dev->flags |= F_NODE;
else if (strcmp(f, "!NODE_ALLOC") == 0)
pkt_dev->flags &= ~F_NODE;
else {
sprintf(pg_result,
"Flag -:%s:- unknown\nAvailable flags, (prepend ! to un-set flag):\n%s",
f,
"IPSRC_RND, IPDST_RND, UDPSRC_RND, UDPDST_RND, "
"MACSRC_RND, MACDST_RND, TXSIZE_RND, IPV6, MPLS_RND, VID_RND, SVID_RND, FLOW_SEQ, IPSEC, NODE_ALLOC\n");
return count;
}
sprintf(pg_result, "OK: flags=0x%x", pkt_dev->flags);
return count;
}
if (!strcmp(name, "dst_min") || !strcmp(name, "dst")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_min) != 0) {
memset(pkt_dev->dst_min, 0, sizeof(pkt_dev->dst_min));
strncpy(pkt_dev->dst_min, buf, len);
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->cur_daddr = pkt_dev->daddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_min set to: %s\n",
pkt_dev->dst_min);
i += len;
sprintf(pg_result, "OK: dst_min=%s", pkt_dev->dst_min);
return count;
}
if (!strcmp(name, "dst_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_max) != 0) {
memset(pkt_dev->dst_max, 0, sizeof(pkt_dev->dst_max));
strncpy(pkt_dev->dst_max, buf, len);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
pkt_dev->cur_daddr = pkt_dev->daddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_max set to: %s\n",
pkt_dev->dst_max);
i += len;
sprintf(pg_result, "OK: dst_max=%s", pkt_dev->dst_max);
return count;
}
if (!strcmp(name, "dst6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_daddr);
pkt_dev->cur_in6_daddr = pkt_dev->in6_daddr;
if (debug)
printk(KERN_DEBUG "pktgen: dst6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6=%s", buf);
return count;
}
if (!strcmp(name, "dst6_min")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->min_in6_daddr);
pkt_dev->cur_in6_daddr = pkt_dev->min_in6_daddr;
if (debug)
printk(KERN_DEBUG "pktgen: dst6_min set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_min=%s", buf);
return count;
}
if (!strcmp(name, "dst6_max")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->max_in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_max set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_max=%s", buf);
return count;
}
if (!strcmp(name, "src6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_saddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_saddr);
pkt_dev->cur_in6_saddr = pkt_dev->in6_saddr;
if (debug)
printk(KERN_DEBUG "pktgen: src6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: src6=%s", buf);
return count;
}
if (!strcmp(name, "src_min")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_min) != 0) {
memset(pkt_dev->src_min, 0, sizeof(pkt_dev->src_min));
strncpy(pkt_dev->src_min, buf, len);
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->cur_saddr = pkt_dev->saddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_min set to: %s\n",
pkt_dev->src_min);
i += len;
sprintf(pg_result, "OK: src_min=%s", pkt_dev->src_min);
return count;
}
if (!strcmp(name, "src_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_max) != 0) {
memset(pkt_dev->src_max, 0, sizeof(pkt_dev->src_max));
strncpy(pkt_dev->src_max, buf, len);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
pkt_dev->cur_saddr = pkt_dev->saddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_max set to: %s\n",
pkt_dev->src_max);
i += len;
sprintf(pg_result, "OK: src_max=%s", pkt_dev->src_max);
return count;
}
if (!strcmp(name, "dst_mac")) {
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
if (!mac_pton(valstr, pkt_dev->dst_mac))
return -EINVAL;
/* Set up Dest MAC */
memcpy(&pkt_dev->hh[0], pkt_dev->dst_mac, ETH_ALEN);
sprintf(pg_result, "OK: dstmac %pM", pkt_dev->dst_mac);
return count;
}
if (!strcmp(name, "src_mac")) {
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
if (!mac_pton(valstr, pkt_dev->src_mac))
return -EINVAL;
/* Set up Src MAC */
memcpy(&pkt_dev->hh[6], pkt_dev->src_mac, ETH_ALEN);
sprintf(pg_result, "OK: srcmac %pM", pkt_dev->src_mac);
return count;
}
if (!strcmp(name, "clear_counters")) {
pktgen_clear_counters(pkt_dev);
sprintf(pg_result, "OK: Clearing counters.\n");
return count;
}
if (!strcmp(name, "flows")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value > MAX_CFLOWS)
value = MAX_CFLOWS;
pkt_dev->cflows = value;
sprintf(pg_result, "OK: flows=%u", pkt_dev->cflows);
return count;
}
if (!strcmp(name, "flowlen")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->lflow = value;
sprintf(pg_result, "OK: flowlen=%u", pkt_dev->lflow);
return count;
}
if (!strcmp(name, "queue_map_min")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_min = value;
sprintf(pg_result, "OK: queue_map_min=%u", pkt_dev->queue_map_min);
return count;
}
if (!strcmp(name, "queue_map_max")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_max = value;
sprintf(pg_result, "OK: queue_map_max=%u", pkt_dev->queue_map_max);
return count;
}
if (!strcmp(name, "mpls")) {
unsigned n, cnt;
len = get_labels(&user_buffer[i], pkt_dev);
if (len < 0)
return len;
i += len;
cnt = sprintf(pg_result, "OK: mpls=");
for (n = 0; n < pkt_dev->nr_labels; n++)
cnt += sprintf(pg_result + cnt,
"%08x%s", ntohl(pkt_dev->labels[n]),
n == pkt_dev->nr_labels-1 ? "" : ",");
if (pkt_dev->nr_labels && pkt_dev->vlan_id != 0xffff) {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN auto turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if (value <= 4095) {
pkt_dev->vlan_id = value; /* turn on VLAN */
if (debug)
printk(KERN_DEBUG "pktgen: VLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: vlan_id=%u", pkt_dev->vlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_p = value;
sprintf(pg_result, "OK: vlan_p=%u", pkt_dev->vlan_p);
} else {
sprintf(pg_result, "ERROR: vlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "vlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_cfi = value;
sprintf(pg_result, "OK: vlan_cfi=%u", pkt_dev->vlan_cfi);
} else {
sprintf(pg_result, "ERROR: vlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "svlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if ((value <= 4095) && ((pkt_dev->vlan_id != 0xffff))) {
pkt_dev->svlan_id = value; /* turn on SVLAN */
if (debug)
printk(KERN_DEBUG "pktgen: SVLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: svlan_id=%u", pkt_dev->svlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "svlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_p = value;
sprintf(pg_result, "OK: svlan_p=%u", pkt_dev->svlan_p);
} else {
sprintf(pg_result, "ERROR: svlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "svlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_cfi = value;
sprintf(pg_result, "OK: svlan_cfi=%u", pkt_dev->svlan_cfi);
} else {
sprintf(pg_result, "ERROR: svlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "tos")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->tos = tmp_value;
sprintf(pg_result, "OK: tos=0x%02x", pkt_dev->tos);
} else {
sprintf(pg_result, "ERROR: tos must be 00-ff");
}
return count;
}
if (!strcmp(name, "traffic_class")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->traffic_class = tmp_value;
sprintf(pg_result, "OK: traffic_class=0x%02x", pkt_dev->traffic_class);
} else {
sprintf(pg_result, "ERROR: traffic_class must be 00-ff");
}
return count;
}
if (!strcmp(name, "skb_priority")) {
len = num_arg(&user_buffer[i], 9, &value);
if (len < 0)
return len;
i += len;
pkt_dev->skb_priority = value;
sprintf(pg_result, "OK: skb_priority=%i",
pkt_dev->skb_priority);
return count;
}
sprintf(pkt_dev->result, "No such parameter \"%s\"", name);
return -EINVAL;
}
static int pktgen_if_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_if_show, PDE(inode)->data);
}
static const struct file_operations pktgen_if_fops = {
.owner = THIS_MODULE,
.open = pktgen_if_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_if_write,
.release = single_release,
};
static int pktgen_thread_show(struct seq_file *seq, void *v)
{
struct pktgen_thread *t = seq->private;
const struct pktgen_dev *pkt_dev;
BUG_ON(!t);
seq_printf(seq, "Running: ");
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
seq_printf(seq, "\nStopped: ");
list_for_each_entry(pkt_dev, &t->if_list, list)
if (!pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
if (t->result[0])
seq_printf(seq, "\nResult: %s\n", t->result);
else
seq_printf(seq, "\nResult: NA\n");
if_unlock(t);
return 0;
}
static ssize_t pktgen_thread_write(struct file *file,
const char __user * user_buffer,
size_t count, loff_t * offset)
{
struct seq_file *seq = file->private_data;
struct pktgen_thread *t = seq->private;
int i, max, len, ret;
char name[40];
char *pg_result;
if (count < 1) {
// sprintf(pg_result, "Wrong command format");
return -EINVAL;
}
max = count;
len = count_trail_chars(user_buffer, max);
if (len < 0)
return len;
i = len;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug)
printk(KERN_DEBUG "pktgen: t=%s, count=%lu\n",
name, (unsigned long)count);
if (!t) {
pr_err("ERROR: No thread\n");
ret = -EINVAL;
goto out;
}
pg_result = &(t->result[0]);
if (!strcmp(name, "add_device")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0) {
ret = len;
goto out;
}
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
mutex_lock(&pktgen_thread_lock);
pktgen_add_device(t, f);
mutex_unlock(&pktgen_thread_lock);
ret = count;
sprintf(pg_result, "OK: add_device=%s", f);
goto out;
}
if (!strcmp(name, "rem_device_all")) {
mutex_lock(&pktgen_thread_lock);
t->control |= T_REMDEVALL;
mutex_unlock(&pktgen_thread_lock);
schedule_timeout_interruptible(msecs_to_jiffies(125)); /* Propagate thread->control */
ret = count;
sprintf(pg_result, "OK: rem_device_all");
goto out;
}
if (!strcmp(name, "max_before_softirq")) {
sprintf(pg_result, "OK: Note! max_before_softirq is obsoleted -- Do not use");
ret = count;
goto out;
}
ret = -EINVAL;
out:
return ret;
}
static int pktgen_thread_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_thread_show, PDE(inode)->data);
}
static const struct file_operations pktgen_thread_fops = {
.owner = THIS_MODULE,
.open = pktgen_thread_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_thread_write,
.release = single_release,
};
/* Think find or remove for NN */
static struct pktgen_dev *__pktgen_NN_threads(const char *ifname, int remove)
{
struct pktgen_thread *t;
struct pktgen_dev *pkt_dev = NULL;
bool exact = (remove == FIND);
list_for_each_entry(t, &pktgen_threads, th_list) {
pkt_dev = pktgen_find_dev(t, ifname, exact);
if (pkt_dev) {
if (remove) {
if_lock(t);
pkt_dev->removal_mark = 1;
t->control |= T_REMDEV;
if_unlock(t);
}
break;
}
}
return pkt_dev;
}
/*
* mark a device for removal
*/
static void pktgen_mark_device(const char *ifname)
{
struct pktgen_dev *pkt_dev = NULL;
const int max_tries = 10, msec_per_try = 125;
int i = 0;
mutex_lock(&pktgen_thread_lock);
pr_debug("%s: marking %s for removal\n", __func__, ifname);
while (1) {
pkt_dev = __pktgen_NN_threads(ifname, REMOVE);
if (pkt_dev == NULL)
break; /* success */
mutex_unlock(&pktgen_thread_lock);
pr_debug("%s: waiting for %s to disappear....\n",
__func__, ifname);
schedule_timeout_interruptible(msecs_to_jiffies(msec_per_try));
mutex_lock(&pktgen_thread_lock);
if (++i >= max_tries) {
pr_err("%s: timed out after waiting %d msec for device %s to be removed\n",
__func__, msec_per_try * i, ifname);
break;
}
}
mutex_unlock(&pktgen_thread_lock);
}
static void pktgen_change_name(struct net_device *dev)
{
struct pktgen_thread *t;
list_for_each_entry(t, &pktgen_threads, th_list) {
struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (pkt_dev->odev != dev)
continue;
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
pkt_dev->entry = proc_create_data(dev->name, 0600,
pg_proc_dir,
&pktgen_if_fops,
pkt_dev);
if (!pkt_dev->entry)
pr_err("can't move proc entry for '%s'\n",
dev->name);
break;
}
}
}
static int pktgen_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
if (!net_eq(dev_net(dev), &init_net) || pktgen_exiting)
return NOTIFY_DONE;
/* It is OK that we do not hold the group lock right now,
* as we run under the RTNL lock.
*/
switch (event) {
case NETDEV_CHANGENAME:
pktgen_change_name(dev);
break;
case NETDEV_UNREGISTER:
pktgen_mark_device(dev->name);
break;
}
return NOTIFY_DONE;
}
static struct net_device *pktgen_dev_get_by_name(struct pktgen_dev *pkt_dev,
const char *ifname)
{
char b[IFNAMSIZ+5];
int i;
for (i = 0; ifname[i] != '@'; i++) {
if (i == IFNAMSIZ)
break;
b[i] = ifname[i];
}
b[i] = 0;
return dev_get_by_name(&init_net, b);
}
/* Associate pktgen_dev with a device. */
static int pktgen_setup_dev(struct pktgen_dev *pkt_dev, const char *ifname)
{
struct net_device *odev;
int err;
/* Clean old setups */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
odev = pktgen_dev_get_by_name(pkt_dev, ifname);
if (!odev) {
pr_err("no such netdevice: \"%s\"\n", ifname);
return -ENODEV;
}
if (odev->type != ARPHRD_ETHER) {
pr_err("not an ethernet device: \"%s\"\n", ifname);
err = -EINVAL;
} else if (!netif_running(odev)) {
pr_err("device is down: \"%s\"\n", ifname);
err = -ENETDOWN;
} else {
pkt_dev->odev = odev;
return 0;
}
dev_put(odev);
return err;
}
/* Read pkt_dev from the interface and set up internal pktgen_dev
* structure to have the right information to create/send packets
*/
static void pktgen_setup_inject(struct pktgen_dev *pkt_dev)
{
int ntxq;
if (!pkt_dev->odev) {
pr_err("ERROR: pkt_dev->odev == NULL in setup_inject\n");
sprintf(pkt_dev->result,
"ERROR: pkt_dev->odev == NULL in setup_inject.\n");
return;
}
/* make sure that we don't pick a non-existing transmit queue */
ntxq = pkt_dev->odev->real_num_tx_queues;
if (ntxq <= pkt_dev->queue_map_min) {
pr_warning("WARNING: Requested queue_map_min (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_min, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_min = (ntxq ?: 1) - 1;
}
if (pkt_dev->queue_map_max >= ntxq) {
pr_warning("WARNING: Requested queue_map_max (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_max, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_max = (ntxq ?: 1) - 1;
}
/* Default to the interface's mac if not explicitly set. */
if (is_zero_ether_addr(pkt_dev->src_mac))
memcpy(&(pkt_dev->hh[6]), pkt_dev->odev->dev_addr, ETH_ALEN);
/* Set up Dest MAC */
memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
/* Set up pkt size */
pkt_dev->cur_pkt_size = pkt_dev->min_pkt_size;
if (pkt_dev->flags & F_IPV6) {
/*
* Skip this automatic address setting until locks or functions
* gets exported
*/
#ifdef NOTNOW
int i, set = 0, err = 1;
struct inet6_dev *idev;
for (i = 0; i < IN6_ADDR_HSIZE; i++)
if (pkt_dev->cur_in6_saddr.s6_addr[i]) {
set = 1;
break;
}
if (!set) {
/*
* Use linklevel address if unconfigured.
*
* use ipv6_get_lladdr if/when it's get exported
*/
rcu_read_lock();
idev = __in6_dev_get(pkt_dev->odev);
if (idev) {
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
for (ifp = idev->addr_list; ifp;
ifp = ifp->if_next) {
if (ifp->scope == IFA_LINK &&
!(ifp->flags & IFA_F_TENTATIVE)) {
pkt_dev->cur_in6_saddr = ifp->addr;
err = 0;
break;
}
}
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
if (err)
pr_err("ERROR: IPv6 link address not available\n");
}
#endif
} else {
pkt_dev->saddr_min = 0;
pkt_dev->saddr_max = 0;
if (strlen(pkt_dev->src_min) == 0) {
struct in_device *in_dev;
rcu_read_lock();
in_dev = __in_dev_get_rcu(pkt_dev->odev);
if (in_dev) {
if (in_dev->ifa_list) {
pkt_dev->saddr_min =
in_dev->ifa_list->ifa_address;
pkt_dev->saddr_max = pkt_dev->saddr_min;
}
}
rcu_read_unlock();
} else {
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
}
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
}
/* Initialize current values. */
pkt_dev->cur_dst_mac_offset = 0;
pkt_dev->cur_src_mac_offset = 0;
pkt_dev->cur_saddr = pkt_dev->saddr_min;
pkt_dev->cur_daddr = pkt_dev->daddr_min;
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
pkt_dev->nflows = 0;
}
static void spin(struct pktgen_dev *pkt_dev, ktime_t spin_until)
{
ktime_t start_time, end_time;
s64 remaining;
struct hrtimer_sleeper t;
hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_set_expires(&t.timer, spin_until);
remaining = ktime_to_ns(hrtimer_expires_remaining(&t.timer));
if (remaining <= 0) {
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
return;
}
start_time = ktime_get();
if (remaining < 100000) {
/* for small delays (<100us), just loop until limit is reached */
do {
end_time = ktime_get();
} while (ktime_compare(end_time, spin_until) < 0);
} else {
/* see do_nanosleep */
hrtimer_init_sleeper(&t, current);
do {
set_current_state(TASK_INTERRUPTIBLE);
hrtimer_start_expires(&t.timer, HRTIMER_MODE_ABS);
if (!hrtimer_active(&t.timer))
t.task = NULL;
if (likely(t.task))
schedule();
hrtimer_cancel(&t.timer);
} while (t.task && pkt_dev->running && !signal_pending(current));
__set_current_state(TASK_RUNNING);
end_time = ktime_get();
}
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(end_time, start_time));
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
}
static inline void set_pkt_overhead(struct pktgen_dev *pkt_dev)
{
pkt_dev->pkt_overhead = 0;
pkt_dev->pkt_overhead += pkt_dev->nr_labels*sizeof(u32);
pkt_dev->pkt_overhead += VLAN_TAG_SIZE(pkt_dev);
pkt_dev->pkt_overhead += SVLAN_TAG_SIZE(pkt_dev);
}
static inline int f_seen(const struct pktgen_dev *pkt_dev, int flow)
{
return !!(pkt_dev->flows[flow].flags & F_INIT);
}
static inline int f_pick(struct pktgen_dev *pkt_dev)
{
int flow = pkt_dev->curfl;
if (pkt_dev->flags & F_FLOW_SEQ) {
if (pkt_dev->flows[flow].count >= pkt_dev->lflow) {
/* reset time */
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
pkt_dev->curfl += 1;
if (pkt_dev->curfl >= pkt_dev->cflows)
pkt_dev->curfl = 0; /*reset */
}
} else {
flow = random32() % pkt_dev->cflows;
pkt_dev->curfl = flow;
if (pkt_dev->flows[flow].count > pkt_dev->lflow) {
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
}
}
return pkt_dev->curfl;
}
#ifdef CONFIG_XFRM
/* If there was already an IPSEC SA, we keep it as is, else
* we go look for it ...
*/
#define DUMMY_MARK 0
static void get_ipsec_sa(struct pktgen_dev *pkt_dev, int flow)
{
struct xfrm_state *x = pkt_dev->flows[flow].x;
if (!x) {
/*slow path: we dont already have xfrm_state*/
x = xfrm_stateonly_find(&init_net, DUMMY_MARK,
(xfrm_address_t *)&pkt_dev->cur_daddr,
(xfrm_address_t *)&pkt_dev->cur_saddr,
AF_INET,
pkt_dev->ipsmode,
pkt_dev->ipsproto, 0);
if (x) {
pkt_dev->flows[flow].x = x;
set_pkt_overhead(pkt_dev);
pkt_dev->pkt_overhead += x->props.header_len;
}
}
}
#endif
static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
pkt_dev->cur_queue_map = smp_processor_id();
else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
__u16 t;
if (pkt_dev->flags & F_QUEUE_MAP_RND) {
t = random32() %
(pkt_dev->queue_map_max -
pkt_dev->queue_map_min + 1)
+ pkt_dev->queue_map_min;
} else {
t = pkt_dev->cur_queue_map + 1;
if (t > pkt_dev->queue_map_max)
t = pkt_dev->queue_map_min;
}
pkt_dev->cur_queue_map = t;
}
pkt_dev->cur_queue_map = pkt_dev->cur_queue_map % pkt_dev->odev->real_num_tx_queues;
}
/* Increment/randomize headers according to flags and current values
* for IP src/dest, UDP src/dst port, MAC-Addr src/dst
*/
static void mod_cur_headers(struct pktgen_dev *pkt_dev)
{
__u32 imn;
__u32 imx;
int flow = 0;
if (pkt_dev->cflows)
flow = f_pick(pkt_dev);
/* Deal with source MAC */
if (pkt_dev->src_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACSRC_RND)
mc = random32() % pkt_dev->src_mac_count;
else {
mc = pkt_dev->cur_src_mac_offset++;
if (pkt_dev->cur_src_mac_offset >=
pkt_dev->src_mac_count)
pkt_dev->cur_src_mac_offset = 0;
}
tmp = pkt_dev->src_mac[5] + (mc & 0xFF);
pkt_dev->hh[11] = tmp;
tmp = (pkt_dev->src_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[10] = tmp;
tmp = (pkt_dev->src_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[9] = tmp;
tmp = (pkt_dev->src_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[8] = tmp;
tmp = (pkt_dev->src_mac[1] + (tmp >> 8));
pkt_dev->hh[7] = tmp;
}
/* Deal with Destination MAC */
if (pkt_dev->dst_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACDST_RND)
mc = random32() % pkt_dev->dst_mac_count;
else {
mc = pkt_dev->cur_dst_mac_offset++;
if (pkt_dev->cur_dst_mac_offset >=
pkt_dev->dst_mac_count) {
pkt_dev->cur_dst_mac_offset = 0;
}
}
tmp = pkt_dev->dst_mac[5] + (mc & 0xFF);
pkt_dev->hh[5] = tmp;
tmp = (pkt_dev->dst_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[4] = tmp;
tmp = (pkt_dev->dst_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[3] = tmp;
tmp = (pkt_dev->dst_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[2] = tmp;
tmp = (pkt_dev->dst_mac[1] + (tmp >> 8));
pkt_dev->hh[1] = tmp;
}
if (pkt_dev->flags & F_MPLS_RND) {
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
if (pkt_dev->labels[i] & MPLS_STACK_BOTTOM)
pkt_dev->labels[i] = MPLS_STACK_BOTTOM |
((__force __be32)random32() &
htonl(0x000fffff));
}
if ((pkt_dev->flags & F_VID_RND) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_id = random32() & (4096-1);
}
if ((pkt_dev->flags & F_SVID_RND) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_id = random32() & (4096 - 1);
}
if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
if (pkt_dev->flags & F_UDPSRC_RND)
pkt_dev->cur_udp_src = random32() %
(pkt_dev->udp_src_max - pkt_dev->udp_src_min)
+ pkt_dev->udp_src_min;
else {
pkt_dev->cur_udp_src++;
if (pkt_dev->cur_udp_src >= pkt_dev->udp_src_max)
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
}
}
if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
if (pkt_dev->flags & F_UDPDST_RND) {
pkt_dev->cur_udp_dst = random32() %
(pkt_dev->udp_dst_max - pkt_dev->udp_dst_min)
+ pkt_dev->udp_dst_min;
} else {
pkt_dev->cur_udp_dst++;
if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
}
}
if (!(pkt_dev->flags & F_IPV6)) {
imn = ntohl(pkt_dev->saddr_min);
imx = ntohl(pkt_dev->saddr_max);
if (imn < imx) {
__u32 t;
if (pkt_dev->flags & F_IPSRC_RND)
t = random32() % (imx - imn) + imn;
else {
t = ntohl(pkt_dev->cur_saddr);
t++;
if (t > imx)
t = imn;
}
pkt_dev->cur_saddr = htonl(t);
}
if (pkt_dev->cflows && f_seen(pkt_dev, flow)) {
pkt_dev->cur_daddr = pkt_dev->flows[flow].cur_daddr;
} else {
imn = ntohl(pkt_dev->daddr_min);
imx = ntohl(pkt_dev->daddr_max);
if (imn < imx) {
__u32 t;
__be32 s;
if (pkt_dev->flags & F_IPDST_RND) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
while (ipv4_is_loopback(s) ||
ipv4_is_multicast(s) ||
ipv4_is_lbcast(s) ||
ipv4_is_zeronet(s) ||
ipv4_is_local_multicast(s)) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
}
pkt_dev->cur_daddr = s;
} else {
t = ntohl(pkt_dev->cur_daddr);
t++;
if (t > imx) {
t = imn;
}
pkt_dev->cur_daddr = htonl(t);
}
}
if (pkt_dev->cflows) {
pkt_dev->flows[flow].flags |= F_INIT;
pkt_dev->flows[flow].cur_daddr =
pkt_dev->cur_daddr;
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
get_ipsec_sa(pkt_dev, flow);
#endif
pkt_dev->nflows++;
}
}
} else { /* IPV6 * */
if (pkt_dev->min_in6_daddr.s6_addr32[0] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[1] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[2] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[3] == 0) ;
else {
int i;
/* Only random destinations yet */
for (i = 0; i < 4; i++) {
pkt_dev->cur_in6_daddr.s6_addr32[i] =
(((__force __be32)random32() |
pkt_dev->min_in6_daddr.s6_addr32[i]) &
pkt_dev->max_in6_daddr.s6_addr32[i]);
}
}
}
if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
__u32 t;
if (pkt_dev->flags & F_TXSIZE_RND) {
t = random32() %
(pkt_dev->max_pkt_size - pkt_dev->min_pkt_size)
+ pkt_dev->min_pkt_size;
} else {
t = pkt_dev->cur_pkt_size + 1;
if (t > pkt_dev->max_pkt_size)
t = pkt_dev->min_pkt_size;
}
pkt_dev->cur_pkt_size = t;
}
set_cur_queue_map(pkt_dev);
pkt_dev->flows[flow].count++;
}
#ifdef CONFIG_XFRM
static int pktgen_output_ipsec(struct sk_buff *skb, struct pktgen_dev *pkt_dev)
{
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int err = 0;
if (!x)
return 0;
/* XXX: we dont support tunnel mode for now until
* we resolve the dst issue */
if (x->props.mode != XFRM_MODE_TRANSPORT)
return 0;
spin_lock(&x->lock);
err = x->outer_mode->output(x, skb);
if (err)
goto error;
err = x->type->output(x, skb);
if (err)
goto error;
x->curlft.bytes += skb->len;
x->curlft.packets++;
error:
spin_unlock(&x->lock);
return err;
}
static void free_SAs(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->cflows) {
/* let go of the SAs if we have them */
int i;
for (i = 0; i < pkt_dev->cflows; i++) {
struct xfrm_state *x = pkt_dev->flows[i].x;
if (x) {
xfrm_state_put(x);
pkt_dev->flows[i].x = NULL;
}
}
}
}
static int process_ipsec(struct pktgen_dev *pkt_dev,
struct sk_buff *skb, __be16 protocol)
{
if (pkt_dev->flags & F_IPSEC_ON) {
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int nhead = 0;
if (x) {
int ret;
__u8 *eth;
nhead = x->props.header_len - skb_headroom(skb);
if (nhead > 0) {
ret = pskb_expand_head(skb, nhead, 0, GFP_ATOMIC);
if (ret < 0) {
pr_err("Error expanding ipsec packet %d\n",
ret);
goto err;
}
}
/* ipsec is not expecting ll header */
skb_pull(skb, ETH_HLEN);
ret = pktgen_output_ipsec(skb, pkt_dev);
if (ret) {
pr_err("Error creating ipsec packet %d\n", ret);
goto err;
}
/* restore ll */
eth = (__u8 *) skb_push(skb, ETH_HLEN);
memcpy(eth, pkt_dev->hh, 12);
*(u16 *) ð[12] = protocol;
}
}
return 1;
err:
kfree_skb(skb);
return 0;
}
#endif
static void mpls_push(__be32 *mpls, struct pktgen_dev *pkt_dev)
{
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
*mpls++ = pkt_dev->labels[i] & ~MPLS_STACK_BOTTOM;
mpls--;
*mpls |= MPLS_STACK_BOTTOM;
}
static inline __be16 build_tci(unsigned int id, unsigned int cfi,
unsigned int prio)
{
return htons(id | (cfi << 12) | (prio << 13));
}
static void pktgen_finalize_skb(struct pktgen_dev *pkt_dev, struct sk_buff *skb,
int datalen)
{
struct timeval timestamp;
struct pktgen_hdr *pgh;
pgh = (struct pktgen_hdr *)skb_put(skb, sizeof(*pgh));
datalen -= sizeof(*pgh);
if (pkt_dev->nfrags <= 0) {
memset(skb_put(skb, datalen), 0, datalen);
} else {
int frags = pkt_dev->nfrags;
int i, len;
int frag_len;
if (frags > MAX_SKB_FRAGS)
frags = MAX_SKB_FRAGS;
len = datalen - frags * PAGE_SIZE;
if (len > 0) {
memset(skb_put(skb, len), 0, len);
datalen = frags * PAGE_SIZE;
}
i = 0;
frag_len = (datalen/frags) < PAGE_SIZE ?
(datalen/frags) : PAGE_SIZE;
while (datalen > 0) {
if (unlikely(!pkt_dev->page)) {
int node = numa_node_id();
if (pkt_dev->node >= 0 && (pkt_dev->flags & F_NODE))
node = pkt_dev->node;
pkt_dev->page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
if (!pkt_dev->page)
break;
}
get_page(pkt_dev->page);
skb_frag_set_page(skb, i, pkt_dev->page);
skb_shinfo(skb)->frags[i].page_offset = 0;
/*last fragment, fill rest of data*/
if (i == (frags - 1))
skb_frag_size_set(&skb_shinfo(skb)->frags[i],
(datalen < PAGE_SIZE ? datalen : PAGE_SIZE));
else
skb_frag_size_set(&skb_shinfo(skb)->frags[i], frag_len);
datalen -= skb_frag_size(&skb_shinfo(skb)->frags[i]);
skb->len += skb_frag_size(&skb_shinfo(skb)->frags[i]);
skb->data_len += skb_frag_size(&skb_shinfo(skb)->frags[i]);
i++;
skb_shinfo(skb)->nr_frags = i;
}
}
/* Stamp the time, and sequence number,
* convert them to network byte order
*/
pgh->pgh_magic = htonl(PKTGEN_MAGIC);
pgh->seq_num = htonl(pkt_dev->seq_num);
do_gettimeofday(×tamp);
pgh->tv_sec = htonl(timestamp.tv_sec);
pgh->tv_usec = htonl(timestamp.tv_usec);
}
static struct sk_buff *fill_packet_ipv4(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen, iplen;
struct iphdr *iph;
__be16 protocol = htons(ETH_P_IP);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
mod_cur_headers(pkt_dev);
queue_map = pkt_dev->cur_queue_map;
datalen = (odev->hard_header_len + 16) & ~0xf;
if (pkt_dev->flags & F_NODE) {
int node;
if (pkt_dev->node >= 0)
node = pkt_dev->node;
else
node = numa_node_id();
skb = __alloc_skb(NET_SKB_PAD + pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT, 0, node);
if (likely(skb)) {
skb_reserve(skb, NET_SKB_PAD);
skb->dev = odev;
}
}
else
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
prefetchw(skb->data);
skb_reserve(skb, datalen);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IP);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct iphdr);
skb_put(skb, sizeof(struct iphdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
skb->priority = pkt_dev->skb_priority;
iph = ip_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) & eth[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 - 20 - 8 -
pkt_dev->pkt_overhead;
if (datalen < sizeof(struct pktgen_hdr))
datalen = sizeof(struct pktgen_hdr);
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + 8); /* DATA + udphdr */
udph->check = 0; /* No checksum */
iph->ihl = 5;
iph->version = 4;
iph->ttl = 32;
iph->tos = pkt_dev->tos;
iph->protocol = IPPROTO_UDP; /* UDP */
iph->saddr = pkt_dev->cur_saddr;
iph->daddr = pkt_dev->cur_daddr;
iph->id = htons(pkt_dev->ip_id);
pkt_dev->ip_id++;
iph->frag_off = 0;
iplen = 20 + 8 + datalen;
iph->tot_len = htons(iplen);
iph->check = 0;
iph->check = ip_fast_csum((void *)iph, iph->ihl);
skb->protocol = protocol;
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
pktgen_finalize_skb(pkt_dev, skb, datalen);
#ifdef CONFIG_XFRM
if (!process_ipsec(pkt_dev, skb, protocol))
return NULL;
#endif
return skb;
}
/*
* scan_ip6, fmt_ip taken from dietlibc-0.21
* Author Felix von Leitner <felix-dietlibc@fefe.de>
*
* Slightly modified for kernel.
* Should be candidate for net/ipv4/utils.c
* --ro
*/
static unsigned int scan_ip6(const char *s, char ip[16])
{
unsigned int i;
unsigned int len = 0;
unsigned long u;
char suffix[16];
unsigned int prefixlen = 0;
unsigned int suffixlen = 0;
__be32 tmp;
char *pos;
for (i = 0; i < 16; i++)
ip[i] = 0;
for (;;) {
if (*s == ':') {
len++;
if (s[1] == ':') { /* Found "::", skip to part 2 */
s += 2;
len++;
break;
}
s++;
}
u = simple_strtoul(s, &pos, 16);
i = pos - s;
if (!i)
return 0;
if (prefixlen == 12 && s[i] == '.') {
/* the last 4 bytes may be written as IPv4 address */
tmp = in_aton(s);
memcpy((struct in_addr *)(ip + 12), &tmp, sizeof(tmp));
return i + len;
}
ip[prefixlen++] = (u >> 8);
ip[prefixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen == 16)
return len;
}
/* part 2, after "::" */
for (;;) {
if (*s == ':') {
if (suffixlen == 0)
break;
s++;
len++;
} else if (suffixlen != 0)
break;
u = simple_strtol(s, &pos, 16);
i = pos - s;
if (!i) {
if (*s)
len--;
break;
}
if (suffixlen + prefixlen <= 12 && s[i] == '.') {
tmp = in_aton(s);
memcpy((struct in_addr *)(suffix + suffixlen), &tmp,
sizeof(tmp));
suffixlen += 4;
len += strlen(s);
break;
}
suffix[suffixlen++] = (u >> 8);
suffix[suffixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen + suffixlen == 16)
break;
}
for (i = 0; i < suffixlen; i++)
ip[16 - suffixlen + i] = suffix[i];
return len;
}
static struct sk_buff *fill_packet_ipv6(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen;
struct ipv6hdr *iph;
__be16 protocol = htons(ETH_P_IPV6);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
mod_cur_headers(pkt_dev);
queue_map = pkt_dev->cur_queue_map;
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ 16 + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
prefetchw(skb->data);
skb_reserve(skb, 16);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IPV6);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct ipv6hdr);
skb_put(skb, sizeof(struct ipv6hdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
skb->priority = pkt_dev->skb_priority;
iph = ipv6_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) ð[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 -
sizeof(struct ipv6hdr) - sizeof(struct udphdr) -
pkt_dev->pkt_overhead;
if (datalen < sizeof(struct pktgen_hdr)) {
datalen = sizeof(struct pktgen_hdr);
if (net_ratelimit())
pr_info("increased datalen to %d\n", datalen);
}
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + sizeof(struct udphdr));
udph->check = 0; /* No checksum */
*(__be32 *) iph = htonl(0x60000000); /* Version + flow */
if (pkt_dev->traffic_class) {
/* Version + traffic class + flow (0) */
*(__be32 *)iph |= htonl(0x60000000 | (pkt_dev->traffic_class << 20));
}
iph->hop_limit = 32;
iph->payload_len = htons(sizeof(struct udphdr) + datalen);
iph->nexthdr = IPPROTO_UDP;
iph->daddr = pkt_dev->cur_in6_daddr;
iph->saddr = pkt_dev->cur_in6_saddr;
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->protocol = protocol;
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
pktgen_finalize_skb(pkt_dev, skb, datalen);
return skb;
}
static struct sk_buff *fill_packet(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_IPV6)
return fill_packet_ipv6(odev, pkt_dev);
else
return fill_packet_ipv4(odev, pkt_dev);
}
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev)
{
pkt_dev->seq_num = 1;
pkt_dev->idle_acc = 0;
pkt_dev->sofar = 0;
pkt_dev->tx_bytes = 0;
pkt_dev->errors = 0;
}
/* Set up structure for sending pkts, clear counters */
static void pktgen_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
int started = 0;
func_enter();
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
/*
* setup odev and create initial packet.
*/
pktgen_setup_inject(pkt_dev);
if (pkt_dev->odev) {
pktgen_clear_counters(pkt_dev);
pkt_dev->running = 1; /* Cranke yeself! */
pkt_dev->skb = NULL;
pkt_dev->started_at = pkt_dev->next_tx = ktime_get();
set_pkt_overhead(pkt_dev);
strcpy(pkt_dev->result, "Starting");
started++;
} else
strcpy(pkt_dev->result, "Error starting");
}
if_unlock(t);
if (started)
t->control &= ~(T_STOP);
}
static void pktgen_stop_all_threads_ifs(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= T_STOP;
mutex_unlock(&pktgen_thread_lock);
}
static int thread_is_running(const struct pktgen_thread *t)
{
const struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
return 1;
return 0;
}
static int pktgen_wait_thread_run(struct pktgen_thread *t)
{
if_lock(t);
while (thread_is_running(t)) {
if_unlock(t);
msleep_interruptible(100);
if (signal_pending(current))
goto signal;
if_lock(t);
}
if_unlock(t);
return 1;
signal:
return 0;
}
static int pktgen_wait_all_threads_run(void)
{
struct pktgen_thread *t;
int sig = 1;
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list) {
sig = pktgen_wait_thread_run(t);
if (sig == 0)
break;
}
if (sig == 0)
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_STOP);
mutex_unlock(&pktgen_thread_lock);
return sig;
}
static void pktgen_run_all_threads(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_RUN);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void pktgen_reset_all_threads(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_REMDEVALL);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void show_results(struct pktgen_dev *pkt_dev, int nr_frags)
{
__u64 bps, mbps, pps;
char *p = pkt_dev->result;
ktime_t elapsed = ktime_sub(pkt_dev->stopped_at,
pkt_dev->started_at);
ktime_t idle = ns_to_ktime(pkt_dev->idle_acc);
p += sprintf(p, "OK: %llu(c%llu+d%llu) usec, %llu (%dbyte,%dfrags)\n",
(unsigned long long)ktime_to_us(elapsed),
(unsigned long long)ktime_to_us(ktime_sub(elapsed, idle)),
(unsigned long long)ktime_to_us(idle),
(unsigned long long)pkt_dev->sofar,
pkt_dev->cur_pkt_size, nr_frags);
pps = div64_u64(pkt_dev->sofar * NSEC_PER_SEC,
ktime_to_ns(elapsed));
bps = pps * 8 * pkt_dev->cur_pkt_size;
mbps = bps;
do_div(mbps, 1000000);
p += sprintf(p, " %llupps %lluMb/sec (%llubps) errors: %llu",
(unsigned long long)pps,
(unsigned long long)mbps,
(unsigned long long)bps,
(unsigned long long)pkt_dev->errors);
}
/* Set stopped-at timer, remove from running list, do counters & statistics */
static int pktgen_stop_device(struct pktgen_dev *pkt_dev)
{
int nr_frags = pkt_dev->skb ? skb_shinfo(pkt_dev->skb)->nr_frags : -1;
if (!pkt_dev->running) {
pr_warning("interface: %s is already stopped\n",
pkt_dev->odevname);
return -EINVAL;
}
kfree_skb(pkt_dev->skb);
pkt_dev->skb = NULL;
pkt_dev->stopped_at = ktime_get();
pkt_dev->running = 0;
show_results(pkt_dev, nr_frags);
return 0;
}
static struct pktgen_dev *next_to_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev, *best = NULL;
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (!pkt_dev->running)
continue;
if (best == NULL)
best = pkt_dev;
else if (ktime_compare(pkt_dev->next_tx, best->next_tx) < 0)
best = pkt_dev;
}
if_unlock(t);
return best;
}
static void pktgen_stop(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
func_enter();
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
pktgen_stop_device(pkt_dev);
}
if_unlock(t);
}
/*
* one of our devices needs to be removed - find it
* and remove it
*/
static void pktgen_rem_one_if(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
func_enter();
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
if (!cur->removal_mark)
continue;
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
break;
}
if_unlock(t);
}
static void pktgen_rem_all_ifs(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
func_enter();
/* Remove all devices, free mem */
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
}
if_unlock(t);
}
static void pktgen_rem_thread(struct pktgen_thread *t)
{
/* Remove from the thread list */
remove_proc_entry(t->tsk->comm, pg_proc_dir);
}
static void pktgen_resched(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_get();
schedule();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_get(), idle_start));
}
static void pktgen_wait_for_skb(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_get();
while (atomic_read(&(pkt_dev->skb->users)) != 1) {
if (signal_pending(current))
break;
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_get(), idle_start));
}
static void pktgen_xmit(struct pktgen_dev *pkt_dev)
{
struct net_device *odev = pkt_dev->odev;
netdev_tx_t (*xmit)(struct sk_buff *, struct net_device *)
= odev->netdev_ops->ndo_start_xmit;
struct netdev_queue *txq;
u16 queue_map;
int ret;
/* If device is offline, then don't send */
if (unlikely(!netif_running(odev) || !netif_carrier_ok(odev))) {
pktgen_stop_device(pkt_dev);
return;
}
/* This is max DELAY, this has special meaning of
* "never transmit"
*/
if (unlikely(pkt_dev->delay == ULLONG_MAX)) {
pkt_dev->next_tx = ktime_add_ns(ktime_get(), ULONG_MAX);
return;
}
/* If no skb or clone count exhausted then get new one */
if (!pkt_dev->skb || (pkt_dev->last_ok &&
++pkt_dev->clone_count >= pkt_dev->clone_skb)) {
/* build a new pkt */
kfree_skb(pkt_dev->skb);
pkt_dev->skb = fill_packet(odev, pkt_dev);
if (pkt_dev->skb == NULL) {
pr_err("ERROR: couldn't allocate skb in fill_packet\n");
schedule();
pkt_dev->clone_count--; /* back out increment, OOM */
return;
}
pkt_dev->last_pkt_size = pkt_dev->skb->len;
pkt_dev->allocated_skbs++;
pkt_dev->clone_count = 0; /* reset counter */
}
if (pkt_dev->delay && pkt_dev->last_ok)
spin(pkt_dev, pkt_dev->next_tx);
queue_map = skb_get_queue_mapping(pkt_dev->skb);
txq = netdev_get_tx_queue(odev, queue_map);
__netif_tx_lock_bh(txq);
if (unlikely(netif_xmit_frozen_or_stopped(txq))) {
ret = NETDEV_TX_BUSY;
pkt_dev->last_ok = 0;
goto unlock;
}
atomic_inc(&(pkt_dev->skb->users));
ret = (*xmit)(pkt_dev->skb, odev);
switch (ret) {
case NETDEV_TX_OK:
txq_trans_update(txq);
pkt_dev->last_ok = 1;
pkt_dev->sofar++;
pkt_dev->seq_num++;
pkt_dev->tx_bytes += pkt_dev->last_pkt_size;
break;
case NET_XMIT_DROP:
case NET_XMIT_CN:
case NET_XMIT_POLICED:
/* skb has been consumed */
pkt_dev->errors++;
break;
default: /* Drivers are not supposed to return other values! */
if (net_ratelimit())
pr_info("%s xmit error: %d\n", pkt_dev->odevname, ret);
pkt_dev->errors++;
/* fallthru */
case NETDEV_TX_LOCKED:
case NETDEV_TX_BUSY:
/* Retry it next time */
atomic_dec(&(pkt_dev->skb->users));
pkt_dev->last_ok = 0;
}
unlock:
__netif_tx_unlock_bh(txq);
/* If pkt_dev->count is zero, then run forever */
if ((pkt_dev->count != 0) && (pkt_dev->sofar >= pkt_dev->count)) {
pktgen_wait_for_skb(pkt_dev);
/* Done with this */
pktgen_stop_device(pkt_dev);
}
}
/*
* Main loop of the thread goes here
*/
static int pktgen_thread_worker(void *arg)
{
DEFINE_WAIT(wait);
struct pktgen_thread *t = arg;
struct pktgen_dev *pkt_dev = NULL;
int cpu = t->cpu;
BUG_ON(smp_processor_id() != cpu);
init_waitqueue_head(&t->queue);
complete(&t->start_done);
pr_debug("starting pktgen/%d: pid=%d\n", cpu, task_pid_nr(current));
set_current_state(TASK_INTERRUPTIBLE);
set_freezable();
while (!kthread_should_stop()) {
pkt_dev = next_to_run(t);
if (unlikely(!pkt_dev && t->control == 0)) {
if (pktgen_exiting)
break;
wait_event_interruptible_timeout(t->queue,
t->control != 0,
HZ/10);
try_to_freeze();
continue;
}
__set_current_state(TASK_RUNNING);
if (likely(pkt_dev)) {
pktgen_xmit(pkt_dev);
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
if (t->control & T_STOP) {
pktgen_stop(t);
t->control &= ~(T_STOP);
}
if (t->control & T_RUN) {
pktgen_run(t);
t->control &= ~(T_RUN);
}
if (t->control & T_REMDEVALL) {
pktgen_rem_all_ifs(t);
t->control &= ~(T_REMDEVALL);
}
if (t->control & T_REMDEV) {
pktgen_rem_one_if(t);
t->control &= ~(T_REMDEV);
}
try_to_freeze();
set_current_state(TASK_INTERRUPTIBLE);
}
pr_debug("%s stopping all device\n", t->tsk->comm);
pktgen_stop(t);
pr_debug("%s removing all device\n", t->tsk->comm);
pktgen_rem_all_ifs(t);
pr_debug("%s removing thread\n", t->tsk->comm);
pktgen_rem_thread(t);
/* Wait for kthread_stop */
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
__set_current_state(TASK_RUNNING);
return 0;
}
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact)
{
struct pktgen_dev *p, *pkt_dev = NULL;
size_t len = strlen(ifname);
if_lock(t);
list_for_each_entry(p, &t->if_list, list)
if (strncmp(p->odevname, ifname, len) == 0) {
if (p->odevname[len]) {
if (exact || p->odevname[len] != '@')
continue;
}
pkt_dev = p;
break;
}
if_unlock(t);
pr_debug("find_dev(%s) returning %p\n", ifname, pkt_dev);
return pkt_dev;
}
/*
* Adds a dev at front of if_list.
*/
static int add_dev_to_thread(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
int rv = 0;
if_lock(t);
if (pkt_dev->pg_thread) {
pr_err("ERROR: already assigned to a thread\n");
rv = -EBUSY;
goto out;
}
list_add(&pkt_dev->list, &t->if_list);
pkt_dev->pg_thread = t;
pkt_dev->running = 0;
out:
if_unlock(t);
return rv;
}
/* Called under thread lock */
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
{
struct pktgen_dev *pkt_dev;
int err;
int node = cpu_to_node(t->cpu);
/* We don't allow a device to be on several threads */
pkt_dev = __pktgen_NN_threads(ifname, FIND);
if (pkt_dev) {
pr_err("ERROR: interface already used\n");
return -EBUSY;
}
pkt_dev = kzalloc_node(sizeof(struct pktgen_dev), GFP_KERNEL, node);
if (!pkt_dev)
return -ENOMEM;
strcpy(pkt_dev->odevname, ifname);
pkt_dev->flows = vzalloc_node(MAX_CFLOWS * sizeof(struct flow_state),
node);
if (pkt_dev->flows == NULL) {
kfree(pkt_dev);
return -ENOMEM;
}
pkt_dev->removal_mark = 0;
pkt_dev->min_pkt_size = ETH_ZLEN;
pkt_dev->max_pkt_size = ETH_ZLEN;
pkt_dev->nfrags = 0;
pkt_dev->delay = pg_delay_d;
pkt_dev->count = pg_count_d;
pkt_dev->sofar = 0;
pkt_dev->udp_src_min = 9; /* sink port */
pkt_dev->udp_src_max = 9;
pkt_dev->udp_dst_min = 9;
pkt_dev->udp_dst_max = 9;
pkt_dev->vlan_p = 0;
pkt_dev->vlan_cfi = 0;
pkt_dev->vlan_id = 0xffff;
pkt_dev->svlan_p = 0;
pkt_dev->svlan_cfi = 0;
pkt_dev->svlan_id = 0xffff;
pkt_dev->node = -1;
err = pktgen_setup_dev(pkt_dev, ifname);
if (err)
goto out1;
if (pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)
pkt_dev->clone_skb = pg_clone_skb_d;
pkt_dev->entry = proc_create_data(ifname, 0600, pg_proc_dir,
&pktgen_if_fops, pkt_dev);
if (!pkt_dev->entry) {
pr_err("cannot create %s/%s procfs entry\n",
PG_PROC_DIR, ifname);
err = -EINVAL;
goto out2;
}
#ifdef CONFIG_XFRM
pkt_dev->ipsmode = XFRM_MODE_TRANSPORT;
pkt_dev->ipsproto = IPPROTO_ESP;
#endif
return add_dev_to_thread(t, pkt_dev);
out2:
dev_put(pkt_dev->odev);
out1:
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
kfree(pkt_dev);
return err;
}
static int __init pktgen_create_thread(int cpu)
{
struct pktgen_thread *t;
struct proc_dir_entry *pe;
struct task_struct *p;
t = kzalloc_node(sizeof(struct pktgen_thread), GFP_KERNEL,
cpu_to_node(cpu));
if (!t) {
pr_err("ERROR: out of memory, can't create new thread\n");
return -ENOMEM;
}
spin_lock_init(&t->if_lock);
t->cpu = cpu;
INIT_LIST_HEAD(&t->if_list);
list_add_tail(&t->th_list, &pktgen_threads);
init_completion(&t->start_done);
p = kthread_create_on_node(pktgen_thread_worker,
t,
cpu_to_node(cpu),
"kpktgend_%d", cpu);
if (IS_ERR(p)) {
pr_err("kernel_thread() failed for cpu %d\n", t->cpu);
list_del(&t->th_list);
kfree(t);
return PTR_ERR(p);
}
kthread_bind(p, cpu);
t->tsk = p;
pe = proc_create_data(t->tsk->comm, 0600, pg_proc_dir,
&pktgen_thread_fops, t);
if (!pe) {
pr_err("cannot create %s/%s procfs entry\n",
PG_PROC_DIR, t->tsk->comm);
kthread_stop(p);
list_del(&t->th_list);
kfree(t);
return -EINVAL;
}
wake_up_process(p);
wait_for_completion(&t->start_done);
return 0;
}
/*
* Removes a device from the thread if_list.
*/
static void _rem_dev_from_if_list(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
struct list_head *q, *n;
struct pktgen_dev *p;
list_for_each_safe(q, n, &t->if_list) {
p = list_entry(q, struct pktgen_dev, list);
if (p == pkt_dev)
list_del(&p->list);
}
}
static int pktgen_remove_device(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
pr_debug("remove_device pkt_dev=%p\n", pkt_dev);
if (pkt_dev->running) {
pr_warning("WARNING: trying to remove a running interface, stopping it now\n");
pktgen_stop_device(pkt_dev);
}
/* Dis-associate from the interface */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
/* And update the thread if_list */
_rem_dev_from_if_list(t, pkt_dev);
if (pkt_dev->entry)
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
if (pkt_dev->page)
put_page(pkt_dev->page);
kfree(pkt_dev);
return 0;
}
static int __init pg_init(void)
{
int cpu;
struct proc_dir_entry *pe;
int ret = 0;
pr_info("%s", version);
pg_proc_dir = proc_mkdir(PG_PROC_DIR, init_net.proc_net);
if (!pg_proc_dir)
return -ENODEV;
pe = proc_create(PGCTRL, 0600, pg_proc_dir, &pktgen_fops);
if (pe == NULL) {
pr_err("ERROR: cannot create %s procfs entry\n", PGCTRL);
ret = -EINVAL;
goto remove_dir;
}
register_netdevice_notifier(&pktgen_notifier_block);
for_each_online_cpu(cpu) {
int err;
err = pktgen_create_thread(cpu);
if (err)
pr_warning("WARNING: Cannot create thread for cpu %d (%d)\n",
cpu, err);
}
if (list_empty(&pktgen_threads)) {
pr_err("ERROR: Initialization failed for all threads\n");
ret = -ENODEV;
goto unregister;
}
return 0;
unregister:
unregister_netdevice_notifier(&pktgen_notifier_block);
remove_proc_entry(PGCTRL, pg_proc_dir);
remove_dir:
proc_net_remove(&init_net, PG_PROC_DIR);
return ret;
}
static void __exit pg_cleanup(void)
{
struct pktgen_thread *t;
struct list_head *q, *n;
LIST_HEAD(list);
/* Stop all interfaces & threads */
pktgen_exiting = true;
mutex_lock(&pktgen_thread_lock);
list_splice_init(&pktgen_threads, &list);
mutex_unlock(&pktgen_thread_lock);
list_for_each_safe(q, n, &list) {
t = list_entry(q, struct pktgen_thread, th_list);
list_del(&t->th_list);
kthread_stop(t->tsk);
kfree(t);
}
/* Un-register us from receiving netdevice events */
unregister_netdevice_notifier(&pktgen_notifier_block);
/* Clean up proc file system */
remove_proc_entry(PGCTRL, pg_proc_dir);
proc_net_remove(&init_net, PG_PROC_DIR);
}
module_init(pg_init);
module_exit(pg_cleanup);
MODULE_AUTHOR("Robert Olsson <robert.olsson@its.uu.se>");
MODULE_DESCRIPTION("Packet Generator tool");
MODULE_LICENSE("GPL");
MODULE_VERSION(VERSION);
module_param(pg_count_d, int, 0);
MODULE_PARM_DESC(pg_count_d, "Default number of packets to inject");
module_param(pg_delay_d, int, 0);
MODULE_PARM_DESC(pg_delay_d, "Default delay between packets (nanoseconds)");
module_param(pg_clone_skb_d, int, 0);
MODULE_PARM_DESC(pg_clone_skb_d, "Default number of copies of the same packet");
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Enable debugging of pktgen module");
| gpl-2.0 |
arpitjain9819/FIRE-AND-FLAMES | drivers/acpi/sleep.c | 2725 | 24581 | /*
* sleep.c - ACPI sleep support.
*
* Copyright (c) 2005 Alexey Starikovskiy <alexey.y.starikovskiy@intel.com>
* Copyright (c) 2004 David Shaohua Li <shaohua.li@intel.com>
* Copyright (c) 2000-2003 Patrick Mochel
* Copyright (c) 2003 Open Source Development Lab
*
* This file is released under the GPLv2.
*
*/
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/dmi.h>
#include <linux/device.h>
#include <linux/suspend.h>
#include <linux/reboot.h>
#include <linux/acpi.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <asm/io.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include "internal.h"
#include "sleep.h"
u8 wake_sleep_flags = ACPI_NO_OPTIONAL_METHODS;
static unsigned int gts, bfs;
static int set_param_wake_flag(const char *val, struct kernel_param *kp)
{
int ret = param_set_int(val, kp);
if (ret)
return ret;
if (kp->arg == (const char *)>s) {
if (gts)
wake_sleep_flags |= ACPI_EXECUTE_GTS;
else
wake_sleep_flags &= ~ACPI_EXECUTE_GTS;
}
if (kp->arg == (const char *)&bfs) {
if (bfs)
wake_sleep_flags |= ACPI_EXECUTE_BFS;
else
wake_sleep_flags &= ~ACPI_EXECUTE_BFS;
}
return ret;
}
module_param_call(gts, set_param_wake_flag, param_get_int, >s, 0644);
module_param_call(bfs, set_param_wake_flag, param_get_int, &bfs, 0644);
MODULE_PARM_DESC(gts, "Enable evaluation of _GTS on suspend.");
MODULE_PARM_DESC(bfs, "Enable evaluation of _BFS on resume".);
static u8 sleep_states[ACPI_S_STATE_COUNT];
static void acpi_sleep_tts_switch(u32 acpi_state)
{
union acpi_object in_arg = { ACPI_TYPE_INTEGER };
struct acpi_object_list arg_list = { 1, &in_arg };
acpi_status status = AE_OK;
in_arg.integer.value = acpi_state;
status = acpi_evaluate_object(NULL, "\\_TTS", &arg_list, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
/*
* OS can't evaluate the _TTS object correctly. Some warning
* message will be printed. But it won't break anything.
*/
printk(KERN_NOTICE "Failure in evaluating _TTS object\n");
}
}
static int tts_notify_reboot(struct notifier_block *this,
unsigned long code, void *x)
{
acpi_sleep_tts_switch(ACPI_STATE_S5);
return NOTIFY_DONE;
}
static struct notifier_block tts_notifier = {
.notifier_call = tts_notify_reboot,
.next = NULL,
.priority = 0,
};
static int acpi_sleep_prepare(u32 acpi_state)
{
#ifdef CONFIG_ACPI_SLEEP
/* do we have a wakeup address for S2 and S3? */
if (acpi_state == ACPI_STATE_S3) {
if (!acpi_wakeup_address) {
return -EFAULT;
}
acpi_set_firmware_waking_vector(
(acpi_physical_address)acpi_wakeup_address);
}
ACPI_FLUSH_CPU_CACHE();
#endif
printk(KERN_INFO PREFIX "Preparing to enter system sleep state S%d\n",
acpi_state);
acpi_enable_wakeup_devices(acpi_state);
acpi_enter_sleep_state_prep(acpi_state);
return 0;
}
#ifdef CONFIG_ACPI_SLEEP
static u32 acpi_target_sleep_state = ACPI_STATE_S0;
/*
* The ACPI specification wants us to save NVS memory regions during hibernation
* and to restore them during the subsequent resume. Windows does that also for
* suspend to RAM. However, it is known that this mechanism does not work on
* all machines, so we allow the user to disable it with the help of the
* 'acpi_sleep=nonvs' kernel command line option.
*/
static bool nvs_nosave;
void __init acpi_nvs_nosave(void)
{
nvs_nosave = true;
}
/*
* ACPI 1.0 wants us to execute _PTS before suspending devices, so we allow the
* user to request that behavior by using the 'acpi_old_suspend_ordering'
* kernel command line option that causes the following variable to be set.
*/
static bool old_suspend_ordering;
void __init acpi_old_suspend_ordering(void)
{
old_suspend_ordering = true;
}
/**
* acpi_pm_freeze - Disable the GPEs and suspend EC transactions.
*/
static int acpi_pm_freeze(void)
{
acpi_disable_all_gpes();
acpi_os_wait_events_complete(NULL);
acpi_ec_block_transactions();
return 0;
}
/**
* acpi_pre_suspend - Enable wakeup devices, "freeze" EC and save NVS.
*/
static int acpi_pm_pre_suspend(void)
{
acpi_pm_freeze();
return suspend_nvs_save();
}
/**
* __acpi_pm_prepare - Prepare the platform to enter the target state.
*
* If necessary, set the firmware waking vector and do arch-specific
* nastiness to get the wakeup code to the waking vector.
*/
static int __acpi_pm_prepare(void)
{
int error = acpi_sleep_prepare(acpi_target_sleep_state);
if (error)
acpi_target_sleep_state = ACPI_STATE_S0;
return error;
}
/**
* acpi_pm_prepare - Prepare the platform to enter the target sleep
* state and disable the GPEs.
*/
static int acpi_pm_prepare(void)
{
int error = __acpi_pm_prepare();
if (!error)
error = acpi_pm_pre_suspend();
return error;
}
/**
* acpi_pm_finish - Instruct the platform to leave a sleep state.
*
* This is called after we wake back up (or if entering the sleep state
* failed).
*/
static void acpi_pm_finish(void)
{
u32 acpi_state = acpi_target_sleep_state;
acpi_ec_unblock_transactions();
suspend_nvs_free();
if (acpi_state == ACPI_STATE_S0)
return;
printk(KERN_INFO PREFIX "Waking up from system sleep state S%d\n",
acpi_state);
acpi_disable_wakeup_devices(acpi_state);
acpi_leave_sleep_state(acpi_state);
/* reset firmware waking vector */
acpi_set_firmware_waking_vector((acpi_physical_address) 0);
acpi_target_sleep_state = ACPI_STATE_S0;
}
/**
* acpi_pm_end - Finish up suspend sequence.
*/
static void acpi_pm_end(void)
{
/*
* This is necessary in case acpi_pm_finish() is not called during a
* failing transition to a sleep state.
*/
acpi_target_sleep_state = ACPI_STATE_S0;
acpi_sleep_tts_switch(acpi_target_sleep_state);
}
#else /* !CONFIG_ACPI_SLEEP */
#define acpi_target_sleep_state ACPI_STATE_S0
#endif /* CONFIG_ACPI_SLEEP */
#ifdef CONFIG_SUSPEND
static u32 acpi_suspend_states[] = {
[PM_SUSPEND_ON] = ACPI_STATE_S0,
[PM_SUSPEND_STANDBY] = ACPI_STATE_S1,
[PM_SUSPEND_MEM] = ACPI_STATE_S3,
[PM_SUSPEND_MAX] = ACPI_STATE_S5
};
/**
* acpi_suspend_begin - Set the target system sleep state to the state
* associated with given @pm_state, if supported.
*/
static int acpi_suspend_begin(suspend_state_t pm_state)
{
u32 acpi_state = acpi_suspend_states[pm_state];
int error = 0;
error = nvs_nosave ? 0 : suspend_nvs_alloc();
if (error)
return error;
if (sleep_states[acpi_state]) {
acpi_target_sleep_state = acpi_state;
acpi_sleep_tts_switch(acpi_target_sleep_state);
} else {
printk(KERN_ERR "ACPI does not support this state: %d\n",
pm_state);
error = -ENOSYS;
}
return error;
}
/**
* acpi_suspend_enter - Actually enter a sleep state.
* @pm_state: ignored
*
* Flush caches and go to sleep. For STR we have to call arch-specific
* assembly, which in turn call acpi_enter_sleep_state().
* It's unfortunate, but it works. Please fix if you're feeling frisky.
*/
static int acpi_suspend_enter(suspend_state_t pm_state)
{
acpi_status status = AE_OK;
u32 acpi_state = acpi_target_sleep_state;
int error;
ACPI_FLUSH_CPU_CACHE();
switch (acpi_state) {
case ACPI_STATE_S1:
barrier();
status = acpi_enter_sleep_state(acpi_state, wake_sleep_flags);
break;
case ACPI_STATE_S3:
error = acpi_suspend_lowlevel();
if (error)
return error;
pr_info(PREFIX "Low-level resume complete\n");
break;
}
/* This violates the spec but is required for bug compatibility. */
acpi_write_bit_register(ACPI_BITREG_SCI_ENABLE, 1);
/* Reprogram control registers and execute _BFS */
acpi_leave_sleep_state_prep(acpi_state, wake_sleep_flags);
/* ACPI 3.0 specs (P62) says that it's the responsibility
* of the OSPM to clear the status bit [ implying that the
* POWER_BUTTON event should not reach userspace ]
*/
if (ACPI_SUCCESS(status) && (acpi_state == ACPI_STATE_S3))
acpi_clear_event(ACPI_EVENT_POWER_BUTTON);
/*
* Disable and clear GPE status before interrupt is enabled. Some GPEs
* (like wakeup GPE) haven't handler, this can avoid such GPE misfire.
* acpi_leave_sleep_state will reenable specific GPEs later
*/
acpi_disable_all_gpes();
/* Allow EC transactions to happen. */
acpi_ec_unblock_transactions_early();
suspend_nvs_restore();
return ACPI_SUCCESS(status) ? 0 : -EFAULT;
}
static int acpi_suspend_state_valid(suspend_state_t pm_state)
{
u32 acpi_state;
switch (pm_state) {
case PM_SUSPEND_ON:
case PM_SUSPEND_STANDBY:
case PM_SUSPEND_MEM:
acpi_state = acpi_suspend_states[pm_state];
return sleep_states[acpi_state];
default:
return 0;
}
}
static const struct platform_suspend_ops acpi_suspend_ops = {
.valid = acpi_suspend_state_valid,
.begin = acpi_suspend_begin,
.prepare_late = acpi_pm_prepare,
.enter = acpi_suspend_enter,
.wake = acpi_pm_finish,
.end = acpi_pm_end,
};
/**
* acpi_suspend_begin_old - Set the target system sleep state to the
* state associated with given @pm_state, if supported, and
* execute the _PTS control method. This function is used if the
* pre-ACPI 2.0 suspend ordering has been requested.
*/
static int acpi_suspend_begin_old(suspend_state_t pm_state)
{
int error = acpi_suspend_begin(pm_state);
if (!error)
error = __acpi_pm_prepare();
return error;
}
/*
* The following callbacks are used if the pre-ACPI 2.0 suspend ordering has
* been requested.
*/
static const struct platform_suspend_ops acpi_suspend_ops_old = {
.valid = acpi_suspend_state_valid,
.begin = acpi_suspend_begin_old,
.prepare_late = acpi_pm_pre_suspend,
.enter = acpi_suspend_enter,
.wake = acpi_pm_finish,
.end = acpi_pm_end,
.recover = acpi_pm_finish,
};
static int __init init_old_suspend_ordering(const struct dmi_system_id *d)
{
old_suspend_ordering = true;
return 0;
}
static int __init init_nvs_nosave(const struct dmi_system_id *d)
{
acpi_nvs_nosave();
return 0;
}
static struct dmi_system_id __initdata acpisleep_dmi_table[] = {
{
.callback = init_old_suspend_ordering,
.ident = "Abit KN9 (nForce4 variant)",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "http://www.abit.com.tw/"),
DMI_MATCH(DMI_BOARD_NAME, "KN9 Series(NF-CK804)"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "HP xw4600 Workstation",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP xw4600 Workstation"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus Pundit P1-AH2 (M2N8L motherboard)",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTek Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "M2N8L"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Panasonic CF51-2L",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR,
"Matsushita Electric Industrial Co.,Ltd."),
DMI_MATCH(DMI_BOARD_NAME, "CF51-2L"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW21E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW21E"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCEB17FX",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB17FX"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-SR11M",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR11M"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Everex StepNote Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Everex Systems, Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Everex StepNote Series"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCEB1Z1E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB1Z1E"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-NW130D",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-NW130D"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCCW29FX",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCCW29FX"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Averatec AV1020-ED2",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "AVERATEC"),
DMI_MATCH(DMI_PRODUCT_NAME, "1000 Series"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus A8N-SLI DELUXE",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "A8N-SLI DELUXE"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus A8N-SLI Premium",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "A8N-SLI Premium"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-SR26GN_P",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR26GN_P"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW520F",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW520F"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Asus K54C",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K54C"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Asus K54HR",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K54HR"),
},
},
{},
};
#endif /* CONFIG_SUSPEND */
#ifdef CONFIG_HIBERNATION
static unsigned long s4_hardware_signature;
static struct acpi_table_facs *facs;
static bool nosigcheck;
void __init acpi_no_s4_hw_signature(void)
{
nosigcheck = true;
}
static int acpi_hibernation_begin(void)
{
int error;
error = nvs_nosave ? 0 : suspend_nvs_alloc();
if (!error) {
acpi_target_sleep_state = ACPI_STATE_S4;
acpi_sleep_tts_switch(acpi_target_sleep_state);
}
return error;
}
static int acpi_hibernation_enter(void)
{
acpi_status status = AE_OK;
ACPI_FLUSH_CPU_CACHE();
/* This shouldn't return. If it returns, we have a problem */
status = acpi_enter_sleep_state(ACPI_STATE_S4, wake_sleep_flags);
/* Reprogram control registers and execute _BFS */
acpi_leave_sleep_state_prep(ACPI_STATE_S4, wake_sleep_flags);
return ACPI_SUCCESS(status) ? 0 : -EFAULT;
}
static void acpi_hibernation_leave(void)
{
/*
* If ACPI is not enabled by the BIOS and the boot kernel, we need to
* enable it here.
*/
acpi_enable();
/* Reprogram control registers and execute _BFS */
acpi_leave_sleep_state_prep(ACPI_STATE_S4, wake_sleep_flags);
/* Check the hardware signature */
if (facs && s4_hardware_signature != facs->hardware_signature) {
printk(KERN_EMERG "ACPI: Hardware changed while hibernated, "
"cannot resume!\n");
panic("ACPI S4 hardware signature mismatch");
}
/* Restore the NVS memory area */
suspend_nvs_restore();
/* Allow EC transactions to happen. */
acpi_ec_unblock_transactions_early();
}
static void acpi_pm_thaw(void)
{
acpi_ec_unblock_transactions();
acpi_enable_all_runtime_gpes();
}
static const struct platform_hibernation_ops acpi_hibernation_ops = {
.begin = acpi_hibernation_begin,
.end = acpi_pm_end,
.pre_snapshot = acpi_pm_prepare,
.finish = acpi_pm_finish,
.prepare = acpi_pm_prepare,
.enter = acpi_hibernation_enter,
.leave = acpi_hibernation_leave,
.pre_restore = acpi_pm_freeze,
.restore_cleanup = acpi_pm_thaw,
};
/**
* acpi_hibernation_begin_old - Set the target system sleep state to
* ACPI_STATE_S4 and execute the _PTS control method. This
* function is used if the pre-ACPI 2.0 suspend ordering has been
* requested.
*/
static int acpi_hibernation_begin_old(void)
{
int error;
/*
* The _TTS object should always be evaluated before the _PTS object.
* When the old_suspended_ordering is true, the _PTS object is
* evaluated in the acpi_sleep_prepare.
*/
acpi_sleep_tts_switch(ACPI_STATE_S4);
error = acpi_sleep_prepare(ACPI_STATE_S4);
if (!error) {
if (!nvs_nosave)
error = suspend_nvs_alloc();
if (!error)
acpi_target_sleep_state = ACPI_STATE_S4;
}
return error;
}
/*
* The following callbacks are used if the pre-ACPI 2.0 suspend ordering has
* been requested.
*/
static const struct platform_hibernation_ops acpi_hibernation_ops_old = {
.begin = acpi_hibernation_begin_old,
.end = acpi_pm_end,
.pre_snapshot = acpi_pm_pre_suspend,
.prepare = acpi_pm_freeze,
.finish = acpi_pm_finish,
.enter = acpi_hibernation_enter,
.leave = acpi_hibernation_leave,
.pre_restore = acpi_pm_freeze,
.restore_cleanup = acpi_pm_thaw,
.recover = acpi_pm_finish,
};
#endif /* CONFIG_HIBERNATION */
int acpi_suspend(u32 acpi_state)
{
suspend_state_t states[] = {
[1] = PM_SUSPEND_STANDBY,
[3] = PM_SUSPEND_MEM,
[5] = PM_SUSPEND_MAX
};
if (acpi_state < 6 && states[acpi_state])
return pm_suspend(states[acpi_state]);
if (acpi_state == 4)
return hibernate();
return -EINVAL;
}
#ifdef CONFIG_PM
/**
* acpi_pm_device_sleep_state - return preferred power state of ACPI device
* in the system sleep state given by %acpi_target_sleep_state
* @dev: device to examine; its driver model wakeup flags control
* whether it should be able to wake up the system
* @d_min_p: used to store the upper limit of allowed states range
* Return value: preferred power state of the device on success, -ENODEV on
* failure (ie. if there's no 'struct acpi_device' for @dev)
*
* Find the lowest power (highest number) ACPI device power state that
* device @dev can be in while the system is in the sleep state represented
* by %acpi_target_sleep_state. If @wake is nonzero, the device should be
* able to wake up the system from this sleep state. If @d_min_p is set,
* the highest power (lowest number) device power state of @dev allowed
* in this system sleep state is stored at the location pointed to by it.
*
* The caller must ensure that @dev is valid before using this function.
* The caller is also responsible for figuring out if the device is
* supposed to be able to wake up the system and passing this information
* via @wake.
*/
int acpi_pm_device_sleep_state(struct device *dev, int *d_min_p)
{
acpi_handle handle = DEVICE_ACPI_HANDLE(dev);
struct acpi_device *adev;
char acpi_method[] = "_SxD";
unsigned long long d_min, d_max;
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &adev))) {
printk(KERN_DEBUG "ACPI handle has no context!\n");
return -ENODEV;
}
acpi_method[2] = '0' + acpi_target_sleep_state;
/*
* If the sleep state is S0, we will return D3, but if the device has
* _S0W, we will use the value from _S0W
*/
d_min = ACPI_STATE_D0;
d_max = ACPI_STATE_D3;
/*
* If present, _SxD methods return the minimum D-state (highest power
* state) we can use for the corresponding S-states. Otherwise, the
* minimum D-state is D0 (ACPI 3.x).
*
* NOTE: We rely on acpi_evaluate_integer() not clobbering the integer
* provided -- that's our fault recovery, we ignore retval.
*/
if (acpi_target_sleep_state > ACPI_STATE_S0)
acpi_evaluate_integer(handle, acpi_method, NULL, &d_min);
/*
* If _PRW says we can wake up the system from the target sleep state,
* the D-state returned by _SxD is sufficient for that (we assume a
* wakeup-aware driver if wake is set). Still, if _SxW exists
* (ACPI 3.x), it should return the maximum (lowest power) D-state that
* can wake the system. _S0W may be valid, too.
*/
if (acpi_target_sleep_state == ACPI_STATE_S0 ||
(device_may_wakeup(dev) &&
adev->wakeup.sleep_state <= acpi_target_sleep_state)) {
acpi_status status;
acpi_method[3] = 'W';
status = acpi_evaluate_integer(handle, acpi_method, NULL,
&d_max);
if (ACPI_FAILURE(status)) {
if (acpi_target_sleep_state != ACPI_STATE_S0 ||
status != AE_NOT_FOUND)
d_max = d_min;
} else if (d_max < d_min) {
/* Warn the user of the broken DSDT */
printk(KERN_WARNING "ACPI: Wrong value from %s\n",
acpi_method);
/* Sanitize it */
d_min = d_max;
}
}
if (d_min_p)
*d_min_p = d_min;
return d_max;
}
#endif /* CONFIG_PM */
#ifdef CONFIG_PM_SLEEP
/**
* acpi_pm_device_run_wake - Enable/disable wake-up for given device.
* @phys_dev: Device to enable/disable the platform to wake-up the system for.
* @enable: Whether enable or disable the wake-up functionality.
*
* Find the ACPI device object corresponding to @pci_dev and try to
* enable/disable the GPE associated with it.
*/
int acpi_pm_device_run_wake(struct device *phys_dev, bool enable)
{
struct acpi_device *dev;
acpi_handle handle;
if (!device_run_wake(phys_dev))
return -EINVAL;
handle = DEVICE_ACPI_HANDLE(phys_dev);
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &dev))) {
dev_dbg(phys_dev, "ACPI handle has no context in %s!\n",
__func__);
return -ENODEV;
}
if (enable) {
acpi_enable_wakeup_device_power(dev, ACPI_STATE_S0);
acpi_enable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number);
} else {
acpi_disable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number);
acpi_disable_wakeup_device_power(dev);
}
return 0;
}
/**
* acpi_pm_device_sleep_wake - enable or disable the system wake-up
* capability of given device
* @dev: device to handle
* @enable: 'true' - enable, 'false' - disable the wake-up capability
*/
int acpi_pm_device_sleep_wake(struct device *dev, bool enable)
{
acpi_handle handle;
struct acpi_device *adev;
int error;
if (!device_can_wakeup(dev))
return -EINVAL;
handle = DEVICE_ACPI_HANDLE(dev);
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &adev))) {
dev_dbg(dev, "ACPI handle has no context in %s!\n", __func__);
return -ENODEV;
}
error = enable ?
acpi_enable_wakeup_device_power(adev, acpi_target_sleep_state) :
acpi_disable_wakeup_device_power(adev);
if (!error)
dev_info(dev, "wake-up capability %s by ACPI\n",
enable ? "enabled" : "disabled");
return error;
}
#endif /* CONFIG_PM_SLEEP */
static void acpi_power_off_prepare(void)
{
/* Prepare to power off the system */
acpi_sleep_prepare(ACPI_STATE_S5);
acpi_disable_all_gpes();
}
static void acpi_power_off(void)
{
/* acpi_sleep_prepare(ACPI_STATE_S5) should have already been called */
printk(KERN_DEBUG "%s called\n", __func__);
local_irq_disable();
acpi_enter_sleep_state(ACPI_STATE_S5, wake_sleep_flags);
}
/*
* ACPI 2.0 created the optional _GTS and _BFS,
* but industry adoption has been neither rapid nor broad.
*
* Linux gets into trouble when it executes poorly validated
* paths through the BIOS, so disable _GTS and _BFS by default,
* but do speak up and offer the option to enable them.
*/
static void __init acpi_gts_bfs_check(void)
{
acpi_handle dummy;
if (ACPI_SUCCESS(acpi_get_handle(ACPI_ROOT_OBJECT, METHOD_PATHNAME__GTS, &dummy)))
{
printk(KERN_NOTICE PREFIX "BIOS offers _GTS\n");
printk(KERN_NOTICE PREFIX "If \"acpi.gts=1\" improves suspend, "
"please notify linux-acpi@vger.kernel.org\n");
}
if (ACPI_SUCCESS(acpi_get_handle(ACPI_ROOT_OBJECT, METHOD_PATHNAME__BFS, &dummy)))
{
printk(KERN_NOTICE PREFIX "BIOS offers _BFS\n");
printk(KERN_NOTICE PREFIX "If \"acpi.bfs=1\" improves resume, "
"please notify linux-acpi@vger.kernel.org\n");
}
}
int __init acpi_sleep_init(void)
{
acpi_status status;
u8 type_a, type_b;
#ifdef CONFIG_SUSPEND
int i = 0;
dmi_check_system(acpisleep_dmi_table);
#endif
if (acpi_disabled)
return 0;
sleep_states[ACPI_STATE_S0] = 1;
printk(KERN_INFO PREFIX "(supports S0");
#ifdef CONFIG_SUSPEND
for (i = ACPI_STATE_S1; i < ACPI_STATE_S4; i++) {
status = acpi_get_sleep_type_data(i, &type_a, &type_b);
if (ACPI_SUCCESS(status)) {
sleep_states[i] = 1;
printk(" S%d", i);
}
}
suspend_set_ops(old_suspend_ordering ?
&acpi_suspend_ops_old : &acpi_suspend_ops);
#endif
#ifdef CONFIG_HIBERNATION
status = acpi_get_sleep_type_data(ACPI_STATE_S4, &type_a, &type_b);
if (ACPI_SUCCESS(status)) {
hibernation_set_ops(old_suspend_ordering ?
&acpi_hibernation_ops_old : &acpi_hibernation_ops);
sleep_states[ACPI_STATE_S4] = 1;
printk(" S4");
if (!nosigcheck) {
acpi_get_table(ACPI_SIG_FACS, 1,
(struct acpi_table_header **)&facs);
if (facs)
s4_hardware_signature =
facs->hardware_signature;
}
}
#endif
status = acpi_get_sleep_type_data(ACPI_STATE_S5, &type_a, &type_b);
if (ACPI_SUCCESS(status)) {
sleep_states[ACPI_STATE_S5] = 1;
printk(" S5");
pm_power_off_prepare = acpi_power_off_prepare;
pm_power_off = acpi_power_off;
}
printk(")\n");
/*
* Register the tts_notifier to reboot notifier list so that the _TTS
* object can also be evaluated when the system enters S5.
*/
register_reboot_notifier(&tts_notifier);
acpi_gts_bfs_check();
return 0;
}
| gpl-2.0 |
KylinUI/android_kernel_samsung_t1 | arch/tile/kernel/process.c | 2725 | 21750 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#include <linux/sched.h>
#include <linux/preempt.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kprobes.h>
#include <linux/elfcore.h>
#include <linux/tick.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/compat.h>
#include <linux/hardirq.h>
#include <linux/syscalls.h>
#include <linux/kernel.h>
#include <linux/tracehook.h>
#include <linux/signal.h>
#include <asm/system.h>
#include <asm/stack.h>
#include <asm/homecache.h>
#include <asm/syscalls.h>
#include <asm/traps.h>
#ifdef CONFIG_HARDWALL
#include <asm/hardwall.h>
#endif
#include <arch/chip.h>
#include <arch/abi.h>
/*
* Use the (x86) "idle=poll" option to prefer low latency when leaving the
* idle loop over low power while in the idle loop, e.g. if we have
* one thread per core and we want to get threads out of futex waits fast.
*/
static int no_idle_nap;
static int __init idle_setup(char *str)
{
if (!str)
return -EINVAL;
if (!strcmp(str, "poll")) {
pr_info("using polling idle threads.\n");
no_idle_nap = 1;
} else if (!strcmp(str, "halt"))
no_idle_nap = 0;
else
return -1;
return 0;
}
early_param("idle", idle_setup);
/*
* The idle thread. There's no useful work to be
* done, so just try to conserve power and have a
* low exit latency (ie sit in a loop waiting for
* somebody to say that they'd like to reschedule)
*/
void cpu_idle(void)
{
int cpu = smp_processor_id();
current_thread_info()->status |= TS_POLLING;
if (no_idle_nap) {
while (1) {
while (!need_resched())
cpu_relax();
schedule();
}
}
/* endless idle loop with no priority at all */
while (1) {
tick_nohz_stop_sched_tick(1);
while (!need_resched()) {
if (cpu_is_offline(cpu))
BUG(); /* no HOTPLUG_CPU */
local_irq_disable();
__get_cpu_var(irq_stat).idle_timestamp = jiffies;
current_thread_info()->status &= ~TS_POLLING;
/*
* TS_POLLING-cleared state must be visible before we
* test NEED_RESCHED:
*/
smp_mb();
if (!need_resched())
_cpu_idle();
else
local_irq_enable();
current_thread_info()->status |= TS_POLLING;
}
tick_nohz_restart_sched_tick();
preempt_enable_no_resched();
schedule();
preempt_disable();
}
}
struct thread_info *alloc_thread_info_node(struct task_struct *task, int node)
{
struct page *page;
gfp_t flags = GFP_KERNEL;
#ifdef CONFIG_DEBUG_STACK_USAGE
flags |= __GFP_ZERO;
#endif
page = alloc_pages_node(node, flags, THREAD_SIZE_ORDER);
if (!page)
return NULL;
return (struct thread_info *)page_address(page);
}
/*
* Free a thread_info node, and all of its derivative
* data structures.
*/
void free_thread_info(struct thread_info *info)
{
struct single_step_state *step_state = info->step_state;
#ifdef CONFIG_HARDWALL
/*
* We free a thread_info from the context of the task that has
* been scheduled next, so the original task is already dead.
* Calling deactivate here just frees up the data structures.
* If the task we're freeing held the last reference to a
* hardwall fd, it would have been released prior to this point
* anyway via exit_files(), and "hardwall" would be NULL by now.
*/
if (info->task->thread.hardwall)
hardwall_deactivate(info->task);
#endif
if (step_state) {
/*
* FIXME: we don't munmap step_state->buffer
* because the mm_struct for this process (info->task->mm)
* has already been zeroed in exit_mm(). Keeping a
* reference to it here seems like a bad move, so this
* means we can't munmap() the buffer, and therefore if we
* ptrace multiple threads in a process, we will slowly
* leak user memory. (Note that as soon as the last
* thread in a process dies, we will reclaim all user
* memory including single-step buffers in the usual way.)
* We should either assign a kernel VA to this buffer
* somehow, or we should associate the buffer(s) with the
* mm itself so we can clean them up that way.
*/
kfree(step_state);
}
free_pages((unsigned long)info, THREAD_SIZE_ORDER);
}
static void save_arch_state(struct thread_struct *t);
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long stack_size,
struct task_struct *p, struct pt_regs *regs)
{
struct pt_regs *childregs;
unsigned long ksp;
/*
* When creating a new kernel thread we pass sp as zero.
* Assign it to a reasonable value now that we have the stack.
*/
if (sp == 0 && regs->ex1 == PL_ICS_EX1(KERNEL_PL, 0))
sp = KSTK_TOP(p);
/*
* Do not clone step state from the parent; each thread
* must make its own lazily.
*/
task_thread_info(p)->step_state = NULL;
/*
* Start new thread in ret_from_fork so it schedules properly
* and then return from interrupt like the parent.
*/
p->thread.pc = (unsigned long) ret_from_fork;
/* Save user stack top pointer so we can ID the stack vm area later. */
p->thread.usp0 = sp;
/* Record the pid of the process that created this one. */
p->thread.creator_pid = current->pid;
/*
* Copy the registers onto the kernel stack so the
* return-from-interrupt code will reload it into registers.
*/
childregs = task_pt_regs(p);
*childregs = *regs;
childregs->regs[0] = 0; /* return value is zero */
childregs->sp = sp; /* override with new user stack pointer */
/*
* If CLONE_SETTLS is set, set "tp" in the new task to "r4",
* which is passed in as arg #5 to sys_clone().
*/
if (clone_flags & CLONE_SETTLS)
childregs->tp = regs->regs[4];
/*
* Copy the callee-saved registers from the passed pt_regs struct
* into the context-switch callee-saved registers area.
* This way when we start the interrupt-return sequence, the
* callee-save registers will be correctly in registers, which
* is how we assume the compiler leaves them as we start doing
* the normal return-from-interrupt path after calling C code.
* Zero out the C ABI save area to mark the top of the stack.
*/
ksp = (unsigned long) childregs;
ksp -= C_ABI_SAVE_AREA_SIZE; /* interrupt-entry save area */
((long *)ksp)[0] = ((long *)ksp)[1] = 0;
ksp -= CALLEE_SAVED_REGS_COUNT * sizeof(unsigned long);
memcpy((void *)ksp, ®s->regs[CALLEE_SAVED_FIRST_REG],
CALLEE_SAVED_REGS_COUNT * sizeof(unsigned long));
ksp -= C_ABI_SAVE_AREA_SIZE; /* __switch_to() save area */
((long *)ksp)[0] = ((long *)ksp)[1] = 0;
p->thread.ksp = ksp;
#if CHIP_HAS_TILE_DMA()
/*
* No DMA in the new thread. We model this on the fact that
* fork() clears the pending signals, alarms, and aio for the child.
*/
memset(&p->thread.tile_dma_state, 0, sizeof(struct tile_dma_state));
memset(&p->thread.dma_async_tlb, 0, sizeof(struct async_tlb));
#endif
#if CHIP_HAS_SN_PROC()
/* Likewise, the new thread is not running static processor code. */
p->thread.sn_proc_running = 0;
memset(&p->thread.sn_async_tlb, 0, sizeof(struct async_tlb));
#endif
#if CHIP_HAS_PROC_STATUS_SPR()
/* New thread has its miscellaneous processor state bits clear. */
p->thread.proc_status = 0;
#endif
#ifdef CONFIG_HARDWALL
/* New thread does not own any networks. */
p->thread.hardwall = NULL;
#endif
/*
* Start the new thread with the current architecture state
* (user interrupt masks, etc.).
*/
save_arch_state(&p->thread);
return 0;
}
/*
* Return "current" if it looks plausible, or else a pointer to a dummy.
* This can be helpful if we are just trying to emit a clean panic.
*/
struct task_struct *validate_current(void)
{
static struct task_struct corrupt = { .comm = "<corrupt>" };
struct task_struct *tsk = current;
if (unlikely((unsigned long)tsk < PAGE_OFFSET ||
(void *)tsk > high_memory ||
((unsigned long)tsk & (__alignof__(*tsk) - 1)) != 0)) {
pr_err("Corrupt 'current' %p (sp %#lx)\n", tsk, stack_pointer);
tsk = &corrupt;
}
return tsk;
}
/* Take and return the pointer to the previous task, for schedule_tail(). */
struct task_struct *sim_notify_fork(struct task_struct *prev)
{
struct task_struct *tsk = current;
__insn_mtspr(SPR_SIM_CONTROL, SIM_CONTROL_OS_FORK_PARENT |
(tsk->thread.creator_pid << _SIM_CONTROL_OPERATOR_BITS));
__insn_mtspr(SPR_SIM_CONTROL, SIM_CONTROL_OS_FORK |
(tsk->pid << _SIM_CONTROL_OPERATOR_BITS));
return prev;
}
int dump_task_regs(struct task_struct *tsk, elf_gregset_t *regs)
{
struct pt_regs *ptregs = task_pt_regs(tsk);
elf_core_copy_regs(regs, ptregs);
return 1;
}
#if CHIP_HAS_TILE_DMA()
/* Allow user processes to access the DMA SPRs */
void grant_dma_mpls(void)
{
#if CONFIG_KERNEL_PL == 2
__insn_mtspr(SPR_MPL_DMA_CPL_SET_1, 1);
__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_1, 1);
#else
__insn_mtspr(SPR_MPL_DMA_CPL_SET_0, 1);
__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_0, 1);
#endif
}
/* Forbid user processes from accessing the DMA SPRs */
void restrict_dma_mpls(void)
{
#if CONFIG_KERNEL_PL == 2
__insn_mtspr(SPR_MPL_DMA_CPL_SET_2, 1);
__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_2, 1);
#else
__insn_mtspr(SPR_MPL_DMA_CPL_SET_1, 1);
__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_1, 1);
#endif
}
/* Pause the DMA engine, then save off its state registers. */
static void save_tile_dma_state(struct tile_dma_state *dma)
{
unsigned long state = __insn_mfspr(SPR_DMA_USER_STATUS);
unsigned long post_suspend_state;
/* If we're running, suspend the engine. */
if ((state & DMA_STATUS_MASK) == SPR_DMA_STATUS__RUNNING_MASK)
__insn_mtspr(SPR_DMA_CTR, SPR_DMA_CTR__SUSPEND_MASK);
/*
* Wait for the engine to idle, then save regs. Note that we
* want to record the "running" bit from before suspension,
* and the "done" bit from after, so that we can properly
* distinguish a case where the user suspended the engine from
* the case where the kernel suspended as part of the context
* swap.
*/
do {
post_suspend_state = __insn_mfspr(SPR_DMA_USER_STATUS);
} while (post_suspend_state & SPR_DMA_STATUS__BUSY_MASK);
dma->src = __insn_mfspr(SPR_DMA_SRC_ADDR);
dma->src_chunk = __insn_mfspr(SPR_DMA_SRC_CHUNK_ADDR);
dma->dest = __insn_mfspr(SPR_DMA_DST_ADDR);
dma->dest_chunk = __insn_mfspr(SPR_DMA_DST_CHUNK_ADDR);
dma->strides = __insn_mfspr(SPR_DMA_STRIDE);
dma->chunk_size = __insn_mfspr(SPR_DMA_CHUNK_SIZE);
dma->byte = __insn_mfspr(SPR_DMA_BYTE);
dma->status = (state & SPR_DMA_STATUS__RUNNING_MASK) |
(post_suspend_state & SPR_DMA_STATUS__DONE_MASK);
}
/* Restart a DMA that was running before we were context-switched out. */
static void restore_tile_dma_state(struct thread_struct *t)
{
const struct tile_dma_state *dma = &t->tile_dma_state;
/*
* The only way to restore the done bit is to run a zero
* length transaction.
*/
if ((dma->status & SPR_DMA_STATUS__DONE_MASK) &&
!(__insn_mfspr(SPR_DMA_USER_STATUS) & SPR_DMA_STATUS__DONE_MASK)) {
__insn_mtspr(SPR_DMA_BYTE, 0);
__insn_mtspr(SPR_DMA_CTR, SPR_DMA_CTR__REQUEST_MASK);
while (__insn_mfspr(SPR_DMA_USER_STATUS) &
SPR_DMA_STATUS__BUSY_MASK)
;
}
__insn_mtspr(SPR_DMA_SRC_ADDR, dma->src);
__insn_mtspr(SPR_DMA_SRC_CHUNK_ADDR, dma->src_chunk);
__insn_mtspr(SPR_DMA_DST_ADDR, dma->dest);
__insn_mtspr(SPR_DMA_DST_CHUNK_ADDR, dma->dest_chunk);
__insn_mtspr(SPR_DMA_STRIDE, dma->strides);
__insn_mtspr(SPR_DMA_CHUNK_SIZE, dma->chunk_size);
__insn_mtspr(SPR_DMA_BYTE, dma->byte);
/*
* Restart the engine if we were running and not done.
* Clear a pending async DMA fault that we were waiting on return
* to user space to execute, since we expect the DMA engine
* to regenerate those faults for us now. Note that we don't
* try to clear the TIF_ASYNC_TLB flag, since it's relatively
* harmless if set, and it covers both DMA and the SN processor.
*/
if ((dma->status & DMA_STATUS_MASK) == SPR_DMA_STATUS__RUNNING_MASK) {
t->dma_async_tlb.fault_num = 0;
__insn_mtspr(SPR_DMA_CTR, SPR_DMA_CTR__REQUEST_MASK);
}
}
#endif
static void save_arch_state(struct thread_struct *t)
{
#if CHIP_HAS_SPLIT_INTR_MASK()
t->interrupt_mask = __insn_mfspr(SPR_INTERRUPT_MASK_0_0) |
((u64)__insn_mfspr(SPR_INTERRUPT_MASK_0_1) << 32);
#else
t->interrupt_mask = __insn_mfspr(SPR_INTERRUPT_MASK_0);
#endif
t->ex_context[0] = __insn_mfspr(SPR_EX_CONTEXT_0_0);
t->ex_context[1] = __insn_mfspr(SPR_EX_CONTEXT_0_1);
t->system_save[0] = __insn_mfspr(SPR_SYSTEM_SAVE_0_0);
t->system_save[1] = __insn_mfspr(SPR_SYSTEM_SAVE_0_1);
t->system_save[2] = __insn_mfspr(SPR_SYSTEM_SAVE_0_2);
t->system_save[3] = __insn_mfspr(SPR_SYSTEM_SAVE_0_3);
t->intctrl_0 = __insn_mfspr(SPR_INTCTRL_0_STATUS);
#if CHIP_HAS_PROC_STATUS_SPR()
t->proc_status = __insn_mfspr(SPR_PROC_STATUS);
#endif
#if !CHIP_HAS_FIXED_INTVEC_BASE()
t->interrupt_vector_base = __insn_mfspr(SPR_INTERRUPT_VECTOR_BASE_0);
#endif
#if CHIP_HAS_TILE_RTF_HWM()
t->tile_rtf_hwm = __insn_mfspr(SPR_TILE_RTF_HWM);
#endif
#if CHIP_HAS_DSTREAM_PF()
t->dstream_pf = __insn_mfspr(SPR_DSTREAM_PF);
#endif
}
static void restore_arch_state(const struct thread_struct *t)
{
#if CHIP_HAS_SPLIT_INTR_MASK()
__insn_mtspr(SPR_INTERRUPT_MASK_0_0, (u32) t->interrupt_mask);
__insn_mtspr(SPR_INTERRUPT_MASK_0_1, t->interrupt_mask >> 32);
#else
__insn_mtspr(SPR_INTERRUPT_MASK_0, t->interrupt_mask);
#endif
__insn_mtspr(SPR_EX_CONTEXT_0_0, t->ex_context[0]);
__insn_mtspr(SPR_EX_CONTEXT_0_1, t->ex_context[1]);
__insn_mtspr(SPR_SYSTEM_SAVE_0_0, t->system_save[0]);
__insn_mtspr(SPR_SYSTEM_SAVE_0_1, t->system_save[1]);
__insn_mtspr(SPR_SYSTEM_SAVE_0_2, t->system_save[2]);
__insn_mtspr(SPR_SYSTEM_SAVE_0_3, t->system_save[3]);
__insn_mtspr(SPR_INTCTRL_0_STATUS, t->intctrl_0);
#if CHIP_HAS_PROC_STATUS_SPR()
__insn_mtspr(SPR_PROC_STATUS, t->proc_status);
#endif
#if !CHIP_HAS_FIXED_INTVEC_BASE()
__insn_mtspr(SPR_INTERRUPT_VECTOR_BASE_0, t->interrupt_vector_base);
#endif
#if CHIP_HAS_TILE_RTF_HWM()
__insn_mtspr(SPR_TILE_RTF_HWM, t->tile_rtf_hwm);
#endif
#if CHIP_HAS_DSTREAM_PF()
__insn_mtspr(SPR_DSTREAM_PF, t->dstream_pf);
#endif
}
void _prepare_arch_switch(struct task_struct *next)
{
#if CHIP_HAS_SN_PROC()
int snctl;
#endif
#if CHIP_HAS_TILE_DMA()
struct tile_dma_state *dma = ¤t->thread.tile_dma_state;
if (dma->enabled)
save_tile_dma_state(dma);
#endif
#if CHIP_HAS_SN_PROC()
/*
* Suspend the static network processor if it was running.
* We do not suspend the fabric itself, just like we don't
* try to suspend the UDN.
*/
snctl = __insn_mfspr(SPR_SNCTL);
current->thread.sn_proc_running =
(snctl & SPR_SNCTL__FRZPROC_MASK) == 0;
if (current->thread.sn_proc_running)
__insn_mtspr(SPR_SNCTL, snctl | SPR_SNCTL__FRZPROC_MASK);
#endif
}
struct task_struct *__sched _switch_to(struct task_struct *prev,
struct task_struct *next)
{
/* DMA state is already saved; save off other arch state. */
save_arch_state(&prev->thread);
#if CHIP_HAS_TILE_DMA()
/*
* Restore DMA in new task if desired.
* Note that it is only safe to restart here since interrupts
* are disabled, so we can't take any DMATLB miss or access
* interrupts before we have finished switching stacks.
*/
if (next->thread.tile_dma_state.enabled) {
restore_tile_dma_state(&next->thread);
grant_dma_mpls();
} else {
restrict_dma_mpls();
}
#endif
/* Restore other arch state. */
restore_arch_state(&next->thread);
#if CHIP_HAS_SN_PROC()
/*
* Restart static network processor in the new process
* if it was running before.
*/
if (next->thread.sn_proc_running) {
int snctl = __insn_mfspr(SPR_SNCTL);
__insn_mtspr(SPR_SNCTL, snctl & ~SPR_SNCTL__FRZPROC_MASK);
}
#endif
#ifdef CONFIG_HARDWALL
/* Enable or disable access to the network registers appropriately. */
if (prev->thread.hardwall != NULL) {
if (next->thread.hardwall == NULL)
restrict_network_mpls();
} else if (next->thread.hardwall != NULL) {
grant_network_mpls();
}
#endif
/*
* Switch kernel SP, PC, and callee-saved registers.
* In the context of the new task, return the old task pointer
* (i.e. the task that actually called __switch_to).
* Pass the value to use for SYSTEM_SAVE_K_0 when we reset our sp.
*/
return __switch_to(prev, next, next_current_ksp0(next));
}
/*
* This routine is called on return from interrupt if any of the
* TIF_WORK_MASK flags are set in thread_info->flags. It is
* entered with interrupts disabled so we don't miss an event
* that modified the thread_info flags. If any flag is set, we
* handle it and return, and the calling assembly code will
* re-disable interrupts, reload the thread flags, and call back
* if more flags need to be handled.
*
* We return whether we need to check the thread_info flags again
* or not. Note that we don't clear TIF_SINGLESTEP here, so it's
* important that it be tested last, and then claim that we don't
* need to recheck the flags.
*/
int do_work_pending(struct pt_regs *regs, u32 thread_info_flags)
{
if (thread_info_flags & _TIF_NEED_RESCHED) {
schedule();
return 1;
}
#if CHIP_HAS_TILE_DMA() || CHIP_HAS_SN_PROC()
if (thread_info_flags & _TIF_ASYNC_TLB) {
do_async_page_fault(regs);
return 1;
}
#endif
if (thread_info_flags & _TIF_SIGPENDING) {
do_signal(regs);
return 1;
}
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
if (current->replacement_session_keyring)
key_replace_session_keyring();
return 1;
}
if (thread_info_flags & _TIF_SINGLESTEP) {
if ((regs->ex1 & SPR_EX_CONTEXT_1_1__PL_MASK) == 0)
single_step_once(regs);
return 0;
}
panic("work_pending: bad flags %#x\n", thread_info_flags);
}
/* Note there is an implicit fifth argument if (clone_flags & CLONE_SETTLS). */
SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
void __user *, parent_tidptr, void __user *, child_tidptr,
struct pt_regs *, regs)
{
if (!newsp)
newsp = regs->sp;
return do_fork(clone_flags, newsp, regs, 0,
parent_tidptr, child_tidptr);
}
/*
* sys_execve() executes a new program.
*/
SYSCALL_DEFINE4(execve, const char __user *, path,
const char __user *const __user *, argv,
const char __user *const __user *, envp,
struct pt_regs *, regs)
{
long error;
char *filename;
filename = getname(path);
error = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
error = do_execve(filename, argv, envp, regs);
putname(filename);
if (error == 0)
single_step_execve();
out:
return error;
}
#ifdef CONFIG_COMPAT
long compat_sys_execve(const char __user *path,
compat_uptr_t __user *argv,
compat_uptr_t __user *envp,
struct pt_regs *regs)
{
long error;
char *filename;
filename = getname(path);
error = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
error = compat_do_execve(filename, argv, envp, regs);
putname(filename);
if (error == 0)
single_step_execve();
out:
return error;
}
#endif
unsigned long get_wchan(struct task_struct *p)
{
struct KBacktraceIterator kbt;
if (!p || p == current || p->state == TASK_RUNNING)
return 0;
for (KBacktraceIterator_init(&kbt, p, NULL);
!KBacktraceIterator_end(&kbt);
KBacktraceIterator_next(&kbt)) {
if (!in_sched_functions(kbt.it.pc))
return kbt.it.pc;
}
return 0;
}
/*
* We pass in lr as zero (cleared in kernel_thread) and the caller
* part of the backtrace ABI on the stack also zeroed (in copy_thread)
* so that backtraces will stop with this function.
* Note that we don't use r0, since copy_thread() clears it.
*/
static void start_kernel_thread(int dummy, int (*fn)(int), int arg)
{
do_exit(fn(arg));
}
/*
* Create a kernel thread
*/
int kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
{
struct pt_regs regs;
memset(®s, 0, sizeof(regs));
regs.ex1 = PL_ICS_EX1(KERNEL_PL, 0); /* run at kernel PL, no ICS */
regs.pc = (long) start_kernel_thread;
regs.flags = PT_FLAGS_CALLER_SAVES; /* need to restore r1 and r2 */
regs.regs[1] = (long) fn; /* function pointer */
regs.regs[2] = (long) arg; /* parameter register */
/* Ok, create the new process.. */
return do_fork(flags | CLONE_VM | CLONE_UNTRACED, 0, ®s,
0, NULL, NULL);
}
EXPORT_SYMBOL(kernel_thread);
/* Flush thread state. */
void flush_thread(void)
{
/* Nothing */
}
/*
* Free current thread data structures etc..
*/
void exit_thread(void)
{
/* Nothing */
}
void show_regs(struct pt_regs *regs)
{
struct task_struct *tsk = validate_current();
int i;
pr_err("\n");
pr_err(" Pid: %d, comm: %20s, CPU: %d\n",
tsk->pid, tsk->comm, smp_processor_id());
#ifdef __tilegx__
for (i = 0; i < 51; i += 3)
pr_err(" r%-2d: "REGFMT" r%-2d: "REGFMT" r%-2d: "REGFMT"\n",
i, regs->regs[i], i+1, regs->regs[i+1],
i+2, regs->regs[i+2]);
pr_err(" r51: "REGFMT" r52: "REGFMT" tp : "REGFMT"\n",
regs->regs[51], regs->regs[52], regs->tp);
pr_err(" sp : "REGFMT" lr : "REGFMT"\n", regs->sp, regs->lr);
#else
for (i = 0; i < 52; i += 4)
pr_err(" r%-2d: "REGFMT" r%-2d: "REGFMT
" r%-2d: "REGFMT" r%-2d: "REGFMT"\n",
i, regs->regs[i], i+1, regs->regs[i+1],
i+2, regs->regs[i+2], i+3, regs->regs[i+3]);
pr_err(" r52: "REGFMT" tp : "REGFMT" sp : "REGFMT" lr : "REGFMT"\n",
regs->regs[52], regs->tp, regs->sp, regs->lr);
#endif
pr_err(" pc : "REGFMT" ex1: %ld faultnum: %ld\n",
regs->pc, regs->ex1, regs->faultnum);
dump_stack_regs(regs);
}
| gpl-2.0 |
avoltz/linux-vybrid | arch/arm/mach-ks8695/irq.c | 2981 | 4284 | /*
* arch/arm/mach-ks8695/irq.c
*
* Copyright (C) 2006 Ben Dooks <ben@simtec.co.uk>
* Copyright (C) 2006 Simtec Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/sysdev.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <mach/regs-irq.h>
#include <mach/regs-gpio.h>
static void ks8695_irq_mask(struct irq_data *d)
{
unsigned long inten;
inten = __raw_readl(KS8695_IRQ_VA + KS8695_INTEN);
inten &= ~(1 << d->irq);
__raw_writel(inten, KS8695_IRQ_VA + KS8695_INTEN);
}
static void ks8695_irq_unmask(struct irq_data *d)
{
unsigned long inten;
inten = __raw_readl(KS8695_IRQ_VA + KS8695_INTEN);
inten |= (1 << d->irq);
__raw_writel(inten, KS8695_IRQ_VA + KS8695_INTEN);
}
static void ks8695_irq_ack(struct irq_data *d)
{
__raw_writel((1 << d->irq), KS8695_IRQ_VA + KS8695_INTST);
}
static struct irq_chip ks8695_irq_level_chip;
static struct irq_chip ks8695_irq_edge_chip;
static int ks8695_irq_set_type(struct irq_data *d, unsigned int type)
{
unsigned long ctrl, mode;
unsigned short level_triggered = 0;
ctrl = __raw_readl(KS8695_GPIO_VA + KS8695_IOPC);
switch (type) {
case IRQ_TYPE_LEVEL_HIGH:
mode = IOPC_TM_HIGH;
level_triggered = 1;
break;
case IRQ_TYPE_LEVEL_LOW:
mode = IOPC_TM_LOW;
level_triggered = 1;
break;
case IRQ_TYPE_EDGE_RISING:
mode = IOPC_TM_RISING;
break;
case IRQ_TYPE_EDGE_FALLING:
mode = IOPC_TM_FALLING;
break;
case IRQ_TYPE_EDGE_BOTH:
mode = IOPC_TM_EDGE;
break;
default:
return -EINVAL;
}
switch (d->irq) {
case KS8695_IRQ_EXTERN0:
ctrl &= ~IOPC_IOEINT0TM;
ctrl |= IOPC_IOEINT0_MODE(mode);
break;
case KS8695_IRQ_EXTERN1:
ctrl &= ~IOPC_IOEINT1TM;
ctrl |= IOPC_IOEINT1_MODE(mode);
break;
case KS8695_IRQ_EXTERN2:
ctrl &= ~IOPC_IOEINT2TM;
ctrl |= IOPC_IOEINT2_MODE(mode);
break;
case KS8695_IRQ_EXTERN3:
ctrl &= ~IOPC_IOEINT3TM;
ctrl |= IOPC_IOEINT3_MODE(mode);
break;
default:
return -EINVAL;
}
if (level_triggered) {
irq_set_chip_and_handler(d->irq, &ks8695_irq_level_chip,
handle_level_irq);
}
else {
irq_set_chip_and_handler(d->irq, &ks8695_irq_edge_chip,
handle_edge_irq);
}
__raw_writel(ctrl, KS8695_GPIO_VA + KS8695_IOPC);
return 0;
}
static struct irq_chip ks8695_irq_level_chip = {
.irq_ack = ks8695_irq_mask,
.irq_mask = ks8695_irq_mask,
.irq_unmask = ks8695_irq_unmask,
.irq_set_type = ks8695_irq_set_type,
};
static struct irq_chip ks8695_irq_edge_chip = {
.irq_ack = ks8695_irq_ack,
.irq_mask = ks8695_irq_mask,
.irq_unmask = ks8695_irq_unmask,
.irq_set_type = ks8695_irq_set_type,
};
void __init ks8695_init_irq(void)
{
unsigned int irq;
/* Disable all interrupts initially */
__raw_writel(0, KS8695_IRQ_VA + KS8695_INTMC);
__raw_writel(0, KS8695_IRQ_VA + KS8695_INTEN);
for (irq = 0; irq < NR_IRQS; irq++) {
switch (irq) {
/* Level-triggered interrupts */
case KS8695_IRQ_BUS_ERROR:
case KS8695_IRQ_UART_MODEM_STATUS:
case KS8695_IRQ_UART_LINE_STATUS:
case KS8695_IRQ_UART_RX:
case KS8695_IRQ_COMM_TX:
case KS8695_IRQ_COMM_RX:
irq_set_chip_and_handler(irq,
&ks8695_irq_level_chip,
handle_level_irq);
break;
/* Edge-triggered interrupts */
default:
/* clear pending bit */
ks8695_irq_ack(irq_get_irq_data(irq));
irq_set_chip_and_handler(irq,
&ks8695_irq_edge_chip,
handle_edge_irq);
}
set_irq_flags(irq, IRQF_VALID);
}
}
| gpl-2.0 |
GameTheory-/android_kernel_lge_l0 | tools/perf/builtin-bench.c | 4261 | 4952 | /*
*
* builtin-bench.c
*
* General benchmarking subsystem provided by perf
*
* Copyright (C) 2009, Hitoshi Mitake <mitake@dcl.info.waseda.ac.jp>
*
*/
/*
*
* Available subsystem list:
* sched ... scheduler and IPC mechanism
* mem ... memory access performance
*
*/
#include "perf.h"
#include "util/util.h"
#include "util/parse-options.h"
#include "builtin.h"
#include "bench/bench.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct bench_suite {
const char *name;
const char *summary;
int (*fn)(int, const char **, const char *);
};
\
/* sentinel: easy for help */
#define suite_all { "all", "test all suite (pseudo suite)", NULL }
static struct bench_suite sched_suites[] = {
{ "messaging",
"Benchmark for scheduler and IPC mechanisms",
bench_sched_messaging },
{ "pipe",
"Flood of communication over pipe() between two processes",
bench_sched_pipe },
suite_all,
{ NULL,
NULL,
NULL }
};
static struct bench_suite mem_suites[] = {
{ "memcpy",
"Simple memory copy in various ways",
bench_mem_memcpy },
suite_all,
{ NULL,
NULL,
NULL }
};
struct bench_subsys {
const char *name;
const char *summary;
struct bench_suite *suites;
};
static struct bench_subsys subsystems[] = {
{ "sched",
"scheduler and IPC mechanism",
sched_suites },
{ "mem",
"memory access performance",
mem_suites },
{ "all", /* sentinel: easy for help */
"test all subsystem (pseudo subsystem)",
NULL },
{ NULL,
NULL,
NULL }
};
static void dump_suites(int subsys_index)
{
int i;
printf("# List of available suites for %s...\n\n",
subsystems[subsys_index].name);
for (i = 0; subsystems[subsys_index].suites[i].name; i++)
printf("%14s: %s\n",
subsystems[subsys_index].suites[i].name,
subsystems[subsys_index].suites[i].summary);
printf("\n");
return;
}
static const char *bench_format_str;
int bench_format = BENCH_FORMAT_DEFAULT;
static const struct option bench_options[] = {
OPT_STRING('f', "format", &bench_format_str, "default",
"Specify format style"),
OPT_END()
};
static const char * const bench_usage[] = {
"perf bench [<common options>] <subsystem> <suite> [<options>]",
NULL
};
static void print_usage(void)
{
int i;
printf("Usage: \n");
for (i = 0; bench_usage[i]; i++)
printf("\t%s\n", bench_usage[i]);
printf("\n");
printf("# List of available subsystems...\n\n");
for (i = 0; subsystems[i].name; i++)
printf("%14s: %s\n",
subsystems[i].name, subsystems[i].summary);
printf("\n");
}
static int bench_str2int(const char *str)
{
if (!str)
return BENCH_FORMAT_DEFAULT;
if (!strcmp(str, BENCH_FORMAT_DEFAULT_STR))
return BENCH_FORMAT_DEFAULT;
else if (!strcmp(str, BENCH_FORMAT_SIMPLE_STR))
return BENCH_FORMAT_SIMPLE;
return BENCH_FORMAT_UNKNOWN;
}
static void all_suite(struct bench_subsys *subsys) /* FROM HERE */
{
int i;
const char *argv[2];
struct bench_suite *suites = subsys->suites;
argv[1] = NULL;
/*
* TODO:
* preparing preset parameters for
* embedded, ordinary PC, HPC, etc...
* will be helpful
*/
for (i = 0; suites[i].fn; i++) {
printf("# Running %s/%s benchmark...\n",
subsys->name,
suites[i].name);
argv[1] = suites[i].name;
suites[i].fn(1, argv, NULL);
printf("\n");
}
}
static void all_subsystem(void)
{
int i;
for (i = 0; subsystems[i].suites; i++)
all_suite(&subsystems[i]);
}
int cmd_bench(int argc, const char **argv, const char *prefix __used)
{
int i, j, status = 0;
if (argc < 2) {
/* No subsystem specified. */
print_usage();
goto end;
}
argc = parse_options(argc, argv, bench_options, bench_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
bench_format = bench_str2int(bench_format_str);
if (bench_format == BENCH_FORMAT_UNKNOWN) {
printf("Unknown format descriptor:%s\n", bench_format_str);
goto end;
}
if (argc < 1) {
print_usage();
goto end;
}
if (!strcmp(argv[0], "all")) {
all_subsystem();
goto end;
}
for (i = 0; subsystems[i].name; i++) {
if (strcmp(subsystems[i].name, argv[0]))
continue;
if (argc < 2) {
/* No suite specified. */
dump_suites(i);
goto end;
}
if (!strcmp(argv[1], "all")) {
all_suite(&subsystems[i]);
goto end;
}
for (j = 0; subsystems[i].suites[j].name; j++) {
if (strcmp(subsystems[i].suites[j].name, argv[1]))
continue;
if (bench_format == BENCH_FORMAT_DEFAULT)
printf("# Running %s/%s benchmark...\n",
subsystems[i].name,
subsystems[i].suites[j].name);
status = subsystems[i].suites[j].fn(argc - 1,
argv + 1, prefix);
goto end;
}
if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
dump_suites(i);
goto end;
}
printf("Unknown suite:%s for %s\n", argv[1], argv[0]);
status = 1;
goto end;
}
printf("Unknown subsystem:%s\n", argv[0]);
status = 1;
end:
return status;
}
| gpl-2.0 |
barome/me102a | arch/s390/kernel/cpcmd.c | 4773 | 3087 | /*
* arch/s390/kernel/cpcmd.c
*
* S390 version
* Copyright IBM Corp. 1999,2007
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
* Christian Borntraeger (cborntra@de.ibm.com),
*/
#define KMSG_COMPONENT "cpcmd"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/stddef.h>
#include <linux/string.h>
#include <asm/ebcdic.h>
#include <asm/cpcmd.h>
#include <asm/system.h>
#include <asm/io.h>
static DEFINE_SPINLOCK(cpcmd_lock);
static char cpcmd_buf[241];
static int diag8_noresponse(int cmdlen)
{
register unsigned long reg2 asm ("2") = (addr_t) cpcmd_buf;
register unsigned long reg3 asm ("3") = cmdlen;
asm volatile(
#ifndef CONFIG_64BIT
" diag %1,%0,0x8\n"
#else /* CONFIG_64BIT */
" sam31\n"
" diag %1,%0,0x8\n"
" sam64\n"
#endif /* CONFIG_64BIT */
: "+d" (reg3) : "d" (reg2) : "cc");
return reg3;
}
static int diag8_response(int cmdlen, char *response, int *rlen)
{
register unsigned long reg2 asm ("2") = (addr_t) cpcmd_buf;
register unsigned long reg3 asm ("3") = (addr_t) response;
register unsigned long reg4 asm ("4") = cmdlen | 0x40000000L;
register unsigned long reg5 asm ("5") = *rlen;
asm volatile(
#ifndef CONFIG_64BIT
" diag %2,%0,0x8\n"
" brc 8,1f\n"
" ar %1,%4\n"
#else /* CONFIG_64BIT */
" sam31\n"
" diag %2,%0,0x8\n"
" sam64\n"
" brc 8,1f\n"
" agr %1,%4\n"
#endif /* CONFIG_64BIT */
"1:\n"
: "+d" (reg4), "+d" (reg5)
: "d" (reg2), "d" (reg3), "d" (*rlen) : "cc");
*rlen = reg5;
return reg4;
}
/*
* __cpcmd has some restrictions over cpcmd
* - the response buffer must reside below 2GB (if any)
* - __cpcmd is unlocked and therefore not SMP-safe
*/
int __cpcmd(const char *cmd, char *response, int rlen, int *response_code)
{
int cmdlen;
int rc;
int response_len;
cmdlen = strlen(cmd);
BUG_ON(cmdlen > 240);
memcpy(cpcmd_buf, cmd, cmdlen);
ASCEBC(cpcmd_buf, cmdlen);
if (response) {
memset(response, 0, rlen);
response_len = rlen;
rc = diag8_response(cmdlen, response, &rlen);
EBCASC(response, response_len);
} else {
rc = diag8_noresponse(cmdlen);
}
if (response_code)
*response_code = rc;
return rlen;
}
EXPORT_SYMBOL(__cpcmd);
int cpcmd(const char *cmd, char *response, int rlen, int *response_code)
{
char *lowbuf;
int len;
unsigned long flags;
if ((virt_to_phys(response) != (unsigned long) response) ||
(((unsigned long)response + rlen) >> 31)) {
lowbuf = kmalloc(rlen, GFP_KERNEL | GFP_DMA);
if (!lowbuf) {
pr_warning("The cpcmd kernel function failed to "
"allocate a response buffer\n");
return -ENOMEM;
}
spin_lock_irqsave(&cpcmd_lock, flags);
len = __cpcmd(cmd, lowbuf, rlen, response_code);
spin_unlock_irqrestore(&cpcmd_lock, flags);
memcpy(response, lowbuf, rlen);
kfree(lowbuf);
} else {
spin_lock_irqsave(&cpcmd_lock, flags);
len = __cpcmd(cmd, response, rlen, response_code);
spin_unlock_irqrestore(&cpcmd_lock, flags);
}
return len;
}
EXPORT_SYMBOL(cpcmd);
| gpl-2.0 |
Cl3Kener/UBER-M | net/netfilter/xt_addrtype.c | 5285 | 6503 | /*
* iptables module to match inet_addr_type() of an ip.
*
* Copyright (c) 2004 Patrick McHardy <kaber@trash.net>
* (C) 2007 Laszlo Attila Toth <panther@balabit.hu>
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/ip.h>
#include <net/route.h>
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/ip6_fib.h>
#endif
#include <linux/netfilter/xt_addrtype.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_DESCRIPTION("Xtables: address type match");
MODULE_ALIAS("ipt_addrtype");
MODULE_ALIAS("ip6t_addrtype");
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
static u32 match_lookup_rt6(struct net *net, const struct net_device *dev,
const struct in6_addr *addr)
{
const struct nf_afinfo *afinfo;
struct flowi6 flow;
struct rt6_info *rt;
u32 ret;
int route_err;
memset(&flow, 0, sizeof(flow));
flow.daddr = *addr;
if (dev)
flow.flowi6_oif = dev->ifindex;
rcu_read_lock();
afinfo = nf_get_afinfo(NFPROTO_IPV6);
if (afinfo != NULL)
route_err = afinfo->route(net, (struct dst_entry **)&rt,
flowi6_to_flowi(&flow), !!dev);
else
route_err = 1;
rcu_read_unlock();
if (route_err)
return XT_ADDRTYPE_UNREACHABLE;
if (rt->rt6i_flags & RTF_REJECT)
ret = XT_ADDRTYPE_UNREACHABLE;
else
ret = 0;
if (rt->rt6i_flags & RTF_LOCAL)
ret |= XT_ADDRTYPE_LOCAL;
if (rt->rt6i_flags & RTF_ANYCAST)
ret |= XT_ADDRTYPE_ANYCAST;
dst_release(&rt->dst);
return ret;
}
static bool match_type6(struct net *net, const struct net_device *dev,
const struct in6_addr *addr, u16 mask)
{
int addr_type = ipv6_addr_type(addr);
if ((mask & XT_ADDRTYPE_MULTICAST) &&
!(addr_type & IPV6_ADDR_MULTICAST))
return false;
if ((mask & XT_ADDRTYPE_UNICAST) && !(addr_type & IPV6_ADDR_UNICAST))
return false;
if ((mask & XT_ADDRTYPE_UNSPEC) && addr_type != IPV6_ADDR_ANY)
return false;
if ((XT_ADDRTYPE_LOCAL | XT_ADDRTYPE_ANYCAST |
XT_ADDRTYPE_UNREACHABLE) & mask)
return !!(mask & match_lookup_rt6(net, dev, addr));
return true;
}
static bool
addrtype_mt6(struct net *net, const struct net_device *dev,
const struct sk_buff *skb, const struct xt_addrtype_info_v1 *info)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
bool ret = true;
if (info->source)
ret &= match_type6(net, dev, &iph->saddr, info->source) ^
(info->flags & XT_ADDRTYPE_INVERT_SOURCE);
if (ret && info->dest)
ret &= match_type6(net, dev, &iph->daddr, info->dest) ^
!!(info->flags & XT_ADDRTYPE_INVERT_DEST);
return ret;
}
#endif
static inline bool match_type(struct net *net, const struct net_device *dev,
__be32 addr, u_int16_t mask)
{
return !!(mask & (1 << inet_dev_addr_type(net, dev, addr)));
}
static bool
addrtype_mt_v0(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_addrtype_info *info = par->matchinfo;
const struct iphdr *iph = ip_hdr(skb);
bool ret = true;
if (info->source)
ret &= match_type(net, NULL, iph->saddr, info->source) ^
info->invert_source;
if (info->dest)
ret &= match_type(net, NULL, iph->daddr, info->dest) ^
info->invert_dest;
return ret;
}
static bool
addrtype_mt_v1(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_addrtype_info_v1 *info = par->matchinfo;
const struct iphdr *iph;
const struct net_device *dev = NULL;
bool ret = true;
if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN)
dev = par->in;
else if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT)
dev = par->out;
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
if (par->family == NFPROTO_IPV6)
return addrtype_mt6(net, dev, skb, info);
#endif
iph = ip_hdr(skb);
if (info->source)
ret &= match_type(net, dev, iph->saddr, info->source) ^
(info->flags & XT_ADDRTYPE_INVERT_SOURCE);
if (ret && info->dest)
ret &= match_type(net, dev, iph->daddr, info->dest) ^
!!(info->flags & XT_ADDRTYPE_INVERT_DEST);
return ret;
}
static int addrtype_mt_checkentry_v1(const struct xt_mtchk_param *par)
{
struct xt_addrtype_info_v1 *info = par->matchinfo;
if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT) {
pr_info("both incoming and outgoing "
"interface limitation cannot be selected\n");
return -EINVAL;
}
if (par->hook_mask & ((1 << NF_INET_PRE_ROUTING) |
(1 << NF_INET_LOCAL_IN)) &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT) {
pr_info("output interface limitation "
"not valid in PREROUTING and INPUT\n");
return -EINVAL;
}
if (par->hook_mask & ((1 << NF_INET_POST_ROUTING) |
(1 << NF_INET_LOCAL_OUT)) &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN) {
pr_info("input interface limitation "
"not valid in POSTROUTING and OUTPUT\n");
return -EINVAL;
}
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
if (par->family == NFPROTO_IPV6) {
if ((info->source | info->dest) & XT_ADDRTYPE_BLACKHOLE) {
pr_err("ipv6 BLACKHOLE matching not supported\n");
return -EINVAL;
}
if ((info->source | info->dest) >= XT_ADDRTYPE_PROHIBIT) {
pr_err("ipv6 PROHIBT (THROW, NAT ..) matching not supported\n");
return -EINVAL;
}
if ((info->source | info->dest) & XT_ADDRTYPE_BROADCAST) {
pr_err("ipv6 does not support BROADCAST matching\n");
return -EINVAL;
}
}
#endif
return 0;
}
static struct xt_match addrtype_mt_reg[] __read_mostly = {
{
.name = "addrtype",
.family = NFPROTO_IPV4,
.match = addrtype_mt_v0,
.matchsize = sizeof(struct xt_addrtype_info),
.me = THIS_MODULE
},
{
.name = "addrtype",
.family = NFPROTO_UNSPEC,
.revision = 1,
.match = addrtype_mt_v1,
.checkentry = addrtype_mt_checkentry_v1,
.matchsize = sizeof(struct xt_addrtype_info_v1),
.me = THIS_MODULE
}
};
static int __init addrtype_mt_init(void)
{
return xt_register_matches(addrtype_mt_reg,
ARRAY_SIZE(addrtype_mt_reg));
}
static void __exit addrtype_mt_exit(void)
{
xt_unregister_matches(addrtype_mt_reg, ARRAY_SIZE(addrtype_mt_reg));
}
module_init(addrtype_mt_init);
module_exit(addrtype_mt_exit);
| gpl-2.0 |
sultanxda/sultan-kernel-pyramid | net/ipv6/netfilter/nf_conntrack_l3proto_ipv6.c | 7589 | 11139 | /*
* Copyright (C)2004 USAGI/WIDE Project
*
* 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.
*
* Author:
* Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
*/
#include <linux/types.h>
#include <linux/ipv6.h>
#include <linux/in6.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/icmp.h>
#include <net/ipv6.h>
#include <net/inet_frag.h>
#include <linux/netfilter_bridge.h>
#include <linux/netfilter_ipv6.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_l3proto.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_zones.h>
#include <net/netfilter/ipv6/nf_conntrack_ipv6.h>
#include <net/netfilter/ipv6/nf_defrag_ipv6.h>
#include <net/netfilter/nf_log.h>
static bool ipv6_pkt_to_tuple(const struct sk_buff *skb, unsigned int nhoff,
struct nf_conntrack_tuple *tuple)
{
const u_int32_t *ap;
u_int32_t _addrs[8];
ap = skb_header_pointer(skb, nhoff + offsetof(struct ipv6hdr, saddr),
sizeof(_addrs), _addrs);
if (ap == NULL)
return false;
memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
return true;
}
static bool ipv6_invert_tuple(struct nf_conntrack_tuple *tuple,
const struct nf_conntrack_tuple *orig)
{
memcpy(tuple->src.u3.ip6, orig->dst.u3.ip6, sizeof(tuple->src.u3.ip6));
memcpy(tuple->dst.u3.ip6, orig->src.u3.ip6, sizeof(tuple->dst.u3.ip6));
return true;
}
static int ipv6_print_tuple(struct seq_file *s,
const struct nf_conntrack_tuple *tuple)
{
return seq_printf(s, "src=%pI6 dst=%pI6 ",
tuple->src.u3.ip6, tuple->dst.u3.ip6);
}
/*
* Based on ipv6_skip_exthdr() in net/ipv6/exthdr.c
*
* This function parses (probably truncated) exthdr set "hdr"
* of length "len". "nexthdrp" initially points to some place,
* where type of the first header can be found.
*
* It skips all well-known exthdrs, and returns pointer to the start
* of unparsable area i.e. the first header with unknown type.
* if success, *nexthdr is updated by type/protocol of this header.
*
* NOTES: - it may return pointer pointing beyond end of packet,
* if the last recognized header is truncated in the middle.
* - if packet is truncated, so that all parsed headers are skipped,
* it returns -1.
* - if packet is fragmented, return pointer of the fragment header.
* - ESP is unparsable for now and considered like
* normal payload protocol.
* - Note also special handling of AUTH header. Thanks to IPsec wizards.
*/
static int nf_ct_ipv6_skip_exthdr(const struct sk_buff *skb, int start,
u8 *nexthdrp, int len)
{
u8 nexthdr = *nexthdrp;
while (ipv6_ext_hdr(nexthdr)) {
struct ipv6_opt_hdr hdr;
int hdrlen;
if (len < (int)sizeof(struct ipv6_opt_hdr))
return -1;
if (nexthdr == NEXTHDR_NONE)
break;
if (nexthdr == NEXTHDR_FRAGMENT)
break;
if (skb_copy_bits(skb, start, &hdr, sizeof(hdr)))
BUG();
if (nexthdr == NEXTHDR_AUTH)
hdrlen = (hdr.hdrlen+2)<<2;
else
hdrlen = ipv6_optlen(&hdr);
nexthdr = hdr.nexthdr;
len -= hdrlen;
start += hdrlen;
}
*nexthdrp = nexthdr;
return start;
}
static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
unsigned int *dataoff, u_int8_t *protonum)
{
unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
unsigned char pnum;
int protoff;
if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
&pnum, sizeof(pnum)) != 0) {
pr_debug("ip6_conntrack_core: can't get nexthdr\n");
return -NF_ACCEPT;
}
protoff = nf_ct_ipv6_skip_exthdr(skb, extoff, &pnum, skb->len - extoff);
/*
* (protoff == skb->len) mean that the packet doesn't have no data
* except of IPv6 & ext headers. but it's tracked anyway. - YK
*/
if ((protoff < 0) || (protoff > skb->len)) {
pr_debug("ip6_conntrack_core: can't find proto in pkt\n");
return -NF_ACCEPT;
}
*dataoff = protoff;
*protonum = pnum;
return NF_ACCEPT;
}
static unsigned int ipv6_confirm(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
struct nf_conn *ct;
const struct nf_conn_help *help;
const struct nf_conntrack_helper *helper;
enum ip_conntrack_info ctinfo;
unsigned int ret, protoff;
unsigned int extoff = (u8 *)(ipv6_hdr(skb) + 1) - skb->data;
unsigned char pnum = ipv6_hdr(skb)->nexthdr;
/* This is where we call the helper: as the packet goes out. */
ct = nf_ct_get(skb, &ctinfo);
if (!ct || ctinfo == IP_CT_RELATED_REPLY)
goto out;
help = nfct_help(ct);
if (!help)
goto out;
/* rcu_read_lock()ed by nf_hook_slow */
helper = rcu_dereference(help->helper);
if (!helper)
goto out;
protoff = nf_ct_ipv6_skip_exthdr(skb, extoff, &pnum,
skb->len - extoff);
if (protoff > skb->len || pnum == NEXTHDR_FRAGMENT) {
pr_debug("proto header not found\n");
return NF_ACCEPT;
}
ret = helper->help(skb, protoff, ct, ctinfo);
if (ret != NF_ACCEPT) {
nf_log_packet(NFPROTO_IPV6, hooknum, skb, in, out, NULL,
"nf_ct_%s: dropping packet", helper->name);
return ret;
}
out:
/* We've seen it coming out the other side: confirm it */
return nf_conntrack_confirm(skb);
}
static unsigned int __ipv6_conntrack_in(struct net *net,
unsigned int hooknum,
struct sk_buff *skb,
int (*okfn)(struct sk_buff *))
{
struct sk_buff *reasm = skb->nfct_reasm;
/* This packet is fragmented and has reassembled packet. */
if (reasm) {
/* Reassembled packet isn't parsed yet ? */
if (!reasm->nfct) {
unsigned int ret;
ret = nf_conntrack_in(net, PF_INET6, hooknum, reasm);
if (ret != NF_ACCEPT)
return ret;
}
nf_conntrack_get(reasm->nfct);
skb->nfct = reasm->nfct;
skb->nfctinfo = reasm->nfctinfo;
return NF_ACCEPT;
}
return nf_conntrack_in(net, PF_INET6, hooknum, skb);
}
static unsigned int ipv6_conntrack_in(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return __ipv6_conntrack_in(dev_net(in), hooknum, skb, okfn);
}
static unsigned int ipv6_conntrack_local(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
/* root is playing with raw sockets. */
if (skb->len < sizeof(struct ipv6hdr)) {
if (net_ratelimit())
pr_notice("ipv6_conntrack_local: packet too short\n");
return NF_ACCEPT;
}
return __ipv6_conntrack_in(dev_net(out), hooknum, skb, okfn);
}
static struct nf_hook_ops ipv6_conntrack_ops[] __read_mostly = {
{
.hook = ipv6_conntrack_in,
.owner = THIS_MODULE,
.pf = NFPROTO_IPV6,
.hooknum = NF_INET_PRE_ROUTING,
.priority = NF_IP6_PRI_CONNTRACK,
},
{
.hook = ipv6_conntrack_local,
.owner = THIS_MODULE,
.pf = NFPROTO_IPV6,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP6_PRI_CONNTRACK,
},
{
.hook = ipv6_confirm,
.owner = THIS_MODULE,
.pf = NFPROTO_IPV6,
.hooknum = NF_INET_POST_ROUTING,
.priority = NF_IP6_PRI_LAST,
},
{
.hook = ipv6_confirm,
.owner = THIS_MODULE,
.pf = NFPROTO_IPV6,
.hooknum = NF_INET_LOCAL_IN,
.priority = NF_IP6_PRI_LAST-1,
},
};
#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nfnetlink_conntrack.h>
static int ipv6_tuple_to_nlattr(struct sk_buff *skb,
const struct nf_conntrack_tuple *tuple)
{
NLA_PUT(skb, CTA_IP_V6_SRC, sizeof(u_int32_t) * 4,
&tuple->src.u3.ip6);
NLA_PUT(skb, CTA_IP_V6_DST, sizeof(u_int32_t) * 4,
&tuple->dst.u3.ip6);
return 0;
nla_put_failure:
return -1;
}
static const struct nla_policy ipv6_nla_policy[CTA_IP_MAX+1] = {
[CTA_IP_V6_SRC] = { .len = sizeof(u_int32_t)*4 },
[CTA_IP_V6_DST] = { .len = sizeof(u_int32_t)*4 },
};
static int ipv6_nlattr_to_tuple(struct nlattr *tb[],
struct nf_conntrack_tuple *t)
{
if (!tb[CTA_IP_V6_SRC] || !tb[CTA_IP_V6_DST])
return -EINVAL;
memcpy(&t->src.u3.ip6, nla_data(tb[CTA_IP_V6_SRC]),
sizeof(u_int32_t) * 4);
memcpy(&t->dst.u3.ip6, nla_data(tb[CTA_IP_V6_DST]),
sizeof(u_int32_t) * 4);
return 0;
}
static int ipv6_nlattr_tuple_size(void)
{
return nla_policy_len(ipv6_nla_policy, CTA_IP_MAX + 1);
}
#endif
struct nf_conntrack_l3proto nf_conntrack_l3proto_ipv6 __read_mostly = {
.l3proto = PF_INET6,
.name = "ipv6",
.pkt_to_tuple = ipv6_pkt_to_tuple,
.invert_tuple = ipv6_invert_tuple,
.print_tuple = ipv6_print_tuple,
.get_l4proto = ipv6_get_l4proto,
#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
.tuple_to_nlattr = ipv6_tuple_to_nlattr,
.nlattr_tuple_size = ipv6_nlattr_tuple_size,
.nlattr_to_tuple = ipv6_nlattr_to_tuple,
.nla_policy = ipv6_nla_policy,
#endif
.me = THIS_MODULE,
};
MODULE_ALIAS("nf_conntrack-" __stringify(AF_INET6));
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yasuyuki KOZAKAI @USAGI <yasuyuki.kozakai@toshiba.co.jp>");
static int __init nf_conntrack_l3proto_ipv6_init(void)
{
int ret = 0;
need_conntrack();
nf_defrag_ipv6_enable();
ret = nf_conntrack_l4proto_register(&nf_conntrack_l4proto_tcp6);
if (ret < 0) {
pr_err("nf_conntrack_ipv6: can't register tcp.\n");
return ret;
}
ret = nf_conntrack_l4proto_register(&nf_conntrack_l4proto_udp6);
if (ret < 0) {
pr_err("nf_conntrack_ipv6: can't register udp.\n");
goto cleanup_tcp;
}
ret = nf_conntrack_l4proto_register(&nf_conntrack_l4proto_icmpv6);
if (ret < 0) {
pr_err("nf_conntrack_ipv6: can't register icmpv6.\n");
goto cleanup_udp;
}
ret = nf_conntrack_l3proto_register(&nf_conntrack_l3proto_ipv6);
if (ret < 0) {
pr_err("nf_conntrack_ipv6: can't register ipv6\n");
goto cleanup_icmpv6;
}
ret = nf_register_hooks(ipv6_conntrack_ops,
ARRAY_SIZE(ipv6_conntrack_ops));
if (ret < 0) {
pr_err("nf_conntrack_ipv6: can't register pre-routing defrag "
"hook.\n");
goto cleanup_ipv6;
}
return ret;
cleanup_ipv6:
nf_conntrack_l3proto_unregister(&nf_conntrack_l3proto_ipv6);
cleanup_icmpv6:
nf_conntrack_l4proto_unregister(&nf_conntrack_l4proto_icmpv6);
cleanup_udp:
nf_conntrack_l4proto_unregister(&nf_conntrack_l4proto_udp6);
cleanup_tcp:
nf_conntrack_l4proto_unregister(&nf_conntrack_l4proto_tcp6);
return ret;
}
static void __exit nf_conntrack_l3proto_ipv6_fini(void)
{
synchronize_net();
nf_unregister_hooks(ipv6_conntrack_ops, ARRAY_SIZE(ipv6_conntrack_ops));
nf_conntrack_l3proto_unregister(&nf_conntrack_l3proto_ipv6);
nf_conntrack_l4proto_unregister(&nf_conntrack_l4proto_icmpv6);
nf_conntrack_l4proto_unregister(&nf_conntrack_l4proto_udp6);
nf_conntrack_l4proto_unregister(&nf_conntrack_l4proto_tcp6);
}
module_init(nf_conntrack_l3proto_ipv6_init);
module_exit(nf_conntrack_l3proto_ipv6_fini);
| gpl-2.0 |
fenten/Kernel-XT701 | drivers/input/touchscreen/inexio.c | 9893 | 4900 | /*
* iNexio serial touchscreen driver
*
* Copyright (c) 2008 Richard Lemon
* Based on the mtouch driver (c) Vojtech Pavlik and Dan Streetman
*
*/
/*
* 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.
*/
/*
* 2008/06/19 Richard Lemon <richard@codelemon.com>
* Copied mtouch.c and edited for iNexio protocol
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "iNexio serial touchscreen driver"
MODULE_AUTHOR("Richard Lemon <richard@codelemon.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define INEXIO_FORMAT_TOUCH_BIT 0x01
#define INEXIO_FORMAT_LENGTH 5
#define INEXIO_RESPONSE_BEGIN_BYTE 0x80
/* todo: check specs for max length of all responses */
#define INEXIO_MAX_LENGTH 16
#define INEXIO_MIN_XC 0
#define INEXIO_MAX_XC 0x3fff
#define INEXIO_MIN_YC 0
#define INEXIO_MAX_YC 0x3fff
#define INEXIO_GET_XC(data) (((data[1])<<7) | data[2])
#define INEXIO_GET_YC(data) (((data[3])<<7) | data[4])
#define INEXIO_GET_TOUCHED(data) (INEXIO_FORMAT_TOUCH_BIT & data[0])
/*
* Per-touchscreen data.
*/
struct inexio {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[INEXIO_MAX_LENGTH];
char phys[32];
};
static void inexio_process_data(struct inexio *pinexio)
{
struct input_dev *dev = pinexio->dev;
if (INEXIO_FORMAT_LENGTH == ++pinexio->idx) {
input_report_abs(dev, ABS_X, INEXIO_GET_XC(pinexio->data));
input_report_abs(dev, ABS_Y, INEXIO_GET_YC(pinexio->data));
input_report_key(dev, BTN_TOUCH, INEXIO_GET_TOUCHED(pinexio->data));
input_sync(dev);
pinexio->idx = 0;
}
}
static irqreturn_t inexio_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct inexio* pinexio = serio_get_drvdata(serio);
pinexio->data[pinexio->idx] = data;
if (INEXIO_RESPONSE_BEGIN_BYTE&pinexio->data[0])
inexio_process_data(pinexio);
else
printk(KERN_DEBUG "inexio.c: unknown/unsynchronized data from device, byte %x\n",pinexio->data[0]);
return IRQ_HANDLED;
}
/*
* inexio_disconnect() is the opposite of inexio_connect()
*/
static void inexio_disconnect(struct serio *serio)
{
struct inexio* pinexio = serio_get_drvdata(serio);
input_get_device(pinexio->dev);
input_unregister_device(pinexio->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(pinexio->dev);
kfree(pinexio);
}
/*
* inexio_connect() is the routine that is called when someone adds a
* new serio device that supports iNexio protocol and registers it as
* an input device. This is usually accomplished using inputattach.
*/
static int inexio_connect(struct serio *serio, struct serio_driver *drv)
{
struct inexio *pinexio;
struct input_dev *input_dev;
int err;
pinexio = kzalloc(sizeof(struct inexio), GFP_KERNEL);
input_dev = input_allocate_device();
if (!pinexio || !input_dev) {
err = -ENOMEM;
goto fail1;
}
pinexio->serio = serio;
pinexio->dev = input_dev;
snprintf(pinexio->phys, sizeof(pinexio->phys), "%s/input0", serio->phys);
input_dev->name = "iNexio Serial TouchScreen";
input_dev->phys = pinexio->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_INEXIO;
input_dev->id.product = 0;
input_dev->id.version = 0x0001;
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);
input_set_abs_params(pinexio->dev, ABS_X, INEXIO_MIN_XC, INEXIO_MAX_XC, 0, 0);
input_set_abs_params(pinexio->dev, ABS_Y, INEXIO_MIN_YC, INEXIO_MAX_YC, 0, 0);
serio_set_drvdata(serio, pinexio);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(pinexio->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(pinexio);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id inexio_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_INEXIO,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, inexio_serio_ids);
static struct serio_driver inexio_drv = {
.driver = {
.name = "inexio",
},
.description = DRIVER_DESC,
.id_table = inexio_serio_ids,
.interrupt = inexio_interrupt,
.connect = inexio_connect,
.disconnect = inexio_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init inexio_init(void)
{
return serio_register_driver(&inexio_drv);
}
static void __exit inexio_exit(void)
{
serio_unregister_driver(&inexio_drv);
}
module_init(inexio_init);
module_exit(inexio_exit);
| gpl-2.0 |
TeamJB/kernel_samsung_smdk4412 | drivers/input/mouse/sermouse.c | 9893 | 9069 | /*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Serial mouse driver for Linux
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "Serial mouse driver"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static const char *sermouse_protocols[] = { "None", "Mouse Systems Mouse", "Sun Mouse", "Microsoft Mouse",
"Logitech M+ Mouse", "Microsoft MZ Mouse", "Logitech MZ+ Mouse",
"Logitech MZ++ Mouse"};
struct sermouse {
struct input_dev *dev;
signed char buf[8];
unsigned char count;
unsigned char type;
unsigned long last;
char phys[32];
};
/*
* sermouse_process_msc() analyzes the incoming MSC/Sun bytestream and
* applies some prediction to the data, resulting in 96 updates per
* second, which is as good as a PS/2 or USB mouse.
*/
static void sermouse_process_msc(struct sermouse *sermouse, signed char data)
{
struct input_dev *dev = sermouse->dev;
signed char *buf = sermouse->buf;
switch (sermouse->count) {
case 0:
if ((data & 0xf8) != 0x80)
return;
input_report_key(dev, BTN_LEFT, !(data & 4));
input_report_key(dev, BTN_RIGHT, !(data & 1));
input_report_key(dev, BTN_MIDDLE, !(data & 2));
break;
case 1:
case 3:
input_report_rel(dev, REL_X, data / 2);
input_report_rel(dev, REL_Y, -buf[1]);
buf[0] = data - data / 2;
break;
case 2:
case 4:
input_report_rel(dev, REL_X, buf[0]);
input_report_rel(dev, REL_Y, buf[1] - data);
buf[1] = data / 2;
break;
}
input_sync(dev);
if (++sermouse->count == 5)
sermouse->count = 0;
}
/*
* sermouse_process_ms() anlyzes the incoming MS(Z/+/++) bytestream and
* generates events. With prediction it gets 80 updates/sec, assuming
* standard 3-byte packets and 1200 bps.
*/
static void sermouse_process_ms(struct sermouse *sermouse, signed char data)
{
struct input_dev *dev = sermouse->dev;
signed char *buf = sermouse->buf;
if (data & 0x40)
sermouse->count = 0;
else if (sermouse->count == 0)
return;
switch (sermouse->count) {
case 0:
buf[1] = data;
input_report_key(dev, BTN_LEFT, (data >> 5) & 1);
input_report_key(dev, BTN_RIGHT, (data >> 4) & 1);
break;
case 1:
buf[2] = data;
data = (signed char) (((buf[1] << 6) & 0xc0) | (data & 0x3f));
input_report_rel(dev, REL_X, data / 2);
input_report_rel(dev, REL_Y, buf[4]);
buf[3] = data - data / 2;
break;
case 2:
/* Guessing the state of the middle button on 3-button MS-protocol mice - ugly. */
if ((sermouse->type == SERIO_MS) && !data && !buf[2] && !((buf[0] & 0xf0) ^ buf[1]))
input_report_key(dev, BTN_MIDDLE, !test_bit(BTN_MIDDLE, dev->key));
buf[0] = buf[1];
data = (signed char) (((buf[1] << 4) & 0xc0) | (data & 0x3f));
input_report_rel(dev, REL_X, buf[3]);
input_report_rel(dev, REL_Y, data - buf[4]);
buf[4] = data / 2;
break;
case 3:
switch (sermouse->type) {
case SERIO_MS:
sermouse->type = SERIO_MP;
case SERIO_MP:
if ((data >> 2) & 3) break; /* M++ Wireless Extension packet. */
input_report_key(dev, BTN_MIDDLE, (data >> 5) & 1);
input_report_key(dev, BTN_SIDE, (data >> 4) & 1);
break;
case SERIO_MZP:
case SERIO_MZPP:
input_report_key(dev, BTN_SIDE, (data >> 5) & 1);
case SERIO_MZ:
input_report_key(dev, BTN_MIDDLE, (data >> 4) & 1);
input_report_rel(dev, REL_WHEEL, (data & 8) - (data & 7));
break;
}
break;
case 4:
case 6: /* MZ++ packet type. We can get these bytes for M++ too but we ignore them later. */
buf[1] = (data >> 2) & 0x0f;
break;
case 5:
case 7: /* Ignore anything besides MZ++ */
if (sermouse->type != SERIO_MZPP)
break;
switch (buf[1]) {
case 1: /* Extra mouse info */
input_report_key(dev, BTN_SIDE, (data >> 4) & 1);
input_report_key(dev, BTN_EXTRA, (data >> 5) & 1);
input_report_rel(dev, data & 0x80 ? REL_HWHEEL : REL_WHEEL, (data & 7) - (data & 8));
break;
default: /* We don't decode anything else yet. */
printk(KERN_WARNING
"sermouse.c: Received MZ++ packet %x, don't know how to handle.\n", buf[1]);
break;
}
break;
}
input_sync(dev);
sermouse->count++;
}
/*
* sermouse_interrupt() handles incoming characters, either gathering them into
* packets or passing them to the command routine as command output.
*/
static irqreturn_t sermouse_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct sermouse *sermouse = serio_get_drvdata(serio);
if (time_after(jiffies, sermouse->last + HZ/10))
sermouse->count = 0;
sermouse->last = jiffies;
if (sermouse->type > SERIO_SUN)
sermouse_process_ms(sermouse, data);
else
sermouse_process_msc(sermouse, data);
return IRQ_HANDLED;
}
/*
* sermouse_disconnect() cleans up after we don't want talk
* to the mouse anymore.
*/
static void sermouse_disconnect(struct serio *serio)
{
struct sermouse *sermouse = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(sermouse->dev);
kfree(sermouse);
}
/*
* sermouse_connect() is a callback form the serio module when
* an unhandled serio port is found.
*/
static int sermouse_connect(struct serio *serio, struct serio_driver *drv)
{
struct sermouse *sermouse;
struct input_dev *input_dev;
unsigned char c = serio->id.extra;
int err = -ENOMEM;
sermouse = kzalloc(sizeof(struct sermouse), GFP_KERNEL);
input_dev = input_allocate_device();
if (!sermouse || !input_dev)
goto fail1;
sermouse->dev = input_dev;
snprintf(sermouse->phys, sizeof(sermouse->phys), "%s/input0", serio->phys);
sermouse->type = serio->id.proto;
input_dev->name = sermouse_protocols[sermouse->type];
input_dev->phys = sermouse->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = sermouse->type;
input_dev->id.product = c;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT);
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
if (c & 0x01) set_bit(BTN_MIDDLE, input_dev->keybit);
if (c & 0x02) set_bit(BTN_SIDE, input_dev->keybit);
if (c & 0x04) set_bit(BTN_EXTRA, input_dev->keybit);
if (c & 0x10) set_bit(REL_WHEEL, input_dev->relbit);
if (c & 0x20) set_bit(REL_HWHEEL, input_dev->relbit);
serio_set_drvdata(serio, sermouse);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(sermouse->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(sermouse);
return err;
}
static struct serio_device_id sermouse_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_MSC,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_SUN,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MS,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MP,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MZ,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MZP,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MZPP,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, sermouse_serio_ids);
static struct serio_driver sermouse_drv = {
.driver = {
.name = "sermouse",
},
.description = DRIVER_DESC,
.id_table = sermouse_serio_ids,
.interrupt = sermouse_interrupt,
.connect = sermouse_connect,
.disconnect = sermouse_disconnect,
};
static int __init sermouse_init(void)
{
return serio_register_driver(&sermouse_drv);
}
static void __exit sermouse_exit(void)
{
serio_unregister_driver(&sermouse_drv);
}
module_init(sermouse_init);
module_exit(sermouse_exit);
| gpl-2.0 |
mhmtemnacr/android_kernel_samsung_matissewifi | drivers/input/touchscreen/inexio.c | 9893 | 4900 | /*
* iNexio serial touchscreen driver
*
* Copyright (c) 2008 Richard Lemon
* Based on the mtouch driver (c) Vojtech Pavlik and Dan Streetman
*
*/
/*
* 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.
*/
/*
* 2008/06/19 Richard Lemon <richard@codelemon.com>
* Copied mtouch.c and edited for iNexio protocol
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "iNexio serial touchscreen driver"
MODULE_AUTHOR("Richard Lemon <richard@codelemon.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define INEXIO_FORMAT_TOUCH_BIT 0x01
#define INEXIO_FORMAT_LENGTH 5
#define INEXIO_RESPONSE_BEGIN_BYTE 0x80
/* todo: check specs for max length of all responses */
#define INEXIO_MAX_LENGTH 16
#define INEXIO_MIN_XC 0
#define INEXIO_MAX_XC 0x3fff
#define INEXIO_MIN_YC 0
#define INEXIO_MAX_YC 0x3fff
#define INEXIO_GET_XC(data) (((data[1])<<7) | data[2])
#define INEXIO_GET_YC(data) (((data[3])<<7) | data[4])
#define INEXIO_GET_TOUCHED(data) (INEXIO_FORMAT_TOUCH_BIT & data[0])
/*
* Per-touchscreen data.
*/
struct inexio {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[INEXIO_MAX_LENGTH];
char phys[32];
};
static void inexio_process_data(struct inexio *pinexio)
{
struct input_dev *dev = pinexio->dev;
if (INEXIO_FORMAT_LENGTH == ++pinexio->idx) {
input_report_abs(dev, ABS_X, INEXIO_GET_XC(pinexio->data));
input_report_abs(dev, ABS_Y, INEXIO_GET_YC(pinexio->data));
input_report_key(dev, BTN_TOUCH, INEXIO_GET_TOUCHED(pinexio->data));
input_sync(dev);
pinexio->idx = 0;
}
}
static irqreturn_t inexio_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct inexio* pinexio = serio_get_drvdata(serio);
pinexio->data[pinexio->idx] = data;
if (INEXIO_RESPONSE_BEGIN_BYTE&pinexio->data[0])
inexio_process_data(pinexio);
else
printk(KERN_DEBUG "inexio.c: unknown/unsynchronized data from device, byte %x\n",pinexio->data[0]);
return IRQ_HANDLED;
}
/*
* inexio_disconnect() is the opposite of inexio_connect()
*/
static void inexio_disconnect(struct serio *serio)
{
struct inexio* pinexio = serio_get_drvdata(serio);
input_get_device(pinexio->dev);
input_unregister_device(pinexio->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(pinexio->dev);
kfree(pinexio);
}
/*
* inexio_connect() is the routine that is called when someone adds a
* new serio device that supports iNexio protocol and registers it as
* an input device. This is usually accomplished using inputattach.
*/
static int inexio_connect(struct serio *serio, struct serio_driver *drv)
{
struct inexio *pinexio;
struct input_dev *input_dev;
int err;
pinexio = kzalloc(sizeof(struct inexio), GFP_KERNEL);
input_dev = input_allocate_device();
if (!pinexio || !input_dev) {
err = -ENOMEM;
goto fail1;
}
pinexio->serio = serio;
pinexio->dev = input_dev;
snprintf(pinexio->phys, sizeof(pinexio->phys), "%s/input0", serio->phys);
input_dev->name = "iNexio Serial TouchScreen";
input_dev->phys = pinexio->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_INEXIO;
input_dev->id.product = 0;
input_dev->id.version = 0x0001;
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);
input_set_abs_params(pinexio->dev, ABS_X, INEXIO_MIN_XC, INEXIO_MAX_XC, 0, 0);
input_set_abs_params(pinexio->dev, ABS_Y, INEXIO_MIN_YC, INEXIO_MAX_YC, 0, 0);
serio_set_drvdata(serio, pinexio);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(pinexio->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(pinexio);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id inexio_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_INEXIO,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, inexio_serio_ids);
static struct serio_driver inexio_drv = {
.driver = {
.name = "inexio",
},
.description = DRIVER_DESC,
.id_table = inexio_serio_ids,
.interrupt = inexio_interrupt,
.connect = inexio_connect,
.disconnect = inexio_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init inexio_init(void)
{
return serio_register_driver(&inexio_drv);
}
static void __exit inexio_exit(void)
{
serio_unregister_driver(&inexio_drv);
}
module_init(inexio_init);
module_exit(inexio_exit);
| gpl-2.0 |
CM-Tab-S/android_kernel_samsung_exynos5420 | arch/m68k/lib/memset.c | 12709 | 1323 | /*
* 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/module.h>
#include <linux/string.h>
void *memset(void *s, int c, size_t count)
{
void *xs = s;
size_t temp;
if (!count)
return xs;
c &= 0xff;
c |= c << 8;
c |= c << 16;
if ((long)s & 1) {
char *cs = s;
*cs++ = c;
s = cs;
count--;
}
if (count > 2 && (long)s & 2) {
short *ss = s;
*ss++ = c;
s = ss;
count -= 2;
}
temp = count >> 2;
if (temp) {
long *ls = s;
#if defined(CONFIG_M68000) || defined(CONFIG_COLDFIRE)
for (; temp; temp--)
*ls++ = c;
#else
size_t temp1;
asm volatile (
" movel %1,%2\n"
" andw #7,%2\n"
" lsrl #3,%1\n"
" negw %2\n"
" jmp %%pc@(2f,%2:w:2)\n"
"1: movel %3,%0@+\n"
" movel %3,%0@+\n"
" movel %3,%0@+\n"
" movel %3,%0@+\n"
" movel %3,%0@+\n"
" movel %3,%0@+\n"
" movel %3,%0@+\n"
" movel %3,%0@+\n"
"2: dbra %1,1b\n"
" clrw %1\n"
" subql #1,%1\n"
" jpl 1b"
: "=a" (ls), "=d" (temp), "=&d" (temp1)
: "d" (c), "0" (ls), "1" (temp));
#endif
s = ls;
}
if (count & 2) {
short *ss = s;
*ss++ = c;
s = ss;
}
if (count & 1) {
char *cs = s;
*cs = c;
}
return xs;
}
EXPORT_SYMBOL(memset);
| gpl-2.0 |
thh/ubuntu-trusty | arch/alpha/kernel/asm-offsets.c | 13733 | 1456 | /*
* Generate definitions needed by assembly language modules.
* This code generates raw asm output which is post-processed to extract
* and format the required data.
*/
#include <linux/types.h>
#include <linux/stddef.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/kbuild.h>
#include <asm/io.h>
void foo(void)
{
DEFINE(TI_TASK, offsetof(struct thread_info, task));
DEFINE(TI_FLAGS, offsetof(struct thread_info, flags));
DEFINE(TI_CPU, offsetof(struct thread_info, cpu));
BLANK();
DEFINE(TASK_BLOCKED, offsetof(struct task_struct, blocked));
DEFINE(TASK_CRED, offsetof(struct task_struct, cred));
DEFINE(TASK_REAL_PARENT, offsetof(struct task_struct, real_parent));
DEFINE(TASK_GROUP_LEADER, offsetof(struct task_struct, group_leader));
DEFINE(TASK_TGID, offsetof(struct task_struct, tgid));
BLANK();
DEFINE(CRED_UID, offsetof(struct cred, uid));
DEFINE(CRED_EUID, offsetof(struct cred, euid));
DEFINE(CRED_GID, offsetof(struct cred, gid));
DEFINE(CRED_EGID, offsetof(struct cred, egid));
BLANK();
DEFINE(SIZEOF_PT_REGS, sizeof(struct pt_regs));
DEFINE(PT_PTRACED, PT_PTRACED);
DEFINE(CLONE_VM, CLONE_VM);
DEFINE(CLONE_UNTRACED, CLONE_UNTRACED);
DEFINE(SIGCHLD, SIGCHLD);
BLANK();
DEFINE(HAE_CACHE, offsetof(struct alpha_machine_vector, hae_cache));
DEFINE(HAE_REG, offsetof(struct alpha_machine_vector, hae_register));
}
| gpl-2.0 |
virajkanwade/rk3188_android_kernel | fs/ext4/xattr.c | 678 | 43039 | /*
* linux/fs/ext4/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* Fix by Harrison Xing <harrison@mountainviewdata.com>.
* Ext4 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
* ----------------
* EXT4_I(inode)->i_file_acl is protected by EXT4_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 <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include <linux/rwsem.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
#define BHDR(bh) ((struct ext4_xattr_header *)((bh)->b_data))
#define ENTRY(ptr) ((struct ext4_xattr_entry *)(ptr))
#define BFIRST(bh) ENTRY(BHDR(bh)+1)
#define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
#ifdef EXT4_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 ext4_xattr_cache_insert(struct buffer_head *);
static struct buffer_head *ext4_xattr_cache_find(struct inode *,
struct ext4_xattr_header *,
struct mb_cache_entry **);
static void ext4_xattr_rehash(struct ext4_xattr_header *,
struct ext4_xattr_entry *);
static int ext4_xattr_list(struct dentry *dentry, char *buffer,
size_t buffer_size);
static struct mb_cache *ext4_xattr_cache;
static const struct xattr_handler *ext4_xattr_handler_map[] = {
[EXT4_XATTR_INDEX_USER] = &ext4_xattr_user_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS] = &ext4_xattr_acl_access_handler,
[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &ext4_xattr_acl_default_handler,
#endif
[EXT4_XATTR_INDEX_TRUSTED] = &ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_SECURITY
[EXT4_XATTR_INDEX_SECURITY] = &ext4_xattr_security_handler,
#endif
};
const struct xattr_handler *ext4_xattr_handlers[] = {
&ext4_xattr_user_handler,
&ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
&ext4_xattr_acl_access_handler,
&ext4_xattr_acl_default_handler,
#endif
#ifdef CONFIG_EXT4_FS_SECURITY
&ext4_xattr_security_handler,
#endif
NULL
};
static inline const struct xattr_handler *
ext4_xattr_handler(int name_index)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
handler = ext4_xattr_handler_map[name_index];
return handler;
}
/*
* Inode operation listxattr()
*
* dentry->d_inode->i_mutex: don't care
*/
ssize_t
ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext4_xattr_list(dentry, buffer, size);
}
static int
ext4_xattr_check_names(struct ext4_xattr_entry *entry, void *end)
{
while (!IS_LAST_ENTRY(entry)) {
struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(entry);
if ((void *)next >= end)
return -EIO;
entry = next;
}
return 0;
}
static inline int
ext4_xattr_check_block(struct buffer_head *bh)
{
int error;
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1))
return -EIO;
error = ext4_xattr_check_names(BFIRST(bh), bh->b_data + bh->b_size);
return error;
}
static inline int
ext4_xattr_check_entry(struct ext4_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
ext4_xattr_find_entry(struct ext4_xattr_entry **pentry, int name_index,
const char *name, size_t size, int sorted)
{
struct ext4_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 = EXT4_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 && ext4_xattr_check_entry(entry, size))
return -EIO;
return cmp ? -ENODATA : 0;
}
static int
ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_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 (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %u", EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_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 (ext4_xattr_check_block(bh)) {
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext4_xattr_cache_insert(bh);
entry = BFIRST(bh);
error = ext4_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
ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return -ENODATA;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = ext4_xattr_check_names(entry, end);
if (error)
goto cleanup;
error = ext4_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;
}
/*
* ext4_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
ext4_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
down_read(&EXT4_I(inode)->xattr_sem);
error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = ext4_xattr_block_get(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
const struct xattr_handler *handler =
ext4_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
ext4_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 (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %u", EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_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 (ext4_xattr_check_block(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
ext4_xattr_cache_insert(bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = ext4_xattr_check_names(IFIRST(header), end);
if (error)
goto cleanup;
error = ext4_xattr_list_entries(dentry, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_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
ext4_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
int ret, ret2;
down_read(&EXT4_I(dentry->d_inode)->xattr_sem);
ret = ret2 = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
if (buffer) {
buffer += ret;
buffer_size -= ret;
}
ret = ext4_xattr_block_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
ret += ret2;
errout:
up_read(&EXT4_I(dentry->d_inode)->xattr_sem);
return ret;
}
/*
* If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext4_xattr_update_super_block(handle_t *handle,
struct super_block *sb)
{
if (EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR))
return;
if (ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh) == 0) {
EXT4_SET_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_EXT_ATTR);
ext4_handle_dirty_super(handle, sb);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement
* it; otherwise free the block.
*/
static void
ext4_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(ext4_xattr_cache, bh->b_bdev, bh->b_blocknr);
error = ext4_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);
get_bh(bh);
ext4_free_blocks(handle, inode, bh, 0, 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
unlock_buffer(bh);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
if (ce)
mb_cache_entry_release(ce);
unlock_buffer(bh);
error = ext4_handle_dirty_metadata(handle, inode, bh);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
dquot_free_block(inode, 1);
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
}
out:
ext4_std_error(inode->i_sb, error);
return;
}
/*
* Find the available free space for EAs. This also returns the total number of
* bytes used by EA entries.
*/
static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
size_t *min_offs, void *base, int *total)
{
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
*total += EXT4_XATTR_LEN(last->e_name_len);
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;
}
}
return (*min_offs - ((void *)last - base) - sizeof(__u32));
}
struct ext4_xattr_info {
int name_index;
const char *name;
const void *value;
size_t value_len;
};
struct ext4_xattr_search {
struct ext4_xattr_entry *first;
void *base;
void *end;
struct ext4_xattr_entry *here;
int not_found;
};
static int
ext4_xattr_set_entry(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
{
struct ext4_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 = EXT4_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 += EXT4_XATTR_SIZE(size);
}
free += EXT4_XATTR_LEN(name_len);
}
if (i->value) {
if (free < EXT4_XATTR_SIZE(i->value_len) ||
free < EXT4_XATTR_LEN(name_len) +
EXT4_XATTR_SIZE(i->value_len))
return -ENOSPC;
}
if (i->value && s->not_found) {
/* Insert the new name. */
size_t size = EXT4_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 = EXT4_XATTR_SIZE(
le32_to_cpu(s->here->e_value_size));
if (i->value && size == EXT4_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 - EXT4_XATTR_PAD, 0,
EXT4_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 = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove the old name. */
size_t size = EXT4_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 = EXT4_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 - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, i->value, i->value_len);
}
}
return 0;
}
struct ext4_xattr_block_find {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_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 (EXT4_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = sb_bread(sb, EXT4_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 (ext4_xattr_check_block(bs->bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_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 = ext4_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
ext4_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
#define header(x) ((struct ext4_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext4_xattr_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
error = ext4_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 = ext4_xattr_set_entry(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
ext4_xattr_cache_insert(bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EIO)
goto bad_block;
if (!error)
error = ext4_handle_dirty_metadata(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
ext4_handle_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(EXT4_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 = ext4_xattr_set_entry(i, s);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = ext4_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 = ext4_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 = ext4_handle_dirty_metadata(handle,
inode,
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 */
ext4_fsblk_t goal, block;
goal = ext4_group_first_block_no(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
/*
* take i_data_sem because we will test
* i_delalloc_reserved_flag in ext4_mb_new_blocks
*/
down_read((&EXT4_I(inode)->i_data_sem));
block = ext4_new_meta_blocks(handle, inode, goal, 0,
NULL, &error);
up_read((&EXT4_I(inode)->i_data_sem));
if (error)
goto cleanup;
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
ea_idebug(inode, "creating block %d", block);
new_bh = sb_getblk(sb, block);
if (!new_bh) {
getblk_failed:
ext4_free_blocks(handle, inode, NULL, block, 1,
EXT4_FREE_BLOCKS_METADATA);
error = -EIO;
goto cleanup;
}
lock_buffer(new_bh);
error = ext4_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);
ext4_xattr_cache_insert(new_bh);
error = ext4_handle_dirty_metadata(handle,
inode, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
ext4_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:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
struct ext4_xattr_ibody_find {
struct ext4_xattr_search s;
struct ext4_iloc iloc;
};
static int
ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
raw_inode = ext4_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 + EXT4_SB(inode->i_sb)->s_inode_size;
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
error = ext4_xattr_check_names(IFIRST(header), is->s.end);
if (error)
return error;
/* Find the named attribute. */
error = ext4_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
ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = ext4_xattr_set_entry(i, s);
if (error)
return error;
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
ext4_set_inode_state(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
}
return 0;
}
/*
* ext4_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
ext4_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 ext4_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
};
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_block_find bs = {
.s = { .not_found = -ENODATA, },
};
unsigned long no_expand;
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
down_write(&EXT4_I(inode)->xattr_sem);
no_expand = ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND);
ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND);
error = ext4_get_inode_loc(inode, &is.iloc);
if (error)
goto cleanup;
error = ext4_journal_get_write_access(handle, is.iloc.bh);
if (error)
goto cleanup;
if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) {
struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
ext4_clear_inode_state(inode, EXT4_STATE_NEW);
}
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = ext4_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 = ext4_xattr_ibody_set(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else {
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
}
error = ext4_xattr_block_set(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = ext4_xattr_ibody_set(handle, inode, &i,
&is);
}
}
}
if (!error) {
ext4_xattr_update_super_block(handle, inode->i_sb);
inode->i_ctime = ext4_current_time(inode);
if (!value)
ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
/*
* The bh is consumed by ext4_mark_iloc_dirty, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
if (no_expand == 0)
ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_set()
*
* Like ext4_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
ext4_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 = ext4_journal_start(inode, EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = ext4_xattr_set_handle(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
return error;
}
/*
* Shift the EA entries in the inode to create space for the increased
* i_extra_isize.
*/
static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
/*
* Expand an inode by new_extra_isize bytes when EAs are present.
* Returns 0 on success or negative error number on failure.
*/
int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry, *last, *first;
struct buffer_head *bh = NULL;
struct ext4_xattr_ibody_find *is = NULL;
struct ext4_xattr_block_find *bs = NULL;
char *buffer = NULL, *b_entry_name = NULL;
size_t min_offs, free;
int total_ino, total_blk;
void *base, *start, *end;
int extra_isize = 0, error = 0, tried_min_extra_isize = 0;
int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
down_write(&EXT4_I(inode)->xattr_sem);
retry:
if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) {
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
}
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
/*
* Check if enough free space is available in the inode to shift the
* entries ahead by new_extra_isize.
*/
base = start = entry;
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
min_offs = end - base;
last = entry;
total_ino = sizeof(struct ext4_xattr_ibody_header);
free = ext4_xattr_free_space(last, &min_offs, base, &total_ino);
if (free >= new_extra_isize) {
entry = IFIRST(header);
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
(void *)header, total_ino,
inode->i_sb->s_blocksize);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
error = 0;
goto cleanup;
}
/*
* Enough free space isn't available in the inode, check if
* EA block can hold new_extra_isize bytes.
*/
if (EXT4_I(inode)->i_file_acl) {
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
if (ext4_xattr_check_block(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
base = BHDR(bh);
first = BFIRST(bh);
end = bh->b_data + bh->b_size;
min_offs = end - base;
free = ext4_xattr_free_space(first, &min_offs, base,
&total_blk);
if (free < new_extra_isize) {
if (!tried_min_extra_isize && s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
} else {
free = inode->i_sb->s_blocksize;
}
while (new_extra_isize > 0) {
size_t offs, size, entry_size;
struct ext4_xattr_entry *small_entry = NULL;
struct ext4_xattr_info i = {
.value = NULL,
.value_len = 0,
};
unsigned int total_size; /* EA entry size + value size */
unsigned int shift_bytes; /* No. of bytes to shift EAs by? */
unsigned int min_total_size = ~0U;
is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
if (!is || !bs) {
error = -ENOMEM;
goto cleanup;
}
is->s.not_found = -ENODATA;
bs->s.not_found = -ENODATA;
is->iloc.bh = NULL;
bs->bh = NULL;
last = IFIRST(header);
/* Find the entry best suited to be pushed into EA block */
entry = NULL;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
total_size =
EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
EXT4_XATTR_LEN(last->e_name_len);
if (total_size <= free && total_size < min_total_size) {
if (total_size < new_extra_isize) {
small_entry = last;
} else {
entry = last;
min_total_size = total_size;
}
}
}
if (entry == NULL) {
if (small_entry) {
entry = small_entry;
} else {
if (!tried_min_extra_isize &&
s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
goto retry;
}
error = -1;
goto cleanup;
}
}
offs = le16_to_cpu(entry->e_value_offs);
size = le32_to_cpu(entry->e_value_size);
entry_size = EXT4_XATTR_LEN(entry->e_name_len);
i.name_index = entry->e_name_index,
buffer = kmalloc(EXT4_XATTR_SIZE(size), GFP_NOFS);
b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
if (!buffer || !b_entry_name) {
error = -ENOMEM;
goto cleanup;
}
/* Save the entry name and the entry value */
memcpy(buffer, (void *)IFIRST(header) + offs,
EXT4_XATTR_SIZE(size));
memcpy(b_entry_name, entry->e_name, entry->e_name_len);
b_entry_name[entry->e_name_len] = '\0';
i.name = b_entry_name;
error = ext4_get_inode_loc(inode, &is->iloc);
if (error)
goto cleanup;
error = ext4_xattr_ibody_find(inode, &i, is);
if (error)
goto cleanup;
/* Remove the chosen entry from the inode */
error = ext4_xattr_ibody_set(handle, inode, &i, is);
if (error)
goto cleanup;
entry = IFIRST(header);
if (entry_size + EXT4_XATTR_SIZE(size) >= new_extra_isize)
shift_bytes = new_extra_isize;
else
shift_bytes = entry_size + size;
/* Adjust the offsets and shift the remaining entries ahead */
ext4_xattr_shift_entries(entry, EXT4_I(inode)->i_extra_isize -
shift_bytes, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + extra_isize + shift_bytes,
(void *)header, total_ino - entry_size,
inode->i_sb->s_blocksize);
extra_isize += shift_bytes;
new_extra_isize -= shift_bytes;
EXT4_I(inode)->i_extra_isize = extra_isize;
i.name = b_entry_name;
i.value = buffer;
i.value_len = size;
error = ext4_xattr_block_find(inode, &i, bs);
if (error)
goto cleanup;
/* Add entry which was removed from the inode into the block */
error = ext4_xattr_block_set(handle, inode, &i, bs);
if (error)
goto cleanup;
kfree(b_entry_name);
kfree(buffer);
b_entry_name = NULL;
buffer = NULL;
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
}
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
cleanup:
kfree(b_entry_name);
kfree(buffer);
if (is)
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_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
ext4_xattr_delete_inode(handle_t *handle, struct inode *inode)
{
struct buffer_head *bh = NULL;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %llu read error",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
ext4_xattr_release_block(handle, inode, bh);
EXT4_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* ext4_xattr_put_super()
*
* This is called when a file system is unmounted.
*/
void
ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* ext4_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
ext4_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(ext4_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);
}
}
/*
* ext4_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
ext4_xattr_cmp(struct ext4_xattr_header *header1,
struct ext4_xattr_header *header2)
{
struct ext4_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 = EXT4_XATTR_NEXT(entry1);
entry2 = EXT4_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* ext4_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 *
ext4_xattr_cache_find(struct inode *inode, struct ext4_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(ext4_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) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_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
/*
* ext4_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static inline void ext4_xattr_hash_entry(struct ext4_xattr_header *header,
struct ext4_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) +
EXT4_XATTR_ROUND) >> EXT4_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
/*
* ext4_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext4_xattr_rehash(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
struct ext4_xattr_entry *here;
__u32 hash = 0;
ext4_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 = EXT4_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
int __init
ext4_init_xattr(void)
{
ext4_xattr_cache = mb_cache_create("ext4_xattr", 6);
if (!ext4_xattr_cache)
return -ENOMEM;
return 0;
}
void
ext4_exit_xattr(void)
{
if (ext4_xattr_cache)
mb_cache_destroy(ext4_xattr_cache);
ext4_xattr_cache = NULL;
}
| gpl-2.0 |
c0d3x42/P8000-Kernel | crypto/asymmetric_keys/asymmetric_type.c | 2470 | 6810 | /* Asymmetric public-key cryptography key type
*
* See Documentation/security/asymmetric-keys.txt
*
* Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "asymmetric_keys.h"
MODULE_LICENSE("GPL");
static LIST_HEAD(asymmetric_key_parsers);
static DECLARE_RWSEM(asymmetric_key_parsers_sem);
/*
* Match asymmetric keys on (part of) their name
* We have some shorthand methods for matching keys. We allow:
*
* "<desc>" - request a key by description
* "id:<id>" - request a key matching the ID
* "<subtype>:<id>" - request a key of a subtype
*/
static int asymmetric_key_match(const struct key *key, const void *description)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *spec = description;
const char *id, *kid;
ptrdiff_t speclen;
size_t idlen, kidlen;
if (!subtype || !spec || !*spec)
return 0;
/* See if the full key description matches as is */
if (key->description && strcmp(key->description, description) == 0)
return 1;
/* All tests from here on break the criterion description into a
* specifier, a colon and then an identifier.
*/
id = strchr(spec, ':');
if (!id)
return 0;
speclen = id - spec;
id++;
/* Anything after here requires a partial match on the ID string */
kid = asymmetric_key_id(key);
if (!kid)
return 0;
idlen = strlen(id);
kidlen = strlen(kid);
if (idlen > kidlen)
return 0;
kid += kidlen - idlen;
if (strcasecmp(id, kid) != 0)
return 0;
if (speclen == 2 &&
memcmp(spec, "id", 2) == 0)
return 1;
if (speclen == subtype->name_len &&
memcmp(spec, subtype->name, speclen) == 0)
return 1;
return 0;
}
/*
* Describe the asymmetric key
*/
static void asymmetric_key_describe(const struct key *key, struct seq_file *m)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *kid = asymmetric_key_id(key);
size_t n;
seq_puts(m, key->description);
if (subtype) {
seq_puts(m, ": ");
subtype->describe(key, m);
if (kid) {
seq_putc(m, ' ');
n = strlen(kid);
if (n <= 8)
seq_puts(m, kid);
else
seq_puts(m, kid + n - 8);
}
seq_puts(m, " [");
/* put something here to indicate the key's capabilities */
seq_putc(m, ']');
}
}
/*
* Preparse a asymmetric payload to get format the contents appropriately for the
* internal payload to cut down on the number of scans of the data performed.
*
* We also generate a proposed description from the contents of the key that
* can be used to name the key if the user doesn't want to provide one.
*/
static int asymmetric_key_preparse(struct key_preparsed_payload *prep)
{
struct asymmetric_key_parser *parser;
int ret;
pr_devel("==>%s()\n", __func__);
if (prep->datalen == 0)
return -EINVAL;
down_read(&asymmetric_key_parsers_sem);
ret = -EBADMSG;
list_for_each_entry(parser, &asymmetric_key_parsers, link) {
pr_debug("Trying parser '%s'\n", parser->name);
ret = parser->parse(prep);
if (ret != -EBADMSG) {
pr_debug("Parser recognised the format (ret %d)\n",
ret);
break;
}
}
up_read(&asymmetric_key_parsers_sem);
pr_devel("<==%s() = %d\n", __func__, ret);
return ret;
}
/*
* Clean up the preparse data
*/
static void asymmetric_key_free_preparse(struct key_preparsed_payload *prep)
{
struct asymmetric_key_subtype *subtype = prep->type_data[0];
pr_devel("==>%s()\n", __func__);
if (subtype) {
subtype->destroy(prep->payload);
module_put(subtype->owner);
}
kfree(prep->type_data[1]);
kfree(prep->description);
}
/*
* Instantiate a asymmetric_key defined key. The key was preparsed, so we just
* have to transfer the data here.
*/
static int asymmetric_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
{
int ret;
pr_devel("==>%s()\n", __func__);
ret = key_payload_reserve(key, prep->quotalen);
if (ret == 0) {
key->type_data.p[0] = prep->type_data[0];
key->type_data.p[1] = prep->type_data[1];
key->payload.data = prep->payload;
prep->type_data[0] = NULL;
prep->type_data[1] = NULL;
prep->payload = NULL;
}
pr_devel("<==%s() = %d\n", __func__, ret);
return ret;
}
/*
* dispose of the data dangling from the corpse of a asymmetric key
*/
static void asymmetric_key_destroy(struct key *key)
{
struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
if (subtype) {
subtype->destroy(key->payload.data);
module_put(subtype->owner);
key->type_data.p[0] = NULL;
}
kfree(key->type_data.p[1]);
key->type_data.p[1] = NULL;
}
struct key_type key_type_asymmetric = {
.name = "asymmetric",
.preparse = asymmetric_key_preparse,
.free_preparse = asymmetric_key_free_preparse,
.instantiate = asymmetric_key_instantiate,
.match = asymmetric_key_match,
.destroy = asymmetric_key_destroy,
.describe = asymmetric_key_describe,
};
EXPORT_SYMBOL_GPL(key_type_asymmetric);
/**
* register_asymmetric_key_parser - Register a asymmetric key blob parser
* @parser: The parser to register
*/
int register_asymmetric_key_parser(struct asymmetric_key_parser *parser)
{
struct asymmetric_key_parser *cursor;
int ret;
down_write(&asymmetric_key_parsers_sem);
list_for_each_entry(cursor, &asymmetric_key_parsers, link) {
if (strcmp(cursor->name, parser->name) == 0) {
pr_err("Asymmetric key parser '%s' already registered\n",
parser->name);
ret = -EEXIST;
goto out;
}
}
list_add_tail(&parser->link, &asymmetric_key_parsers);
pr_notice("Asymmetric key parser '%s' registered\n", parser->name);
ret = 0;
out:
up_write(&asymmetric_key_parsers_sem);
return ret;
}
EXPORT_SYMBOL_GPL(register_asymmetric_key_parser);
/**
* unregister_asymmetric_key_parser - Unregister a asymmetric key blob parser
* @parser: The parser to unregister
*/
void unregister_asymmetric_key_parser(struct asymmetric_key_parser *parser)
{
down_write(&asymmetric_key_parsers_sem);
list_del(&parser->link);
up_write(&asymmetric_key_parsers_sem);
pr_notice("Asymmetric key parser '%s' unregistered\n", parser->name);
}
EXPORT_SYMBOL_GPL(unregister_asymmetric_key_parser);
/*
* Module stuff
*/
static int __init asymmetric_key_init(void)
{
return register_key_type(&key_type_asymmetric);
}
static void __exit asymmetric_key_cleanup(void)
{
unregister_key_type(&key_type_asymmetric);
}
module_init(asymmetric_key_init);
module_exit(asymmetric_key_cleanup);
| gpl-2.0 |
MadRocker/jet-2.6.39.5 | drivers/gpio/pcf857x.c | 2726 | 10044 | /*
* pcf857x - driver for pcf857x, pca857x, and pca967x I2C GPIO expanders
*
* Copyright (C) 2007 David Brownell
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/i2c/pcf857x.h>
static const struct i2c_device_id pcf857x_id[] = {
{ "pcf8574", 8 },
{ "pcf8574a", 8 },
{ "pca8574", 8 },
{ "pca9670", 8 },
{ "pca9672", 8 },
{ "pca9674", 8 },
{ "pcf8575", 16 },
{ "pca8575", 16 },
{ "pca9671", 16 },
{ "pca9673", 16 },
{ "pca9675", 16 },
{ "max7328", 8 },
{ "max7329", 8 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pcf857x_id);
/*
* The pcf857x, pca857x, and pca967x chips only expose one read and one
* write register. Writing a "one" bit (to match the reset state) lets
* that pin be used as an input; it's not an open-drain model, but acts
* a bit like one. This is described as "quasi-bidirectional"; read the
* chip documentation for details.
*
* Many other I2C GPIO expander chips (like the pca953x models) have
* more complex register models and more conventional circuitry using
* push/pull drivers. They often use the same 0x20..0x27 addresses as
* pcf857x parts, making the "legacy" I2C driver model problematic.
*/
struct pcf857x {
struct gpio_chip chip;
struct i2c_client *client;
struct mutex lock; /* protect 'out' */
unsigned out; /* software latch */
};
/*-------------------------------------------------------------------------*/
/* Talk to 8-bit I/O expander */
static int pcf857x_input8(struct gpio_chip *chip, unsigned offset)
{
struct pcf857x *gpio = container_of(chip, struct pcf857x, chip);
int status;
mutex_lock(&gpio->lock);
gpio->out |= (1 << offset);
status = i2c_smbus_write_byte(gpio->client, gpio->out);
mutex_unlock(&gpio->lock);
return status;
}
static int pcf857x_get8(struct gpio_chip *chip, unsigned offset)
{
struct pcf857x *gpio = container_of(chip, struct pcf857x, chip);
s32 value;
value = i2c_smbus_read_byte(gpio->client);
return (value < 0) ? 0 : (value & (1 << offset));
}
static int pcf857x_output8(struct gpio_chip *chip, unsigned offset, int value)
{
struct pcf857x *gpio = container_of(chip, struct pcf857x, chip);
unsigned bit = 1 << offset;
int status;
mutex_lock(&gpio->lock);
if (value)
gpio->out |= bit;
else
gpio->out &= ~bit;
status = i2c_smbus_write_byte(gpio->client, gpio->out);
mutex_unlock(&gpio->lock);
return status;
}
static void pcf857x_set8(struct gpio_chip *chip, unsigned offset, int value)
{
pcf857x_output8(chip, offset, value);
}
/*-------------------------------------------------------------------------*/
/* Talk to 16-bit I/O expander */
static int i2c_write_le16(struct i2c_client *client, u16 word)
{
u8 buf[2] = { word & 0xff, word >> 8, };
int status;
status = i2c_master_send(client, buf, 2);
return (status < 0) ? status : 0;
}
static int i2c_read_le16(struct i2c_client *client)
{
u8 buf[2];
int status;
status = i2c_master_recv(client, buf, 2);
if (status < 0)
return status;
return (buf[1] << 8) | buf[0];
}
static int pcf857x_input16(struct gpio_chip *chip, unsigned offset)
{
struct pcf857x *gpio = container_of(chip, struct pcf857x, chip);
int status;
mutex_lock(&gpio->lock);
gpio->out |= (1 << offset);
status = i2c_write_le16(gpio->client, gpio->out);
mutex_unlock(&gpio->lock);
return status;
}
static int pcf857x_get16(struct gpio_chip *chip, unsigned offset)
{
struct pcf857x *gpio = container_of(chip, struct pcf857x, chip);
int value;
value = i2c_read_le16(gpio->client);
return (value < 0) ? 0 : (value & (1 << offset));
}
static int pcf857x_output16(struct gpio_chip *chip, unsigned offset, int value)
{
struct pcf857x *gpio = container_of(chip, struct pcf857x, chip);
unsigned bit = 1 << offset;
int status;
mutex_lock(&gpio->lock);
if (value)
gpio->out |= bit;
else
gpio->out &= ~bit;
status = i2c_write_le16(gpio->client, gpio->out);
mutex_unlock(&gpio->lock);
return status;
}
static void pcf857x_set16(struct gpio_chip *chip, unsigned offset, int value)
{
pcf857x_output16(chip, offset, value);
}
/*-------------------------------------------------------------------------*/
static int pcf857x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pcf857x_platform_data *pdata;
struct pcf857x *gpio;
int status;
pdata = client->dev.platform_data;
if (!pdata) {
dev_dbg(&client->dev, "no platform data\n");
}
/* Allocate, initialize, and register this gpio_chip. */
gpio = kzalloc(sizeof *gpio, GFP_KERNEL);
if (!gpio)
return -ENOMEM;
mutex_init(&gpio->lock);
gpio->chip.base = pdata ? pdata->gpio_base : -1;
gpio->chip.can_sleep = 1;
gpio->chip.dev = &client->dev;
gpio->chip.owner = THIS_MODULE;
/* NOTE: the OnSemi jlc1562b is also largely compatible with
* these parts, notably for output. It has a low-resolution
* DAC instead of pin change IRQs; and its inputs can be the
* result of comparators.
*/
/* 8574 addresses are 0x20..0x27; 8574a uses 0x38..0x3f;
* 9670, 9672, 9764, and 9764a use quite a variety.
*
* NOTE: we don't distinguish here between *4 and *4a parts.
*/
gpio->chip.ngpio = id->driver_data;
if (gpio->chip.ngpio == 8) {
gpio->chip.direction_input = pcf857x_input8;
gpio->chip.get = pcf857x_get8;
gpio->chip.direction_output = pcf857x_output8;
gpio->chip.set = pcf857x_set8;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE))
status = -EIO;
/* fail if there's no chip present */
else
status = i2c_smbus_read_byte(client);
/* '75/'75c addresses are 0x20..0x27, just like the '74;
* the '75c doesn't have a current source pulling high.
* 9671, 9673, and 9765 use quite a variety of addresses.
*
* NOTE: we don't distinguish here between '75 and '75c parts.
*/
} else if (gpio->chip.ngpio == 16) {
gpio->chip.direction_input = pcf857x_input16;
gpio->chip.get = pcf857x_get16;
gpio->chip.direction_output = pcf857x_output16;
gpio->chip.set = pcf857x_set16;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
status = -EIO;
/* fail if there's no chip present */
else
status = i2c_read_le16(client);
} else {
dev_dbg(&client->dev, "unsupported number of gpios\n");
status = -EINVAL;
}
if (status < 0)
goto fail;
gpio->chip.label = client->name;
gpio->client = client;
i2c_set_clientdata(client, gpio);
/* NOTE: these chips have strange "quasi-bidirectional" I/O pins.
* We can't actually know whether a pin is configured (a) as output
* and driving the signal low, or (b) as input and reporting a low
* value ... without knowing the last value written since the chip
* came out of reset (if any). We can't read the latched output.
*
* In short, the only reliable solution for setting up pin direction
* is to do it explicitly. The setup() method can do that, but it
* may cause transient glitching since it can't know the last value
* written (some pins may need to be driven low).
*
* Using pdata->n_latch avoids that trouble. When left initialized
* to zero, our software copy of the "latch" then matches the chip's
* all-ones reset state. Otherwise it flags pins to be driven low.
*/
gpio->out = pdata ? ~pdata->n_latch : ~0;
status = gpiochip_add(&gpio->chip);
if (status < 0)
goto fail;
/* NOTE: these chips can issue "some pin-changed" IRQs, which we
* don't yet even try to use. Among other issues, the relevant
* genirq state isn't available to modular drivers; and most irq
* methods can't be called from sleeping contexts.
*/
dev_info(&client->dev, "gpios %d..%d on a %s%s\n",
gpio->chip.base,
gpio->chip.base + gpio->chip.ngpio - 1,
client->name,
client->irq ? " (irq ignored)" : "");
/* Let platform code set up the GPIOs and their users.
* Now is the first time anyone could use them.
*/
if (pdata && pdata->setup) {
status = pdata->setup(client,
gpio->chip.base, gpio->chip.ngpio,
pdata->context);
if (status < 0)
dev_warn(&client->dev, "setup --> %d\n", status);
}
return 0;
fail:
dev_dbg(&client->dev, "probe error %d for '%s'\n",
status, client->name);
kfree(gpio);
return status;
}
static int pcf857x_remove(struct i2c_client *client)
{
struct pcf857x_platform_data *pdata = client->dev.platform_data;
struct pcf857x *gpio = i2c_get_clientdata(client);
int status = 0;
if (pdata && pdata->teardown) {
status = pdata->teardown(client,
gpio->chip.base, gpio->chip.ngpio,
pdata->context);
if (status < 0) {
dev_err(&client->dev, "%s --> %d\n",
"teardown", status);
return status;
}
}
status = gpiochip_remove(&gpio->chip);
if (status == 0)
kfree(gpio);
else
dev_err(&client->dev, "%s --> %d\n", "remove", status);
return status;
}
static struct i2c_driver pcf857x_driver = {
.driver = {
.name = "pcf857x",
.owner = THIS_MODULE,
},
.probe = pcf857x_probe,
.remove = pcf857x_remove,
.id_table = pcf857x_id,
};
static int __init pcf857x_init(void)
{
return i2c_add_driver(&pcf857x_driver);
}
/* register after i2c postcore initcall and before
* subsys initcalls that may rely on these GPIOs
*/
subsys_initcall(pcf857x_init);
static void __exit pcf857x_exit(void)
{
i2c_del_driver(&pcf857x_driver);
}
module_exit(pcf857x_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Brownell");
| gpl-2.0 |
eugene373/Kernel | arch/powerpc/kernel/vdso.c | 2726 | 21414 |
/*
* Copyright (C) 2004 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/elf.h>
#include <linux/security.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <asm/pgtable.h>
#include <asm/system.h>
#include <asm/processor.h>
#include <asm/mmu.h>
#include <asm/mmu_context.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/cputable.h>
#include <asm/sections.h>
#include <asm/firmware.h>
#include <asm/vdso.h>
#include <asm/vdso_datapage.h>
#include "setup.h"
#undef DEBUG
#ifdef DEBUG
#define DBG(fmt...) printk(fmt)
#else
#define DBG(fmt...)
#endif
/* Max supported size for symbol names */
#define MAX_SYMNAME 64
/* The alignment of the vDSO */
#define VDSO_ALIGNMENT (1 << 16)
extern char vdso32_start, vdso32_end;
static void *vdso32_kbase = &vdso32_start;
static unsigned int vdso32_pages;
static struct page **vdso32_pagelist;
unsigned long vdso32_sigtramp;
unsigned long vdso32_rt_sigtramp;
#ifdef CONFIG_PPC64
extern char vdso64_start, vdso64_end;
static void *vdso64_kbase = &vdso64_start;
static unsigned int vdso64_pages;
static struct page **vdso64_pagelist;
unsigned long vdso64_rt_sigtramp;
#endif /* CONFIG_PPC64 */
static int vdso_ready;
/*
* The vdso data page (aka. systemcfg for old ppc64 fans) is here.
* Once the early boot kernel code no longer needs to muck around
* with it, it will become dynamically allocated
*/
static union {
struct vdso_data data;
u8 page[PAGE_SIZE];
} vdso_data_store __page_aligned_data;
struct vdso_data *vdso_data = &vdso_data_store.data;
/* Format of the patch table */
struct vdso_patch_def
{
unsigned long ftr_mask, ftr_value;
const char *gen_name;
const char *fix_name;
};
/* Table of functions to patch based on the CPU type/revision
*
* Currently, we only change sync_dicache to do nothing on processors
* with a coherent icache
*/
static struct vdso_patch_def vdso_patches[] = {
{
CPU_FTR_COHERENT_ICACHE, CPU_FTR_COHERENT_ICACHE,
"__kernel_sync_dicache", "__kernel_sync_dicache_p5"
},
{
CPU_FTR_USE_TB, 0,
"__kernel_gettimeofday", NULL
},
{
CPU_FTR_USE_TB, 0,
"__kernel_clock_gettime", NULL
},
{
CPU_FTR_USE_TB, 0,
"__kernel_clock_getres", NULL
},
{
CPU_FTR_USE_TB, 0,
"__kernel_get_tbfreq", NULL
},
};
/*
* Some infos carried around for each of them during parsing at
* boot time.
*/
struct lib32_elfinfo
{
Elf32_Ehdr *hdr; /* ptr to ELF */
Elf32_Sym *dynsym; /* ptr to .dynsym section */
unsigned long dynsymsize; /* size of .dynsym section */
char *dynstr; /* ptr to .dynstr section */
unsigned long text; /* offset of .text section in .so */
};
struct lib64_elfinfo
{
Elf64_Ehdr *hdr;
Elf64_Sym *dynsym;
unsigned long dynsymsize;
char *dynstr;
unsigned long text;
};
#ifdef __DEBUG
static void dump_one_vdso_page(struct page *pg, struct page *upg)
{
printk("kpg: %p (c:%d,f:%08lx)", __va(page_to_pfn(pg) << PAGE_SHIFT),
page_count(pg),
pg->flags);
if (upg && !IS_ERR(upg) /* && pg != upg*/) {
printk(" upg: %p (c:%d,f:%08lx)", __va(page_to_pfn(upg)
<< PAGE_SHIFT),
page_count(upg),
upg->flags);
}
printk("\n");
}
static void dump_vdso_pages(struct vm_area_struct * vma)
{
int i;
if (!vma || is_32bit_task()) {
printk("vDSO32 @ %016lx:\n", (unsigned long)vdso32_kbase);
for (i=0; i<vdso32_pages; i++) {
struct page *pg = virt_to_page(vdso32_kbase +
i*PAGE_SIZE);
struct page *upg = (vma && vma->vm_mm) ?
follow_page(vma, vma->vm_start + i*PAGE_SIZE, 0)
: NULL;
dump_one_vdso_page(pg, upg);
}
}
if (!vma || !is_32bit_task()) {
printk("vDSO64 @ %016lx:\n", (unsigned long)vdso64_kbase);
for (i=0; i<vdso64_pages; i++) {
struct page *pg = virt_to_page(vdso64_kbase +
i*PAGE_SIZE);
struct page *upg = (vma && vma->vm_mm) ?
follow_page(vma, vma->vm_start + i*PAGE_SIZE, 0)
: NULL;
dump_one_vdso_page(pg, upg);
}
}
}
#endif /* DEBUG */
/*
* This is called from binfmt_elf, we create the special vma for the
* vDSO and insert it into the mm struct tree
*/
int arch_setup_additional_pages(struct linux_binprm *bprm, int uses_interp)
{
struct mm_struct *mm = current->mm;
struct page **vdso_pagelist;
unsigned long vdso_pages;
unsigned long vdso_base;
int rc;
if (!vdso_ready)
return 0;
#ifdef CONFIG_PPC64
if (is_32bit_task()) {
vdso_pagelist = vdso32_pagelist;
vdso_pages = vdso32_pages;
vdso_base = VDSO32_MBASE;
} else {
vdso_pagelist = vdso64_pagelist;
vdso_pages = vdso64_pages;
/*
* On 64bit we don't have a preferred map address. This
* allows get_unmapped_area to find an area near other mmaps
* and most likely share a SLB entry.
*/
vdso_base = 0;
}
#else
vdso_pagelist = vdso32_pagelist;
vdso_pages = vdso32_pages;
vdso_base = VDSO32_MBASE;
#endif
current->mm->context.vdso_base = 0;
/* vDSO has a problem and was disabled, just don't "enable" it for the
* process
*/
if (vdso_pages == 0)
return 0;
/* Add a page to the vdso size for the data page */
vdso_pages ++;
/*
* pick a base address for the vDSO in process space. We try to put it
* at vdso_base which is the "natural" base for it, but we might fail
* and end up putting it elsewhere.
* Add enough to the size so that the result can be aligned.
*/
down_write(&mm->mmap_sem);
vdso_base = get_unmapped_area(NULL, vdso_base,
(vdso_pages << PAGE_SHIFT) +
((VDSO_ALIGNMENT - 1) & PAGE_MASK),
0, 0);
if (IS_ERR_VALUE(vdso_base)) {
rc = vdso_base;
goto fail_mmapsem;
}
/* Add required alignment. */
vdso_base = ALIGN(vdso_base, VDSO_ALIGNMENT);
/*
* Put vDSO base into mm struct. We need to do this before calling
* install_special_mapping or the perf counter mmap tracking code
* will fail to recognise it as a vDSO (since arch_vma_name fails).
*/
current->mm->context.vdso_base = vdso_base;
/*
* our vma flags don't have VM_WRITE so by default, the process isn't
* allowed to write those pages.
* gdb can break that with ptrace interface, and thus trigger COW on
* those pages but it's then your responsibility to never do that on
* the "data" page of the vDSO or you'll stop getting kernel updates
* and your nice userland gettimeofday will be totally dead.
* It's fine to use that for setting breakpoints in the vDSO code
* pages though
*
* Make sure the vDSO gets into every core dump.
* Dumping its contents makes post-mortem fully interpretable later
* without matching up the same kernel and hardware config to see
* what PC values meant.
*/
rc = install_special_mapping(mm, vdso_base, vdso_pages << PAGE_SHIFT,
VM_READ|VM_EXEC|
VM_MAYREAD|VM_MAYWRITE|VM_MAYEXEC|
VM_ALWAYSDUMP,
vdso_pagelist);
if (rc) {
current->mm->context.vdso_base = 0;
goto fail_mmapsem;
}
up_write(&mm->mmap_sem);
return 0;
fail_mmapsem:
up_write(&mm->mmap_sem);
return rc;
}
const char *arch_vma_name(struct vm_area_struct *vma)
{
if (vma->vm_mm && vma->vm_start == vma->vm_mm->context.vdso_base)
return "[vdso]";
return NULL;
}
static void * __init find_section32(Elf32_Ehdr *ehdr, const char *secname,
unsigned long *size)
{
Elf32_Shdr *sechdrs;
unsigned int i;
char *secnames;
/* Grab section headers and strings so we can tell who is who */
sechdrs = (void *)ehdr + ehdr->e_shoff;
secnames = (void *)ehdr + sechdrs[ehdr->e_shstrndx].sh_offset;
/* Find the section they want */
for (i = 1; i < ehdr->e_shnum; i++) {
if (strcmp(secnames+sechdrs[i].sh_name, secname) == 0) {
if (size)
*size = sechdrs[i].sh_size;
return (void *)ehdr + sechdrs[i].sh_offset;
}
}
*size = 0;
return NULL;
}
static Elf32_Sym * __init find_symbol32(struct lib32_elfinfo *lib,
const char *symname)
{
unsigned int i;
char name[MAX_SYMNAME], *c;
for (i = 0; i < (lib->dynsymsize / sizeof(Elf32_Sym)); i++) {
if (lib->dynsym[i].st_name == 0)
continue;
strlcpy(name, lib->dynstr + lib->dynsym[i].st_name,
MAX_SYMNAME);
c = strchr(name, '@');
if (c)
*c = 0;
if (strcmp(symname, name) == 0)
return &lib->dynsym[i];
}
return NULL;
}
/* Note that we assume the section is .text and the symbol is relative to
* the library base
*/
static unsigned long __init find_function32(struct lib32_elfinfo *lib,
const char *symname)
{
Elf32_Sym *sym = find_symbol32(lib, symname);
if (sym == NULL) {
printk(KERN_WARNING "vDSO32: function %s not found !\n",
symname);
return 0;
}
return sym->st_value - VDSO32_LBASE;
}
static int __init vdso_do_func_patch32(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64,
const char *orig, const char *fix)
{
Elf32_Sym *sym32_gen, *sym32_fix;
sym32_gen = find_symbol32(v32, orig);
if (sym32_gen == NULL) {
printk(KERN_ERR "vDSO32: Can't find symbol %s !\n", orig);
return -1;
}
if (fix == NULL) {
sym32_gen->st_name = 0;
return 0;
}
sym32_fix = find_symbol32(v32, fix);
if (sym32_fix == NULL) {
printk(KERN_ERR "vDSO32: Can't find symbol %s !\n", fix);
return -1;
}
sym32_gen->st_value = sym32_fix->st_value;
sym32_gen->st_size = sym32_fix->st_size;
sym32_gen->st_info = sym32_fix->st_info;
sym32_gen->st_other = sym32_fix->st_other;
sym32_gen->st_shndx = sym32_fix->st_shndx;
return 0;
}
#ifdef CONFIG_PPC64
static void * __init find_section64(Elf64_Ehdr *ehdr, const char *secname,
unsigned long *size)
{
Elf64_Shdr *sechdrs;
unsigned int i;
char *secnames;
/* Grab section headers and strings so we can tell who is who */
sechdrs = (void *)ehdr + ehdr->e_shoff;
secnames = (void *)ehdr + sechdrs[ehdr->e_shstrndx].sh_offset;
/* Find the section they want */
for (i = 1; i < ehdr->e_shnum; i++) {
if (strcmp(secnames+sechdrs[i].sh_name, secname) == 0) {
if (size)
*size = sechdrs[i].sh_size;
return (void *)ehdr + sechdrs[i].sh_offset;
}
}
if (size)
*size = 0;
return NULL;
}
static Elf64_Sym * __init find_symbol64(struct lib64_elfinfo *lib,
const char *symname)
{
unsigned int i;
char name[MAX_SYMNAME], *c;
for (i = 0; i < (lib->dynsymsize / sizeof(Elf64_Sym)); i++) {
if (lib->dynsym[i].st_name == 0)
continue;
strlcpy(name, lib->dynstr + lib->dynsym[i].st_name,
MAX_SYMNAME);
c = strchr(name, '@');
if (c)
*c = 0;
if (strcmp(symname, name) == 0)
return &lib->dynsym[i];
}
return NULL;
}
/* Note that we assume the section is .text and the symbol is relative to
* the library base
*/
static unsigned long __init find_function64(struct lib64_elfinfo *lib,
const char *symname)
{
Elf64_Sym *sym = find_symbol64(lib, symname);
if (sym == NULL) {
printk(KERN_WARNING "vDSO64: function %s not found !\n",
symname);
return 0;
}
#ifdef VDS64_HAS_DESCRIPTORS
return *((u64 *)(vdso64_kbase + sym->st_value - VDSO64_LBASE)) -
VDSO64_LBASE;
#else
return sym->st_value - VDSO64_LBASE;
#endif
}
static int __init vdso_do_func_patch64(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64,
const char *orig, const char *fix)
{
Elf64_Sym *sym64_gen, *sym64_fix;
sym64_gen = find_symbol64(v64, orig);
if (sym64_gen == NULL) {
printk(KERN_ERR "vDSO64: Can't find symbol %s !\n", orig);
return -1;
}
if (fix == NULL) {
sym64_gen->st_name = 0;
return 0;
}
sym64_fix = find_symbol64(v64, fix);
if (sym64_fix == NULL) {
printk(KERN_ERR "vDSO64: Can't find symbol %s !\n", fix);
return -1;
}
sym64_gen->st_value = sym64_fix->st_value;
sym64_gen->st_size = sym64_fix->st_size;
sym64_gen->st_info = sym64_fix->st_info;
sym64_gen->st_other = sym64_fix->st_other;
sym64_gen->st_shndx = sym64_fix->st_shndx;
return 0;
}
#endif /* CONFIG_PPC64 */
static __init int vdso_do_find_sections(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64)
{
void *sect;
/*
* Locate symbol tables & text section
*/
v32->dynsym = find_section32(v32->hdr, ".dynsym", &v32->dynsymsize);
v32->dynstr = find_section32(v32->hdr, ".dynstr", NULL);
if (v32->dynsym == NULL || v32->dynstr == NULL) {
printk(KERN_ERR "vDSO32: required symbol section not found\n");
return -1;
}
sect = find_section32(v32->hdr, ".text", NULL);
if (sect == NULL) {
printk(KERN_ERR "vDSO32: the .text section was not found\n");
return -1;
}
v32->text = sect - vdso32_kbase;
#ifdef CONFIG_PPC64
v64->dynsym = find_section64(v64->hdr, ".dynsym", &v64->dynsymsize);
v64->dynstr = find_section64(v64->hdr, ".dynstr", NULL);
if (v64->dynsym == NULL || v64->dynstr == NULL) {
printk(KERN_ERR "vDSO64: required symbol section not found\n");
return -1;
}
sect = find_section64(v64->hdr, ".text", NULL);
if (sect == NULL) {
printk(KERN_ERR "vDSO64: the .text section was not found\n");
return -1;
}
v64->text = sect - vdso64_kbase;
#endif /* CONFIG_PPC64 */
return 0;
}
static __init void vdso_setup_trampolines(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64)
{
/*
* Find signal trampolines
*/
#ifdef CONFIG_PPC64
vdso64_rt_sigtramp = find_function64(v64, "__kernel_sigtramp_rt64");
#endif
vdso32_sigtramp = find_function32(v32, "__kernel_sigtramp32");
vdso32_rt_sigtramp = find_function32(v32, "__kernel_sigtramp_rt32");
}
static __init int vdso_fixup_datapage(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64)
{
Elf32_Sym *sym32;
#ifdef CONFIG_PPC64
Elf64_Sym *sym64;
sym64 = find_symbol64(v64, "__kernel_datapage_offset");
if (sym64 == NULL) {
printk(KERN_ERR "vDSO64: Can't find symbol "
"__kernel_datapage_offset !\n");
return -1;
}
*((int *)(vdso64_kbase + sym64->st_value - VDSO64_LBASE)) =
(vdso64_pages << PAGE_SHIFT) -
(sym64->st_value - VDSO64_LBASE);
#endif /* CONFIG_PPC64 */
sym32 = find_symbol32(v32, "__kernel_datapage_offset");
if (sym32 == NULL) {
printk(KERN_ERR "vDSO32: Can't find symbol "
"__kernel_datapage_offset !\n");
return -1;
}
*((int *)(vdso32_kbase + (sym32->st_value - VDSO32_LBASE))) =
(vdso32_pages << PAGE_SHIFT) -
(sym32->st_value - VDSO32_LBASE);
return 0;
}
static __init int vdso_fixup_features(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64)
{
void *start32;
unsigned long size32;
#ifdef CONFIG_PPC64
void *start64;
unsigned long size64;
start64 = find_section64(v64->hdr, "__ftr_fixup", &size64);
if (start64)
do_feature_fixups(cur_cpu_spec->cpu_features,
start64, start64 + size64);
start64 = find_section64(v64->hdr, "__mmu_ftr_fixup", &size64);
if (start64)
do_feature_fixups(cur_cpu_spec->mmu_features,
start64, start64 + size64);
start64 = find_section64(v64->hdr, "__fw_ftr_fixup", &size64);
if (start64)
do_feature_fixups(powerpc_firmware_features,
start64, start64 + size64);
start64 = find_section64(v64->hdr, "__lwsync_fixup", &size64);
if (start64)
do_lwsync_fixups(cur_cpu_spec->cpu_features,
start64, start64 + size64);
#endif /* CONFIG_PPC64 */
start32 = find_section32(v32->hdr, "__ftr_fixup", &size32);
if (start32)
do_feature_fixups(cur_cpu_spec->cpu_features,
start32, start32 + size32);
start32 = find_section32(v32->hdr, "__mmu_ftr_fixup", &size32);
if (start32)
do_feature_fixups(cur_cpu_spec->mmu_features,
start32, start32 + size32);
#ifdef CONFIG_PPC64
start32 = find_section32(v32->hdr, "__fw_ftr_fixup", &size32);
if (start32)
do_feature_fixups(powerpc_firmware_features,
start32, start32 + size32);
#endif /* CONFIG_PPC64 */
start32 = find_section32(v32->hdr, "__lwsync_fixup", &size32);
if (start32)
do_lwsync_fixups(cur_cpu_spec->cpu_features,
start32, start32 + size32);
return 0;
}
static __init int vdso_fixup_alt_funcs(struct lib32_elfinfo *v32,
struct lib64_elfinfo *v64)
{
int i;
for (i = 0; i < ARRAY_SIZE(vdso_patches); i++) {
struct vdso_patch_def *patch = &vdso_patches[i];
int match = (cur_cpu_spec->cpu_features & patch->ftr_mask)
== patch->ftr_value;
if (!match)
continue;
DBG("replacing %s with %s...\n", patch->gen_name,
patch->fix_name ? "NONE" : patch->fix_name);
/*
* Patch the 32 bits and 64 bits symbols. Note that we do not
* patch the "." symbol on 64 bits.
* It would be easy to do, but doesn't seem to be necessary,
* patching the OPD symbol is enough.
*/
vdso_do_func_patch32(v32, v64, patch->gen_name,
patch->fix_name);
#ifdef CONFIG_PPC64
vdso_do_func_patch64(v32, v64, patch->gen_name,
patch->fix_name);
#endif /* CONFIG_PPC64 */
}
return 0;
}
static __init int vdso_setup(void)
{
struct lib32_elfinfo v32;
struct lib64_elfinfo v64;
v32.hdr = vdso32_kbase;
#ifdef CONFIG_PPC64
v64.hdr = vdso64_kbase;
#endif
if (vdso_do_find_sections(&v32, &v64))
return -1;
if (vdso_fixup_datapage(&v32, &v64))
return -1;
if (vdso_fixup_features(&v32, &v64))
return -1;
if (vdso_fixup_alt_funcs(&v32, &v64))
return -1;
vdso_setup_trampolines(&v32, &v64);
return 0;
}
/*
* Called from setup_arch to initialize the bitmap of available
* syscalls in the systemcfg page
*/
static void __init vdso_setup_syscall_map(void)
{
unsigned int i;
extern unsigned long *sys_call_table;
extern unsigned long sys_ni_syscall;
for (i = 0; i < __NR_syscalls; i++) {
#ifdef CONFIG_PPC64
if (sys_call_table[i*2] != sys_ni_syscall)
vdso_data->syscall_map_64[i >> 5] |=
0x80000000UL >> (i & 0x1f);
if (sys_call_table[i*2+1] != sys_ni_syscall)
vdso_data->syscall_map_32[i >> 5] |=
0x80000000UL >> (i & 0x1f);
#else /* CONFIG_PPC64 */
if (sys_call_table[i] != sys_ni_syscall)
vdso_data->syscall_map_32[i >> 5] |=
0x80000000UL >> (i & 0x1f);
#endif /* CONFIG_PPC64 */
}
}
static int __init vdso_init(void)
{
int i;
#ifdef CONFIG_PPC64
/*
* Fill up the "systemcfg" stuff for backward compatibility
*/
strcpy((char *)vdso_data->eye_catcher, "SYSTEMCFG:PPC64");
vdso_data->version.major = SYSTEMCFG_MAJOR;
vdso_data->version.minor = SYSTEMCFG_MINOR;
vdso_data->processor = mfspr(SPRN_PVR);
/*
* Fake the old platform number for pSeries and iSeries and add
* in LPAR bit if necessary
*/
vdso_data->platform = machine_is(iseries) ? 0x200 : 0x100;
if (firmware_has_feature(FW_FEATURE_LPAR))
vdso_data->platform |= 1;
vdso_data->physicalMemorySize = memblock_phys_mem_size();
vdso_data->dcache_size = ppc64_caches.dsize;
vdso_data->dcache_line_size = ppc64_caches.dline_size;
vdso_data->icache_size = ppc64_caches.isize;
vdso_data->icache_line_size = ppc64_caches.iline_size;
/* XXXOJN: Blocks should be added to ppc64_caches and used instead */
vdso_data->dcache_block_size = ppc64_caches.dline_size;
vdso_data->icache_block_size = ppc64_caches.iline_size;
vdso_data->dcache_log_block_size = ppc64_caches.log_dline_size;
vdso_data->icache_log_block_size = ppc64_caches.log_iline_size;
/*
* Calculate the size of the 64 bits vDSO
*/
vdso64_pages = (&vdso64_end - &vdso64_start) >> PAGE_SHIFT;
DBG("vdso64_kbase: %p, 0x%x pages\n", vdso64_kbase, vdso64_pages);
#else
vdso_data->dcache_block_size = L1_CACHE_BYTES;
vdso_data->dcache_log_block_size = L1_CACHE_SHIFT;
vdso_data->icache_block_size = L1_CACHE_BYTES;
vdso_data->icache_log_block_size = L1_CACHE_SHIFT;
#endif /* CONFIG_PPC64 */
/*
* Calculate the size of the 32 bits vDSO
*/
vdso32_pages = (&vdso32_end - &vdso32_start) >> PAGE_SHIFT;
DBG("vdso32_kbase: %p, 0x%x pages\n", vdso32_kbase, vdso32_pages);
/*
* Setup the syscall map in the vDOS
*/
vdso_setup_syscall_map();
/*
* Initialize the vDSO images in memory, that is do necessary
* fixups of vDSO symbols, locate trampolines, etc...
*/
if (vdso_setup()) {
printk(KERN_ERR "vDSO setup failure, not enabled !\n");
vdso32_pages = 0;
#ifdef CONFIG_PPC64
vdso64_pages = 0;
#endif
return 0;
}
/* Make sure pages are in the correct state */
vdso32_pagelist = kzalloc(sizeof(struct page *) * (vdso32_pages + 2),
GFP_KERNEL);
BUG_ON(vdso32_pagelist == NULL);
for (i = 0; i < vdso32_pages; i++) {
struct page *pg = virt_to_page(vdso32_kbase + i*PAGE_SIZE);
ClearPageReserved(pg);
get_page(pg);
vdso32_pagelist[i] = pg;
}
vdso32_pagelist[i++] = virt_to_page(vdso_data);
vdso32_pagelist[i] = NULL;
#ifdef CONFIG_PPC64
vdso64_pagelist = kzalloc(sizeof(struct page *) * (vdso64_pages + 2),
GFP_KERNEL);
BUG_ON(vdso64_pagelist == NULL);
for (i = 0; i < vdso64_pages; i++) {
struct page *pg = virt_to_page(vdso64_kbase + i*PAGE_SIZE);
ClearPageReserved(pg);
get_page(pg);
vdso64_pagelist[i] = pg;
}
vdso64_pagelist[i++] = virt_to_page(vdso_data);
vdso64_pagelist[i] = NULL;
#endif /* CONFIG_PPC64 */
get_page(virt_to_page(vdso_data));
smp_wmb();
vdso_ready = 1;
return 0;
}
arch_initcall(vdso_init);
int in_gate_area_no_mm(unsigned long addr)
{
return 0;
}
int in_gate_area(struct mm_struct *mm, unsigned long addr)
{
return 0;
}
struct vm_area_struct *get_gate_vma(struct mm_struct *mm)
{
return NULL;
}
| gpl-2.0 |
Badadroid/android_kernel_samsung_wave | kernel/sched_stoptask.c | 2726 | 2148 | /*
* stop-task scheduling class.
*
* The stop task is the highest priority task in the system, it preempts
* everything and will be preempted by nothing.
*
* See kernel/stop_machine.c
*/
#ifdef CONFIG_SMP
static int
select_task_rq_stop(struct task_struct *p, int sd_flag, int flags)
{
return task_cpu(p); /* stop tasks as never migrate */
}
#endif /* CONFIG_SMP */
static void
check_preempt_curr_stop(struct rq *rq, struct task_struct *p, int flags)
{
/* we're never preempted */
}
static struct task_struct *pick_next_task_stop(struct rq *rq)
{
struct task_struct *stop = rq->stop;
if (stop && stop->on_rq)
return stop;
return NULL;
}
static void
enqueue_task_stop(struct rq *rq, struct task_struct *p, int flags)
{
}
static void
dequeue_task_stop(struct rq *rq, struct task_struct *p, int flags)
{
}
static void yield_task_stop(struct rq *rq)
{
BUG(); /* the stop task should never yield, its pointless. */
}
static void put_prev_task_stop(struct rq *rq, struct task_struct *prev)
{
}
static void task_tick_stop(struct rq *rq, struct task_struct *curr, int queued)
{
}
static void set_curr_task_stop(struct rq *rq)
{
}
static void switched_to_stop(struct rq *rq, struct task_struct *p)
{
BUG(); /* its impossible to change to this class */
}
static void
prio_changed_stop(struct rq *rq, struct task_struct *p, int oldprio)
{
BUG(); /* how!?, what priority? */
}
static unsigned int
get_rr_interval_stop(struct rq *rq, struct task_struct *task)
{
return 0;
}
/*
* Simple, special scheduling class for the per-CPU stop tasks:
*/
static const struct sched_class stop_sched_class = {
.next = &rt_sched_class,
.enqueue_task = enqueue_task_stop,
.dequeue_task = dequeue_task_stop,
.yield_task = yield_task_stop,
.check_preempt_curr = check_preempt_curr_stop,
.pick_next_task = pick_next_task_stop,
.put_prev_task = put_prev_task_stop,
#ifdef CONFIG_SMP
.select_task_rq = select_task_rq_stop,
#endif
.set_curr_task = set_curr_task_stop,
.task_tick = task_tick_stop,
.get_rr_interval = get_rr_interval_stop,
.prio_changed = prio_changed_stop,
.switched_to = switched_to_stop,
};
| gpl-2.0 |
AOKP-SGS2/android_kernel_samsung_espresso | arch/s390/boot/compressed/misc.c | 2726 | 3781 | /*
* Definitions and wrapper functions for kernel decompressor
*
* Copyright IBM Corp. 2010
*
* Author(s): Martin Schwidefsky <schwidefsky@de.ibm.com>
*/
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/ipl.h>
#include "sizes.h"
/*
* gzip declarations
*/
#define STATIC static
#undef memset
#undef memcpy
#undef memmove
#define memmove memmove
#define memzero(s, n) memset((s), 0, (n))
/* Symbols defined by linker scripts */
extern char input_data[];
extern int input_len;
extern char _text, _end;
extern char _bss, _ebss;
static void error(char *m);
static unsigned long free_mem_ptr;
static unsigned long free_mem_end_ptr;
#ifdef CONFIG_HAVE_KERNEL_BZIP2
#define HEAP_SIZE 0x400000
#else
#define HEAP_SIZE 0x10000
#endif
#ifdef CONFIG_KERNEL_GZIP
#include "../../../../lib/decompress_inflate.c"
#endif
#ifdef CONFIG_KERNEL_BZIP2
#include "../../../../lib/decompress_bunzip2.c"
#endif
#ifdef CONFIG_KERNEL_LZMA
#include "../../../../lib/decompress_unlzma.c"
#endif
#ifdef CONFIG_KERNEL_LZO
#include "../../../../lib/decompress_unlzo.c"
#endif
#ifdef CONFIG_KERNEL_XZ
#include "../../../../lib/decompress_unxz.c"
#endif
extern _sclp_print_early(const char *);
int puts(const char *s)
{
_sclp_print_early(s);
return 0;
}
void *memset(void *s, int c, size_t n)
{
char *xs;
if (c == 0)
return __builtin_memset(s, 0, n);
xs = (char *) s;
if (n > 0)
do {
*xs++ = c;
} while (--n > 0);
return s;
}
void *memcpy(void *__dest, __const void *__src, size_t __n)
{
return __builtin_memcpy(__dest, __src, __n);
}
void *memmove(void *__dest, __const void *__src, size_t __n)
{
char *d;
const char *s;
if (__dest <= __src)
return __builtin_memcpy(__dest, __src, __n);
d = __dest + __n;
s = __src + __n;
while (__n--)
*--d = *--s;
return __dest;
}
static void error(char *x)
{
unsigned long long psw = 0x000a0000deadbeefULL;
puts("\n\n");
puts(x);
puts("\n\n -- System halted");
asm volatile("lpsw %0" : : "Q" (psw));
}
/*
* Safe guard the ipl parameter block against a memory area that will be
* overwritten. The validity check for the ipl parameter block is complex
* (see cio_get_iplinfo and ipl_save_parameters) but if the pointer to
* the ipl parameter block intersects with the passed memory area we can
* safely assume that we can read from that memory. In that case just copy
* the memory to IPL_PARMBLOCK_ORIGIN even if there is no ipl parameter
* block.
*/
static void check_ipl_parmblock(void *start, unsigned long size)
{
void *src, *dst;
src = (void *)(unsigned long) S390_lowcore.ipl_parmblock_ptr;
if (src + PAGE_SIZE <= start || src >= start + size)
return;
dst = (void *) IPL_PARMBLOCK_ORIGIN;
memmove(dst, src, PAGE_SIZE);
S390_lowcore.ipl_parmblock_ptr = IPL_PARMBLOCK_ORIGIN;
}
unsigned long decompress_kernel(void)
{
unsigned long output_addr;
unsigned char *output;
output_addr = ((unsigned long) &_end + HEAP_SIZE + 4095UL) & -4096UL;
check_ipl_parmblock((void *) 0, output_addr + SZ__bss_start);
memset(&_bss, 0, &_ebss - &_bss);
free_mem_ptr = (unsigned long)&_end;
free_mem_end_ptr = free_mem_ptr + HEAP_SIZE;
output = (unsigned char *) output_addr;
#ifdef CONFIG_BLK_DEV_INITRD
/*
* Move the initrd right behind the end of the decompressed
* kernel image.
*/
if (INITRD_START && INITRD_SIZE &&
INITRD_START < (unsigned long) output + SZ__bss_start) {
check_ipl_parmblock(output + SZ__bss_start,
INITRD_START + INITRD_SIZE);
memmove(output + SZ__bss_start,
(void *) INITRD_START, INITRD_SIZE);
INITRD_START = (unsigned long) output + SZ__bss_start;
}
#endif
puts("Uncompressing Linux... ");
decompress(input_data, input_len, NULL, NULL, output, NULL, error);
puts("Ok, booting the kernel.\n");
return (unsigned long) output;
}
| gpl-2.0 |
xDARKMATT3Rx/xDARKMATT3Rx_davidskernel | drivers/pci/pcie/aer/aerdrv_core.c | 3494 | 22680 | /*
* drivers/pci/pcie/aer/aerdrv_core.c
*
* 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.
*
* This file implements the core part of PCI-Express AER. When an pci-express
* error is delivered, an error message will be collected and printed to
* console, then, an error recovery procedure will be executed by following
* the pci error recovery rules.
*
* Copyright (C) 2006 Intel Corp.
* Tom Long Nguyen (tom.l.nguyen@intel.com)
* Zhang Yanmin (yanmin.zhang@intel.com)
*
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/pm.h>
#include <linux/suspend.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/kfifo.h>
#include "aerdrv.h"
static bool forceload;
static bool nosourceid;
module_param(forceload, bool, 0);
module_param(nosourceid, bool, 0);
int pci_enable_pcie_error_reporting(struct pci_dev *dev)
{
u16 reg16 = 0;
int pos;
if (pcie_aer_get_firmware_first(dev))
return -EIO;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return -EIO;
pos = pci_pcie_cap(dev);
if (!pos)
return -EIO;
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
reg16 |= (PCI_EXP_DEVCTL_CERE |
PCI_EXP_DEVCTL_NFERE |
PCI_EXP_DEVCTL_FERE |
PCI_EXP_DEVCTL_URRE);
pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, reg16);
return 0;
}
EXPORT_SYMBOL_GPL(pci_enable_pcie_error_reporting);
int pci_disable_pcie_error_reporting(struct pci_dev *dev)
{
u16 reg16 = 0;
int pos;
if (pcie_aer_get_firmware_first(dev))
return -EIO;
pos = pci_pcie_cap(dev);
if (!pos)
return -EIO;
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
reg16 &= ~(PCI_EXP_DEVCTL_CERE |
PCI_EXP_DEVCTL_NFERE |
PCI_EXP_DEVCTL_FERE |
PCI_EXP_DEVCTL_URRE);
pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, reg16);
return 0;
}
EXPORT_SYMBOL_GPL(pci_disable_pcie_error_reporting);
int pci_cleanup_aer_uncorrect_error_status(struct pci_dev *dev)
{
int pos;
u32 status;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return -EIO;
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
if (status)
pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status);
return 0;
}
EXPORT_SYMBOL_GPL(pci_cleanup_aer_uncorrect_error_status);
/**
* add_error_device - list device to be handled
* @e_info: pointer to error info
* @dev: pointer to pci_dev to be added
*/
static int add_error_device(struct aer_err_info *e_info, struct pci_dev *dev)
{
if (e_info->error_dev_num < AER_MAX_MULTI_ERR_DEVICES) {
e_info->dev[e_info->error_dev_num] = dev;
e_info->error_dev_num++;
return 0;
}
return -ENOSPC;
}
#define PCI_BUS(x) (((x) >> 8) & 0xff)
/**
* is_error_source - check whether the device is source of reported error
* @dev: pointer to pci_dev to be checked
* @e_info: pointer to reported error info
*/
static bool is_error_source(struct pci_dev *dev, struct aer_err_info *e_info)
{
int pos;
u32 status, mask;
u16 reg16;
/*
* When bus id is equal to 0, it might be a bad id
* reported by root port.
*/
if (!nosourceid && (PCI_BUS(e_info->id) != 0)) {
/* Device ID match? */
if (e_info->id == ((dev->bus->number << 8) | dev->devfn))
return true;
/* Continue id comparing if there is no multiple error */
if (!e_info->multi_error_valid)
return false;
}
/*
* When either
* 1) nosourceid==y;
* 2) bus id is equal to 0. Some ports might lose the bus
* id of error source id;
* 3) There are multiple errors and prior id comparing fails;
* We check AER status registers to find possible reporter.
*/
if (atomic_read(&dev->enable_cnt) == 0)
return false;
pos = pci_pcie_cap(dev);
if (!pos)
return false;
/* Check if AER is enabled */
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
if (!(reg16 & (
PCI_EXP_DEVCTL_CERE |
PCI_EXP_DEVCTL_NFERE |
PCI_EXP_DEVCTL_FERE |
PCI_EXP_DEVCTL_URRE)))
return false;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return false;
/* Check if error is recorded */
if (e_info->severity == AER_CORRECTABLE) {
pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS, &status);
pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK, &mask);
} else {
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, &mask);
}
if (status & ~mask)
return true;
return false;
}
static int find_device_iter(struct pci_dev *dev, void *data)
{
struct aer_err_info *e_info = (struct aer_err_info *)data;
if (is_error_source(dev, e_info)) {
/* List this device */
if (add_error_device(e_info, dev)) {
/* We cannot handle more... Stop iteration */
/* TODO: Should print error message here? */
return 1;
}
/* If there is only a single error, stop iteration */
if (!e_info->multi_error_valid)
return 1;
}
return 0;
}
/**
* find_source_device - search through device hierarchy for source device
* @parent: pointer to Root Port pci_dev data structure
* @e_info: including detailed error information such like id
*
* Return true if found.
*
* Invoked by DPC when error is detected at the Root Port.
* Caller of this function must set id, severity, and multi_error_valid of
* struct aer_err_info pointed by @e_info properly. This function must fill
* e_info->error_dev_num and e_info->dev[], based on the given information.
*/
static bool find_source_device(struct pci_dev *parent,
struct aer_err_info *e_info)
{
struct pci_dev *dev = parent;
int result;
/* Must reset in this function */
e_info->error_dev_num = 0;
/* Is Root Port an agent that sends error message? */
result = find_device_iter(dev, e_info);
if (result)
return true;
pci_walk_bus(parent->subordinate, find_device_iter, e_info);
if (!e_info->error_dev_num) {
dev_printk(KERN_DEBUG, &parent->dev,
"can't find device of ID%04x\n",
e_info->id);
return false;
}
return true;
}
static int report_error_detected(struct pci_dev *dev, void *data)
{
pci_ers_result_t vote;
struct pci_error_handlers *err_handler;
struct aer_broadcast_data *result_data;
result_data = (struct aer_broadcast_data *) data;
dev->error_state = result_data->state;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->error_detected) {
if (result_data->state == pci_channel_io_frozen &&
!(dev->hdr_type & PCI_HEADER_TYPE_BRIDGE)) {
/*
* In case of fatal recovery, if one of down-
* stream device has no driver. We might be
* unable to recover because a later insmod
* of a driver for this device is unaware of
* its hw state.
*/
dev_printk(KERN_DEBUG, &dev->dev, "device has %s\n",
dev->driver ?
"no AER-aware driver" : "no driver");
}
return 0;
}
err_handler = dev->driver->err_handler;
vote = err_handler->error_detected(dev, result_data->state);
result_data->result = merge_result(result_data->result, vote);
return 0;
}
static int report_mmio_enabled(struct pci_dev *dev, void *data)
{
pci_ers_result_t vote;
struct pci_error_handlers *err_handler;
struct aer_broadcast_data *result_data;
result_data = (struct aer_broadcast_data *) data;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->mmio_enabled)
return 0;
err_handler = dev->driver->err_handler;
vote = err_handler->mmio_enabled(dev);
result_data->result = merge_result(result_data->result, vote);
return 0;
}
static int report_slot_reset(struct pci_dev *dev, void *data)
{
pci_ers_result_t vote;
struct pci_error_handlers *err_handler;
struct aer_broadcast_data *result_data;
result_data = (struct aer_broadcast_data *) data;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->slot_reset)
return 0;
err_handler = dev->driver->err_handler;
vote = err_handler->slot_reset(dev);
result_data->result = merge_result(result_data->result, vote);
return 0;
}
static int report_resume(struct pci_dev *dev, void *data)
{
struct pci_error_handlers *err_handler;
dev->error_state = pci_channel_io_normal;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->resume)
return 0;
err_handler = dev->driver->err_handler;
err_handler->resume(dev);
return 0;
}
/**
* broadcast_error_message - handle message broadcast to downstream drivers
* @dev: pointer to from where in a hierarchy message is broadcasted down
* @state: error state
* @error_mesg: message to print
* @cb: callback to be broadcasted
*
* Invoked during error recovery process. Once being invoked, the content
* of error severity will be broadcasted to all downstream drivers in a
* hierarchy in question.
*/
static pci_ers_result_t broadcast_error_message(struct pci_dev *dev,
enum pci_channel_state state,
char *error_mesg,
int (*cb)(struct pci_dev *, void *))
{
struct aer_broadcast_data result_data;
dev_printk(KERN_DEBUG, &dev->dev, "broadcast %s message\n", error_mesg);
result_data.state = state;
if (cb == report_error_detected)
result_data.result = PCI_ERS_RESULT_CAN_RECOVER;
else
result_data.result = PCI_ERS_RESULT_RECOVERED;
if (dev->hdr_type & PCI_HEADER_TYPE_BRIDGE) {
/*
* If the error is reported by a bridge, we think this error
* is related to the downstream link of the bridge, so we
* do error recovery on all subordinates of the bridge instead
* of the bridge and clear the error status of the bridge.
*/
if (cb == report_error_detected)
dev->error_state = state;
pci_walk_bus(dev->subordinate, cb, &result_data);
if (cb == report_resume) {
pci_cleanup_aer_uncorrect_error_status(dev);
dev->error_state = pci_channel_io_normal;
}
} else {
/*
* If the error is reported by an end point, we think this
* error is related to the upstream link of the end point.
*/
pci_walk_bus(dev->bus, cb, &result_data);
}
return result_data.result;
}
/**
* aer_do_secondary_bus_reset - perform secondary bus reset
* @dev: pointer to bridge's pci_dev data structure
*
* Invoked when performing link reset at Root Port or Downstream Port.
*/
void aer_do_secondary_bus_reset(struct pci_dev *dev)
{
u16 p2p_ctrl;
/* Assert Secondary Bus Reset */
pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &p2p_ctrl);
p2p_ctrl |= PCI_BRIDGE_CTL_BUS_RESET;
pci_write_config_word(dev, PCI_BRIDGE_CONTROL, p2p_ctrl);
/*
* we should send hot reset message for 2ms to allow it time to
* propagate to all downstream ports
*/
msleep(2);
/* De-assert Secondary Bus Reset */
p2p_ctrl &= ~PCI_BRIDGE_CTL_BUS_RESET;
pci_write_config_word(dev, PCI_BRIDGE_CONTROL, p2p_ctrl);
/*
* System software must wait for at least 100ms from the end
* of a reset of one or more device before it is permitted
* to issue Configuration Requests to those devices.
*/
msleep(200);
}
/**
* default_downstream_reset_link - default reset function for Downstream Port
* @dev: pointer to downstream port's pci_dev data structure
*
* Invoked when performing link reset at Downstream Port w/ no aer driver.
*/
static pci_ers_result_t default_downstream_reset_link(struct pci_dev *dev)
{
aer_do_secondary_bus_reset(dev);
dev_printk(KERN_DEBUG, &dev->dev,
"Downstream Port link has been reset\n");
return PCI_ERS_RESULT_RECOVERED;
}
static int find_aer_service_iter(struct device *device, void *data)
{
struct pcie_port_service_driver *service_driver, **drv;
drv = (struct pcie_port_service_driver **) data;
if (device->bus == &pcie_port_bus_type && device->driver) {
service_driver = to_service_driver(device->driver);
if (service_driver->service == PCIE_PORT_SERVICE_AER) {
*drv = service_driver;
return 1;
}
}
return 0;
}
static struct pcie_port_service_driver *find_aer_service(struct pci_dev *dev)
{
struct pcie_port_service_driver *drv = NULL;
device_for_each_child(&dev->dev, &drv, find_aer_service_iter);
return drv;
}
static pci_ers_result_t reset_link(struct pci_dev *dev)
{
struct pci_dev *udev;
pci_ers_result_t status;
struct pcie_port_service_driver *driver;
if (dev->hdr_type & PCI_HEADER_TYPE_BRIDGE) {
/* Reset this port for all subordinates */
udev = dev;
} else {
/* Reset the upstream component (likely downstream port) */
udev = dev->bus->self;
}
/* Use the aer driver of the component firstly */
driver = find_aer_service(udev);
if (driver && driver->reset_link) {
status = driver->reset_link(udev);
} else if (udev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM) {
status = default_downstream_reset_link(udev);
} else {
dev_printk(KERN_DEBUG, &dev->dev,
"no link-reset support at upstream device %s\n",
pci_name(udev));
return PCI_ERS_RESULT_DISCONNECT;
}
if (status != PCI_ERS_RESULT_RECOVERED) {
dev_printk(KERN_DEBUG, &dev->dev,
"link reset at upstream device %s failed\n",
pci_name(udev));
return PCI_ERS_RESULT_DISCONNECT;
}
return status;
}
/**
* do_recovery - handle nonfatal/fatal error recovery process
* @dev: pointer to a pci_dev data structure of agent detecting an error
* @severity: error severity type
*
* Invoked when an error is nonfatal/fatal. Once being invoked, broadcast
* error detected message to all downstream drivers within a hierarchy in
* question and return the returned code.
*/
static void do_recovery(struct pci_dev *dev, int severity)
{
pci_ers_result_t status, result = PCI_ERS_RESULT_RECOVERED;
enum pci_channel_state state;
if (severity == AER_FATAL)
state = pci_channel_io_frozen;
else
state = pci_channel_io_normal;
status = broadcast_error_message(dev,
state,
"error_detected",
report_error_detected);
if (severity == AER_FATAL) {
result = reset_link(dev);
if (result != PCI_ERS_RESULT_RECOVERED)
goto failed;
}
if (status == PCI_ERS_RESULT_CAN_RECOVER)
status = broadcast_error_message(dev,
state,
"mmio_enabled",
report_mmio_enabled);
if (status == PCI_ERS_RESULT_NEED_RESET) {
/*
* TODO: Should call platform-specific
* functions to reset slot before calling
* drivers' slot_reset callbacks?
*/
status = broadcast_error_message(dev,
state,
"slot_reset",
report_slot_reset);
}
if (status != PCI_ERS_RESULT_RECOVERED)
goto failed;
broadcast_error_message(dev,
state,
"resume",
report_resume);
dev_printk(KERN_DEBUG, &dev->dev,
"AER driver successfully recovered\n");
return;
failed:
/* TODO: Should kernel panic here? */
dev_printk(KERN_DEBUG, &dev->dev,
"AER driver didn't recover\n");
}
/**
* handle_error_source - handle logging error into an event log
* @aerdev: pointer to pcie_device data structure of the root port
* @dev: pointer to pci_dev data structure of error source device
* @info: comprehensive error information
*
* Invoked when an error being detected by Root Port.
*/
static void handle_error_source(struct pcie_device *aerdev,
struct pci_dev *dev,
struct aer_err_info *info)
{
int pos;
if (info->severity == AER_CORRECTABLE) {
/*
* Correctable error does not need software intevention.
* No need to go through error recovery process.
*/
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (pos)
pci_write_config_dword(dev, pos + PCI_ERR_COR_STATUS,
info->status);
} else
do_recovery(dev, info->severity);
}
#ifdef CONFIG_ACPI_APEI_PCIEAER
static void aer_recover_work_func(struct work_struct *work);
#define AER_RECOVER_RING_ORDER 4
#define AER_RECOVER_RING_SIZE (1 << AER_RECOVER_RING_ORDER)
struct aer_recover_entry
{
u8 bus;
u8 devfn;
u16 domain;
int severity;
};
static DEFINE_KFIFO(aer_recover_ring, struct aer_recover_entry,
AER_RECOVER_RING_SIZE);
/*
* Mutual exclusion for writers of aer_recover_ring, reader side don't
* need lock, because there is only one reader and lock is not needed
* between reader and writer.
*/
static DEFINE_SPINLOCK(aer_recover_ring_lock);
static DECLARE_WORK(aer_recover_work, aer_recover_work_func);
void aer_recover_queue(int domain, unsigned int bus, unsigned int devfn,
int severity)
{
unsigned long flags;
struct aer_recover_entry entry = {
.bus = bus,
.devfn = devfn,
.domain = domain,
.severity = severity,
};
spin_lock_irqsave(&aer_recover_ring_lock, flags);
if (kfifo_put(&aer_recover_ring, &entry))
schedule_work(&aer_recover_work);
else
pr_err("AER recover: Buffer overflow when recovering AER for %04x:%02x:%02x:%x\n",
domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
spin_unlock_irqrestore(&aer_recover_ring_lock, flags);
}
EXPORT_SYMBOL_GPL(aer_recover_queue);
static void aer_recover_work_func(struct work_struct *work)
{
struct aer_recover_entry entry;
struct pci_dev *pdev;
while (kfifo_get(&aer_recover_ring, &entry)) {
pdev = pci_get_domain_bus_and_slot(entry.domain, entry.bus,
entry.devfn);
if (!pdev) {
pr_err("AER recover: Can not find pci_dev for %04x:%02x:%02x:%x\n",
entry.domain, entry.bus,
PCI_SLOT(entry.devfn), PCI_FUNC(entry.devfn));
continue;
}
do_recovery(pdev, entry.severity);
}
}
#endif
/**
* get_device_error_info - read error status from dev and store it to info
* @dev: pointer to the device expected to have a error record
* @info: pointer to structure to store the error record
*
* Return 1 on success, 0 on error.
*
* Note that @info is reused among all error devices. Clear fields properly.
*/
static int get_device_error_info(struct pci_dev *dev, struct aer_err_info *info)
{
int pos, temp;
/* Must reset in this function */
info->status = 0;
info->tlp_header_valid = 0;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
/* The device might not support AER */
if (!pos)
return 1;
if (info->severity == AER_CORRECTABLE) {
pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS,
&info->status);
pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK,
&info->mask);
if (!(info->status & ~info->mask))
return 0;
} else if (dev->hdr_type & PCI_HEADER_TYPE_BRIDGE ||
info->severity == AER_NONFATAL) {
/* Link is still healthy for IO reads */
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS,
&info->status);
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK,
&info->mask);
if (!(info->status & ~info->mask))
return 0;
/* Get First Error Pointer */
pci_read_config_dword(dev, pos + PCI_ERR_CAP, &temp);
info->first_error = PCI_ERR_CAP_FEP(temp);
if (info->status & AER_LOG_TLP_MASKS) {
info->tlp_header_valid = 1;
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG, &info->tlp.dw0);
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG + 4, &info->tlp.dw1);
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG + 8, &info->tlp.dw2);
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG + 12, &info->tlp.dw3);
}
}
return 1;
}
static inline void aer_process_err_devices(struct pcie_device *p_device,
struct aer_err_info *e_info)
{
int i;
/* Report all before handle them, not to lost records by reset etc. */
for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) {
if (get_device_error_info(e_info->dev[i], e_info))
aer_print_error(e_info->dev[i], e_info);
}
for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) {
if (get_device_error_info(e_info->dev[i], e_info))
handle_error_source(p_device, e_info->dev[i], e_info);
}
}
/**
* aer_isr_one_error - consume an error detected by root port
* @p_device: pointer to error root port service device
* @e_src: pointer to an error source
*/
static void aer_isr_one_error(struct pcie_device *p_device,
struct aer_err_source *e_src)
{
struct aer_err_info *e_info;
/* struct aer_err_info might be big, so we allocate it with slab */
e_info = kmalloc(sizeof(struct aer_err_info), GFP_KERNEL);
if (!e_info) {
dev_printk(KERN_DEBUG, &p_device->port->dev,
"Can't allocate mem when processing AER errors\n");
return;
}
/*
* There is a possibility that both correctable error and
* uncorrectable error being logged. Report correctable error first.
*/
if (e_src->status & PCI_ERR_ROOT_COR_RCV) {
e_info->id = ERR_COR_ID(e_src->id);
e_info->severity = AER_CORRECTABLE;
if (e_src->status & PCI_ERR_ROOT_MULTI_COR_RCV)
e_info->multi_error_valid = 1;
else
e_info->multi_error_valid = 0;
aer_print_port_info(p_device->port, e_info);
if (find_source_device(p_device->port, e_info))
aer_process_err_devices(p_device, e_info);
}
if (e_src->status & PCI_ERR_ROOT_UNCOR_RCV) {
e_info->id = ERR_UNCOR_ID(e_src->id);
if (e_src->status & PCI_ERR_ROOT_FATAL_RCV)
e_info->severity = AER_FATAL;
else
e_info->severity = AER_NONFATAL;
if (e_src->status & PCI_ERR_ROOT_MULTI_UNCOR_RCV)
e_info->multi_error_valid = 1;
else
e_info->multi_error_valid = 0;
aer_print_port_info(p_device->port, e_info);
if (find_source_device(p_device->port, e_info))
aer_process_err_devices(p_device, e_info);
}
kfree(e_info);
}
/**
* get_e_source - retrieve an error source
* @rpc: pointer to the root port which holds an error
* @e_src: pointer to store retrieved error source
*
* Return 1 if an error source is retrieved, otherwise 0.
*
* Invoked by DPC handler to consume an error.
*/
static int get_e_source(struct aer_rpc *rpc, struct aer_err_source *e_src)
{
unsigned long flags;
/* Lock access to Root error producer/consumer index */
spin_lock_irqsave(&rpc->e_lock, flags);
if (rpc->prod_idx == rpc->cons_idx) {
spin_unlock_irqrestore(&rpc->e_lock, flags);
return 0;
}
*e_src = rpc->e_sources[rpc->cons_idx];
rpc->cons_idx++;
if (rpc->cons_idx == AER_ERROR_SOURCES_MAX)
rpc->cons_idx = 0;
spin_unlock_irqrestore(&rpc->e_lock, flags);
return 1;
}
/**
* aer_isr - consume errors detected by root port
* @work: definition of this work item
*
* Invoked, as DPC, when root port records new detected error
*/
void aer_isr(struct work_struct *work)
{
struct aer_rpc *rpc = container_of(work, struct aer_rpc, dpc_handler);
struct pcie_device *p_device = rpc->rpd;
struct aer_err_source uninitialized_var(e_src);
mutex_lock(&rpc->rpc_mutex);
while (get_e_source(rpc, &e_src))
aer_isr_one_error(p_device, &e_src);
mutex_unlock(&rpc->rpc_mutex);
wake_up(&rpc->wait_release);
}
/**
* aer_init - provide AER initialization
* @dev: pointer to AER pcie device
*
* Invoked when AER service driver is loaded.
*/
int aer_init(struct pcie_device *dev)
{
if (forceload) {
dev_printk(KERN_DEBUG, &dev->device,
"aerdrv forceload requested.\n");
pcie_aer_force_firmware_first(dev->port, 0);
}
return 0;
}
| gpl-2.0 |
shouhu1993/NX511J_kernel | tools/perf/ui/helpline.c | 4262 | 1192 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../debug.h"
#include "helpline.h"
#include "ui.h"
char ui_helpline__current[512];
static void nop_helpline__pop(void)
{
}
static void nop_helpline__push(const char *msg __maybe_unused)
{
}
static int nop_helpline__show(const char *fmt __maybe_unused,
va_list ap __maybe_unused)
{
return 0;
}
static struct ui_helpline default_helpline_fns = {
.pop = nop_helpline__pop,
.push = nop_helpline__push,
.show = nop_helpline__show,
};
struct ui_helpline *helpline_fns = &default_helpline_fns;
void ui_helpline__pop(void)
{
helpline_fns->pop();
}
void ui_helpline__push(const char *msg)
{
helpline_fns->push(msg);
}
void ui_helpline__vpush(const char *fmt, va_list ap)
{
char *s;
if (vasprintf(&s, fmt, ap) < 0)
vfprintf(stderr, fmt, ap);
else {
ui_helpline__push(s);
free(s);
}
}
void ui_helpline__fpush(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
ui_helpline__vpush(fmt, ap);
va_end(ap);
}
void ui_helpline__puts(const char *msg)
{
ui_helpline__pop();
ui_helpline__push(msg);
}
int ui_helpline__vshow(const char *fmt, va_list ap)
{
return helpline_fns->show(fmt, ap);
}
| gpl-2.0 |
drewx2/caf-kernel | drivers/media/video/videobuf-core.c | 4262 | 27390 | /*
* generic helper functions for handling video4linux capture buffers
*
* (c) 2007 Mauro Carvalho Chehab, <mchehab@infradead.org>
*
* Highly based on video-buf written originally by:
* (c) 2001,02 Gerd Knorr <kraxel@bytesex.org>
* (c) 2006 Mauro Carvalho Chehab, <mchehab@infradead.org>
* (c) 2006 Ted Walther and John Sokol
*
* 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
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <media/videobuf-core.h>
#define MAGIC_BUFFER 0x20070728
#define MAGIC_CHECK(is, should) \
do { \
if (unlikely((is) != (should))) { \
printk(KERN_ERR \
"magic mismatch: %x (expected %x)\n", \
is, should); \
BUG(); \
} \
} while (0)
static int debug;
module_param(debug, int, 0644);
MODULE_DESCRIPTION("helper module to manage video4linux buffers");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
MODULE_LICENSE("GPL");
#define dprintk(level, fmt, arg...) \
do { \
if (debug >= level) \
printk(KERN_DEBUG "vbuf: " fmt, ## arg); \
} while (0)
/* --------------------------------------------------------------------- */
#define CALL(q, f, arg...) \
((q->int_ops->f) ? q->int_ops->f(arg) : 0)
struct videobuf_buffer *videobuf_alloc_vb(struct videobuf_queue *q)
{
struct videobuf_buffer *vb;
BUG_ON(q->msize < sizeof(*vb));
if (!q->int_ops || !q->int_ops->alloc_vb) {
printk(KERN_ERR "No specific ops defined!\n");
BUG();
}
vb = q->int_ops->alloc_vb(q->msize);
if (NULL != vb) {
init_waitqueue_head(&vb->done);
vb->magic = MAGIC_BUFFER;
}
return vb;
}
EXPORT_SYMBOL_GPL(videobuf_alloc_vb);
static int is_state_active_or_queued(struct videobuf_queue *q, struct videobuf_buffer *vb)
{
unsigned long flags;
bool rc;
spin_lock_irqsave(q->irqlock, flags);
rc = vb->state != VIDEOBUF_ACTIVE && vb->state != VIDEOBUF_QUEUED;
spin_unlock_irqrestore(q->irqlock, flags);
return rc;
};
int videobuf_waiton(struct videobuf_queue *q, struct videobuf_buffer *vb,
int non_blocking, int intr)
{
bool is_ext_locked;
int ret = 0;
MAGIC_CHECK(vb->magic, MAGIC_BUFFER);
if (non_blocking) {
if (is_state_active_or_queued(q, vb))
return 0;
return -EAGAIN;
}
is_ext_locked = q->ext_lock && mutex_is_locked(q->ext_lock);
/* Release vdev lock to prevent this wait from blocking outside access to
the device. */
if (is_ext_locked)
mutex_unlock(q->ext_lock);
if (intr)
ret = wait_event_interruptible(vb->done, is_state_active_or_queued(q, vb));
else
wait_event(vb->done, is_state_active_or_queued(q, vb));
/* Relock */
if (is_ext_locked)
mutex_lock(q->ext_lock);
return ret;
}
EXPORT_SYMBOL_GPL(videobuf_waiton);
int videobuf_iolock(struct videobuf_queue *q, struct videobuf_buffer *vb,
struct v4l2_framebuffer *fbuf)
{
MAGIC_CHECK(vb->magic, MAGIC_BUFFER);
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
return CALL(q, iolock, q, vb, fbuf);
}
EXPORT_SYMBOL_GPL(videobuf_iolock);
void *videobuf_queue_to_vaddr(struct videobuf_queue *q,
struct videobuf_buffer *buf)
{
if (q->int_ops->vaddr)
return q->int_ops->vaddr(buf);
return NULL;
}
EXPORT_SYMBOL_GPL(videobuf_queue_to_vaddr);
/* --------------------------------------------------------------------- */
void videobuf_queue_core_init(struct videobuf_queue *q,
const struct videobuf_queue_ops *ops,
struct device *dev,
spinlock_t *irqlock,
enum v4l2_buf_type type,
enum v4l2_field field,
unsigned int msize,
void *priv,
struct videobuf_qtype_ops *int_ops,
struct mutex *ext_lock)
{
BUG_ON(!q);
memset(q, 0, sizeof(*q));
q->irqlock = irqlock;
q->ext_lock = ext_lock;
q->dev = dev;
q->type = type;
q->field = field;
q->msize = msize;
q->ops = ops;
q->priv_data = priv;
q->int_ops = int_ops;
/* All buffer operations are mandatory */
BUG_ON(!q->ops->buf_setup);
BUG_ON(!q->ops->buf_prepare);
BUG_ON(!q->ops->buf_queue);
BUG_ON(!q->ops->buf_release);
/* Lock is mandatory for queue_cancel to work */
BUG_ON(!irqlock);
/* Having implementations for abstract methods are mandatory */
BUG_ON(!q->int_ops);
mutex_init(&q->vb_lock);
init_waitqueue_head(&q->wait);
INIT_LIST_HEAD(&q->stream);
}
EXPORT_SYMBOL_GPL(videobuf_queue_core_init);
/* Locking: Only usage in bttv unsafe find way to remove */
int videobuf_queue_is_busy(struct videobuf_queue *q)
{
int i;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
if (q->streaming) {
dprintk(1, "busy: streaming active\n");
return 1;
}
if (q->reading) {
dprintk(1, "busy: pending read #1\n");
return 1;
}
if (q->read_buf) {
dprintk(1, "busy: pending read #2\n");
return 1;
}
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map) {
dprintk(1, "busy: buffer #%d mapped\n", i);
return 1;
}
if (q->bufs[i]->state == VIDEOBUF_QUEUED) {
dprintk(1, "busy: buffer #%d queued\n", i);
return 1;
}
if (q->bufs[i]->state == VIDEOBUF_ACTIVE) {
dprintk(1, "busy: buffer #%d avtive\n", i);
return 1;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(videobuf_queue_is_busy);
/**
* __videobuf_free() - free all the buffers and their control structures
*
* This function can only be called if streaming/reading is off, i.e. no buffers
* are under control of the driver.
*/
/* Locking: Caller holds q->vb_lock */
static int __videobuf_free(struct videobuf_queue *q)
{
int i;
dprintk(1, "%s\n", __func__);
if (!q)
return 0;
if (q->streaming || q->reading) {
dprintk(1, "Cannot free buffers when streaming or reading\n");
return -EBUSY;
}
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
for (i = 0; i < VIDEO_MAX_FRAME; i++)
if (q->bufs[i] && q->bufs[i]->map) {
dprintk(1, "Cannot free mmapped buffers\n");
return -EBUSY;
}
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
q->ops->buf_release(q, q->bufs[i]);
kfree(q->bufs[i]);
q->bufs[i] = NULL;
}
return 0;
}
/* Locking: Caller holds q->vb_lock */
void videobuf_queue_cancel(struct videobuf_queue *q)
{
unsigned long flags = 0;
int i;
q->streaming = 0;
q->reading = 0;
wake_up_interruptible_sync(&q->wait);
/* remove queued buffers from list */
spin_lock_irqsave(q->irqlock, flags);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->state == VIDEOBUF_QUEUED) {
list_del(&q->bufs[i]->queue);
q->bufs[i]->state = VIDEOBUF_ERROR;
wake_up_all(&q->bufs[i]->done);
}
}
spin_unlock_irqrestore(q->irqlock, flags);
/* free all buffers + clear queue */
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
q->ops->buf_release(q, q->bufs[i]);
}
INIT_LIST_HEAD(&q->stream);
}
EXPORT_SYMBOL_GPL(videobuf_queue_cancel);
/* --------------------------------------------------------------------- */
/* Locking: Caller holds q->vb_lock */
enum v4l2_field videobuf_next_field(struct videobuf_queue *q)
{
enum v4l2_field field = q->field;
BUG_ON(V4L2_FIELD_ANY == field);
if (V4L2_FIELD_ALTERNATE == field) {
if (V4L2_FIELD_TOP == q->last) {
field = V4L2_FIELD_BOTTOM;
q->last = V4L2_FIELD_BOTTOM;
} else {
field = V4L2_FIELD_TOP;
q->last = V4L2_FIELD_TOP;
}
}
return field;
}
EXPORT_SYMBOL_GPL(videobuf_next_field);
/* Locking: Caller holds q->vb_lock */
static void videobuf_status(struct videobuf_queue *q, struct v4l2_buffer *b,
struct videobuf_buffer *vb, enum v4l2_buf_type type)
{
MAGIC_CHECK(vb->magic, MAGIC_BUFFER);
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
b->index = vb->i;
b->type = type;
b->memory = vb->memory;
switch (b->memory) {
case V4L2_MEMORY_MMAP:
b->m.offset = vb->boff;
b->length = vb->bsize;
break;
case V4L2_MEMORY_USERPTR:
b->m.userptr = vb->baddr;
b->reserved = vb->boff;
b->length = vb->bsize;
break;
case V4L2_MEMORY_OVERLAY:
b->m.offset = vb->boff;
break;
}
b->flags = 0;
if (vb->map)
b->flags |= V4L2_BUF_FLAG_MAPPED;
switch (vb->state) {
case VIDEOBUF_PREPARED:
case VIDEOBUF_QUEUED:
case VIDEOBUF_ACTIVE:
b->flags |= V4L2_BUF_FLAG_QUEUED;
break;
case VIDEOBUF_ERROR:
b->flags |= V4L2_BUF_FLAG_ERROR;
/* fall through */
case VIDEOBUF_DONE:
b->flags |= V4L2_BUF_FLAG_DONE;
break;
case VIDEOBUF_NEEDS_INIT:
case VIDEOBUF_IDLE:
/* nothing */
break;
}
if (vb->input != UNSET) {
b->flags |= V4L2_BUF_FLAG_INPUT;
b->input = vb->input;
}
b->field = vb->field;
b->timestamp = vb->ts;
b->bytesused = vb->size;
b->sequence = vb->field_count >> 1;
}
int videobuf_mmap_free(struct videobuf_queue *q)
{
int ret;
videobuf_queue_lock(q);
ret = __videobuf_free(q);
videobuf_queue_unlock(q);
return ret;
}
EXPORT_SYMBOL_GPL(videobuf_mmap_free);
/* Locking: Caller holds q->vb_lock */
int __videobuf_mmap_setup(struct videobuf_queue *q,
unsigned int bcount, unsigned int bsize,
enum v4l2_memory memory)
{
unsigned int i;
int err;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
err = __videobuf_free(q);
if (0 != err)
return err;
/* Allocate and initialize buffers */
for (i = 0; i < bcount; i++) {
q->bufs[i] = videobuf_alloc_vb(q);
if (NULL == q->bufs[i])
break;
q->bufs[i]->i = i;
q->bufs[i]->input = UNSET;
q->bufs[i]->memory = memory;
q->bufs[i]->bsize = bsize;
switch (memory) {
case V4L2_MEMORY_MMAP:
q->bufs[i]->boff = PAGE_ALIGN(bsize) * i;
break;
case V4L2_MEMORY_USERPTR:
case V4L2_MEMORY_OVERLAY:
/* nothing */
break;
}
}
if (!i)
return -ENOMEM;
dprintk(1, "mmap setup: %d buffers, %d bytes each\n", i, bsize);
return i;
}
EXPORT_SYMBOL_GPL(__videobuf_mmap_setup);
int videobuf_mmap_setup(struct videobuf_queue *q,
unsigned int bcount, unsigned int bsize,
enum v4l2_memory memory)
{
int ret;
videobuf_queue_lock(q);
ret = __videobuf_mmap_setup(q, bcount, bsize, memory);
videobuf_queue_unlock(q);
return ret;
}
EXPORT_SYMBOL_GPL(videobuf_mmap_setup);
int videobuf_reqbufs(struct videobuf_queue *q,
struct v4l2_requestbuffers *req)
{
unsigned int size, count;
int retval;
if (req->count < 1) {
dprintk(1, "reqbufs: count invalid (%d)\n", req->count);
return -EINVAL;
}
if (req->memory != V4L2_MEMORY_MMAP &&
req->memory != V4L2_MEMORY_USERPTR &&
req->memory != V4L2_MEMORY_OVERLAY) {
dprintk(1, "reqbufs: memory type invalid\n");
return -EINVAL;
}
videobuf_queue_lock(q);
if (req->type != q->type) {
dprintk(1, "reqbufs: queue type invalid\n");
retval = -EINVAL;
goto done;
}
if (q->streaming) {
dprintk(1, "reqbufs: streaming already exists\n");
retval = -EBUSY;
goto done;
}
if (!list_empty(&q->stream)) {
dprintk(1, "reqbufs: stream running\n");
retval = -EBUSY;
goto done;
}
count = req->count;
if (count > VIDEO_MAX_FRAME)
count = VIDEO_MAX_FRAME;
size = 0;
q->ops->buf_setup(q, &count, &size);
dprintk(1, "reqbufs: bufs=%d, size=0x%x [%u pages total]\n",
count, size,
(unsigned int)((count * PAGE_ALIGN(size)) >> PAGE_SHIFT));
retval = __videobuf_mmap_setup(q, count, size, req->memory);
if (retval < 0) {
dprintk(1, "reqbufs: mmap setup returned %d\n", retval);
goto done;
}
req->count = retval;
retval = 0;
done:
videobuf_queue_unlock(q);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_reqbufs);
int videobuf_querybuf(struct videobuf_queue *q, struct v4l2_buffer *b)
{
int ret = -EINVAL;
videobuf_queue_lock(q);
if (unlikely(b->type != q->type)) {
dprintk(1, "querybuf: Wrong type.\n");
goto done;
}
if (unlikely(b->index >= VIDEO_MAX_FRAME)) {
dprintk(1, "querybuf: index out of range.\n");
goto done;
}
if (unlikely(NULL == q->bufs[b->index])) {
dprintk(1, "querybuf: buffer is null.\n");
goto done;
}
videobuf_status(q, b, q->bufs[b->index], q->type);
ret = 0;
done:
videobuf_queue_unlock(q);
return ret;
}
EXPORT_SYMBOL_GPL(videobuf_querybuf);
int videobuf_qbuf(struct videobuf_queue *q, struct v4l2_buffer *b)
{
struct videobuf_buffer *buf;
enum v4l2_field field;
unsigned long flags = 0;
int retval;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
if (b->memory == V4L2_MEMORY_MMAP)
down_read(¤t->mm->mmap_sem);
videobuf_queue_lock(q);
retval = -EBUSY;
if (q->reading) {
dprintk(1, "qbuf: Reading running...\n");
goto done;
}
retval = -EINVAL;
if (b->type != q->type) {
dprintk(1, "qbuf: Wrong type.\n");
goto done;
}
if (b->index >= VIDEO_MAX_FRAME) {
dprintk(1, "qbuf: index out of range.\n");
goto done;
}
buf = q->bufs[b->index];
if (NULL == buf) {
dprintk(1, "qbuf: buffer is null.\n");
goto done;
}
MAGIC_CHECK(buf->magic, MAGIC_BUFFER);
if (buf->memory != b->memory) {
dprintk(1, "qbuf: memory type is wrong.\n");
goto done;
}
if (buf->state != VIDEOBUF_NEEDS_INIT && buf->state != VIDEOBUF_IDLE) {
dprintk(1, "qbuf: buffer is already queued or active.\n");
goto done;
}
if (b->flags & V4L2_BUF_FLAG_INPUT) {
if (b->input >= q->inputs) {
dprintk(1, "qbuf: wrong input.\n");
goto done;
}
buf->input = b->input;
} else {
buf->input = UNSET;
}
switch (b->memory) {
case V4L2_MEMORY_MMAP:
if (0 == buf->baddr) {
dprintk(1, "qbuf: mmap requested "
"but buffer addr is zero!\n");
goto done;
}
if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT
|| q->type == V4L2_BUF_TYPE_VBI_OUTPUT
|| q->type == V4L2_BUF_TYPE_SLICED_VBI_OUTPUT) {
buf->size = b->bytesused;
buf->field = b->field;
buf->ts = b->timestamp;
}
break;
case V4L2_MEMORY_USERPTR:
if (b->length < buf->bsize) {
dprintk(1, "qbuf: buffer length is not enough\n");
goto done;
}
if (VIDEOBUF_NEEDS_INIT != buf->state &&
buf->baddr != b->m.userptr)
q->ops->buf_release(q, buf);
buf->baddr = b->m.userptr;
buf->boff = b->reserved;
break;
case V4L2_MEMORY_OVERLAY:
buf->boff = b->m.offset;
break;
default:
dprintk(1, "qbuf: wrong memory type\n");
goto done;
}
dprintk(1, "qbuf: requesting next field\n");
field = videobuf_next_field(q);
retval = q->ops->buf_prepare(q, buf, field);
if (0 != retval) {
dprintk(1, "qbuf: buffer_prepare returned %d\n", retval);
goto done;
}
list_add_tail(&buf->stream, &q->stream);
if (q->streaming) {
spin_lock_irqsave(q->irqlock, flags);
q->ops->buf_queue(q, buf);
spin_unlock_irqrestore(q->irqlock, flags);
}
dprintk(1, "qbuf: succeeded\n");
retval = 0;
wake_up_interruptible_sync(&q->wait);
done:
videobuf_queue_unlock(q);
if (b->memory == V4L2_MEMORY_MMAP)
up_read(¤t->mm->mmap_sem);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_qbuf);
/* Locking: Caller holds q->vb_lock */
static int stream_next_buffer_check_queue(struct videobuf_queue *q, int noblock)
{
int retval;
checks:
if (!q->streaming) {
dprintk(1, "next_buffer: Not streaming\n");
retval = -EINVAL;
goto done;
}
if (list_empty(&q->stream)) {
if (noblock) {
retval = -EAGAIN;
dprintk(2, "next_buffer: no buffers to dequeue\n");
goto done;
} else {
dprintk(2, "next_buffer: waiting on buffer\n");
/* Drop lock to avoid deadlock with qbuf */
videobuf_queue_unlock(q);
/* Checking list_empty and streaming is safe without
* locks because we goto checks to validate while
* holding locks before proceeding */
retval = wait_event_interruptible(q->wait,
!list_empty(&q->stream) || !q->streaming);
videobuf_queue_lock(q);
if (retval)
goto done;
goto checks;
}
}
retval = 0;
done:
return retval;
}
/* Locking: Caller holds q->vb_lock */
static int stream_next_buffer(struct videobuf_queue *q,
struct videobuf_buffer **vb, int nonblocking)
{
int retval;
struct videobuf_buffer *buf = NULL;
retval = stream_next_buffer_check_queue(q, nonblocking);
if (retval)
goto done;
buf = list_entry(q->stream.next, struct videobuf_buffer, stream);
retval = videobuf_waiton(q, buf, nonblocking, 1);
if (retval < 0)
goto done;
*vb = buf;
done:
return retval;
}
int videobuf_dqbuf(struct videobuf_queue *q,
struct v4l2_buffer *b, int nonblocking)
{
struct videobuf_buffer *buf = NULL;
int retval;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
memset(b, 0, sizeof(*b));
videobuf_queue_lock(q);
retval = stream_next_buffer(q, &buf, nonblocking);
if (retval < 0) {
dprintk(1, "dqbuf: next_buffer error: %i\n", retval);
goto done;
}
switch (buf->state) {
case VIDEOBUF_ERROR:
dprintk(1, "dqbuf: state is error\n");
break;
case VIDEOBUF_DONE:
dprintk(1, "dqbuf: state is done\n");
break;
default:
dprintk(1, "dqbuf: state invalid\n");
retval = -EINVAL;
goto done;
}
CALL(q, sync, q, buf);
videobuf_status(q, b, buf, q->type);
list_del(&buf->stream);
buf->state = VIDEOBUF_IDLE;
b->flags &= ~V4L2_BUF_FLAG_DONE;
done:
videobuf_queue_unlock(q);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_dqbuf);
int videobuf_streamon(struct videobuf_queue *q)
{
struct videobuf_buffer *buf;
unsigned long flags = 0;
int retval;
videobuf_queue_lock(q);
retval = -EBUSY;
if (q->reading)
goto done;
retval = 0;
if (q->streaming)
goto done;
q->streaming = 1;
spin_lock_irqsave(q->irqlock, flags);
list_for_each_entry(buf, &q->stream, stream)
if (buf->state == VIDEOBUF_PREPARED)
q->ops->buf_queue(q, buf);
spin_unlock_irqrestore(q->irqlock, flags);
wake_up_interruptible_sync(&q->wait);
done:
videobuf_queue_unlock(q);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_streamon);
/* Locking: Caller holds q->vb_lock */
static int __videobuf_streamoff(struct videobuf_queue *q)
{
if (!q->streaming)
return -EINVAL;
videobuf_queue_cancel(q);
return 0;
}
int videobuf_streamoff(struct videobuf_queue *q)
{
int retval;
videobuf_queue_lock(q);
retval = __videobuf_streamoff(q);
videobuf_queue_unlock(q);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_streamoff);
/* Locking: Caller holds q->vb_lock */
static ssize_t videobuf_read_zerocopy(struct videobuf_queue *q,
char __user *data,
size_t count, loff_t *ppos)
{
enum v4l2_field field;
unsigned long flags = 0;
int retval;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
/* setup stuff */
q->read_buf = videobuf_alloc_vb(q);
if (NULL == q->read_buf)
return -ENOMEM;
q->read_buf->memory = V4L2_MEMORY_USERPTR;
q->read_buf->baddr = (unsigned long)data;
q->read_buf->bsize = count;
field = videobuf_next_field(q);
retval = q->ops->buf_prepare(q, q->read_buf, field);
if (0 != retval)
goto done;
/* start capture & wait */
spin_lock_irqsave(q->irqlock, flags);
q->ops->buf_queue(q, q->read_buf);
spin_unlock_irqrestore(q->irqlock, flags);
retval = videobuf_waiton(q, q->read_buf, 0, 0);
if (0 == retval) {
CALL(q, sync, q, q->read_buf);
if (VIDEOBUF_ERROR == q->read_buf->state)
retval = -EIO;
else
retval = q->read_buf->size;
}
done:
/* cleanup */
q->ops->buf_release(q, q->read_buf);
kfree(q->read_buf);
q->read_buf = NULL;
return retval;
}
static int __videobuf_copy_to_user(struct videobuf_queue *q,
struct videobuf_buffer *buf,
char __user *data, size_t count,
int nonblocking)
{
void *vaddr = CALL(q, vaddr, buf);
/* copy to userspace */
if (count > buf->size - q->read_off)
count = buf->size - q->read_off;
if (copy_to_user(data, vaddr + q->read_off, count))
return -EFAULT;
return count;
}
static int __videobuf_copy_stream(struct videobuf_queue *q,
struct videobuf_buffer *buf,
char __user *data, size_t count, size_t pos,
int vbihack, int nonblocking)
{
unsigned int *fc = CALL(q, vaddr, buf);
if (vbihack) {
/* dirty, undocumented hack -- pass the frame counter
* within the last four bytes of each vbi data block.
* We need that one to maintain backward compatibility
* to all vbi decoding software out there ... */
fc += (buf->size >> 2) - 1;
*fc = buf->field_count >> 1;
dprintk(1, "vbihack: %d\n", *fc);
}
/* copy stuff using the common method */
count = __videobuf_copy_to_user(q, buf, data, count, nonblocking);
if ((count == -EFAULT) && (pos == 0))
return -EFAULT;
return count;
}
ssize_t videobuf_read_one(struct videobuf_queue *q,
char __user *data, size_t count, loff_t *ppos,
int nonblocking)
{
enum v4l2_field field;
unsigned long flags = 0;
unsigned size = 0, nbufs = 1;
int retval;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
videobuf_queue_lock(q);
q->ops->buf_setup(q, &nbufs, &size);
if (NULL == q->read_buf &&
count >= size &&
!nonblocking) {
retval = videobuf_read_zerocopy(q, data, count, ppos);
if (retval >= 0 || retval == -EIO)
/* ok, all done */
goto done;
/* fallback to kernel bounce buffer on failures */
}
if (NULL == q->read_buf) {
/* need to capture a new frame */
retval = -ENOMEM;
q->read_buf = videobuf_alloc_vb(q);
dprintk(1, "video alloc=0x%p\n", q->read_buf);
if (NULL == q->read_buf)
goto done;
q->read_buf->memory = V4L2_MEMORY_USERPTR;
q->read_buf->bsize = count; /* preferred size */
field = videobuf_next_field(q);
retval = q->ops->buf_prepare(q, q->read_buf, field);
if (0 != retval) {
kfree(q->read_buf);
q->read_buf = NULL;
goto done;
}
spin_lock_irqsave(q->irqlock, flags);
q->ops->buf_queue(q, q->read_buf);
spin_unlock_irqrestore(q->irqlock, flags);
q->read_off = 0;
}
/* wait until capture is done */
retval = videobuf_waiton(q, q->read_buf, nonblocking, 1);
if (0 != retval)
goto done;
CALL(q, sync, q, q->read_buf);
if (VIDEOBUF_ERROR == q->read_buf->state) {
/* catch I/O errors */
q->ops->buf_release(q, q->read_buf);
kfree(q->read_buf);
q->read_buf = NULL;
retval = -EIO;
goto done;
}
/* Copy to userspace */
retval = __videobuf_copy_to_user(q, q->read_buf, data, count, nonblocking);
if (retval < 0)
goto done;
q->read_off += retval;
if (q->read_off == q->read_buf->size) {
/* all data copied, cleanup */
q->ops->buf_release(q, q->read_buf);
kfree(q->read_buf);
q->read_buf = NULL;
}
done:
videobuf_queue_unlock(q);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_read_one);
/* Locking: Caller holds q->vb_lock */
static int __videobuf_read_start(struct videobuf_queue *q)
{
enum v4l2_field field;
unsigned long flags = 0;
unsigned int count = 0, size = 0;
int err, i;
q->ops->buf_setup(q, &count, &size);
if (count < 2)
count = 2;
if (count > VIDEO_MAX_FRAME)
count = VIDEO_MAX_FRAME;
size = PAGE_ALIGN(size);
err = __videobuf_mmap_setup(q, count, size, V4L2_MEMORY_USERPTR);
if (err < 0)
return err;
count = err;
for (i = 0; i < count; i++) {
field = videobuf_next_field(q);
err = q->ops->buf_prepare(q, q->bufs[i], field);
if (err)
return err;
list_add_tail(&q->bufs[i]->stream, &q->stream);
}
spin_lock_irqsave(q->irqlock, flags);
for (i = 0; i < count; i++)
q->ops->buf_queue(q, q->bufs[i]);
spin_unlock_irqrestore(q->irqlock, flags);
q->reading = 1;
return 0;
}
static void __videobuf_read_stop(struct videobuf_queue *q)
{
int i;
videobuf_queue_cancel(q);
__videobuf_free(q);
INIT_LIST_HEAD(&q->stream);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
kfree(q->bufs[i]);
q->bufs[i] = NULL;
}
q->read_buf = NULL;
}
int videobuf_read_start(struct videobuf_queue *q)
{
int rc;
videobuf_queue_lock(q);
rc = __videobuf_read_start(q);
videobuf_queue_unlock(q);
return rc;
}
EXPORT_SYMBOL_GPL(videobuf_read_start);
void videobuf_read_stop(struct videobuf_queue *q)
{
videobuf_queue_lock(q);
__videobuf_read_stop(q);
videobuf_queue_unlock(q);
}
EXPORT_SYMBOL_GPL(videobuf_read_stop);
void videobuf_stop(struct videobuf_queue *q)
{
videobuf_queue_lock(q);
if (q->streaming)
__videobuf_streamoff(q);
if (q->reading)
__videobuf_read_stop(q);
videobuf_queue_unlock(q);
}
EXPORT_SYMBOL_GPL(videobuf_stop);
ssize_t videobuf_read_stream(struct videobuf_queue *q,
char __user *data, size_t count, loff_t *ppos,
int vbihack, int nonblocking)
{
int rc, retval;
unsigned long flags = 0;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
dprintk(2, "%s\n", __func__);
videobuf_queue_lock(q);
retval = -EBUSY;
if (q->streaming)
goto done;
if (!q->reading) {
retval = __videobuf_read_start(q);
if (retval < 0)
goto done;
}
retval = 0;
while (count > 0) {
/* get / wait for data */
if (NULL == q->read_buf) {
q->read_buf = list_entry(q->stream.next,
struct videobuf_buffer,
stream);
list_del(&q->read_buf->stream);
q->read_off = 0;
}
rc = videobuf_waiton(q, q->read_buf, nonblocking, 1);
if (rc < 0) {
if (0 == retval)
retval = rc;
break;
}
if (q->read_buf->state == VIDEOBUF_DONE) {
rc = __videobuf_copy_stream(q, q->read_buf, data + retval, count,
retval, vbihack, nonblocking);
if (rc < 0) {
retval = rc;
break;
}
retval += rc;
count -= rc;
q->read_off += rc;
} else {
/* some error */
q->read_off = q->read_buf->size;
if (0 == retval)
retval = -EIO;
}
/* requeue buffer when done with copying */
if (q->read_off == q->read_buf->size) {
list_add_tail(&q->read_buf->stream,
&q->stream);
spin_lock_irqsave(q->irqlock, flags);
q->ops->buf_queue(q, q->read_buf);
spin_unlock_irqrestore(q->irqlock, flags);
q->read_buf = NULL;
}
if (retval < 0)
break;
}
done:
videobuf_queue_unlock(q);
return retval;
}
EXPORT_SYMBOL_GPL(videobuf_read_stream);
unsigned int videobuf_poll_stream(struct file *file,
struct videobuf_queue *q,
poll_table *wait)
{
struct videobuf_buffer *buf = NULL;
unsigned int rc = 0;
videobuf_queue_lock(q);
if (q->streaming) {
if (!list_empty(&q->stream))
buf = list_entry(q->stream.next,
struct videobuf_buffer, stream);
} else {
if (!q->reading) {
rc = POLLERR;
} else if (NULL == q->read_buf) {
q->read_buf = list_entry(q->stream.next,
struct videobuf_buffer,
stream);
list_del(&q->read_buf->stream);
q->read_off = 0;
}
buf = q->read_buf;
}
if (!buf)
rc = POLLERR;
if (0 == rc) {
poll_wait(file, &buf->done, wait);
if (buf->state == VIDEOBUF_DONE ||
buf->state == VIDEOBUF_ERROR) {
switch (q->type) {
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
case V4L2_BUF_TYPE_VBI_OUTPUT:
case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
rc = POLLOUT | POLLWRNORM;
break;
default:
rc = POLLIN | POLLRDNORM;
break;
}
}
}
videobuf_queue_unlock(q);
return rc;
}
EXPORT_SYMBOL_GPL(videobuf_poll_stream);
int videobuf_mmap_mapper(struct videobuf_queue *q, struct vm_area_struct *vma)
{
int rc = -EINVAL;
int i;
MAGIC_CHECK(q->int_ops->magic, MAGIC_QTYPE_OPS);
if (!(vma->vm_flags & VM_WRITE) || !(vma->vm_flags & VM_SHARED)) {
dprintk(1, "mmap appl bug: PROT_WRITE and MAP_SHARED are required\n");
return -EINVAL;
}
videobuf_queue_lock(q);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
struct videobuf_buffer *buf = q->bufs[i];
if (buf && buf->memory == V4L2_MEMORY_MMAP &&
buf->boff == (vma->vm_pgoff << PAGE_SHIFT)) {
rc = CALL(q, mmap_mapper, q, buf, vma);
break;
}
}
videobuf_queue_unlock(q);
return rc;
}
EXPORT_SYMBOL_GPL(videobuf_mmap_mapper);
| gpl-2.0 |
jumpstarter-io/linux | drivers/ide/sis5513.c | 4518 | 18494 | /*
* Copyright (C) 1999-2000 Andre Hedrick <andre@linux-ide.org>
* Copyright (C) 2002 Lionel Bouton <Lionel.Bouton@inet6.fr>, Maintainer
* Copyright (C) 2003 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (C) 2007-2009 Bartlomiej Zolnierkiewicz
*
* May be copied or modified under the terms of the GNU General Public License
*
*
* Thanks :
*
* SiS Taiwan : for direct support and hardware.
* Daniela Engert : for initial ATA100 advices and numerous others.
* John Fremlin, Manfred Spraul, Dave Morgan, Peter Kjellerstedt :
* for checking code correctness, providing patches.
*
*
* Original tests and design on the SiS620 chipset.
* ATA100 tests and design on the SiS735 chipset.
* ATA16/33 support from specs
* ATA133 support for SiS961/962 by L.C. Chang <lcchang@sis.com.tw>
* ATA133 961/962/963 fixes by Vojtech Pavlik <vojtech@suse.cz>
*
* Documentation:
* SiS chipset documentation available under NDA to companies only
* (not to individuals).
*/
/*
* The original SiS5513 comes from a SiS5511/55112/5513 chipset. The original
* SiS5513 was also used in the SiS5596/5513 chipset. Thus if we see a SiS5511
* or SiS5596, we can assume we see the first MWDMA-16 capable SiS5513 chip.
*
* Later SiS chipsets integrated the 5513 functionality into the NorthBridge,
* starting with SiS5571 and up to SiS745. The PCI ID didn't change, though. We
* can figure out that we have a more modern and more capable 5513 by looking
* for the respective NorthBridge IDs.
*
* Even later (96x family) SiS chipsets use the MuTIOL link and place the 5513
* into the SouthBrige. Here we cannot rely on looking up the NorthBridge PCI
* ID, while the now ATA-133 capable 5513 still has the same PCI ID.
* Fortunately the 5513 can be 'unmasked' by fiddling with some config space
* bits, changing its device id to the true one - 5517 for 961 and 5518 for
* 962/963.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ide.h>
#define DRV_NAME "sis5513"
/* registers layout and init values are chipset family dependent */
#define ATA_16 0x01
#define ATA_33 0x02
#define ATA_66 0x03
#define ATA_100a 0x04 /* SiS730/SiS550 is ATA100 with ATA66 layout */
#define ATA_100 0x05
#define ATA_133a 0x06 /* SiS961b with 133 support */
#define ATA_133 0x07 /* SiS962/963 */
static u8 chipset_family;
/*
* Devices supported
*/
static const struct {
const char *name;
u16 host_id;
u8 chipset_family;
u8 flags;
} SiSHostChipInfo[] = {
{ "SiS968", PCI_DEVICE_ID_SI_968, ATA_133 },
{ "SiS966", PCI_DEVICE_ID_SI_966, ATA_133 },
{ "SiS965", PCI_DEVICE_ID_SI_965, ATA_133 },
{ "SiS745", PCI_DEVICE_ID_SI_745, ATA_100 },
{ "SiS735", PCI_DEVICE_ID_SI_735, ATA_100 },
{ "SiS733", PCI_DEVICE_ID_SI_733, ATA_100 },
{ "SiS635", PCI_DEVICE_ID_SI_635, ATA_100 },
{ "SiS633", PCI_DEVICE_ID_SI_633, ATA_100 },
{ "SiS730", PCI_DEVICE_ID_SI_730, ATA_100a },
{ "SiS550", PCI_DEVICE_ID_SI_550, ATA_100a },
{ "SiS640", PCI_DEVICE_ID_SI_640, ATA_66 },
{ "SiS630", PCI_DEVICE_ID_SI_630, ATA_66 },
{ "SiS620", PCI_DEVICE_ID_SI_620, ATA_66 },
{ "SiS540", PCI_DEVICE_ID_SI_540, ATA_66 },
{ "SiS530", PCI_DEVICE_ID_SI_530, ATA_66 },
{ "SiS5600", PCI_DEVICE_ID_SI_5600, ATA_33 },
{ "SiS5598", PCI_DEVICE_ID_SI_5598, ATA_33 },
{ "SiS5597", PCI_DEVICE_ID_SI_5597, ATA_33 },
{ "SiS5591/2", PCI_DEVICE_ID_SI_5591, ATA_33 },
{ "SiS5582", PCI_DEVICE_ID_SI_5582, ATA_33 },
{ "SiS5581", PCI_DEVICE_ID_SI_5581, ATA_33 },
{ "SiS5596", PCI_DEVICE_ID_SI_5596, ATA_16 },
{ "SiS5571", PCI_DEVICE_ID_SI_5571, ATA_16 },
{ "SiS5517", PCI_DEVICE_ID_SI_5517, ATA_16 },
{ "SiS551x", PCI_DEVICE_ID_SI_5511, ATA_16 },
};
/* Cycle time bits and values vary across chip dma capabilities
These three arrays hold the register layout and the values to set.
Indexed by chipset_family and (dma_mode - XFER_UDMA_0) */
/* {0, ATA_16, ATA_33, ATA_66, ATA_100a, ATA_100, ATA_133} */
static u8 cycle_time_offset[] = { 0, 0, 5, 4, 4, 0, 0 };
static u8 cycle_time_range[] = { 0, 0, 2, 3, 3, 4, 4 };
static u8 cycle_time_value[][XFER_UDMA_6 - XFER_UDMA_0 + 1] = {
{ 0, 0, 0, 0, 0, 0, 0 }, /* no UDMA */
{ 0, 0, 0, 0, 0, 0, 0 }, /* no UDMA */
{ 3, 2, 1, 0, 0, 0, 0 }, /* ATA_33 */
{ 7, 5, 3, 2, 1, 0, 0 }, /* ATA_66 */
{ 7, 5, 3, 2, 1, 0, 0 }, /* ATA_100a (730 specific),
different cycle_time range and offset */
{ 11, 7, 5, 4, 2, 1, 0 }, /* ATA_100 */
{ 15, 10, 7, 5, 3, 2, 1 }, /* ATA_133a (earliest 691 southbridges) */
{ 15, 10, 7, 5, 3, 2, 1 }, /* ATA_133 */
};
/* CRC Valid Setup Time vary across IDE clock setting 33/66/100/133
See SiS962 data sheet for more detail */
static u8 cvs_time_value[][XFER_UDMA_6 - XFER_UDMA_0 + 1] = {
{ 0, 0, 0, 0, 0, 0, 0 }, /* no UDMA */
{ 0, 0, 0, 0, 0, 0, 0 }, /* no UDMA */
{ 2, 1, 1, 0, 0, 0, 0 },
{ 4, 3, 2, 1, 0, 0, 0 },
{ 4, 3, 2, 1, 0, 0, 0 },
{ 6, 4, 3, 1, 1, 1, 0 },
{ 9, 6, 4, 2, 2, 2, 2 },
{ 9, 6, 4, 2, 2, 2, 2 },
};
/* Initialize time, Active time, Recovery time vary across
IDE clock settings. These 3 arrays hold the register value
for PIO0/1/2/3/4 and DMA0/1/2 mode in order */
static u8 ini_time_value[][8] = {
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 2, 1, 0, 0, 0, 1, 0, 0 },
{ 4, 3, 1, 1, 1, 3, 1, 1 },
{ 4, 3, 1, 1, 1, 3, 1, 1 },
{ 6, 4, 2, 2, 2, 4, 2, 2 },
{ 9, 6, 3, 3, 3, 6, 3, 3 },
{ 9, 6, 3, 3, 3, 6, 3, 3 },
};
static u8 act_time_value[][8] = {
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 9, 9, 9, 2, 2, 7, 2, 2 },
{ 19, 19, 19, 5, 4, 14, 5, 4 },
{ 19, 19, 19, 5, 4, 14, 5, 4 },
{ 28, 28, 28, 7, 6, 21, 7, 6 },
{ 38, 38, 38, 10, 9, 28, 10, 9 },
{ 38, 38, 38, 10, 9, 28, 10, 9 },
};
static u8 rco_time_value[][8] = {
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 9, 2, 0, 2, 0, 7, 1, 1 },
{ 19, 5, 1, 5, 2, 16, 3, 2 },
{ 19, 5, 1, 5, 2, 16, 3, 2 },
{ 30, 9, 3, 9, 4, 25, 6, 4 },
{ 40, 12, 4, 12, 5, 34, 12, 5 },
{ 40, 12, 4, 12, 5, 34, 12, 5 },
};
/*
* Printing configuration
*/
/* Used for chipset type printing at boot time */
static char *chipset_capability[] = {
"ATA", "ATA 16",
"ATA 33", "ATA 66",
"ATA 100 (1st gen)", "ATA 100 (2nd gen)",
"ATA 133 (1st gen)", "ATA 133 (2nd gen)"
};
/*
* Configuration functions
*/
static u8 sis_ata133_get_base(ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u32 reg54 = 0;
pci_read_config_dword(dev, 0x54, ®54);
return ((reg54 & 0x40000000) ? 0x70 : 0x40) + drive->dn * 4;
}
static void sis_ata16_program_timings(ide_drive_t *drive, const u8 mode)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u16 t1 = 0;
u8 drive_pci = 0x40 + drive->dn * 2;
const u16 pio_timings[] = { 0x000, 0x607, 0x404, 0x303, 0x301 };
const u16 mwdma_timings[] = { 0x008, 0x302, 0x301 };
pci_read_config_word(dev, drive_pci, &t1);
/* clear active/recovery timings */
t1 &= ~0x070f;
if (mode >= XFER_MW_DMA_0) {
if (chipset_family > ATA_16)
t1 &= ~0x8000; /* disable UDMA */
t1 |= mwdma_timings[mode - XFER_MW_DMA_0];
} else
t1 |= pio_timings[mode - XFER_PIO_0];
pci_write_config_word(dev, drive_pci, t1);
}
static void sis_ata100_program_timings(ide_drive_t *drive, const u8 mode)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u8 t1, drive_pci = 0x40 + drive->dn * 2;
/* timing bits: 7:4 active 3:0 recovery */
const u8 pio_timings[] = { 0x00, 0x67, 0x44, 0x33, 0x31 };
const u8 mwdma_timings[] = { 0x08, 0x32, 0x31 };
if (mode >= XFER_MW_DMA_0) {
u8 t2 = 0;
pci_read_config_byte(dev, drive_pci, &t2);
t2 &= ~0x80; /* disable UDMA */
pci_write_config_byte(dev, drive_pci, t2);
t1 = mwdma_timings[mode - XFER_MW_DMA_0];
} else
t1 = pio_timings[mode - XFER_PIO_0];
pci_write_config_byte(dev, drive_pci + 1, t1);
}
static void sis_ata133_program_timings(ide_drive_t *drive, const u8 mode)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u32 t1 = 0;
u8 drive_pci = sis_ata133_get_base(drive), clk, idx;
pci_read_config_dword(dev, drive_pci, &t1);
t1 &= 0xc0c00fff;
clk = (t1 & 0x08) ? ATA_133 : ATA_100;
if (mode >= XFER_MW_DMA_0) {
t1 &= ~0x04; /* disable UDMA */
idx = mode - XFER_MW_DMA_0 + 5;
} else
idx = mode - XFER_PIO_0;
t1 |= ini_time_value[clk][idx] << 12;
t1 |= act_time_value[clk][idx] << 16;
t1 |= rco_time_value[clk][idx] << 24;
pci_write_config_dword(dev, drive_pci, t1);
}
static void sis_program_timings(ide_drive_t *drive, const u8 mode)
{
if (chipset_family < ATA_100) /* ATA_16/33/66/100a */
sis_ata16_program_timings(drive, mode);
else if (chipset_family < ATA_133) /* ATA_100/133a */
sis_ata100_program_timings(drive, mode);
else /* ATA_133 */
sis_ata133_program_timings(drive, mode);
}
static void config_drive_art_rwp(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 reg4bh = 0;
u8 rw_prefetch = 0;
pci_read_config_byte(dev, 0x4b, ®4bh);
rw_prefetch = reg4bh & ~(0x11 << drive->dn);
if (drive->media == ide_disk)
rw_prefetch |= 0x11 << drive->dn;
if (reg4bh != rw_prefetch)
pci_write_config_byte(dev, 0x4b, rw_prefetch);
}
static void sis_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
config_drive_art_rwp(drive);
sis_program_timings(drive, drive->pio_mode);
}
static void sis_ata133_program_udma_timings(ide_drive_t *drive, const u8 mode)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u32 regdw = 0;
u8 drive_pci = sis_ata133_get_base(drive), clk, idx;
pci_read_config_dword(dev, drive_pci, ®dw);
regdw |= 0x04;
regdw &= 0xfffff00f;
/* check if ATA133 enable */
clk = (regdw & 0x08) ? ATA_133 : ATA_100;
idx = mode - XFER_UDMA_0;
regdw |= cycle_time_value[clk][idx] << 4;
regdw |= cvs_time_value[clk][idx] << 8;
pci_write_config_dword(dev, drive_pci, regdw);
}
static void sis_ata33_program_udma_timings(ide_drive_t *drive, const u8 mode)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u8 drive_pci = 0x40 + drive->dn * 2, reg = 0, i = chipset_family;
pci_read_config_byte(dev, drive_pci + 1, ®);
/* force the UDMA bit on if we want to use UDMA */
reg |= 0x80;
/* clean reg cycle time bits */
reg &= ~((0xff >> (8 - cycle_time_range[i])) << cycle_time_offset[i]);
/* set reg cycle time bits */
reg |= cycle_time_value[i][mode - XFER_UDMA_0] << cycle_time_offset[i];
pci_write_config_byte(dev, drive_pci + 1, reg);
}
static void sis_program_udma_timings(ide_drive_t *drive, const u8 mode)
{
if (chipset_family >= ATA_133) /* ATA_133 */
sis_ata133_program_udma_timings(drive, mode);
else /* ATA_33/66/100a/100/133a */
sis_ata33_program_udma_timings(drive, mode);
}
static void sis_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
const u8 speed = drive->dma_mode;
if (speed >= XFER_UDMA_0)
sis_program_udma_timings(drive, speed);
else
sis_program_timings(drive, speed);
}
static u8 sis_ata133_udma_filter(ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u32 regdw = 0;
u8 drive_pci = sis_ata133_get_base(drive);
pci_read_config_dword(dev, drive_pci, ®dw);
/* if ATA133 disable, we should not set speed above UDMA5 */
return (regdw & 0x08) ? ATA_UDMA6 : ATA_UDMA5;
}
static int sis_find_family(struct pci_dev *dev)
{
struct pci_dev *host;
int i = 0;
chipset_family = 0;
for (i = 0; i < ARRAY_SIZE(SiSHostChipInfo) && !chipset_family; i++) {
host = pci_get_device(PCI_VENDOR_ID_SI, SiSHostChipInfo[i].host_id, NULL);
if (!host)
continue;
chipset_family = SiSHostChipInfo[i].chipset_family;
/* Special case for SiS630 : 630S/ET is ATA_100a */
if (SiSHostChipInfo[i].host_id == PCI_DEVICE_ID_SI_630) {
if (host->revision >= 0x30)
chipset_family = ATA_100a;
}
pci_dev_put(host);
printk(KERN_INFO DRV_NAME " %s: %s %s controller\n",
pci_name(dev), SiSHostChipInfo[i].name,
chipset_capability[chipset_family]);
}
if (!chipset_family) { /* Belongs to pci-quirks */
u32 idemisc;
u16 trueid;
/* Disable ID masking and register remapping */
pci_read_config_dword(dev, 0x54, &idemisc);
pci_write_config_dword(dev, 0x54, (idemisc & 0x7fffffff));
pci_read_config_word(dev, PCI_DEVICE_ID, &trueid);
pci_write_config_dword(dev, 0x54, idemisc);
if (trueid == 0x5518) {
printk(KERN_INFO DRV_NAME " %s: SiS 962/963 MuTIOL IDE UDMA133 controller\n",
pci_name(dev));
chipset_family = ATA_133;
/* Check for 5513 compatibility mapping
* We must use this, else the port enabled code will fail,
* as it expects the enablebits at 0x4a.
*/
if ((idemisc & 0x40000000) == 0) {
pci_write_config_dword(dev, 0x54, idemisc | 0x40000000);
printk(KERN_INFO DRV_NAME " %s: Switching to 5513 register mapping\n",
pci_name(dev));
}
}
}
if (!chipset_family) { /* Belongs to pci-quirks */
struct pci_dev *lpc_bridge;
u16 trueid;
u8 prefctl;
u8 idecfg;
pci_read_config_byte(dev, 0x4a, &idecfg);
pci_write_config_byte(dev, 0x4a, idecfg | 0x10);
pci_read_config_word(dev, PCI_DEVICE_ID, &trueid);
pci_write_config_byte(dev, 0x4a, idecfg);
if (trueid == 0x5517) { /* SiS 961/961B */
lpc_bridge = pci_get_slot(dev->bus, 0x10); /* Bus 0, Dev 2, Fn 0 */
pci_read_config_byte(dev, 0x49, &prefctl);
pci_dev_put(lpc_bridge);
if (lpc_bridge->revision == 0x10 && (prefctl & 0x80)) {
printk(KERN_INFO DRV_NAME " %s: SiS 961B MuTIOL IDE UDMA133 controller\n",
pci_name(dev));
chipset_family = ATA_133a;
} else {
printk(KERN_INFO DRV_NAME " %s: SiS 961 MuTIOL IDE UDMA100 controller\n",
pci_name(dev));
chipset_family = ATA_100;
}
}
}
return chipset_family;
}
static int init_chipset_sis5513(struct pci_dev *dev)
{
/* Make general config ops here
1/ tell IDE channels to operate in Compatibility mode only
2/ tell old chips to allow per drive IDE timings */
u8 reg;
u16 regw;
switch (chipset_family) {
case ATA_133:
/* SiS962 operation mode */
pci_read_config_word(dev, 0x50, ®w);
if (regw & 0x08)
pci_write_config_word(dev, 0x50, regw&0xfff7);
pci_read_config_word(dev, 0x52, ®w);
if (regw & 0x08)
pci_write_config_word(dev, 0x52, regw&0xfff7);
break;
case ATA_133a:
case ATA_100:
/* Fixup latency */
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x80);
/* Set compatibility bit */
pci_read_config_byte(dev, 0x49, ®);
if (!(reg & 0x01))
pci_write_config_byte(dev, 0x49, reg|0x01);
break;
case ATA_100a:
case ATA_66:
/* Fixup latency */
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x10);
/* On ATA_66 chips the bit was elsewhere */
pci_read_config_byte(dev, 0x52, ®);
if (!(reg & 0x04))
pci_write_config_byte(dev, 0x52, reg|0x04);
break;
case ATA_33:
/* On ATA_33 we didn't have a single bit to set */
pci_read_config_byte(dev, 0x09, ®);
if ((reg & 0x0f) != 0x00)
pci_write_config_byte(dev, 0x09, reg&0xf0);
case ATA_16:
/* force per drive recovery and active timings
needed on ATA_33 and below chips */
pci_read_config_byte(dev, 0x52, ®);
if (!(reg & 0x08))
pci_write_config_byte(dev, 0x52, reg|0x08);
break;
}
return 0;
}
struct sis_laptop {
u16 device;
u16 subvendor;
u16 subdevice;
};
static const struct sis_laptop sis_laptop[] = {
/* devid, subvendor, subdev */
{ 0x5513, 0x1043, 0x1107 }, /* ASUS A6K */
{ 0x5513, 0x1734, 0x105f }, /* FSC Amilo A1630 */
{ 0x5513, 0x1071, 0x8640 }, /* EasyNote K5305 */
/* end marker */
{ 0, }
};
static u8 sis_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *pdev = to_pci_dev(hwif->dev);
const struct sis_laptop *lap = &sis_laptop[0];
u8 ata66 = 0;
while (lap->device) {
if (lap->device == pdev->device &&
lap->subvendor == pdev->subsystem_vendor &&
lap->subdevice == pdev->subsystem_device)
return ATA_CBL_PATA40_SHORT;
lap++;
}
if (chipset_family >= ATA_133) {
u16 regw = 0;
u16 reg_addr = hwif->channel ? 0x52: 0x50;
pci_read_config_word(pdev, reg_addr, ®w);
ata66 = (regw & 0x8000) ? 0 : 1;
} else if (chipset_family >= ATA_66) {
u8 reg48h = 0;
u8 mask = hwif->channel ? 0x20 : 0x10;
pci_read_config_byte(pdev, 0x48, ®48h);
ata66 = (reg48h & mask) ? 0 : 1;
}
return ata66 ? ATA_CBL_PATA80 : ATA_CBL_PATA40;
}
static const struct ide_port_ops sis_port_ops = {
.set_pio_mode = sis_set_pio_mode,
.set_dma_mode = sis_set_dma_mode,
.cable_detect = sis_cable_detect,
};
static const struct ide_port_ops sis_ata133_port_ops = {
.set_pio_mode = sis_set_pio_mode,
.set_dma_mode = sis_set_dma_mode,
.udma_filter = sis_ata133_udma_filter,
.cable_detect = sis_cable_detect,
};
static const struct ide_port_info sis5513_chipset = {
.name = DRV_NAME,
.init_chipset = init_chipset_sis5513,
.enablebits = { {0x4a, 0x02, 0x02}, {0x4a, 0x04, 0x04} },
.host_flags = IDE_HFLAG_NO_AUTODMA,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
};
static int sis5513_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct ide_port_info d = sis5513_chipset;
u8 udma_rates[] = { 0x00, 0x00, 0x07, 0x1f, 0x3f, 0x3f, 0x7f, 0x7f };
int rc;
rc = pci_enable_device(dev);
if (rc)
return rc;
if (sis_find_family(dev) == 0)
return -ENOTSUPP;
if (chipset_family >= ATA_133)
d.port_ops = &sis_ata133_port_ops;
else
d.port_ops = &sis_port_ops;
d.udma_mask = udma_rates[chipset_family];
return ide_pci_init_one(dev, &d, NULL);
}
static void sis5513_remove(struct pci_dev *dev)
{
ide_pci_remove(dev);
pci_disable_device(dev);
}
static const struct pci_device_id sis5513_pci_tbl[] = {
{ PCI_VDEVICE(SI, PCI_DEVICE_ID_SI_5513), 0 },
{ PCI_VDEVICE(SI, PCI_DEVICE_ID_SI_5518), 0 },
{ PCI_VDEVICE(SI, PCI_DEVICE_ID_SI_1180), 0 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, sis5513_pci_tbl);
static struct pci_driver sis5513_pci_driver = {
.name = "SIS_IDE",
.id_table = sis5513_pci_tbl,
.probe = sis5513_init_one,
.remove = sis5513_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init sis5513_ide_init(void)
{
return ide_pci_register_driver(&sis5513_pci_driver);
}
static void __exit sis5513_ide_exit(void)
{
pci_unregister_driver(&sis5513_pci_driver);
}
module_init(sis5513_ide_init);
module_exit(sis5513_ide_exit);
MODULE_AUTHOR("Lionel Bouton, L C Chang, Andre Hedrick, Vojtech Pavlik");
MODULE_DESCRIPTION("PCI driver module for SIS IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DeviceTREE/android_kernel_samsung_jf | fs/btrfs/ctree.c | 4774 | 115160 | /*
* Copyright (C) 2007,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 "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "print-tree.h"
#include "locking.h"
static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
*root, struct btrfs_path *path, int level);
static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
*root, struct btrfs_key *ins_key,
struct btrfs_path *path, int data_size, int extend);
static int push_node_left(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct extent_buffer *dst,
struct extent_buffer *src, int empty);
static int balance_node_right(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct extent_buffer *dst_buf,
struct extent_buffer *src_buf);
static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
struct btrfs_path *path, int level, int slot);
struct btrfs_path *btrfs_alloc_path(void)
{
struct btrfs_path *path;
path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
return path;
}
/*
* set all locked nodes in the path to blocking locks. This should
* be done before scheduling
*/
noinline void btrfs_set_path_blocking(struct btrfs_path *p)
{
int i;
for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
if (!p->nodes[i] || !p->locks[i])
continue;
btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
if (p->locks[i] == BTRFS_READ_LOCK)
p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
else if (p->locks[i] == BTRFS_WRITE_LOCK)
p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
}
}
/*
* reset all the locked nodes in the patch to spinning locks.
*
* held is used to keep lockdep happy, when lockdep is enabled
* we set held to a blocking lock before we go around and
* retake all the spinlocks in the path. You can safely use NULL
* for held
*/
noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
struct extent_buffer *held, int held_rw)
{
int i;
#ifdef CONFIG_DEBUG_LOCK_ALLOC
/* lockdep really cares that we take all of these spinlocks
* in the right order. If any of the locks in the path are not
* currently blocking, it is going to complain. So, make really
* really sure by forcing the path to blocking before we clear
* the path blocking.
*/
if (held) {
btrfs_set_lock_blocking_rw(held, held_rw);
if (held_rw == BTRFS_WRITE_LOCK)
held_rw = BTRFS_WRITE_LOCK_BLOCKING;
else if (held_rw == BTRFS_READ_LOCK)
held_rw = BTRFS_READ_LOCK_BLOCKING;
}
btrfs_set_path_blocking(p);
#endif
for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
if (p->nodes[i] && p->locks[i]) {
btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
p->locks[i] = BTRFS_WRITE_LOCK;
else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
p->locks[i] = BTRFS_READ_LOCK;
}
}
#ifdef CONFIG_DEBUG_LOCK_ALLOC
if (held)
btrfs_clear_lock_blocking_rw(held, held_rw);
#endif
}
/* this also releases the path */
void btrfs_free_path(struct btrfs_path *p)
{
if (!p)
return;
btrfs_release_path(p);
kmem_cache_free(btrfs_path_cachep, p);
}
/*
* path release drops references on the extent buffers in the path
* and it drops any locks held by this path
*
* It is safe to call this on paths that no locks or extent buffers held.
*/
noinline void btrfs_release_path(struct btrfs_path *p)
{
int i;
for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
p->slots[i] = 0;
if (!p->nodes[i])
continue;
if (p->locks[i]) {
btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
p->locks[i] = 0;
}
free_extent_buffer(p->nodes[i]);
p->nodes[i] = NULL;
}
}
/*
* safely gets a reference on the root node of a tree. A lock
* is not taken, so a concurrent writer may put a different node
* at the root of the tree. See btrfs_lock_root_node for the
* looping required.
*
* The extent buffer returned by this has a reference taken, so
* it won't disappear. It may stop being the root of the tree
* at any time because there are no locks held.
*/
struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
{
struct extent_buffer *eb;
while (1) {
rcu_read_lock();
eb = rcu_dereference(root->node);
/*
* RCU really hurts here, we could free up the root node because
* it was cow'ed but we may not get the new root node yet so do
* the inc_not_zero dance and if it doesn't work then
* synchronize_rcu and try again.
*/
if (atomic_inc_not_zero(&eb->refs)) {
rcu_read_unlock();
break;
}
rcu_read_unlock();
synchronize_rcu();
}
return eb;
}
/* loop around taking references on and locking the root node of the
* tree until you end up with a lock on the root. A locked buffer
* is returned, with a reference held.
*/
struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
{
struct extent_buffer *eb;
while (1) {
eb = btrfs_root_node(root);
btrfs_tree_lock(eb);
if (eb == root->node)
break;
btrfs_tree_unlock(eb);
free_extent_buffer(eb);
}
return eb;
}
/* loop around taking references on and locking the root node of the
* tree until you end up with a lock on the root. A locked buffer
* is returned, with a reference held.
*/
struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
{
struct extent_buffer *eb;
while (1) {
eb = btrfs_root_node(root);
btrfs_tree_read_lock(eb);
if (eb == root->node)
break;
btrfs_tree_read_unlock(eb);
free_extent_buffer(eb);
}
return eb;
}
/* cowonly root (everything not a reference counted cow subvolume), just get
* put onto a simple dirty list. transaction.c walks this to make sure they
* get properly updated on disk.
*/
static void add_root_to_dirty_list(struct btrfs_root *root)
{
spin_lock(&root->fs_info->trans_lock);
if (root->track_dirty && list_empty(&root->dirty_list)) {
list_add(&root->dirty_list,
&root->fs_info->dirty_cowonly_roots);
}
spin_unlock(&root->fs_info->trans_lock);
}
/*
* used by snapshot creation to make a copy of a root for a tree with
* a given objectid. The buffer with the new root node is returned in
* cow_ret, and this func returns zero on success or a negative error code.
*/
int btrfs_copy_root(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct extent_buffer *buf,
struct extent_buffer **cow_ret, u64 new_root_objectid)
{
struct extent_buffer *cow;
int ret = 0;
int level;
struct btrfs_disk_key disk_key;
WARN_ON(root->ref_cows && trans->transid !=
root->fs_info->running_transaction->transid);
WARN_ON(root->ref_cows && trans->transid != root->last_trans);
level = btrfs_header_level(buf);
if (level == 0)
btrfs_item_key(buf, &disk_key, 0);
else
btrfs_node_key(buf, &disk_key, 0);
cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
new_root_objectid, &disk_key, level,
buf->start, 0, 1);
if (IS_ERR(cow))
return PTR_ERR(cow);
copy_extent_buffer(cow, buf, 0, 0, cow->len);
btrfs_set_header_bytenr(cow, cow->start);
btrfs_set_header_generation(cow, trans->transid);
btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
BTRFS_HEADER_FLAG_RELOC);
if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
else
btrfs_set_header_owner(cow, new_root_objectid);
write_extent_buffer(cow, root->fs_info->fsid,
(unsigned long)btrfs_header_fsid(cow),
BTRFS_FSID_SIZE);
WARN_ON(btrfs_header_generation(buf) > trans->transid);
if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
ret = btrfs_inc_ref(trans, root, cow, 1, 1);
else
ret = btrfs_inc_ref(trans, root, cow, 0, 1);
if (ret)
return ret;
btrfs_mark_buffer_dirty(cow);
*cow_ret = cow;
return 0;
}
/*
* check if the tree block can be shared by multiple trees
*/
int btrfs_block_can_be_shared(struct btrfs_root *root,
struct extent_buffer *buf)
{
/*
* Tree blocks not in refernece counted trees and tree roots
* are never shared. If a block was allocated after the last
* snapshot and the block was not allocated by tree relocation,
* we know the block is not shared.
*/
if (root->ref_cows &&
buf != root->node && buf != root->commit_root &&
(btrfs_header_generation(buf) <=
btrfs_root_last_snapshot(&root->root_item) ||
btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
return 1;
#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
if (root->ref_cows &&
btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
return 1;
#endif
return 0;
}
static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct extent_buffer *buf,
struct extent_buffer *cow,
int *last_ref)
{
u64 refs;
u64 owner;
u64 flags;
u64 new_flags = 0;
int ret;
/*
* Backrefs update rules:
*
* Always use full backrefs for extent pointers in tree block
* allocated by tree relocation.
*
* If a shared tree block is no longer referenced by its owner
* tree (btrfs_header_owner(buf) == root->root_key.objectid),
* use full backrefs for extent pointers in tree block.
*
* If a tree block is been relocating
* (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
* use full backrefs for extent pointers in tree block.
* The reason for this is some operations (such as drop tree)
* are only allowed for blocks use full backrefs.
*/
if (btrfs_block_can_be_shared(root, buf)) {
ret = btrfs_lookup_extent_info(trans, root, buf->start,
buf->len, &refs, &flags);
if (ret)
return ret;
if (refs == 0) {
ret = -EROFS;
btrfs_std_error(root->fs_info, ret);
return ret;
}
} else {
refs = 1;
if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
else
flags = 0;
}
owner = btrfs_header_owner(buf);
BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
if (refs > 1) {
if ((owner == root->root_key.objectid ||
root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
ret = btrfs_inc_ref(trans, root, buf, 1, 1);
BUG_ON(ret); /* -ENOMEM */
if (root->root_key.objectid ==
BTRFS_TREE_RELOC_OBJECTID) {
ret = btrfs_dec_ref(trans, root, buf, 0, 1);
BUG_ON(ret); /* -ENOMEM */
ret = btrfs_inc_ref(trans, root, cow, 1, 1);
BUG_ON(ret); /* -ENOMEM */
}
new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
} else {
if (root->root_key.objectid ==
BTRFS_TREE_RELOC_OBJECTID)
ret = btrfs_inc_ref(trans, root, cow, 1, 1);
else
ret = btrfs_inc_ref(trans, root, cow, 0, 1);
BUG_ON(ret); /* -ENOMEM */
}
if (new_flags != 0) {
ret = btrfs_set_disk_extent_flags(trans, root,
buf->start,
buf->len,
new_flags, 0);
if (ret)
return ret;
}
} else {
if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
if (root->root_key.objectid ==
BTRFS_TREE_RELOC_OBJECTID)
ret = btrfs_inc_ref(trans, root, cow, 1, 1);
else
ret = btrfs_inc_ref(trans, root, cow, 0, 1);
BUG_ON(ret); /* -ENOMEM */
ret = btrfs_dec_ref(trans, root, buf, 1, 1);
BUG_ON(ret); /* -ENOMEM */
}
clean_tree_block(trans, root, buf);
*last_ref = 1;
}
return 0;
}
/*
* does the dirty work in cow of a single block. The parent block (if
* supplied) is updated to point to the new cow copy. The new buffer is marked
* dirty and returned locked. If you modify the block it needs to be marked
* dirty again.
*
* search_start -- an allocation hint for the new block
*
* empty_size -- a hint that you plan on doing more cow. This is the size in
* bytes the allocator should try to find free next to the block it returns.
* This is just a hint and may be ignored by the allocator.
*/
static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct extent_buffer *buf,
struct extent_buffer *parent, int parent_slot,
struct extent_buffer **cow_ret,
u64 search_start, u64 empty_size)
{
struct btrfs_disk_key disk_key;
struct extent_buffer *cow;
int level, ret;
int last_ref = 0;
int unlock_orig = 0;
u64 parent_start;
if (*cow_ret == buf)
unlock_orig = 1;
btrfs_assert_tree_locked(buf);
WARN_ON(root->ref_cows && trans->transid !=
root->fs_info->running_transaction->transid);
WARN_ON(root->ref_cows && trans->transid != root->last_trans);
level = btrfs_header_level(buf);
if (level == 0)
btrfs_item_key(buf, &disk_key, 0);
else
btrfs_node_key(buf, &disk_key, 0);
if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
if (parent)
parent_start = parent->start;
else
parent_start = 0;
} else
parent_start = 0;
cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
root->root_key.objectid, &disk_key,
level, search_start, empty_size, 1);
if (IS_ERR(cow))
return PTR_ERR(cow);
/* cow is set to blocking by btrfs_init_new_buffer */
copy_extent_buffer(cow, buf, 0, 0, cow->len);
btrfs_set_header_bytenr(cow, cow->start);
btrfs_set_header_generation(cow, trans->transid);
btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
BTRFS_HEADER_FLAG_RELOC);
if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
else
btrfs_set_header_owner(cow, root->root_key.objectid);
write_extent_buffer(cow, root->fs_info->fsid,
(unsigned long)btrfs_header_fsid(cow),
BTRFS_FSID_SIZE);
ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
if (root->ref_cows)
btrfs_reloc_cow_block(trans, root, buf, cow);
if (buf == root->node) {
WARN_ON(parent && parent != buf);
if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
parent_start = buf->start;
else
parent_start = 0;
extent_buffer_get(cow);
rcu_assign_pointer(root->node, cow);
btrfs_free_tree_block(trans, root, buf, parent_start,
last_ref, 1);
free_extent_buffer(buf);
add_root_to_dirty_list(root);
} else {
if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
parent_start = parent->start;
else
parent_start = 0;
WARN_ON(trans->transid != btrfs_header_generation(parent));
btrfs_set_node_blockptr(parent, parent_slot,
cow->start);
btrfs_set_node_ptr_generation(parent, parent_slot,
trans->transid);
btrfs_mark_buffer_dirty(parent);
btrfs_free_tree_block(trans, root, buf, parent_start,
last_ref, 1);
}
if (unlock_orig)
btrfs_tree_unlock(buf);
free_extent_buffer_stale(buf);
btrfs_mark_buffer_dirty(cow);
*cow_ret = cow;
return 0;
}
static inline int should_cow_block(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct extent_buffer *buf)
{
/* ensure we can see the force_cow */
smp_rmb();
/*
* We do not need to cow a block if
* 1) this block is not created or changed in this transaction;
* 2) this block does not belong to TREE_RELOC tree;
* 3) the root is not forced COW.
*
* What is forced COW:
* when we create snapshot during commiting the transaction,
* after we've finished coping src root, we must COW the shared
* block to ensure the metadata consistency.
*/
if (btrfs_header_generation(buf) == trans->transid &&
!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
!(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
!root->force_cow)
return 0;
return 1;
}
/*
* cows a single block, see __btrfs_cow_block for the real work.
* This version of it has extra checks so that a block isn't cow'd more than
* once per transaction, as long as it hasn't been written yet
*/
noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct extent_buffer *buf,
struct extent_buffer *parent, int parent_slot,
struct extent_buffer **cow_ret)
{
u64 search_start;
int ret;
if (trans->transaction != root->fs_info->running_transaction) {
printk(KERN_CRIT "trans %llu running %llu\n",
(unsigned long long)trans->transid,
(unsigned long long)
root->fs_info->running_transaction->transid);
WARN_ON(1);
}
if (trans->transid != root->fs_info->generation) {
printk(KERN_CRIT "trans %llu running %llu\n",
(unsigned long long)trans->transid,
(unsigned long long)root->fs_info->generation);
WARN_ON(1);
}
if (!should_cow_block(trans, root, buf)) {
*cow_ret = buf;
return 0;
}
search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
if (parent)
btrfs_set_lock_blocking(parent);
btrfs_set_lock_blocking(buf);
ret = __btrfs_cow_block(trans, root, buf, parent,
parent_slot, cow_ret, search_start, 0);
trace_btrfs_cow_block(root, buf, *cow_ret);
return ret;
}
/*
* helper function for defrag to decide if two blocks pointed to by a
* node are actually close by
*/
static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
{
if (blocknr < other && other - (blocknr + blocksize) < 32768)
return 1;
if (blocknr > other && blocknr - (other + blocksize) < 32768)
return 1;
return 0;
}
/*
* compare two keys in a memcmp fashion
*/
static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
{
struct btrfs_key k1;
btrfs_disk_key_to_cpu(&k1, disk);
return btrfs_comp_cpu_keys(&k1, k2);
}
/*
* same as comp_keys only with two btrfs_key's
*/
int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
{
if (k1->objectid > k2->objectid)
return 1;
if (k1->objectid < k2->objectid)
return -1;
if (k1->type > k2->type)
return 1;
if (k1->type < k2->type)
return -1;
if (k1->offset > k2->offset)
return 1;
if (k1->offset < k2->offset)
return -1;
return 0;
}
/*
* this is used by the defrag code to go through all the
* leaves pointed to by a node and reallocate them so that
* disk order is close to key order
*/
int btrfs_realloc_node(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct extent_buffer *parent,
int start_slot, int cache_only, u64 *last_ret,
struct btrfs_key *progress)
{
struct extent_buffer *cur;
u64 blocknr;
u64 gen;
u64 search_start = *last_ret;
u64 last_block = 0;
u64 other;
u32 parent_nritems;
int end_slot;
int i;
int err = 0;
int parent_level;
int uptodate;
u32 blocksize;
int progress_passed = 0;
struct btrfs_disk_key disk_key;
parent_level = btrfs_header_level(parent);
if (cache_only && parent_level != 1)
return 0;
if (trans->transaction != root->fs_info->running_transaction)
WARN_ON(1);
if (trans->transid != root->fs_info->generation)
WARN_ON(1);
parent_nritems = btrfs_header_nritems(parent);
blocksize = btrfs_level_size(root, parent_level - 1);
end_slot = parent_nritems;
if (parent_nritems == 1)
return 0;
btrfs_set_lock_blocking(parent);
for (i = start_slot; i < end_slot; i++) {
int close = 1;
btrfs_node_key(parent, &disk_key, i);
if (!progress_passed && comp_keys(&disk_key, progress) < 0)
continue;
progress_passed = 1;
blocknr = btrfs_node_blockptr(parent, i);
gen = btrfs_node_ptr_generation(parent, i);
if (last_block == 0)
last_block = blocknr;
if (i > 0) {
other = btrfs_node_blockptr(parent, i - 1);
close = close_blocks(blocknr, other, blocksize);
}
if (!close && i < end_slot - 2) {
other = btrfs_node_blockptr(parent, i + 1);
close = close_blocks(blocknr, other, blocksize);
}
if (close) {
last_block = blocknr;
continue;
}
cur = btrfs_find_tree_block(root, blocknr, blocksize);
if (cur)
uptodate = btrfs_buffer_uptodate(cur, gen, 0);
else
uptodate = 0;
if (!cur || !uptodate) {
if (cache_only) {
free_extent_buffer(cur);
continue;
}
if (!cur) {
cur = read_tree_block(root, blocknr,
blocksize, gen);
if (!cur)
return -EIO;
} else if (!uptodate) {
btrfs_read_buffer(cur, gen);
}
}
if (search_start == 0)
search_start = last_block;
btrfs_tree_lock(cur);
btrfs_set_lock_blocking(cur);
err = __btrfs_cow_block(trans, root, cur, parent, i,
&cur, search_start,
min(16 * blocksize,
(end_slot - i) * blocksize));
if (err) {
btrfs_tree_unlock(cur);
free_extent_buffer(cur);
break;
}
search_start = cur->start;
last_block = cur->start;
*last_ret = search_start;
btrfs_tree_unlock(cur);
free_extent_buffer(cur);
}
return err;
}
/*
* The leaf data grows from end-to-front in the node.
* this returns the address of the start of the last item,
* which is the stop of the leaf data stack
*/
static inline unsigned int leaf_data_end(struct btrfs_root *root,
struct extent_buffer *leaf)
{
u32 nr = btrfs_header_nritems(leaf);
if (nr == 0)
return BTRFS_LEAF_DATA_SIZE(root);
return btrfs_item_offset_nr(leaf, nr - 1);
}
/*
* search for key in the extent_buffer. The items start at offset p,
* and they are item_size apart. There are 'max' items in p.
*
* the slot in the array is returned via slot, and it points to
* the place where you would insert key if it is not found in
* the array.
*
* slot may point to max if the key is bigger than all of the keys
*/
static noinline int generic_bin_search(struct extent_buffer *eb,
unsigned long p,
int item_size, struct btrfs_key *key,
int max, int *slot)
{
int low = 0;
int high = max;
int mid;
int ret;
struct btrfs_disk_key *tmp = NULL;
struct btrfs_disk_key unaligned;
unsigned long offset;
char *kaddr = NULL;
unsigned long map_start = 0;
unsigned long map_len = 0;
int err;
while (low < high) {
mid = (low + high) / 2;
offset = p + mid * item_size;
if (!kaddr || offset < map_start ||
(offset + sizeof(struct btrfs_disk_key)) >
map_start + map_len) {
err = map_private_extent_buffer(eb, offset,
sizeof(struct btrfs_disk_key),
&kaddr, &map_start, &map_len);
if (!err) {
tmp = (struct btrfs_disk_key *)(kaddr + offset -
map_start);
} else {
read_extent_buffer(eb, &unaligned,
offset, sizeof(unaligned));
tmp = &unaligned;
}
} else {
tmp = (struct btrfs_disk_key *)(kaddr + offset -
map_start);
}
ret = comp_keys(tmp, key);
if (ret < 0)
low = mid + 1;
else if (ret > 0)
high = mid;
else {
*slot = mid;
return 0;
}
}
*slot = low;
return 1;
}
/*
* simple bin_search frontend that does the right thing for
* leaves vs nodes
*/
static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
int level, int *slot)
{
if (level == 0) {
return generic_bin_search(eb,
offsetof(struct btrfs_leaf, items),
sizeof(struct btrfs_item),
key, btrfs_header_nritems(eb),
slot);
} else {
return generic_bin_search(eb,
offsetof(struct btrfs_node, ptrs),
sizeof(struct btrfs_key_ptr),
key, btrfs_header_nritems(eb),
slot);
}
return -1;
}
int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
int level, int *slot)
{
return bin_search(eb, key, level, slot);
}
static void root_add_used(struct btrfs_root *root, u32 size)
{
spin_lock(&root->accounting_lock);
btrfs_set_root_used(&root->root_item,
btrfs_root_used(&root->root_item) + size);
spin_unlock(&root->accounting_lock);
}
static void root_sub_used(struct btrfs_root *root, u32 size)
{
spin_lock(&root->accounting_lock);
btrfs_set_root_used(&root->root_item,
btrfs_root_used(&root->root_item) - size);
spin_unlock(&root->accounting_lock);
}
/* given a node and slot number, this reads the blocks it points to. The
* extent buffer is returned with a reference taken (but unlocked).
* NULL is returned on error.
*/
static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
struct extent_buffer *parent, int slot)
{
int level = btrfs_header_level(parent);
if (slot < 0)
return NULL;
if (slot >= btrfs_header_nritems(parent))
return NULL;
BUG_ON(level == 0);
return read_tree_block(root, btrfs_node_blockptr(parent, slot),
btrfs_level_size(root, level - 1),
btrfs_node_ptr_generation(parent, slot));
}
/*
* node level balancing, used to make sure nodes are in proper order for
* item deletion. We balance from the top down, so we have to make sure
* that a deletion won't leave an node completely empty later on.
*/
static noinline int balance_level(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int level)
{
struct extent_buffer *right = NULL;
struct extent_buffer *mid;
struct extent_buffer *left = NULL;
struct extent_buffer *parent = NULL;
int ret = 0;
int wret;
int pslot;
int orig_slot = path->slots[level];
u64 orig_ptr;
if (level == 0)
return 0;
mid = path->nodes[level];
WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
WARN_ON(btrfs_header_generation(mid) != trans->transid);
orig_ptr = btrfs_node_blockptr(mid, orig_slot);
if (level < BTRFS_MAX_LEVEL - 1) {
parent = path->nodes[level + 1];
pslot = path->slots[level + 1];
}
/*
* deal with the case where there is only one pointer in the root
* by promoting the node below to a root
*/
if (!parent) {
struct extent_buffer *child;
if (btrfs_header_nritems(mid) != 1)
return 0;
/* promote the child to a root */
child = read_node_slot(root, mid, 0);
if (!child) {
ret = -EROFS;
btrfs_std_error(root->fs_info, ret);
goto enospc;
}
btrfs_tree_lock(child);
btrfs_set_lock_blocking(child);
ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
if (ret) {
btrfs_tree_unlock(child);
free_extent_buffer(child);
goto enospc;
}
rcu_assign_pointer(root->node, child);
add_root_to_dirty_list(root);
btrfs_tree_unlock(child);
path->locks[level] = 0;
path->nodes[level] = NULL;
clean_tree_block(trans, root, mid);
btrfs_tree_unlock(mid);
/* once for the path */
free_extent_buffer(mid);
root_sub_used(root, mid->len);
btrfs_free_tree_block(trans, root, mid, 0, 1, 0);
/* once for the root ptr */
free_extent_buffer_stale(mid);
return 0;
}
if (btrfs_header_nritems(mid) >
BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
return 0;
btrfs_header_nritems(mid);
left = read_node_slot(root, parent, pslot - 1);
if (left) {
btrfs_tree_lock(left);
btrfs_set_lock_blocking(left);
wret = btrfs_cow_block(trans, root, left,
parent, pslot - 1, &left);
if (wret) {
ret = wret;
goto enospc;
}
}
right = read_node_slot(root, parent, pslot + 1);
if (right) {
btrfs_tree_lock(right);
btrfs_set_lock_blocking(right);
wret = btrfs_cow_block(trans, root, right,
parent, pslot + 1, &right);
if (wret) {
ret = wret;
goto enospc;
}
}
/* first, try to make some room in the middle buffer */
if (left) {
orig_slot += btrfs_header_nritems(left);
wret = push_node_left(trans, root, left, mid, 1);
if (wret < 0)
ret = wret;
btrfs_header_nritems(mid);
}
/*
* then try to empty the right most buffer into the middle
*/
if (right) {
wret = push_node_left(trans, root, mid, right, 1);
if (wret < 0 && wret != -ENOSPC)
ret = wret;
if (btrfs_header_nritems(right) == 0) {
clean_tree_block(trans, root, right);
btrfs_tree_unlock(right);
del_ptr(trans, root, path, level + 1, pslot + 1);
root_sub_used(root, right->len);
btrfs_free_tree_block(trans, root, right, 0, 1, 0);
free_extent_buffer_stale(right);
right = NULL;
} else {
struct btrfs_disk_key right_key;
btrfs_node_key(right, &right_key, 0);
btrfs_set_node_key(parent, &right_key, pslot + 1);
btrfs_mark_buffer_dirty(parent);
}
}
if (btrfs_header_nritems(mid) == 1) {
/*
* we're not allowed to leave a node with one item in the
* tree during a delete. A deletion from lower in the tree
* could try to delete the only pointer in this node.
* So, pull some keys from the left.
* There has to be a left pointer at this point because
* otherwise we would have pulled some pointers from the
* right
*/
if (!left) {
ret = -EROFS;
btrfs_std_error(root->fs_info, ret);
goto enospc;
}
wret = balance_node_right(trans, root, mid, left);
if (wret < 0) {
ret = wret;
goto enospc;
}
if (wret == 1) {
wret = push_node_left(trans, root, left, mid, 1);
if (wret < 0)
ret = wret;
}
BUG_ON(wret == 1);
}
if (btrfs_header_nritems(mid) == 0) {
clean_tree_block(trans, root, mid);
btrfs_tree_unlock(mid);
del_ptr(trans, root, path, level + 1, pslot);
root_sub_used(root, mid->len);
btrfs_free_tree_block(trans, root, mid, 0, 1, 0);
free_extent_buffer_stale(mid);
mid = NULL;
} else {
/* update the parent key to reflect our changes */
struct btrfs_disk_key mid_key;
btrfs_node_key(mid, &mid_key, 0);
btrfs_set_node_key(parent, &mid_key, pslot);
btrfs_mark_buffer_dirty(parent);
}
/* update the path */
if (left) {
if (btrfs_header_nritems(left) > orig_slot) {
extent_buffer_get(left);
/* left was locked after cow */
path->nodes[level] = left;
path->slots[level + 1] -= 1;
path->slots[level] = orig_slot;
if (mid) {
btrfs_tree_unlock(mid);
free_extent_buffer(mid);
}
} else {
orig_slot -= btrfs_header_nritems(left);
path->slots[level] = orig_slot;
}
}
/* double check we haven't messed things up */
if (orig_ptr !=
btrfs_node_blockptr(path->nodes[level], path->slots[level]))
BUG();
enospc:
if (right) {
btrfs_tree_unlock(right);
free_extent_buffer(right);
}
if (left) {
if (path->nodes[level] != left)
btrfs_tree_unlock(left);
free_extent_buffer(left);
}
return ret;
}
/* Node balancing for insertion. Here we only split or push nodes around
* when they are completely full. This is also done top down, so we
* have to be pessimistic.
*/
static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int level)
{
struct extent_buffer *right = NULL;
struct extent_buffer *mid;
struct extent_buffer *left = NULL;
struct extent_buffer *parent = NULL;
int ret = 0;
int wret;
int pslot;
int orig_slot = path->slots[level];
if (level == 0)
return 1;
mid = path->nodes[level];
WARN_ON(btrfs_header_generation(mid) != trans->transid);
if (level < BTRFS_MAX_LEVEL - 1) {
parent = path->nodes[level + 1];
pslot = path->slots[level + 1];
}
if (!parent)
return 1;
left = read_node_slot(root, parent, pslot - 1);
/* first, try to make some room in the middle buffer */
if (left) {
u32 left_nr;
btrfs_tree_lock(left);
btrfs_set_lock_blocking(left);
left_nr = btrfs_header_nritems(left);
if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
wret = 1;
} else {
ret = btrfs_cow_block(trans, root, left, parent,
pslot - 1, &left);
if (ret)
wret = 1;
else {
wret = push_node_left(trans, root,
left, mid, 0);
}
}
if (wret < 0)
ret = wret;
if (wret == 0) {
struct btrfs_disk_key disk_key;
orig_slot += left_nr;
btrfs_node_key(mid, &disk_key, 0);
btrfs_set_node_key(parent, &disk_key, pslot);
btrfs_mark_buffer_dirty(parent);
if (btrfs_header_nritems(left) > orig_slot) {
path->nodes[level] = left;
path->slots[level + 1] -= 1;
path->slots[level] = orig_slot;
btrfs_tree_unlock(mid);
free_extent_buffer(mid);
} else {
orig_slot -=
btrfs_header_nritems(left);
path->slots[level] = orig_slot;
btrfs_tree_unlock(left);
free_extent_buffer(left);
}
return 0;
}
btrfs_tree_unlock(left);
free_extent_buffer(left);
}
right = read_node_slot(root, parent, pslot + 1);
/*
* then try to empty the right most buffer into the middle
*/
if (right) {
u32 right_nr;
btrfs_tree_lock(right);
btrfs_set_lock_blocking(right);
right_nr = btrfs_header_nritems(right);
if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
wret = 1;
} else {
ret = btrfs_cow_block(trans, root, right,
parent, pslot + 1,
&right);
if (ret)
wret = 1;
else {
wret = balance_node_right(trans, root,
right, mid);
}
}
if (wret < 0)
ret = wret;
if (wret == 0) {
struct btrfs_disk_key disk_key;
btrfs_node_key(right, &disk_key, 0);
btrfs_set_node_key(parent, &disk_key, pslot + 1);
btrfs_mark_buffer_dirty(parent);
if (btrfs_header_nritems(mid) <= orig_slot) {
path->nodes[level] = right;
path->slots[level + 1] += 1;
path->slots[level] = orig_slot -
btrfs_header_nritems(mid);
btrfs_tree_unlock(mid);
free_extent_buffer(mid);
} else {
btrfs_tree_unlock(right);
free_extent_buffer(right);
}
return 0;
}
btrfs_tree_unlock(right);
free_extent_buffer(right);
}
return 1;
}
/*
* readahead one full node of leaves, finding things that are close
* to the block in 'slot', and triggering ra on them.
*/
static void reada_for_search(struct btrfs_root *root,
struct btrfs_path *path,
int level, int slot, u64 objectid)
{
struct extent_buffer *node;
struct btrfs_disk_key disk_key;
u32 nritems;
u64 search;
u64 target;
u64 nread = 0;
u64 gen;
int direction = path->reada;
struct extent_buffer *eb;
u32 nr;
u32 blocksize;
u32 nscan = 0;
if (level != 1)
return;
if (!path->nodes[level])
return;
node = path->nodes[level];
search = btrfs_node_blockptr(node, slot);
blocksize = btrfs_level_size(root, level - 1);
eb = btrfs_find_tree_block(root, search, blocksize);
if (eb) {
free_extent_buffer(eb);
return;
}
target = search;
nritems = btrfs_header_nritems(node);
nr = slot;
while (1) {
if (direction < 0) {
if (nr == 0)
break;
nr--;
} else if (direction > 0) {
nr++;
if (nr >= nritems)
break;
}
if (path->reada < 0 && objectid) {
btrfs_node_key(node, &disk_key, nr);
if (btrfs_disk_key_objectid(&disk_key) != objectid)
break;
}
search = btrfs_node_blockptr(node, nr);
if ((search <= target && target - search <= 65536) ||
(search > target && search - target <= 65536)) {
gen = btrfs_node_ptr_generation(node, nr);
readahead_tree_block(root, search, blocksize, gen);
nread += blocksize;
}
nscan++;
if ((nread > 65536 || nscan > 32))
break;
}
}
/*
* returns -EAGAIN if it had to drop the path, or zero if everything was in
* cache
*/
static noinline int reada_for_balance(struct btrfs_root *root,
struct btrfs_path *path, int level)
{
int slot;
int nritems;
struct extent_buffer *parent;
struct extent_buffer *eb;
u64 gen;
u64 block1 = 0;
u64 block2 = 0;
int ret = 0;
int blocksize;
parent = path->nodes[level + 1];
if (!parent)
return 0;
nritems = btrfs_header_nritems(parent);
slot = path->slots[level + 1];
blocksize = btrfs_level_size(root, level);
if (slot > 0) {
block1 = btrfs_node_blockptr(parent, slot - 1);
gen = btrfs_node_ptr_generation(parent, slot - 1);
eb = btrfs_find_tree_block(root, block1, blocksize);
/*
* if we get -eagain from btrfs_buffer_uptodate, we
* don't want to return eagain here. That will loop
* forever
*/
if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
block1 = 0;
free_extent_buffer(eb);
}
if (slot + 1 < nritems) {
block2 = btrfs_node_blockptr(parent, slot + 1);
gen = btrfs_node_ptr_generation(parent, slot + 1);
eb = btrfs_find_tree_block(root, block2, blocksize);
if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
block2 = 0;
free_extent_buffer(eb);
}
if (block1 || block2) {
ret = -EAGAIN;
/* release the whole path */
btrfs_release_path(path);
/* read the blocks */
if (block1)
readahead_tree_block(root, block1, blocksize, 0);
if (block2)
readahead_tree_block(root, block2, blocksize, 0);
if (block1) {
eb = read_tree_block(root, block1, blocksize, 0);
free_extent_buffer(eb);
}
if (block2) {
eb = read_tree_block(root, block2, blocksize, 0);
free_extent_buffer(eb);
}
}
return ret;
}
/*
* when we walk down the tree, it is usually safe to unlock the higher layers
* in the tree. The exceptions are when our path goes through slot 0, because
* operations on the tree might require changing key pointers higher up in the
* tree.
*
* callers might also have set path->keep_locks, which tells this code to keep
* the lock if the path points to the last slot in the block. This is part of
* walking through the tree, and selecting the next slot in the higher block.
*
* lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
* if lowest_unlock is 1, level 0 won't be unlocked
*/
static noinline void unlock_up(struct btrfs_path *path, int level,
int lowest_unlock, int min_write_lock_level,
int *write_lock_level)
{
int i;
int skip_level = level;
int no_skips = 0;
struct extent_buffer *t;
for (i = level; i < BTRFS_MAX_LEVEL; i++) {
if (!path->nodes[i])
break;
if (!path->locks[i])
break;
if (!no_skips && path->slots[i] == 0) {
skip_level = i + 1;
continue;
}
if (!no_skips && path->keep_locks) {
u32 nritems;
t = path->nodes[i];
nritems = btrfs_header_nritems(t);
if (nritems < 1 || path->slots[i] >= nritems - 1) {
skip_level = i + 1;
continue;
}
}
if (skip_level < i && i >= lowest_unlock)
no_skips = 1;
t = path->nodes[i];
if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
btrfs_tree_unlock_rw(t, path->locks[i]);
path->locks[i] = 0;
if (write_lock_level &&
i > min_write_lock_level &&
i <= *write_lock_level) {
*write_lock_level = i - 1;
}
}
}
}
/*
* This releases any locks held in the path starting at level and
* going all the way up to the root.
*
* btrfs_search_slot will keep the lock held on higher nodes in a few
* corner cases, such as COW of the block at slot zero in the node. This
* ignores those rules, and it should only be called when there are no
* more updates to be done higher up in the tree.
*/
noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
{
int i;
if (path->keep_locks)
return;
for (i = level; i < BTRFS_MAX_LEVEL; i++) {
if (!path->nodes[i])
continue;
if (!path->locks[i])
continue;
btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
path->locks[i] = 0;
}
}
/*
* helper function for btrfs_search_slot. The goal is to find a block
* in cache without setting the path to blocking. If we find the block
* we return zero and the path is unchanged.
*
* If we can't find the block, we set the path blocking and do some
* reada. -EAGAIN is returned and the search must be repeated.
*/
static int
read_block_for_search(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *p,
struct extent_buffer **eb_ret, int level, int slot,
struct btrfs_key *key)
{
u64 blocknr;
u64 gen;
u32 blocksize;
struct extent_buffer *b = *eb_ret;
struct extent_buffer *tmp;
int ret;
blocknr = btrfs_node_blockptr(b, slot);
gen = btrfs_node_ptr_generation(b, slot);
blocksize = btrfs_level_size(root, level - 1);
tmp = btrfs_find_tree_block(root, blocknr, blocksize);
if (tmp) {
/* first we do an atomic uptodate check */
if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
/*
* we found an up to date block without
* sleeping, return
* right away
*/
*eb_ret = tmp;
return 0;
}
/* the pages were up to date, but we failed
* the generation number check. Do a full
* read for the generation number that is correct.
* We must do this without dropping locks so
* we can trust our generation number
*/
free_extent_buffer(tmp);
btrfs_set_path_blocking(p);
/* now we're allowed to do a blocking uptodate check */
tmp = read_tree_block(root, blocknr, blocksize, gen);
if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
*eb_ret = tmp;
return 0;
}
free_extent_buffer(tmp);
btrfs_release_path(p);
return -EIO;
}
}
/*
* reduce lock contention at high levels
* of the btree by dropping locks before
* we read. Don't release the lock on the current
* level because we need to walk this node to figure
* out which blocks to read.
*/
btrfs_unlock_up_safe(p, level + 1);
btrfs_set_path_blocking(p);
free_extent_buffer(tmp);
if (p->reada)
reada_for_search(root, p, level, slot, key->objectid);
btrfs_release_path(p);
ret = -EAGAIN;
tmp = read_tree_block(root, blocknr, blocksize, 0);
if (tmp) {
/*
* If the read above didn't mark this buffer up to date,
* it will never end up being up to date. Set ret to EIO now
* and give up so that our caller doesn't loop forever
* on our EAGAINs.
*/
if (!btrfs_buffer_uptodate(tmp, 0, 0))
ret = -EIO;
free_extent_buffer(tmp);
}
return ret;
}
/*
* helper function for btrfs_search_slot. This does all of the checks
* for node-level blocks and does any balancing required based on
* the ins_len.
*
* If no extra work was required, zero is returned. If we had to
* drop the path, -EAGAIN is returned and btrfs_search_slot must
* start over
*/
static int
setup_nodes_for_search(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *p,
struct extent_buffer *b, int level, int ins_len,
int *write_lock_level)
{
int ret;
if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
int sret;
if (*write_lock_level < level + 1) {
*write_lock_level = level + 1;
btrfs_release_path(p);
goto again;
}
sret = reada_for_balance(root, p, level);
if (sret)
goto again;
btrfs_set_path_blocking(p);
sret = split_node(trans, root, p, level);
btrfs_clear_path_blocking(p, NULL, 0);
BUG_ON(sret > 0);
if (sret) {
ret = sret;
goto done;
}
b = p->nodes[level];
} else if (ins_len < 0 && btrfs_header_nritems(b) <
BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
int sret;
if (*write_lock_level < level + 1) {
*write_lock_level = level + 1;
btrfs_release_path(p);
goto again;
}
sret = reada_for_balance(root, p, level);
if (sret)
goto again;
btrfs_set_path_blocking(p);
sret = balance_level(trans, root, p, level);
btrfs_clear_path_blocking(p, NULL, 0);
if (sret) {
ret = sret;
goto done;
}
b = p->nodes[level];
if (!b) {
btrfs_release_path(p);
goto again;
}
BUG_ON(btrfs_header_nritems(b) == 1);
}
return 0;
again:
ret = -EAGAIN;
done:
return ret;
}
/*
* look for key in the tree. path is filled in with nodes along the way
* if key is found, we return zero and you can find the item in the leaf
* level of the path (level 0)
*
* If the key isn't found, the path points to the slot where it should
* be inserted, and 1 is returned. If there are other errors during the
* search a negative error number is returned.
*
* if ins_len > 0, nodes and leaves will be split as we walk down the
* tree. if ins_len < 0, nodes will be merged as we walk down the tree (if
* possible)
*/
int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
*root, struct btrfs_key *key, struct btrfs_path *p, int
ins_len, int cow)
{
struct extent_buffer *b;
int slot;
int ret;
int err;
int level;
int lowest_unlock = 1;
int root_lock;
/* everything at write_lock_level or lower must be write locked */
int write_lock_level = 0;
u8 lowest_level = 0;
int min_write_lock_level;
lowest_level = p->lowest_level;
WARN_ON(lowest_level && ins_len > 0);
WARN_ON(p->nodes[0] != NULL);
if (ins_len < 0) {
lowest_unlock = 2;
/* when we are removing items, we might have to go up to level
* two as we update tree pointers Make sure we keep write
* for those levels as well
*/
write_lock_level = 2;
} else if (ins_len > 0) {
/*
* for inserting items, make sure we have a write lock on
* level 1 so we can update keys
*/
write_lock_level = 1;
}
if (!cow)
write_lock_level = -1;
if (cow && (p->keep_locks || p->lowest_level))
write_lock_level = BTRFS_MAX_LEVEL;
min_write_lock_level = write_lock_level;
again:
/*
* we try very hard to do read locks on the root
*/
root_lock = BTRFS_READ_LOCK;
level = 0;
if (p->search_commit_root) {
/*
* the commit roots are read only
* so we always do read locks
*/
b = root->commit_root;
extent_buffer_get(b);
level = btrfs_header_level(b);
if (!p->skip_locking)
btrfs_tree_read_lock(b);
} else {
if (p->skip_locking) {
b = btrfs_root_node(root);
level = btrfs_header_level(b);
} else {
/* we don't know the level of the root node
* until we actually have it read locked
*/
b = btrfs_read_lock_root_node(root);
level = btrfs_header_level(b);
if (level <= write_lock_level) {
/* whoops, must trade for write lock */
btrfs_tree_read_unlock(b);
free_extent_buffer(b);
b = btrfs_lock_root_node(root);
root_lock = BTRFS_WRITE_LOCK;
/* the level might have changed, check again */
level = btrfs_header_level(b);
}
}
}
p->nodes[level] = b;
if (!p->skip_locking)
p->locks[level] = root_lock;
while (b) {
level = btrfs_header_level(b);
/*
* setup the path here so we can release it under lock
* contention with the cow code
*/
if (cow) {
/*
* if we don't really need to cow this block
* then we don't want to set the path blocking,
* so we test it here
*/
if (!should_cow_block(trans, root, b))
goto cow_done;
btrfs_set_path_blocking(p);
/*
* must have write locks on this node and the
* parent
*/
if (level + 1 > write_lock_level) {
write_lock_level = level + 1;
btrfs_release_path(p);
goto again;
}
err = btrfs_cow_block(trans, root, b,
p->nodes[level + 1],
p->slots[level + 1], &b);
if (err) {
ret = err;
goto done;
}
}
cow_done:
BUG_ON(!cow && ins_len);
p->nodes[level] = b;
btrfs_clear_path_blocking(p, NULL, 0);
/*
* we have a lock on b and as long as we aren't changing
* the tree, there is no way to for the items in b to change.
* It is safe to drop the lock on our parent before we
* go through the expensive btree search on b.
*
* If cow is true, then we might be changing slot zero,
* which may require changing the parent. So, we can't
* drop the lock until after we know which slot we're
* operating on.
*/
if (!cow)
btrfs_unlock_up_safe(p, level + 1);
ret = bin_search(b, key, level, &slot);
if (level != 0) {
int dec = 0;
if (ret && slot > 0) {
dec = 1;
slot -= 1;
}
p->slots[level] = slot;
err = setup_nodes_for_search(trans, root, p, b, level,
ins_len, &write_lock_level);
if (err == -EAGAIN)
goto again;
if (err) {
ret = err;
goto done;
}
b = p->nodes[level];
slot = p->slots[level];
/*
* slot 0 is special, if we change the key
* we have to update the parent pointer
* which means we must have a write lock
* on the parent
*/
if (slot == 0 && cow &&
write_lock_level < level + 1) {
write_lock_level = level + 1;
btrfs_release_path(p);
goto again;
}
unlock_up(p, level, lowest_unlock,
min_write_lock_level, &write_lock_level);
if (level == lowest_level) {
if (dec)
p->slots[level]++;
goto done;
}
err = read_block_for_search(trans, root, p,
&b, level, slot, key);
if (err == -EAGAIN)
goto again;
if (err) {
ret = err;
goto done;
}
if (!p->skip_locking) {
level = btrfs_header_level(b);
if (level <= write_lock_level) {
err = btrfs_try_tree_write_lock(b);
if (!err) {
btrfs_set_path_blocking(p);
btrfs_tree_lock(b);
btrfs_clear_path_blocking(p, b,
BTRFS_WRITE_LOCK);
}
p->locks[level] = BTRFS_WRITE_LOCK;
} else {
err = btrfs_try_tree_read_lock(b);
if (!err) {
btrfs_set_path_blocking(p);
btrfs_tree_read_lock(b);
btrfs_clear_path_blocking(p, b,
BTRFS_READ_LOCK);
}
p->locks[level] = BTRFS_READ_LOCK;
}
p->nodes[level] = b;
}
} else {
p->slots[level] = slot;
if (ins_len > 0 &&
btrfs_leaf_free_space(root, b) < ins_len) {
if (write_lock_level < 1) {
write_lock_level = 1;
btrfs_release_path(p);
goto again;
}
btrfs_set_path_blocking(p);
err = split_leaf(trans, root, key,
p, ins_len, ret == 0);
btrfs_clear_path_blocking(p, NULL, 0);
BUG_ON(err > 0);
if (err) {
ret = err;
goto done;
}
}
if (!p->search_for_split)
unlock_up(p, level, lowest_unlock,
min_write_lock_level, &write_lock_level);
goto done;
}
}
ret = 1;
done:
/*
* we don't really know what they plan on doing with the path
* from here on, so for now just mark it as blocking
*/
if (!p->leave_spinning)
btrfs_set_path_blocking(p);
if (ret < 0)
btrfs_release_path(p);
return ret;
}
/*
* adjust the pointers going up the tree, starting at level
* making sure the right key of each node is points to 'key'.
* This is used after shifting pointers to the left, so it stops
* fixing up pointers when a given leaf/node is not in slot 0 of the
* higher levels
*
*/
static void fixup_low_keys(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *path,
struct btrfs_disk_key *key, int level)
{
int i;
struct extent_buffer *t;
for (i = level; i < BTRFS_MAX_LEVEL; i++) {
int tslot = path->slots[i];
if (!path->nodes[i])
break;
t = path->nodes[i];
btrfs_set_node_key(t, key, tslot);
btrfs_mark_buffer_dirty(path->nodes[i]);
if (tslot != 0)
break;
}
}
/*
* update item key.
*
* This function isn't completely safe. It's the caller's responsibility
* that the new key won't break the order
*/
void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *path,
struct btrfs_key *new_key)
{
struct btrfs_disk_key disk_key;
struct extent_buffer *eb;
int slot;
eb = path->nodes[0];
slot = path->slots[0];
if (slot > 0) {
btrfs_item_key(eb, &disk_key, slot - 1);
BUG_ON(comp_keys(&disk_key, new_key) >= 0);
}
if (slot < btrfs_header_nritems(eb) - 1) {
btrfs_item_key(eb, &disk_key, slot + 1);
BUG_ON(comp_keys(&disk_key, new_key) <= 0);
}
btrfs_cpu_key_to_disk(&disk_key, new_key);
btrfs_set_item_key(eb, &disk_key, slot);
btrfs_mark_buffer_dirty(eb);
if (slot == 0)
fixup_low_keys(trans, root, path, &disk_key, 1);
}
/*
* try to push data from one node into the next node left in the
* tree.
*
* returns 0 if some ptrs were pushed left, < 0 if there was some horrible
* error, and > 0 if there was no room in the left hand block.
*/
static int push_node_left(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct extent_buffer *dst,
struct extent_buffer *src, int empty)
{
int push_items = 0;
int src_nritems;
int dst_nritems;
int ret = 0;
src_nritems = btrfs_header_nritems(src);
dst_nritems = btrfs_header_nritems(dst);
push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
WARN_ON(btrfs_header_generation(src) != trans->transid);
WARN_ON(btrfs_header_generation(dst) != trans->transid);
if (!empty && src_nritems <= 8)
return 1;
if (push_items <= 0)
return 1;
if (empty) {
push_items = min(src_nritems, push_items);
if (push_items < src_nritems) {
/* leave at least 8 pointers in the node if
* we aren't going to empty it
*/
if (src_nritems - push_items < 8) {
if (push_items <= 8)
return 1;
push_items -= 8;
}
}
} else
push_items = min(src_nritems - 8, push_items);
copy_extent_buffer(dst, src,
btrfs_node_key_ptr_offset(dst_nritems),
btrfs_node_key_ptr_offset(0),
push_items * sizeof(struct btrfs_key_ptr));
if (push_items < src_nritems) {
memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
btrfs_node_key_ptr_offset(push_items),
(src_nritems - push_items) *
sizeof(struct btrfs_key_ptr));
}
btrfs_set_header_nritems(src, src_nritems - push_items);
btrfs_set_header_nritems(dst, dst_nritems + push_items);
btrfs_mark_buffer_dirty(src);
btrfs_mark_buffer_dirty(dst);
return ret;
}
/*
* try to push data from one node into the next node right in the
* tree.
*
* returns 0 if some ptrs were pushed, < 0 if there was some horrible
* error, and > 0 if there was no room in the right hand block.
*
* this will only push up to 1/2 the contents of the left node over
*/
static int balance_node_right(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct extent_buffer *dst,
struct extent_buffer *src)
{
int push_items = 0;
int max_push;
int src_nritems;
int dst_nritems;
int ret = 0;
WARN_ON(btrfs_header_generation(src) != trans->transid);
WARN_ON(btrfs_header_generation(dst) != trans->transid);
src_nritems = btrfs_header_nritems(src);
dst_nritems = btrfs_header_nritems(dst);
push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
if (push_items <= 0)
return 1;
if (src_nritems < 4)
return 1;
max_push = src_nritems / 2 + 1;
/* don't try to empty the node */
if (max_push >= src_nritems)
return 1;
if (max_push < push_items)
push_items = max_push;
memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
btrfs_node_key_ptr_offset(0),
(dst_nritems) *
sizeof(struct btrfs_key_ptr));
copy_extent_buffer(dst, src,
btrfs_node_key_ptr_offset(0),
btrfs_node_key_ptr_offset(src_nritems - push_items),
push_items * sizeof(struct btrfs_key_ptr));
btrfs_set_header_nritems(src, src_nritems - push_items);
btrfs_set_header_nritems(dst, dst_nritems + push_items);
btrfs_mark_buffer_dirty(src);
btrfs_mark_buffer_dirty(dst);
return ret;
}
/*
* helper function to insert a new root level in the tree.
* A new node is allocated, and a single item is inserted to
* point to the existing root
*
* returns zero on success or < 0 on failure.
*/
static noinline int insert_new_root(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int level)
{
u64 lower_gen;
struct extent_buffer *lower;
struct extent_buffer *c;
struct extent_buffer *old;
struct btrfs_disk_key lower_key;
BUG_ON(path->nodes[level]);
BUG_ON(path->nodes[level-1] != root->node);
lower = path->nodes[level-1];
if (level == 1)
btrfs_item_key(lower, &lower_key, 0);
else
btrfs_node_key(lower, &lower_key, 0);
c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
root->root_key.objectid, &lower_key,
level, root->node->start, 0, 0);
if (IS_ERR(c))
return PTR_ERR(c);
root_add_used(root, root->nodesize);
memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
btrfs_set_header_nritems(c, 1);
btrfs_set_header_level(c, level);
btrfs_set_header_bytenr(c, c->start);
btrfs_set_header_generation(c, trans->transid);
btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
btrfs_set_header_owner(c, root->root_key.objectid);
write_extent_buffer(c, root->fs_info->fsid,
(unsigned long)btrfs_header_fsid(c),
BTRFS_FSID_SIZE);
write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
(unsigned long)btrfs_header_chunk_tree_uuid(c),
BTRFS_UUID_SIZE);
btrfs_set_node_key(c, &lower_key, 0);
btrfs_set_node_blockptr(c, 0, lower->start);
lower_gen = btrfs_header_generation(lower);
WARN_ON(lower_gen != trans->transid);
btrfs_set_node_ptr_generation(c, 0, lower_gen);
btrfs_mark_buffer_dirty(c);
old = root->node;
rcu_assign_pointer(root->node, c);
/* the super has an extra ref to root->node */
free_extent_buffer(old);
add_root_to_dirty_list(root);
extent_buffer_get(c);
path->nodes[level] = c;
path->locks[level] = BTRFS_WRITE_LOCK;
path->slots[level] = 0;
return 0;
}
/*
* worker function to insert a single pointer in a node.
* the node should have enough room for the pointer already
*
* slot and level indicate where you want the key to go, and
* blocknr is the block the key points to.
*/
static void insert_ptr(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *path,
struct btrfs_disk_key *key, u64 bytenr,
int slot, int level)
{
struct extent_buffer *lower;
int nritems;
BUG_ON(!path->nodes[level]);
btrfs_assert_tree_locked(path->nodes[level]);
lower = path->nodes[level];
nritems = btrfs_header_nritems(lower);
BUG_ON(slot > nritems);
BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
if (slot != nritems) {
memmove_extent_buffer(lower,
btrfs_node_key_ptr_offset(slot + 1),
btrfs_node_key_ptr_offset(slot),
(nritems - slot) * sizeof(struct btrfs_key_ptr));
}
btrfs_set_node_key(lower, key, slot);
btrfs_set_node_blockptr(lower, slot, bytenr);
WARN_ON(trans->transid == 0);
btrfs_set_node_ptr_generation(lower, slot, trans->transid);
btrfs_set_header_nritems(lower, nritems + 1);
btrfs_mark_buffer_dirty(lower);
}
/*
* split the node at the specified level in path in two.
* The path is corrected to point to the appropriate node after the split
*
* Before splitting this tries to make some room in the node by pushing
* left and right, if either one works, it returns right away.
*
* returns 0 on success and < 0 on failure
*/
static noinline int split_node(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int level)
{
struct extent_buffer *c;
struct extent_buffer *split;
struct btrfs_disk_key disk_key;
int mid;
int ret;
u32 c_nritems;
c = path->nodes[level];
WARN_ON(btrfs_header_generation(c) != trans->transid);
if (c == root->node) {
/* trying to split the root, lets make a new one */
ret = insert_new_root(trans, root, path, level + 1);
if (ret)
return ret;
} else {
ret = push_nodes_for_insert(trans, root, path, level);
c = path->nodes[level];
if (!ret && btrfs_header_nritems(c) <
BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
return 0;
if (ret < 0)
return ret;
}
c_nritems = btrfs_header_nritems(c);
mid = (c_nritems + 1) / 2;
btrfs_node_key(c, &disk_key, mid);
split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
root->root_key.objectid,
&disk_key, level, c->start, 0, 0);
if (IS_ERR(split))
return PTR_ERR(split);
root_add_used(root, root->nodesize);
memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
btrfs_set_header_level(split, btrfs_header_level(c));
btrfs_set_header_bytenr(split, split->start);
btrfs_set_header_generation(split, trans->transid);
btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
btrfs_set_header_owner(split, root->root_key.objectid);
write_extent_buffer(split, root->fs_info->fsid,
(unsigned long)btrfs_header_fsid(split),
BTRFS_FSID_SIZE);
write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
(unsigned long)btrfs_header_chunk_tree_uuid(split),
BTRFS_UUID_SIZE);
copy_extent_buffer(split, c,
btrfs_node_key_ptr_offset(0),
btrfs_node_key_ptr_offset(mid),
(c_nritems - mid) * sizeof(struct btrfs_key_ptr));
btrfs_set_header_nritems(split, c_nritems - mid);
btrfs_set_header_nritems(c, mid);
ret = 0;
btrfs_mark_buffer_dirty(c);
btrfs_mark_buffer_dirty(split);
insert_ptr(trans, root, path, &disk_key, split->start,
path->slots[level + 1] + 1, level + 1);
if (path->slots[level] >= mid) {
path->slots[level] -= mid;
btrfs_tree_unlock(c);
free_extent_buffer(c);
path->nodes[level] = split;
path->slots[level + 1] += 1;
} else {
btrfs_tree_unlock(split);
free_extent_buffer(split);
}
return ret;
}
/*
* how many bytes are required to store the items in a leaf. start
* and nr indicate which items in the leaf to check. This totals up the
* space used both by the item structs and the item data
*/
static int leaf_space_used(struct extent_buffer *l, int start, int nr)
{
int data_len;
int nritems = btrfs_header_nritems(l);
int end = min(nritems, start + nr) - 1;
if (!nr)
return 0;
data_len = btrfs_item_end_nr(l, start);
data_len = data_len - btrfs_item_offset_nr(l, end);
data_len += sizeof(struct btrfs_item) * nr;
WARN_ON(data_len < 0);
return data_len;
}
/*
* The space between the end of the leaf items and
* the start of the leaf data. IOW, how much room
* the leaf has left for both items and data
*/
noinline int btrfs_leaf_free_space(struct btrfs_root *root,
struct extent_buffer *leaf)
{
int nritems = btrfs_header_nritems(leaf);
int ret;
ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
if (ret < 0) {
printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
"used %d nritems %d\n",
ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
leaf_space_used(leaf, 0, nritems), nritems);
}
return ret;
}
/*
* min slot controls the lowest index we're willing to push to the
* right. We'll push up to and including min_slot, but no lower
*/
static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
int data_size, int empty,
struct extent_buffer *right,
int free_space, u32 left_nritems,
u32 min_slot)
{
struct extent_buffer *left = path->nodes[0];
struct extent_buffer *upper = path->nodes[1];
struct btrfs_map_token token;
struct btrfs_disk_key disk_key;
int slot;
u32 i;
int push_space = 0;
int push_items = 0;
struct btrfs_item *item;
u32 nr;
u32 right_nritems;
u32 data_end;
u32 this_item_size;
btrfs_init_map_token(&token);
if (empty)
nr = 0;
else
nr = max_t(u32, 1, min_slot);
if (path->slots[0] >= left_nritems)
push_space += data_size;
slot = path->slots[1];
i = left_nritems - 1;
while (i >= nr) {
item = btrfs_item_nr(left, i);
if (!empty && push_items > 0) {
if (path->slots[0] > i)
break;
if (path->slots[0] == i) {
int space = btrfs_leaf_free_space(root, left);
if (space + push_space * 2 > free_space)
break;
}
}
if (path->slots[0] == i)
push_space += data_size;
this_item_size = btrfs_item_size(left, item);
if (this_item_size + sizeof(*item) + push_space > free_space)
break;
push_items++;
push_space += this_item_size + sizeof(*item);
if (i == 0)
break;
i--;
}
if (push_items == 0)
goto out_unlock;
if (!empty && push_items == left_nritems)
WARN_ON(1);
/* push left to right */
right_nritems = btrfs_header_nritems(right);
push_space = btrfs_item_end_nr(left, left_nritems - push_items);
push_space -= leaf_data_end(root, left);
/* make room in the right data area */
data_end = leaf_data_end(root, right);
memmove_extent_buffer(right,
btrfs_leaf_data(right) + data_end - push_space,
btrfs_leaf_data(right) + data_end,
BTRFS_LEAF_DATA_SIZE(root) - data_end);
/* copy from the left data area */
copy_extent_buffer(right, left, btrfs_leaf_data(right) +
BTRFS_LEAF_DATA_SIZE(root) - push_space,
btrfs_leaf_data(left) + leaf_data_end(root, left),
push_space);
memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
btrfs_item_nr_offset(0),
right_nritems * sizeof(struct btrfs_item));
/* copy the items from left to right */
copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
btrfs_item_nr_offset(left_nritems - push_items),
push_items * sizeof(struct btrfs_item));
/* update the item pointers */
right_nritems += push_items;
btrfs_set_header_nritems(right, right_nritems);
push_space = BTRFS_LEAF_DATA_SIZE(root);
for (i = 0; i < right_nritems; i++) {
item = btrfs_item_nr(right, i);
push_space -= btrfs_token_item_size(right, item, &token);
btrfs_set_token_item_offset(right, item, push_space, &token);
}
left_nritems -= push_items;
btrfs_set_header_nritems(left, left_nritems);
if (left_nritems)
btrfs_mark_buffer_dirty(left);
else
clean_tree_block(trans, root, left);
btrfs_mark_buffer_dirty(right);
btrfs_item_key(right, &disk_key, 0);
btrfs_set_node_key(upper, &disk_key, slot + 1);
btrfs_mark_buffer_dirty(upper);
/* then fixup the leaf pointer in the path */
if (path->slots[0] >= left_nritems) {
path->slots[0] -= left_nritems;
if (btrfs_header_nritems(path->nodes[0]) == 0)
clean_tree_block(trans, root, path->nodes[0]);
btrfs_tree_unlock(path->nodes[0]);
free_extent_buffer(path->nodes[0]);
path->nodes[0] = right;
path->slots[1] += 1;
} else {
btrfs_tree_unlock(right);
free_extent_buffer(right);
}
return 0;
out_unlock:
btrfs_tree_unlock(right);
free_extent_buffer(right);
return 1;
}
/*
* push some data in the path leaf to the right, trying to free up at
* least data_size bytes. returns zero if the push worked, nonzero otherwise
*
* returns 1 if the push failed because the other node didn't have enough
* room, 0 if everything worked out and < 0 if there were major errors.
*
* this will push starting from min_slot to the end of the leaf. It won't
* push any slot lower than min_slot
*/
static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
*root, struct btrfs_path *path,
int min_data_size, int data_size,
int empty, u32 min_slot)
{
struct extent_buffer *left = path->nodes[0];
struct extent_buffer *right;
struct extent_buffer *upper;
int slot;
int free_space;
u32 left_nritems;
int ret;
if (!path->nodes[1])
return 1;
slot = path->slots[1];
upper = path->nodes[1];
if (slot >= btrfs_header_nritems(upper) - 1)
return 1;
btrfs_assert_tree_locked(path->nodes[1]);
right = read_node_slot(root, upper, slot + 1);
if (right == NULL)
return 1;
btrfs_tree_lock(right);
btrfs_set_lock_blocking(right);
free_space = btrfs_leaf_free_space(root, right);
if (free_space < data_size)
goto out_unlock;
/* cow and double check */
ret = btrfs_cow_block(trans, root, right, upper,
slot + 1, &right);
if (ret)
goto out_unlock;
free_space = btrfs_leaf_free_space(root, right);
if (free_space < data_size)
goto out_unlock;
left_nritems = btrfs_header_nritems(left);
if (left_nritems == 0)
goto out_unlock;
return __push_leaf_right(trans, root, path, min_data_size, empty,
right, free_space, left_nritems, min_slot);
out_unlock:
btrfs_tree_unlock(right);
free_extent_buffer(right);
return 1;
}
/*
* push some data in the path leaf to the left, trying to free up at
* least data_size bytes. returns zero if the push worked, nonzero otherwise
*
* max_slot can put a limit on how far into the leaf we'll push items. The
* item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
* items
*/
static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int data_size,
int empty, struct extent_buffer *left,
int free_space, u32 right_nritems,
u32 max_slot)
{
struct btrfs_disk_key disk_key;
struct extent_buffer *right = path->nodes[0];
int i;
int push_space = 0;
int push_items = 0;
struct btrfs_item *item;
u32 old_left_nritems;
u32 nr;
int ret = 0;
u32 this_item_size;
u32 old_left_item_size;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
if (empty)
nr = min(right_nritems, max_slot);
else
nr = min(right_nritems - 1, max_slot);
for (i = 0; i < nr; i++) {
item = btrfs_item_nr(right, i);
if (!empty && push_items > 0) {
if (path->slots[0] < i)
break;
if (path->slots[0] == i) {
int space = btrfs_leaf_free_space(root, right);
if (space + push_space * 2 > free_space)
break;
}
}
if (path->slots[0] == i)
push_space += data_size;
this_item_size = btrfs_item_size(right, item);
if (this_item_size + sizeof(*item) + push_space > free_space)
break;
push_items++;
push_space += this_item_size + sizeof(*item);
}
if (push_items == 0) {
ret = 1;
goto out;
}
if (!empty && push_items == btrfs_header_nritems(right))
WARN_ON(1);
/* push data from right to left */
copy_extent_buffer(left, right,
btrfs_item_nr_offset(btrfs_header_nritems(left)),
btrfs_item_nr_offset(0),
push_items * sizeof(struct btrfs_item));
push_space = BTRFS_LEAF_DATA_SIZE(root) -
btrfs_item_offset_nr(right, push_items - 1);
copy_extent_buffer(left, right, btrfs_leaf_data(left) +
leaf_data_end(root, left) - push_space,
btrfs_leaf_data(right) +
btrfs_item_offset_nr(right, push_items - 1),
push_space);
old_left_nritems = btrfs_header_nritems(left);
BUG_ON(old_left_nritems <= 0);
old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
u32 ioff;
item = btrfs_item_nr(left, i);
ioff = btrfs_token_item_offset(left, item, &token);
btrfs_set_token_item_offset(left, item,
ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
&token);
}
btrfs_set_header_nritems(left, old_left_nritems + push_items);
/* fixup right node */
if (push_items > right_nritems) {
printk(KERN_CRIT "push items %d nr %u\n", push_items,
right_nritems);
WARN_ON(1);
}
if (push_items < right_nritems) {
push_space = btrfs_item_offset_nr(right, push_items - 1) -
leaf_data_end(root, right);
memmove_extent_buffer(right, btrfs_leaf_data(right) +
BTRFS_LEAF_DATA_SIZE(root) - push_space,
btrfs_leaf_data(right) +
leaf_data_end(root, right), push_space);
memmove_extent_buffer(right, btrfs_item_nr_offset(0),
btrfs_item_nr_offset(push_items),
(btrfs_header_nritems(right) - push_items) *
sizeof(struct btrfs_item));
}
right_nritems -= push_items;
btrfs_set_header_nritems(right, right_nritems);
push_space = BTRFS_LEAF_DATA_SIZE(root);
for (i = 0; i < right_nritems; i++) {
item = btrfs_item_nr(right, i);
push_space = push_space - btrfs_token_item_size(right,
item, &token);
btrfs_set_token_item_offset(right, item, push_space, &token);
}
btrfs_mark_buffer_dirty(left);
if (right_nritems)
btrfs_mark_buffer_dirty(right);
else
clean_tree_block(trans, root, right);
btrfs_item_key(right, &disk_key, 0);
fixup_low_keys(trans, root, path, &disk_key, 1);
/* then fixup the leaf pointer in the path */
if (path->slots[0] < push_items) {
path->slots[0] += old_left_nritems;
btrfs_tree_unlock(path->nodes[0]);
free_extent_buffer(path->nodes[0]);
path->nodes[0] = left;
path->slots[1] -= 1;
} else {
btrfs_tree_unlock(left);
free_extent_buffer(left);
path->slots[0] -= push_items;
}
BUG_ON(path->slots[0] < 0);
return ret;
out:
btrfs_tree_unlock(left);
free_extent_buffer(left);
return ret;
}
/*
* push some data in the path leaf to the left, trying to free up at
* least data_size bytes. returns zero if the push worked, nonzero otherwise
*
* max_slot can put a limit on how far into the leaf we'll push items. The
* item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
* items
*/
static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
*root, struct btrfs_path *path, int min_data_size,
int data_size, int empty, u32 max_slot)
{
struct extent_buffer *right = path->nodes[0];
struct extent_buffer *left;
int slot;
int free_space;
u32 right_nritems;
int ret = 0;
slot = path->slots[1];
if (slot == 0)
return 1;
if (!path->nodes[1])
return 1;
right_nritems = btrfs_header_nritems(right);
if (right_nritems == 0)
return 1;
btrfs_assert_tree_locked(path->nodes[1]);
left = read_node_slot(root, path->nodes[1], slot - 1);
if (left == NULL)
return 1;
btrfs_tree_lock(left);
btrfs_set_lock_blocking(left);
free_space = btrfs_leaf_free_space(root, left);
if (free_space < data_size) {
ret = 1;
goto out;
}
/* cow and double check */
ret = btrfs_cow_block(trans, root, left,
path->nodes[1], slot - 1, &left);
if (ret) {
/* we hit -ENOSPC, but it isn't fatal here */
if (ret == -ENOSPC)
ret = 1;
goto out;
}
free_space = btrfs_leaf_free_space(root, left);
if (free_space < data_size) {
ret = 1;
goto out;
}
return __push_leaf_left(trans, root, path, min_data_size,
empty, left, free_space, right_nritems,
max_slot);
out:
btrfs_tree_unlock(left);
free_extent_buffer(left);
return ret;
}
/*
* split the path's leaf in two, making sure there is at least data_size
* available for the resulting leaf level of the path.
*/
static noinline void copy_for_split(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct extent_buffer *l,
struct extent_buffer *right,
int slot, int mid, int nritems)
{
int data_copy_size;
int rt_data_off;
int i;
struct btrfs_disk_key disk_key;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
nritems = nritems - mid;
btrfs_set_header_nritems(right, nritems);
data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
btrfs_item_nr_offset(mid),
nritems * sizeof(struct btrfs_item));
copy_extent_buffer(right, l,
btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
data_copy_size, btrfs_leaf_data(l) +
leaf_data_end(root, l), data_copy_size);
rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
btrfs_item_end_nr(l, mid);
for (i = 0; i < nritems; i++) {
struct btrfs_item *item = btrfs_item_nr(right, i);
u32 ioff;
ioff = btrfs_token_item_offset(right, item, &token);
btrfs_set_token_item_offset(right, item,
ioff + rt_data_off, &token);
}
btrfs_set_header_nritems(l, mid);
btrfs_item_key(right, &disk_key, 0);
insert_ptr(trans, root, path, &disk_key, right->start,
path->slots[1] + 1, 1);
btrfs_mark_buffer_dirty(right);
btrfs_mark_buffer_dirty(l);
BUG_ON(path->slots[0] != slot);
if (mid <= slot) {
btrfs_tree_unlock(path->nodes[0]);
free_extent_buffer(path->nodes[0]);
path->nodes[0] = right;
path->slots[0] -= mid;
path->slots[1] += 1;
} else {
btrfs_tree_unlock(right);
free_extent_buffer(right);
}
BUG_ON(path->slots[0] < 0);
}
/*
* double splits happen when we need to insert a big item in the middle
* of a leaf. A double split can leave us with 3 mostly empty leaves:
* leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
* A B C
*
* We avoid this by trying to push the items on either side of our target
* into the adjacent leaves. If all goes well we can avoid the double split
* completely.
*/
static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
int data_size)
{
int ret;
int progress = 0;
int slot;
u32 nritems;
slot = path->slots[0];
/*
* try to push all the items after our slot into the
* right leaf
*/
ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
if (ret < 0)
return ret;
if (ret == 0)
progress++;
nritems = btrfs_header_nritems(path->nodes[0]);
/*
* our goal is to get our slot at the start or end of a leaf. If
* we've done so we're done
*/
if (path->slots[0] == 0 || path->slots[0] == nritems)
return 0;
if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
return 0;
/* try to push all the items before our slot into the next leaf */
slot = path->slots[0];
ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
if (ret < 0)
return ret;
if (ret == 0)
progress++;
if (progress)
return 0;
return 1;
}
/*
* split the path's leaf in two, making sure there is at least data_size
* available for the resulting leaf level of the path.
*
* returns 0 if all went well and < 0 on failure.
*/
static noinline int split_leaf(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_key *ins_key,
struct btrfs_path *path, int data_size,
int extend)
{
struct btrfs_disk_key disk_key;
struct extent_buffer *l;
u32 nritems;
int mid;
int slot;
struct extent_buffer *right;
int ret = 0;
int wret;
int split;
int num_doubles = 0;
int tried_avoid_double = 0;
l = path->nodes[0];
slot = path->slots[0];
if (extend && data_size + btrfs_item_size_nr(l, slot) +
sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
return -EOVERFLOW;
/* first try to make some room by pushing left and right */
if (data_size) {
wret = push_leaf_right(trans, root, path, data_size,
data_size, 0, 0);
if (wret < 0)
return wret;
if (wret) {
wret = push_leaf_left(trans, root, path, data_size,
data_size, 0, (u32)-1);
if (wret < 0)
return wret;
}
l = path->nodes[0];
/* did the pushes work? */
if (btrfs_leaf_free_space(root, l) >= data_size)
return 0;
}
if (!path->nodes[1]) {
ret = insert_new_root(trans, root, path, 1);
if (ret)
return ret;
}
again:
split = 1;
l = path->nodes[0];
slot = path->slots[0];
nritems = btrfs_header_nritems(l);
mid = (nritems + 1) / 2;
if (mid <= slot) {
if (nritems == 1 ||
leaf_space_used(l, mid, nritems - mid) + data_size >
BTRFS_LEAF_DATA_SIZE(root)) {
if (slot >= nritems) {
split = 0;
} else {
mid = slot;
if (mid != nritems &&
leaf_space_used(l, mid, nritems - mid) +
data_size > BTRFS_LEAF_DATA_SIZE(root)) {
if (data_size && !tried_avoid_double)
goto push_for_double;
split = 2;
}
}
}
} else {
if (leaf_space_used(l, 0, mid) + data_size >
BTRFS_LEAF_DATA_SIZE(root)) {
if (!extend && data_size && slot == 0) {
split = 0;
} else if ((extend || !data_size) && slot == 0) {
mid = 1;
} else {
mid = slot;
if (mid != nritems &&
leaf_space_used(l, mid, nritems - mid) +
data_size > BTRFS_LEAF_DATA_SIZE(root)) {
if (data_size && !tried_avoid_double)
goto push_for_double;
split = 2 ;
}
}
}
}
if (split == 0)
btrfs_cpu_key_to_disk(&disk_key, ins_key);
else
btrfs_item_key(l, &disk_key, mid);
right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
root->root_key.objectid,
&disk_key, 0, l->start, 0, 0);
if (IS_ERR(right))
return PTR_ERR(right);
root_add_used(root, root->leafsize);
memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
btrfs_set_header_bytenr(right, right->start);
btrfs_set_header_generation(right, trans->transid);
btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
btrfs_set_header_owner(right, root->root_key.objectid);
btrfs_set_header_level(right, 0);
write_extent_buffer(right, root->fs_info->fsid,
(unsigned long)btrfs_header_fsid(right),
BTRFS_FSID_SIZE);
write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
(unsigned long)btrfs_header_chunk_tree_uuid(right),
BTRFS_UUID_SIZE);
if (split == 0) {
if (mid <= slot) {
btrfs_set_header_nritems(right, 0);
insert_ptr(trans, root, path, &disk_key, right->start,
path->slots[1] + 1, 1);
btrfs_tree_unlock(path->nodes[0]);
free_extent_buffer(path->nodes[0]);
path->nodes[0] = right;
path->slots[0] = 0;
path->slots[1] += 1;
} else {
btrfs_set_header_nritems(right, 0);
insert_ptr(trans, root, path, &disk_key, right->start,
path->slots[1], 1);
btrfs_tree_unlock(path->nodes[0]);
free_extent_buffer(path->nodes[0]);
path->nodes[0] = right;
path->slots[0] = 0;
if (path->slots[1] == 0)
fixup_low_keys(trans, root, path,
&disk_key, 1);
}
btrfs_mark_buffer_dirty(right);
return ret;
}
copy_for_split(trans, root, path, l, right, slot, mid, nritems);
if (split == 2) {
BUG_ON(num_doubles != 0);
num_doubles++;
goto again;
}
return 0;
push_for_double:
push_for_double_split(trans, root, path, data_size);
tried_avoid_double = 1;
if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
return 0;
goto again;
}
static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path, int ins_len)
{
struct btrfs_key key;
struct extent_buffer *leaf;
struct btrfs_file_extent_item *fi;
u64 extent_len = 0;
u32 item_size;
int ret;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
key.type != BTRFS_EXTENT_CSUM_KEY);
if (btrfs_leaf_free_space(root, leaf) >= ins_len)
return 0;
item_size = btrfs_item_size_nr(leaf, path->slots[0]);
if (key.type == BTRFS_EXTENT_DATA_KEY) {
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_len = btrfs_file_extent_num_bytes(leaf, fi);
}
btrfs_release_path(path);
path->keep_locks = 1;
path->search_for_split = 1;
ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
path->search_for_split = 0;
if (ret < 0)
goto err;
ret = -EAGAIN;
leaf = path->nodes[0];
/* if our item isn't there or got smaller, return now */
if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
goto err;
/* the leaf has changed, it now has room. return now */
if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
goto err;
if (key.type == BTRFS_EXTENT_DATA_KEY) {
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
goto err;
}
btrfs_set_path_blocking(path);
ret = split_leaf(trans, root, &key, path, ins_len, 1);
if (ret)
goto err;
path->keep_locks = 0;
btrfs_unlock_up_safe(path, 1);
return 0;
err:
path->keep_locks = 0;
return ret;
}
static noinline int split_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_key *new_key,
unsigned long split_offset)
{
struct extent_buffer *leaf;
struct btrfs_item *item;
struct btrfs_item *new_item;
int slot;
char *buf;
u32 nritems;
u32 item_size;
u32 orig_offset;
struct btrfs_disk_key disk_key;
leaf = path->nodes[0];
BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
btrfs_set_path_blocking(path);
item = btrfs_item_nr(leaf, path->slots[0]);
orig_offset = btrfs_item_offset(leaf, item);
item_size = btrfs_item_size(leaf, item);
buf = kmalloc(item_size, GFP_NOFS);
if (!buf)
return -ENOMEM;
read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
path->slots[0]), item_size);
slot = path->slots[0] + 1;
nritems = btrfs_header_nritems(leaf);
if (slot != nritems) {
/* shift the items */
memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
btrfs_item_nr_offset(slot),
(nritems - slot) * sizeof(struct btrfs_item));
}
btrfs_cpu_key_to_disk(&disk_key, new_key);
btrfs_set_item_key(leaf, &disk_key, slot);
new_item = btrfs_item_nr(leaf, slot);
btrfs_set_item_offset(leaf, new_item, orig_offset);
btrfs_set_item_size(leaf, new_item, item_size - split_offset);
btrfs_set_item_offset(leaf, item,
orig_offset + item_size - split_offset);
btrfs_set_item_size(leaf, item, split_offset);
btrfs_set_header_nritems(leaf, nritems + 1);
/* write the data for the start of the original item */
write_extent_buffer(leaf, buf,
btrfs_item_ptr_offset(leaf, path->slots[0]),
split_offset);
/* write the data for the new item */
write_extent_buffer(leaf, buf + split_offset,
btrfs_item_ptr_offset(leaf, slot),
item_size - split_offset);
btrfs_mark_buffer_dirty(leaf);
BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
kfree(buf);
return 0;
}
/*
* This function splits a single item into two items,
* giving 'new_key' to the new item and splitting the
* old one at split_offset (from the start of the item).
*
* The path may be released by this operation. After
* the split, the path is pointing to the old item. The
* new item is going to be in the same node as the old one.
*
* Note, the item being split must be smaller enough to live alone on
* a tree block with room for one extra struct btrfs_item
*
* This allows us to split the item in place, keeping a lock on the
* leaf the entire time.
*/
int btrfs_split_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_key *new_key,
unsigned long split_offset)
{
int ret;
ret = setup_leaf_for_split(trans, root, path,
sizeof(struct btrfs_item));
if (ret)
return ret;
ret = split_item(trans, root, path, new_key, split_offset);
return ret;
}
/*
* This function duplicate a item, giving 'new_key' to the new item.
* It guarantees both items live in the same tree leaf and the new item
* is contiguous with the original item.
*
* This allows us to split file extent in place, keeping a lock on the
* leaf the entire time.
*/
int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_key *new_key)
{
struct extent_buffer *leaf;
int ret;
u32 item_size;
leaf = path->nodes[0];
item_size = btrfs_item_size_nr(leaf, path->slots[0]);
ret = setup_leaf_for_split(trans, root, path,
item_size + sizeof(struct btrfs_item));
if (ret)
return ret;
path->slots[0]++;
setup_items_for_insert(trans, root, path, new_key, &item_size,
item_size, item_size +
sizeof(struct btrfs_item), 1);
leaf = path->nodes[0];
memcpy_extent_buffer(leaf,
btrfs_item_ptr_offset(leaf, path->slots[0]),
btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
item_size);
return 0;
}
/*
* make the item pointed to by the path smaller. new_size indicates
* how small to make it, and from_end tells us if we just chop bytes
* off the end of the item or if we shift the item to chop bytes off
* the front.
*/
void btrfs_truncate_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
u32 new_size, int from_end)
{
int slot;
struct extent_buffer *leaf;
struct btrfs_item *item;
u32 nritems;
unsigned int data_end;
unsigned int old_data_start;
unsigned int old_size;
unsigned int size_diff;
int i;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
leaf = path->nodes[0];
slot = path->slots[0];
old_size = btrfs_item_size_nr(leaf, slot);
if (old_size == new_size)
return;
nritems = btrfs_header_nritems(leaf);
data_end = leaf_data_end(root, leaf);
old_data_start = btrfs_item_offset_nr(leaf, slot);
size_diff = old_size - new_size;
BUG_ON(slot < 0);
BUG_ON(slot >= nritems);
/*
* item0..itemN ... dataN.offset..dataN.size .. data0.size
*/
/* first correct the data pointers */
for (i = slot; i < nritems; i++) {
u32 ioff;
item = btrfs_item_nr(leaf, i);
ioff = btrfs_token_item_offset(leaf, item, &token);
btrfs_set_token_item_offset(leaf, item,
ioff + size_diff, &token);
}
/* shift the data */
if (from_end) {
memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
data_end + size_diff, btrfs_leaf_data(leaf) +
data_end, old_data_start + new_size - data_end);
} else {
struct btrfs_disk_key disk_key;
u64 offset;
btrfs_item_key(leaf, &disk_key, slot);
if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
unsigned long ptr;
struct btrfs_file_extent_item *fi;
fi = btrfs_item_ptr(leaf, slot,
struct btrfs_file_extent_item);
fi = (struct btrfs_file_extent_item *)(
(unsigned long)fi - size_diff);
if (btrfs_file_extent_type(leaf, fi) ==
BTRFS_FILE_EXTENT_INLINE) {
ptr = btrfs_item_ptr_offset(leaf, slot);
memmove_extent_buffer(leaf, ptr,
(unsigned long)fi,
offsetof(struct btrfs_file_extent_item,
disk_bytenr));
}
}
memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
data_end + size_diff, btrfs_leaf_data(leaf) +
data_end, old_data_start - data_end);
offset = btrfs_disk_key_offset(&disk_key);
btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
btrfs_set_item_key(leaf, &disk_key, slot);
if (slot == 0)
fixup_low_keys(trans, root, path, &disk_key, 1);
}
item = btrfs_item_nr(leaf, slot);
btrfs_set_item_size(leaf, item, new_size);
btrfs_mark_buffer_dirty(leaf);
if (btrfs_leaf_free_space(root, leaf) < 0) {
btrfs_print_leaf(root, leaf);
BUG();
}
}
/*
* make the item pointed to by the path bigger, data_size is the new size.
*/
void btrfs_extend_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *path,
u32 data_size)
{
int slot;
struct extent_buffer *leaf;
struct btrfs_item *item;
u32 nritems;
unsigned int data_end;
unsigned int old_data;
unsigned int old_size;
int i;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
leaf = path->nodes[0];
nritems = btrfs_header_nritems(leaf);
data_end = leaf_data_end(root, leaf);
if (btrfs_leaf_free_space(root, leaf) < data_size) {
btrfs_print_leaf(root, leaf);
BUG();
}
slot = path->slots[0];
old_data = btrfs_item_end_nr(leaf, slot);
BUG_ON(slot < 0);
if (slot >= nritems) {
btrfs_print_leaf(root, leaf);
printk(KERN_CRIT "slot %d too large, nritems %d\n",
slot, nritems);
BUG_ON(1);
}
/*
* item0..itemN ... dataN.offset..dataN.size .. data0.size
*/
/* first correct the data pointers */
for (i = slot; i < nritems; i++) {
u32 ioff;
item = btrfs_item_nr(leaf, i);
ioff = btrfs_token_item_offset(leaf, item, &token);
btrfs_set_token_item_offset(leaf, item,
ioff - data_size, &token);
}
/* shift the data */
memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
data_end - data_size, btrfs_leaf_data(leaf) +
data_end, old_data - data_end);
data_end = old_data;
old_size = btrfs_item_size_nr(leaf, slot);
item = btrfs_item_nr(leaf, slot);
btrfs_set_item_size(leaf, item, old_size + data_size);
btrfs_mark_buffer_dirty(leaf);
if (btrfs_leaf_free_space(root, leaf) < 0) {
btrfs_print_leaf(root, leaf);
BUG();
}
}
/*
* Given a key and some data, insert items into the tree.
* This does all the path init required, making room in the tree if needed.
* Returns the number of keys that were inserted.
*/
int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_key *cpu_key, u32 *data_size,
int nr)
{
struct extent_buffer *leaf;
struct btrfs_item *item;
int ret = 0;
int slot;
int i;
u32 nritems;
u32 total_data = 0;
u32 total_size = 0;
unsigned int data_end;
struct btrfs_disk_key disk_key;
struct btrfs_key found_key;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
for (i = 0; i < nr; i++) {
if (total_size + data_size[i] + sizeof(struct btrfs_item) >
BTRFS_LEAF_DATA_SIZE(root)) {
break;
nr = i;
}
total_data += data_size[i];
total_size += data_size[i] + sizeof(struct btrfs_item);
}
BUG_ON(nr == 0);
ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
if (ret == 0)
return -EEXIST;
if (ret < 0)
goto out;
leaf = path->nodes[0];
nritems = btrfs_header_nritems(leaf);
data_end = leaf_data_end(root, leaf);
if (btrfs_leaf_free_space(root, leaf) < total_size) {
for (i = nr; i >= 0; i--) {
total_data -= data_size[i];
total_size -= data_size[i] + sizeof(struct btrfs_item);
if (total_size < btrfs_leaf_free_space(root, leaf))
break;
}
nr = i;
}
slot = path->slots[0];
BUG_ON(slot < 0);
if (slot != nritems) {
unsigned int old_data = btrfs_item_end_nr(leaf, slot);
item = btrfs_item_nr(leaf, slot);
btrfs_item_key_to_cpu(leaf, &found_key, slot);
/* figure out how many keys we can insert in here */
total_data = data_size[0];
for (i = 1; i < nr; i++) {
if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
break;
total_data += data_size[i];
}
nr = i;
if (old_data < data_end) {
btrfs_print_leaf(root, leaf);
printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
slot, old_data, data_end);
BUG_ON(1);
}
/*
* item0..itemN ... dataN.offset..dataN.size .. data0.size
*/
/* first correct the data pointers */
for (i = slot; i < nritems; i++) {
u32 ioff;
item = btrfs_item_nr(leaf, i);
ioff = btrfs_token_item_offset(leaf, item, &token);
btrfs_set_token_item_offset(leaf, item,
ioff - total_data, &token);
}
/* shift the items */
memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
btrfs_item_nr_offset(slot),
(nritems - slot) * sizeof(struct btrfs_item));
/* shift the data */
memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
data_end - total_data, btrfs_leaf_data(leaf) +
data_end, old_data - data_end);
data_end = old_data;
} else {
/*
* this sucks but it has to be done, if we are inserting at
* the end of the leaf only insert 1 of the items, since we
* have no way of knowing whats on the next leaf and we'd have
* to drop our current locks to figure it out
*/
nr = 1;
}
/* setup the item for the new data */
for (i = 0; i < nr; i++) {
btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
btrfs_set_item_key(leaf, &disk_key, slot + i);
item = btrfs_item_nr(leaf, slot + i);
btrfs_set_token_item_offset(leaf, item,
data_end - data_size[i], &token);
data_end -= data_size[i];
btrfs_set_token_item_size(leaf, item, data_size[i], &token);
}
btrfs_set_header_nritems(leaf, nritems + nr);
btrfs_mark_buffer_dirty(leaf);
ret = 0;
if (slot == 0) {
btrfs_cpu_key_to_disk(&disk_key, cpu_key);
fixup_low_keys(trans, root, path, &disk_key, 1);
}
if (btrfs_leaf_free_space(root, leaf) < 0) {
btrfs_print_leaf(root, leaf);
BUG();
}
out:
if (!ret)
ret = nr;
return ret;
}
/*
* this is a helper for btrfs_insert_empty_items, the main goal here is
* to save stack depth by doing the bulk of the work in a function
* that doesn't call btrfs_search_slot
*/
void setup_items_for_insert(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct btrfs_path *path,
struct btrfs_key *cpu_key, u32 *data_size,
u32 total_data, u32 total_size, int nr)
{
struct btrfs_item *item;
int i;
u32 nritems;
unsigned int data_end;
struct btrfs_disk_key disk_key;
struct extent_buffer *leaf;
int slot;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
leaf = path->nodes[0];
slot = path->slots[0];
nritems = btrfs_header_nritems(leaf);
data_end = leaf_data_end(root, leaf);
if (btrfs_leaf_free_space(root, leaf) < total_size) {
btrfs_print_leaf(root, leaf);
printk(KERN_CRIT "not enough freespace need %u have %d\n",
total_size, btrfs_leaf_free_space(root, leaf));
BUG();
}
if (slot != nritems) {
unsigned int old_data = btrfs_item_end_nr(leaf, slot);
if (old_data < data_end) {
btrfs_print_leaf(root, leaf);
printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
slot, old_data, data_end);
BUG_ON(1);
}
/*
* item0..itemN ... dataN.offset..dataN.size .. data0.size
*/
/* first correct the data pointers */
for (i = slot; i < nritems; i++) {
u32 ioff;
item = btrfs_item_nr(leaf, i);
ioff = btrfs_token_item_offset(leaf, item, &token);
btrfs_set_token_item_offset(leaf, item,
ioff - total_data, &token);
}
/* shift the items */
memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
btrfs_item_nr_offset(slot),
(nritems - slot) * sizeof(struct btrfs_item));
/* shift the data */
memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
data_end - total_data, btrfs_leaf_data(leaf) +
data_end, old_data - data_end);
data_end = old_data;
}
/* setup the item for the new data */
for (i = 0; i < nr; i++) {
btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
btrfs_set_item_key(leaf, &disk_key, slot + i);
item = btrfs_item_nr(leaf, slot + i);
btrfs_set_token_item_offset(leaf, item,
data_end - data_size[i], &token);
data_end -= data_size[i];
btrfs_set_token_item_size(leaf, item, data_size[i], &token);
}
btrfs_set_header_nritems(leaf, nritems + nr);
if (slot == 0) {
btrfs_cpu_key_to_disk(&disk_key, cpu_key);
fixup_low_keys(trans, root, path, &disk_key, 1);
}
btrfs_unlock_up_safe(path, 1);
btrfs_mark_buffer_dirty(leaf);
if (btrfs_leaf_free_space(root, leaf) < 0) {
btrfs_print_leaf(root, leaf);
BUG();
}
}
/*
* Given a key and some data, insert items into the tree.
* This does all the path init required, making room in the tree if needed.
*/
int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct btrfs_key *cpu_key, u32 *data_size,
int nr)
{
int ret = 0;
int slot;
int i;
u32 total_size = 0;
u32 total_data = 0;
for (i = 0; i < nr; i++)
total_data += data_size[i];
total_size = total_data + (nr * sizeof(struct btrfs_item));
ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
if (ret == 0)
return -EEXIST;
if (ret < 0)
return ret;
slot = path->slots[0];
BUG_ON(slot < 0);
setup_items_for_insert(trans, root, path, cpu_key, data_size,
total_data, total_size, nr);
return 0;
}
/*
* Given a key and some data, insert an item into the tree.
* This does all the path init required, making room in the tree if needed.
*/
int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
*root, struct btrfs_key *cpu_key, void *data, u32
data_size)
{
int ret = 0;
struct btrfs_path *path;
struct extent_buffer *leaf;
unsigned long ptr;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
if (!ret) {
leaf = path->nodes[0];
ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
write_extent_buffer(leaf, data, ptr, data_size);
btrfs_mark_buffer_dirty(leaf);
}
btrfs_free_path(path);
return ret;
}
/*
* delete the pointer from a given node.
*
* the tree should have been previously balanced so the deletion does not
* empty a node.
*/
static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
struct btrfs_path *path, int level, int slot)
{
struct extent_buffer *parent = path->nodes[level];
u32 nritems;
nritems = btrfs_header_nritems(parent);
if (slot != nritems - 1) {
memmove_extent_buffer(parent,
btrfs_node_key_ptr_offset(slot),
btrfs_node_key_ptr_offset(slot + 1),
sizeof(struct btrfs_key_ptr) *
(nritems - slot - 1));
}
nritems--;
btrfs_set_header_nritems(parent, nritems);
if (nritems == 0 && parent == root->node) {
BUG_ON(btrfs_header_level(root->node) != 1);
/* just turn the root into a leaf and break */
btrfs_set_header_level(root->node, 0);
} else if (slot == 0) {
struct btrfs_disk_key disk_key;
btrfs_node_key(parent, &disk_key, 0);
fixup_low_keys(trans, root, path, &disk_key, level + 1);
}
btrfs_mark_buffer_dirty(parent);
}
/*
* a helper function to delete the leaf pointed to by path->slots[1] and
* path->nodes[1].
*
* This deletes the pointer in path->nodes[1] and frees the leaf
* block extent. zero is returned if it all worked out, < 0 otherwise.
*
* The path must have already been setup for deleting the leaf, including
* all the proper balancing. path->nodes[1] must be locked.
*/
static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_path *path,
struct extent_buffer *leaf)
{
WARN_ON(btrfs_header_generation(leaf) != trans->transid);
del_ptr(trans, root, path, 1, path->slots[1]);
/*
* btrfs_free_extent is expensive, we want to make sure we
* aren't holding any locks when we call it
*/
btrfs_unlock_up_safe(path, 0);
root_sub_used(root, leaf->len);
extent_buffer_get(leaf);
btrfs_free_tree_block(trans, root, leaf, 0, 1, 0);
free_extent_buffer_stale(leaf);
}
/*
* delete the item at the leaf level in path. If that empties
* the leaf, remove it from the tree
*/
int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
struct btrfs_path *path, int slot, int nr)
{
struct extent_buffer *leaf;
struct btrfs_item *item;
int last_off;
int dsize = 0;
int ret = 0;
int wret;
int i;
u32 nritems;
struct btrfs_map_token token;
btrfs_init_map_token(&token);
leaf = path->nodes[0];
last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
for (i = 0; i < nr; i++)
dsize += btrfs_item_size_nr(leaf, slot + i);
nritems = btrfs_header_nritems(leaf);
if (slot + nr != nritems) {
int data_end = leaf_data_end(root, leaf);
memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
data_end + dsize,
btrfs_leaf_data(leaf) + data_end,
last_off - data_end);
for (i = slot + nr; i < nritems; i++) {
u32 ioff;
item = btrfs_item_nr(leaf, i);
ioff = btrfs_token_item_offset(leaf, item, &token);
btrfs_set_token_item_offset(leaf, item,
ioff + dsize, &token);
}
memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
btrfs_item_nr_offset(slot + nr),
sizeof(struct btrfs_item) *
(nritems - slot - nr));
}
btrfs_set_header_nritems(leaf, nritems - nr);
nritems -= nr;
/* delete the leaf if we've emptied it */
if (nritems == 0) {
if (leaf == root->node) {
btrfs_set_header_level(leaf, 0);
} else {
btrfs_set_path_blocking(path);
clean_tree_block(trans, root, leaf);
btrfs_del_leaf(trans, root, path, leaf);
}
} else {
int used = leaf_space_used(leaf, 0, nritems);
if (slot == 0) {
struct btrfs_disk_key disk_key;
btrfs_item_key(leaf, &disk_key, 0);
fixup_low_keys(trans, root, path, &disk_key, 1);
}
/* delete the leaf if it is mostly empty */
if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
/* push_leaf_left fixes the path.
* make sure the path still points to our leaf
* for possible call to del_ptr below
*/
slot = path->slots[1];
extent_buffer_get(leaf);
btrfs_set_path_blocking(path);
wret = push_leaf_left(trans, root, path, 1, 1,
1, (u32)-1);
if (wret < 0 && wret != -ENOSPC)
ret = wret;
if (path->nodes[0] == leaf &&
btrfs_header_nritems(leaf)) {
wret = push_leaf_right(trans, root, path, 1,
1, 1, 0);
if (wret < 0 && wret != -ENOSPC)
ret = wret;
}
if (btrfs_header_nritems(leaf) == 0) {
path->slots[1] = slot;
btrfs_del_leaf(trans, root, path, leaf);
free_extent_buffer(leaf);
ret = 0;
} else {
/* if we're still in the path, make sure
* we're dirty. Otherwise, one of the
* push_leaf functions must have already
* dirtied this buffer
*/
if (path->nodes[0] == leaf)
btrfs_mark_buffer_dirty(leaf);
free_extent_buffer(leaf);
}
} else {
btrfs_mark_buffer_dirty(leaf);
}
}
return ret;
}
/*
* search the tree again to find a leaf with lesser keys
* returns 0 if it found something or 1 if there are no lesser leaves.
* returns < 0 on io errors.
*
* This may release the path, and so you may lose any locks held at the
* time you call it.
*/
int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
{
struct btrfs_key key;
struct btrfs_disk_key found_key;
int ret;
btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
if (key.offset > 0)
key.offset--;
else if (key.type > 0)
key.type--;
else if (key.objectid > 0)
key.objectid--;
else
return 1;
btrfs_release_path(path);
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
return ret;
btrfs_item_key(path->nodes[0], &found_key, 0);
ret = comp_keys(&found_key, &key);
if (ret < 0)
return 0;
return 1;
}
/*
* A helper function to walk down the tree starting at min_key, and looking
* for nodes or leaves that are either in cache or have a minimum
* transaction id. This is used by the btree defrag code, and tree logging
*
* This does not cow, but it does stuff the starting key it finds back
* into min_key, so you can call btrfs_search_slot with cow=1 on the
* key and get a writable path.
*
* This does lock as it descends, and path->keep_locks should be set
* to 1 by the caller.
*
* This honors path->lowest_level to prevent descent past a given level
* of the tree.
*
* min_trans indicates the oldest transaction that you are interested
* in walking through. Any nodes or leaves older than min_trans are
* skipped over (without reading them).
*
* returns zero if something useful was found, < 0 on error and 1 if there
* was nothing in the tree that matched the search criteria.
*/
int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
struct btrfs_key *max_key,
struct btrfs_path *path, int cache_only,
u64 min_trans)
{
struct extent_buffer *cur;
struct btrfs_key found_key;
int slot;
int sret;
u32 nritems;
int level;
int ret = 1;
WARN_ON(!path->keep_locks);
again:
cur = btrfs_read_lock_root_node(root);
level = btrfs_header_level(cur);
WARN_ON(path->nodes[level]);
path->nodes[level] = cur;
path->locks[level] = BTRFS_READ_LOCK;
if (btrfs_header_generation(cur) < min_trans) {
ret = 1;
goto out;
}
while (1) {
nritems = btrfs_header_nritems(cur);
level = btrfs_header_level(cur);
sret = bin_search(cur, min_key, level, &slot);
/* at the lowest level, we're done, setup the path and exit */
if (level == path->lowest_level) {
if (slot >= nritems)
goto find_next_key;
ret = 0;
path->slots[level] = slot;
btrfs_item_key_to_cpu(cur, &found_key, slot);
goto out;
}
if (sret && slot > 0)
slot--;
/*
* check this node pointer against the cache_only and
* min_trans parameters. If it isn't in cache or is too
* old, skip to the next one.
*/
while (slot < nritems) {
u64 blockptr;
u64 gen;
struct extent_buffer *tmp;
struct btrfs_disk_key disk_key;
blockptr = btrfs_node_blockptr(cur, slot);
gen = btrfs_node_ptr_generation(cur, slot);
if (gen < min_trans) {
slot++;
continue;
}
if (!cache_only)
break;
if (max_key) {
btrfs_node_key(cur, &disk_key, slot);
if (comp_keys(&disk_key, max_key) >= 0) {
ret = 1;
goto out;
}
}
tmp = btrfs_find_tree_block(root, blockptr,
btrfs_level_size(root, level - 1));
if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
free_extent_buffer(tmp);
break;
}
if (tmp)
free_extent_buffer(tmp);
slot++;
}
find_next_key:
/*
* we didn't find a candidate key in this node, walk forward
* and find another one
*/
if (slot >= nritems) {
path->slots[level] = slot;
btrfs_set_path_blocking(path);
sret = btrfs_find_next_key(root, path, min_key, level,
cache_only, min_trans);
if (sret == 0) {
btrfs_release_path(path);
goto again;
} else {
goto out;
}
}
/* save our key for returning back */
btrfs_node_key_to_cpu(cur, &found_key, slot);
path->slots[level] = slot;
if (level == path->lowest_level) {
ret = 0;
unlock_up(path, level, 1, 0, NULL);
goto out;
}
btrfs_set_path_blocking(path);
cur = read_node_slot(root, cur, slot);
BUG_ON(!cur); /* -ENOMEM */
btrfs_tree_read_lock(cur);
path->locks[level - 1] = BTRFS_READ_LOCK;
path->nodes[level - 1] = cur;
unlock_up(path, level, 1, 0, NULL);
btrfs_clear_path_blocking(path, NULL, 0);
}
out:
if (ret == 0)
memcpy(min_key, &found_key, sizeof(found_key));
btrfs_set_path_blocking(path);
return ret;
}
/*
* this is similar to btrfs_next_leaf, but does not try to preserve
* and fixup the path. It looks for and returns the next key in the
* tree based on the current path and the cache_only and min_trans
* parameters.
*
* 0 is returned if another key is found, < 0 if there are any errors
* and 1 is returned if there are no higher keys in the tree
*
* path->keep_locks should be set to 1 on the search made before
* calling this function.
*/
int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
struct btrfs_key *key, int level,
int cache_only, u64 min_trans)
{
int slot;
struct extent_buffer *c;
WARN_ON(!path->keep_locks);
while (level < BTRFS_MAX_LEVEL) {
if (!path->nodes[level])
return 1;
slot = path->slots[level] + 1;
c = path->nodes[level];
next:
if (slot >= btrfs_header_nritems(c)) {
int ret;
int orig_lowest;
struct btrfs_key cur_key;
if (level + 1 >= BTRFS_MAX_LEVEL ||
!path->nodes[level + 1])
return 1;
if (path->locks[level + 1]) {
level++;
continue;
}
slot = btrfs_header_nritems(c) - 1;
if (level == 0)
btrfs_item_key_to_cpu(c, &cur_key, slot);
else
btrfs_node_key_to_cpu(c, &cur_key, slot);
orig_lowest = path->lowest_level;
btrfs_release_path(path);
path->lowest_level = level;
ret = btrfs_search_slot(NULL, root, &cur_key, path,
0, 0);
path->lowest_level = orig_lowest;
if (ret < 0)
return ret;
c = path->nodes[level];
slot = path->slots[level];
if (ret == 0)
slot++;
goto next;
}
if (level == 0)
btrfs_item_key_to_cpu(c, key, slot);
else {
u64 blockptr = btrfs_node_blockptr(c, slot);
u64 gen = btrfs_node_ptr_generation(c, slot);
if (cache_only) {
struct extent_buffer *cur;
cur = btrfs_find_tree_block(root, blockptr,
btrfs_level_size(root, level - 1));
if (!cur ||
btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
slot++;
if (cur)
free_extent_buffer(cur);
goto next;
}
free_extent_buffer(cur);
}
if (gen < min_trans) {
slot++;
goto next;
}
btrfs_node_key_to_cpu(c, key, slot);
}
return 0;
}
return 1;
}
/*
* search the tree again to find a leaf with greater keys
* returns 0 if it found something or 1 if there are no greater leaves.
* returns < 0 on io errors.
*/
int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
{
int slot;
int level;
struct extent_buffer *c;
struct extent_buffer *next;
struct btrfs_key key;
u32 nritems;
int ret;
int old_spinning = path->leave_spinning;
int next_rw_lock = 0;
nritems = btrfs_header_nritems(path->nodes[0]);
if (nritems == 0)
return 1;
btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
again:
level = 1;
next = NULL;
next_rw_lock = 0;
btrfs_release_path(path);
path->keep_locks = 1;
path->leave_spinning = 1;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
path->keep_locks = 0;
if (ret < 0)
return ret;
nritems = btrfs_header_nritems(path->nodes[0]);
/*
* by releasing the path above we dropped all our locks. A balance
* could have added more items next to the key that used to be
* at the very end of the block. So, check again here and
* advance the path if there are now more items available.
*/
if (nritems > 0 && path->slots[0] < nritems - 1) {
if (ret == 0)
path->slots[0]++;
ret = 0;
goto done;
}
while (level < BTRFS_MAX_LEVEL) {
if (!path->nodes[level]) {
ret = 1;
goto done;
}
slot = path->slots[level] + 1;
c = path->nodes[level];
if (slot >= btrfs_header_nritems(c)) {
level++;
if (level == BTRFS_MAX_LEVEL) {
ret = 1;
goto done;
}
continue;
}
if (next) {
btrfs_tree_unlock_rw(next, next_rw_lock);
free_extent_buffer(next);
}
next = c;
next_rw_lock = path->locks[level];
ret = read_block_for_search(NULL, root, path, &next, level,
slot, &key);
if (ret == -EAGAIN)
goto again;
if (ret < 0) {
btrfs_release_path(path);
goto done;
}
if (!path->skip_locking) {
ret = btrfs_try_tree_read_lock(next);
if (!ret) {
btrfs_set_path_blocking(path);
btrfs_tree_read_lock(next);
btrfs_clear_path_blocking(path, next,
BTRFS_READ_LOCK);
}
next_rw_lock = BTRFS_READ_LOCK;
}
break;
}
path->slots[level] = slot;
while (1) {
level--;
c = path->nodes[level];
if (path->locks[level])
btrfs_tree_unlock_rw(c, path->locks[level]);
free_extent_buffer(c);
path->nodes[level] = next;
path->slots[level] = 0;
if (!path->skip_locking)
path->locks[level] = next_rw_lock;
if (!level)
break;
ret = read_block_for_search(NULL, root, path, &next, level,
0, &key);
if (ret == -EAGAIN)
goto again;
if (ret < 0) {
btrfs_release_path(path);
goto done;
}
if (!path->skip_locking) {
ret = btrfs_try_tree_read_lock(next);
if (!ret) {
btrfs_set_path_blocking(path);
btrfs_tree_read_lock(next);
btrfs_clear_path_blocking(path, next,
BTRFS_READ_LOCK);
}
next_rw_lock = BTRFS_READ_LOCK;
}
}
ret = 0;
done:
unlock_up(path, 0, 1, 0, NULL);
path->leave_spinning = old_spinning;
if (!old_spinning)
btrfs_set_path_blocking(path);
return ret;
}
/*
* this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
* searching until it gets past min_objectid or finds an item of 'type'
*
* returns 0 if something is found, 1 if nothing was found and < 0 on error
*/
int btrfs_previous_item(struct btrfs_root *root,
struct btrfs_path *path, u64 min_objectid,
int type)
{
struct btrfs_key found_key;
struct extent_buffer *leaf;
u32 nritems;
int ret;
while (1) {
if (path->slots[0] == 0) {
btrfs_set_path_blocking(path);
ret = btrfs_prev_leaf(root, path);
if (ret != 0)
return ret;
} else {
path->slots[0]--;
}
leaf = path->nodes[0];
nritems = btrfs_header_nritems(leaf);
if (nritems == 0)
return 1;
if (path->slots[0] == nritems)
path->slots[0]--;
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid < min_objectid)
break;
if (found_key.type == type)
return 0;
if (found_key.objectid == min_objectid &&
found_key.type < type)
break;
}
return 1;
}
| gpl-2.0 |
JackpotClavin/android_kernel_lge_g2 | drivers/misc/ibmasm/uart.c | 5030 | 2064 |
/*
* IBM ASM Service Processor Device Driver
*
* 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.
*
* Copyright (C) IBM Corporation, 2004
*
* Author: Max Asböck <amax@us.ibm.com>
*
*/
#include <linux/termios.h>
#include <linux/tty.h>
#include <linux/serial_core.h>
#include <linux/serial_reg.h>
#include <linux/serial_8250.h>
#include "ibmasm.h"
#include "lowlevel.h"
void ibmasm_register_uart(struct service_processor *sp)
{
struct uart_port uport;
void __iomem *iomem_base;
iomem_base = sp->base_address + SCOUT_COM_B_BASE;
/* read the uart scratch register to determine if the UART
* is dedicated to the service processor or if the OS can use it
*/
if (0 == readl(iomem_base + UART_SCR)) {
dev_info(sp->dev, "IBM SP UART not registered, owned by service processor\n");
sp->serial_line = -1;
return;
}
memset(&uport, 0, sizeof(struct uart_port));
uport.irq = sp->irq;
uport.uartclk = 3686400;
uport.flags = UPF_SHARE_IRQ;
uport.iotype = UPIO_MEM;
uport.membase = iomem_base;
sp->serial_line = serial8250_register_port(&uport);
if (sp->serial_line < 0) {
dev_err(sp->dev, "Failed to register serial port\n");
return;
}
enable_uart_interrupts(sp->base_address);
}
void ibmasm_unregister_uart(struct service_processor *sp)
{
if (sp->serial_line < 0)
return;
disable_uart_interrupts(sp->base_address);
serial8250_unregister_port(sp->serial_line);
}
| gpl-2.0 |
HelpMeRuth/Ruthless_Kernel | arch/ia64/sn/kernel/sn2/sn2_smp.c | 7334 | 15742 | /*
* SN2 Platform specific SMP Support
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2000-2006 Silicon Graphics, Inc. All rights reserved.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/threads.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/bitops.h>
#include <linux/nodemask.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/processor.h>
#include <asm/irq.h>
#include <asm/sal.h>
#include <asm/delay.h>
#include <asm/io.h>
#include <asm/smp.h>
#include <asm/tlb.h>
#include <asm/numa.h>
#include <asm/hw_irq.h>
#include <asm/current.h>
#include <asm/sn/sn_cpuid.h>
#include <asm/sn/sn_sal.h>
#include <asm/sn/addrs.h>
#include <asm/sn/shub_mmr.h>
#include <asm/sn/nodepda.h>
#include <asm/sn/rw_mmr.h>
#include <asm/sn/sn_feature_sets.h>
DEFINE_PER_CPU(struct ptc_stats, ptcstats);
DECLARE_PER_CPU(struct ptc_stats, ptcstats);
static __cacheline_aligned DEFINE_SPINLOCK(sn2_global_ptc_lock);
/* 0 = old algorithm (no IPI flushes), 1 = ipi deadlock flush, 2 = ipi instead of SHUB ptc, >2 = always ipi */
static int sn2_flush_opt = 0;
extern unsigned long
sn2_ptc_deadlock_recovery_core(volatile unsigned long *, unsigned long,
volatile unsigned long *, unsigned long,
volatile unsigned long *, unsigned long);
void
sn2_ptc_deadlock_recovery(short *, short, short, int,
volatile unsigned long *, unsigned long,
volatile unsigned long *, unsigned long);
/*
* Note: some is the following is captured here to make degugging easier
* (the macros make more sense if you see the debug patch - not posted)
*/
#define sn2_ptctest 0
#define local_node_uses_ptc_ga(sh1) ((sh1) ? 1 : 0)
#define max_active_pio(sh1) ((sh1) ? 32 : 7)
#define reset_max_active_on_deadlock() 1
#define PTC_LOCK(sh1) ((sh1) ? &sn2_global_ptc_lock : &sn_nodepda->ptc_lock)
struct ptc_stats {
unsigned long ptc_l;
unsigned long change_rid;
unsigned long shub_ptc_flushes;
unsigned long nodes_flushed;
unsigned long deadlocks;
unsigned long deadlocks2;
unsigned long lock_itc_clocks;
unsigned long shub_itc_clocks;
unsigned long shub_itc_clocks_max;
unsigned long shub_ptc_flushes_not_my_mm;
unsigned long shub_ipi_flushes;
unsigned long shub_ipi_flushes_itc_clocks;
};
#define sn2_ptctest 0
static inline unsigned long wait_piowc(void)
{
volatile unsigned long *piows;
unsigned long zeroval, ws;
piows = pda->pio_write_status_addr;
zeroval = pda->pio_write_status_val;
do {
cpu_relax();
} while (((ws = *piows) & SH_PIO_WRITE_STATUS_PENDING_WRITE_COUNT_MASK) != zeroval);
return (ws & SH_PIO_WRITE_STATUS_WRITE_DEADLOCK_MASK) != 0;
}
/**
* sn_migrate - SN-specific task migration actions
* @task: Task being migrated to new CPU
*
* SN2 PIO writes from separate CPUs are not guaranteed to arrive in order.
* Context switching user threads which have memory-mapped MMIO may cause
* PIOs to issue from separate CPUs, thus the PIO writes must be drained
* from the previous CPU's Shub before execution resumes on the new CPU.
*/
void sn_migrate(struct task_struct *task)
{
pda_t *last_pda = pdacpu(task_thread_info(task)->last_cpu);
volatile unsigned long *adr = last_pda->pio_write_status_addr;
unsigned long val = last_pda->pio_write_status_val;
/* Drain PIO writes from old CPU's Shub */
while (unlikely((*adr & SH_PIO_WRITE_STATUS_PENDING_WRITE_COUNT_MASK)
!= val))
cpu_relax();
}
void sn_tlb_migrate_finish(struct mm_struct *mm)
{
/* flush_tlb_mm is inefficient if more than 1 users of mm */
if (mm == current->mm && mm && atomic_read(&mm->mm_users) == 1)
flush_tlb_mm(mm);
}
static void
sn2_ipi_flush_all_tlb(struct mm_struct *mm)
{
unsigned long itc;
itc = ia64_get_itc();
smp_flush_tlb_cpumask(*mm_cpumask(mm));
itc = ia64_get_itc() - itc;
__get_cpu_var(ptcstats).shub_ipi_flushes_itc_clocks += itc;
__get_cpu_var(ptcstats).shub_ipi_flushes++;
}
/**
* sn2_global_tlb_purge - globally purge translation cache of virtual address range
* @mm: mm_struct containing virtual address range
* @start: start of virtual address range
* @end: end of virtual address range
* @nbits: specifies number of bytes to purge per instruction (num = 1<<(nbits & 0xfc))
*
* Purges the translation caches of all processors of the given virtual address
* range.
*
* Note:
* - cpu_vm_mask is a bit mask that indicates which cpus have loaded the context.
* - cpu_vm_mask is converted into a nodemask of the nodes containing the
* cpus in cpu_vm_mask.
* - if only one bit is set in cpu_vm_mask & it is the current cpu & the
* process is purging its own virtual address range, then only the
* local TLB needs to be flushed. This flushing can be done using
* ptc.l. This is the common case & avoids the global spinlock.
* - if multiple cpus have loaded the context, then flushing has to be
* done with ptc.g/MMRs under protection of the global ptc_lock.
*/
void
sn2_global_tlb_purge(struct mm_struct *mm, unsigned long start,
unsigned long end, unsigned long nbits)
{
int i, ibegin, shub1, cnode, mynasid, cpu, lcpu = 0, nasid;
int mymm = (mm == current->active_mm && mm == current->mm);
int use_cpu_ptcga;
volatile unsigned long *ptc0, *ptc1;
unsigned long itc, itc2, flags, data0 = 0, data1 = 0, rr_value, old_rr = 0;
short nasids[MAX_NUMNODES], nix;
nodemask_t nodes_flushed;
int active, max_active, deadlock, flush_opt = sn2_flush_opt;
if (flush_opt > 2) {
sn2_ipi_flush_all_tlb(mm);
return;
}
nodes_clear(nodes_flushed);
i = 0;
for_each_cpu(cpu, mm_cpumask(mm)) {
cnode = cpu_to_node(cpu);
node_set(cnode, nodes_flushed);
lcpu = cpu;
i++;
}
if (i == 0)
return;
preempt_disable();
if (likely(i == 1 && lcpu == smp_processor_id() && mymm)) {
do {
ia64_ptcl(start, nbits << 2);
start += (1UL << nbits);
} while (start < end);
ia64_srlz_i();
__get_cpu_var(ptcstats).ptc_l++;
preempt_enable();
return;
}
if (atomic_read(&mm->mm_users) == 1 && mymm) {
flush_tlb_mm(mm);
__get_cpu_var(ptcstats).change_rid++;
preempt_enable();
return;
}
if (flush_opt == 2) {
sn2_ipi_flush_all_tlb(mm);
preempt_enable();
return;
}
itc = ia64_get_itc();
nix = 0;
for_each_node_mask(cnode, nodes_flushed)
nasids[nix++] = cnodeid_to_nasid(cnode);
rr_value = (mm->context << 3) | REGION_NUMBER(start);
shub1 = is_shub1();
if (shub1) {
data0 = (1UL << SH1_PTC_0_A_SHFT) |
(nbits << SH1_PTC_0_PS_SHFT) |
(rr_value << SH1_PTC_0_RID_SHFT) |
(1UL << SH1_PTC_0_START_SHFT);
ptc0 = (long *)GLOBAL_MMR_PHYS_ADDR(0, SH1_PTC_0);
ptc1 = (long *)GLOBAL_MMR_PHYS_ADDR(0, SH1_PTC_1);
} else {
data0 = (1UL << SH2_PTC_A_SHFT) |
(nbits << SH2_PTC_PS_SHFT) |
(1UL << SH2_PTC_START_SHFT);
ptc0 = (long *)GLOBAL_MMR_PHYS_ADDR(0, SH2_PTC +
(rr_value << SH2_PTC_RID_SHFT));
ptc1 = NULL;
}
mynasid = get_nasid();
use_cpu_ptcga = local_node_uses_ptc_ga(shub1);
max_active = max_active_pio(shub1);
itc = ia64_get_itc();
spin_lock_irqsave(PTC_LOCK(shub1), flags);
itc2 = ia64_get_itc();
__get_cpu_var(ptcstats).lock_itc_clocks += itc2 - itc;
__get_cpu_var(ptcstats).shub_ptc_flushes++;
__get_cpu_var(ptcstats).nodes_flushed += nix;
if (!mymm)
__get_cpu_var(ptcstats).shub_ptc_flushes_not_my_mm++;
if (use_cpu_ptcga && !mymm) {
old_rr = ia64_get_rr(start);
ia64_set_rr(start, (old_rr & 0xff) | (rr_value << 8));
ia64_srlz_d();
}
wait_piowc();
do {
if (shub1)
data1 = start | (1UL << SH1_PTC_1_START_SHFT);
else
data0 = (data0 & ~SH2_PTC_ADDR_MASK) | (start & SH2_PTC_ADDR_MASK);
deadlock = 0;
active = 0;
for (ibegin = 0, i = 0; i < nix; i++) {
nasid = nasids[i];
if (use_cpu_ptcga && unlikely(nasid == mynasid)) {
ia64_ptcga(start, nbits << 2);
ia64_srlz_i();
} else {
ptc0 = CHANGE_NASID(nasid, ptc0);
if (ptc1)
ptc1 = CHANGE_NASID(nasid, ptc1);
pio_atomic_phys_write_mmrs(ptc0, data0, ptc1, data1);
active++;
}
if (active >= max_active || i == (nix - 1)) {
if ((deadlock = wait_piowc())) {
if (flush_opt == 1)
goto done;
sn2_ptc_deadlock_recovery(nasids, ibegin, i, mynasid, ptc0, data0, ptc1, data1);
if (reset_max_active_on_deadlock())
max_active = 1;
}
active = 0;
ibegin = i + 1;
}
}
start += (1UL << nbits);
} while (start < end);
done:
itc2 = ia64_get_itc() - itc2;
__get_cpu_var(ptcstats).shub_itc_clocks += itc2;
if (itc2 > __get_cpu_var(ptcstats).shub_itc_clocks_max)
__get_cpu_var(ptcstats).shub_itc_clocks_max = itc2;
if (old_rr) {
ia64_set_rr(start, old_rr);
ia64_srlz_d();
}
spin_unlock_irqrestore(PTC_LOCK(shub1), flags);
if (flush_opt == 1 && deadlock) {
__get_cpu_var(ptcstats).deadlocks++;
sn2_ipi_flush_all_tlb(mm);
}
preempt_enable();
}
/*
* sn2_ptc_deadlock_recovery
*
* Recover from PTC deadlocks conditions. Recovery requires stepping thru each
* TLB flush transaction. The recovery sequence is somewhat tricky & is
* coded in assembly language.
*/
void
sn2_ptc_deadlock_recovery(short *nasids, short ib, short ie, int mynasid,
volatile unsigned long *ptc0, unsigned long data0,
volatile unsigned long *ptc1, unsigned long data1)
{
short nasid, i;
unsigned long *piows, zeroval, n;
__get_cpu_var(ptcstats).deadlocks++;
piows = (unsigned long *) pda->pio_write_status_addr;
zeroval = pda->pio_write_status_val;
for (i=ib; i <= ie; i++) {
nasid = nasids[i];
if (local_node_uses_ptc_ga(is_shub1()) && nasid == mynasid)
continue;
ptc0 = CHANGE_NASID(nasid, ptc0);
if (ptc1)
ptc1 = CHANGE_NASID(nasid, ptc1);
n = sn2_ptc_deadlock_recovery_core(ptc0, data0, ptc1, data1, piows, zeroval);
__get_cpu_var(ptcstats).deadlocks2 += n;
}
}
/**
* sn_send_IPI_phys - send an IPI to a Nasid and slice
* @nasid: nasid to receive the interrupt (may be outside partition)
* @physid: physical cpuid to receive the interrupt.
* @vector: command to send
* @delivery_mode: delivery mechanism
*
* Sends an IPI (interprocessor interrupt) to the processor specified by
* @physid
*
* @delivery_mode can be one of the following
*
* %IA64_IPI_DM_INT - pend an interrupt
* %IA64_IPI_DM_PMI - pend a PMI
* %IA64_IPI_DM_NMI - pend an NMI
* %IA64_IPI_DM_INIT - pend an INIT interrupt
*/
void sn_send_IPI_phys(int nasid, long physid, int vector, int delivery_mode)
{
long val;
unsigned long flags = 0;
volatile long *p;
p = (long *)GLOBAL_MMR_PHYS_ADDR(nasid, SH_IPI_INT);
val = (1UL << SH_IPI_INT_SEND_SHFT) |
(physid << SH_IPI_INT_PID_SHFT) |
((long)delivery_mode << SH_IPI_INT_TYPE_SHFT) |
((long)vector << SH_IPI_INT_IDX_SHFT) |
(0x000feeUL << SH_IPI_INT_BASE_SHFT);
mb();
if (enable_shub_wars_1_1()) {
spin_lock_irqsave(&sn2_global_ptc_lock, flags);
}
pio_phys_write_mmr(p, val);
if (enable_shub_wars_1_1()) {
wait_piowc();
spin_unlock_irqrestore(&sn2_global_ptc_lock, flags);
}
}
EXPORT_SYMBOL(sn_send_IPI_phys);
/**
* sn2_send_IPI - send an IPI to a processor
* @cpuid: target of the IPI
* @vector: command to send
* @delivery_mode: delivery mechanism
* @redirect: redirect the IPI?
*
* Sends an IPI (InterProcessor Interrupt) to the processor specified by
* @cpuid. @vector specifies the command to send, while @delivery_mode can
* be one of the following
*
* %IA64_IPI_DM_INT - pend an interrupt
* %IA64_IPI_DM_PMI - pend a PMI
* %IA64_IPI_DM_NMI - pend an NMI
* %IA64_IPI_DM_INIT - pend an INIT interrupt
*/
void sn2_send_IPI(int cpuid, int vector, int delivery_mode, int redirect)
{
long physid;
int nasid;
physid = cpu_physical_id(cpuid);
nasid = cpuid_to_nasid(cpuid);
/* the following is used only when starting cpus at boot time */
if (unlikely(nasid == -1))
ia64_sn_get_sapic_info(physid, &nasid, NULL, NULL);
sn_send_IPI_phys(nasid, physid, vector, delivery_mode);
}
#ifdef CONFIG_HOTPLUG_CPU
/**
* sn_cpu_disable_allowed - Determine if a CPU can be disabled.
* @cpu - CPU that is requested to be disabled.
*
* CPU disable is only allowed on SHub2 systems running with a PROM
* that supports CPU disable. It is not permitted to disable the boot processor.
*/
bool sn_cpu_disable_allowed(int cpu)
{
if (is_shub2() && sn_prom_feature_available(PRF_CPU_DISABLE_SUPPORT)) {
if (cpu != 0)
return true;
else
printk(KERN_WARNING
"Disabling the boot processor is not allowed.\n");
} else
printk(KERN_WARNING
"CPU disable is not supported on this system.\n");
return false;
}
#endif /* CONFIG_HOTPLUG_CPU */
#ifdef CONFIG_PROC_FS
#define PTC_BASENAME "sgi_sn/ptc_statistics"
static void *sn2_ptc_seq_start(struct seq_file *file, loff_t * offset)
{
if (*offset < nr_cpu_ids)
return offset;
return NULL;
}
static void *sn2_ptc_seq_next(struct seq_file *file, void *data, loff_t * offset)
{
(*offset)++;
if (*offset < nr_cpu_ids)
return offset;
return NULL;
}
static void sn2_ptc_seq_stop(struct seq_file *file, void *data)
{
}
static int sn2_ptc_seq_show(struct seq_file *file, void *data)
{
struct ptc_stats *stat;
int cpu;
cpu = *(loff_t *) data;
if (!cpu) {
seq_printf(file,
"# cpu ptc_l newrid ptc_flushes nodes_flushed deadlocks lock_nsec shub_nsec shub_nsec_max not_my_mm deadlock2 ipi_fluches ipi_nsec\n");
seq_printf(file, "# ptctest %d, flushopt %d\n", sn2_ptctest, sn2_flush_opt);
}
if (cpu < nr_cpu_ids && cpu_online(cpu)) {
stat = &per_cpu(ptcstats, cpu);
seq_printf(file, "cpu %d %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\n", cpu, stat->ptc_l,
stat->change_rid, stat->shub_ptc_flushes, stat->nodes_flushed,
stat->deadlocks,
1000 * stat->lock_itc_clocks / per_cpu(ia64_cpu_info, cpu).cyc_per_usec,
1000 * stat->shub_itc_clocks / per_cpu(ia64_cpu_info, cpu).cyc_per_usec,
1000 * stat->shub_itc_clocks_max / per_cpu(ia64_cpu_info, cpu).cyc_per_usec,
stat->shub_ptc_flushes_not_my_mm,
stat->deadlocks2,
stat->shub_ipi_flushes,
1000 * stat->shub_ipi_flushes_itc_clocks / per_cpu(ia64_cpu_info, cpu).cyc_per_usec);
}
return 0;
}
static ssize_t sn2_ptc_proc_write(struct file *file, const char __user *user, size_t count, loff_t *data)
{
int cpu;
char optstr[64];
if (count == 0 || count > sizeof(optstr))
return -EINVAL;
if (copy_from_user(optstr, user, count))
return -EFAULT;
optstr[count - 1] = '\0';
sn2_flush_opt = simple_strtoul(optstr, NULL, 0);
for_each_online_cpu(cpu)
memset(&per_cpu(ptcstats, cpu), 0, sizeof(struct ptc_stats));
return count;
}
static const struct seq_operations sn2_ptc_seq_ops = {
.start = sn2_ptc_seq_start,
.next = sn2_ptc_seq_next,
.stop = sn2_ptc_seq_stop,
.show = sn2_ptc_seq_show
};
static int sn2_ptc_proc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &sn2_ptc_seq_ops);
}
static const struct file_operations proc_sn2_ptc_operations = {
.open = sn2_ptc_proc_open,
.read = seq_read,
.write = sn2_ptc_proc_write,
.llseek = seq_lseek,
.release = seq_release,
};
static struct proc_dir_entry *proc_sn2_ptc;
static int __init sn2_ptc_init(void)
{
if (!ia64_platform_is("sn2"))
return 0;
proc_sn2_ptc = proc_create(PTC_BASENAME, 0444,
NULL, &proc_sn2_ptc_operations);
if (!proc_sn2_ptc) {
printk(KERN_ERR "unable to create %s proc entry", PTC_BASENAME);
return -EINVAL;
}
spin_lock_init(&sn2_global_ptc_lock);
return 0;
}
static void __exit sn2_ptc_exit(void)
{
remove_proc_entry(PTC_BASENAME, NULL);
}
module_init(sn2_ptc_init);
module_exit(sn2_ptc_exit);
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
NamanArora/flamingo_kernel | net/netfilter/xt_hl.c | 10406 | 2330 | /*
* IP tables module for matching the value of the TTL
* (C) 2000,2001 by Harald Welte <laforge@netfilter.org>
*
* Hop Limit matching module
* (C) 2001-2002 Maciej Soltysiak <solt@dns.toxicfilms.tv>
*
* 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/ip.h>
#include <linux/ipv6.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv4/ipt_ttl.h>
#include <linux/netfilter_ipv6/ip6t_hl.h>
MODULE_AUTHOR("Maciej Soltysiak <solt@dns.toxicfilms.tv>");
MODULE_DESCRIPTION("Xtables: Hoplimit/TTL field match");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_ttl");
MODULE_ALIAS("ip6t_hl");
static bool ttl_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct ipt_ttl_info *info = par->matchinfo;
const u8 ttl = ip_hdr(skb)->ttl;
switch (info->mode) {
case IPT_TTL_EQ:
return ttl == info->ttl;
case IPT_TTL_NE:
return ttl != info->ttl;
case IPT_TTL_LT:
return ttl < info->ttl;
case IPT_TTL_GT:
return ttl > info->ttl;
}
return false;
}
static bool hl_mt6(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct ip6t_hl_info *info = par->matchinfo;
const struct ipv6hdr *ip6h = ipv6_hdr(skb);
switch (info->mode) {
case IP6T_HL_EQ:
return ip6h->hop_limit == info->hop_limit;
case IP6T_HL_NE:
return ip6h->hop_limit != info->hop_limit;
case IP6T_HL_LT:
return ip6h->hop_limit < info->hop_limit;
case IP6T_HL_GT:
return ip6h->hop_limit > info->hop_limit;
}
return false;
}
static struct xt_match hl_mt_reg[] __read_mostly = {
{
.name = "ttl",
.revision = 0,
.family = NFPROTO_IPV4,
.match = ttl_mt,
.matchsize = sizeof(struct ipt_ttl_info),
.me = THIS_MODULE,
},
{
.name = "hl",
.revision = 0,
.family = NFPROTO_IPV6,
.match = hl_mt6,
.matchsize = sizeof(struct ip6t_hl_info),
.me = THIS_MODULE,
},
};
static int __init hl_mt_init(void)
{
return xt_register_matches(hl_mt_reg, ARRAY_SIZE(hl_mt_reg));
}
static void __exit hl_mt_exit(void)
{
xt_unregister_matches(hl_mt_reg, ARRAY_SIZE(hl_mt_reg));
}
module_init(hl_mt_init);
module_exit(hl_mt_exit);
| gpl-2.0 |
Dm47021/android_kernel_samsung_centura_sch738c | drivers/char/uv_mmtimer.c | 13734 | 5647 | /*
* Timer device implementation for SGI UV platform.
*
* 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) 2009 Silicon Graphics, Inc. All rights reserved.
*
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ioctl.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/mmtimer.h>
#include <linux/miscdevice.h>
#include <linux/posix-timers.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/math64.h>
#include <asm/genapic.h>
#include <asm/uv/uv_hub.h>
#include <asm/uv/bios.h>
#include <asm/uv/uv.h>
MODULE_AUTHOR("Dimitri Sivanich <sivanich@sgi.com>");
MODULE_DESCRIPTION("SGI UV Memory Mapped RTC Timer");
MODULE_LICENSE("GPL");
/* name of the device, usually in /dev */
#define UV_MMTIMER_NAME "mmtimer"
#define UV_MMTIMER_DESC "SGI UV Memory Mapped RTC Timer"
#define UV_MMTIMER_VERSION "1.0"
static long uv_mmtimer_ioctl(struct file *file, unsigned int cmd,
unsigned long arg);
static int uv_mmtimer_mmap(struct file *file, struct vm_area_struct *vma);
/*
* Period in femtoseconds (10^-15 s)
*/
static unsigned long uv_mmtimer_femtoperiod;
static const struct file_operations uv_mmtimer_fops = {
.owner = THIS_MODULE,
.mmap = uv_mmtimer_mmap,
.unlocked_ioctl = uv_mmtimer_ioctl,
.llseek = noop_llseek,
};
/**
* uv_mmtimer_ioctl - ioctl interface for /dev/uv_mmtimer
* @file: file structure for the device
* @cmd: command to execute
* @arg: optional argument to command
*
* Executes the command specified by @cmd. Returns 0 for success, < 0 for
* failure.
*
* Valid commands:
*
* %MMTIMER_GETOFFSET - Should return the offset (relative to the start
* of the page where the registers are mapped) for the counter in question.
*
* %MMTIMER_GETRES - Returns the resolution of the clock in femto (10^-15)
* seconds
*
* %MMTIMER_GETFREQ - Copies the frequency of the clock in Hz to the address
* specified by @arg
*
* %MMTIMER_GETBITS - Returns the number of bits in the clock's counter
*
* %MMTIMER_MMAPAVAIL - Returns 1 if registers can be mmap'd into userspace
*
* %MMTIMER_GETCOUNTER - Gets the current value in the counter and places it
* in the address specified by @arg.
*/
static long uv_mmtimer_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int ret = 0;
switch (cmd) {
case MMTIMER_GETOFFSET: /* offset of the counter */
/*
* Starting with HUB rev 2.0, the UV RTC register is
* replicated across all cachelines of it's own page.
* This allows faster simultaneous reads from a given socket.
*
* The offset returned is in 64 bit units.
*/
if (uv_get_min_hub_revision_id() == 1)
ret = 0;
else
ret = ((uv_blade_processor_id() * L1_CACHE_BYTES) %
PAGE_SIZE) / 8;
break;
case MMTIMER_GETRES: /* resolution of the clock in 10^-15 s */
if (copy_to_user((unsigned long __user *)arg,
&uv_mmtimer_femtoperiod, sizeof(unsigned long)))
ret = -EFAULT;
break;
case MMTIMER_GETFREQ: /* frequency in Hz */
if (copy_to_user((unsigned long __user *)arg,
&sn_rtc_cycles_per_second,
sizeof(unsigned long)))
ret = -EFAULT;
break;
case MMTIMER_GETBITS: /* number of bits in the clock */
ret = hweight64(UVH_RTC_REAL_TIME_CLOCK_MASK);
break;
case MMTIMER_MMAPAVAIL:
ret = 1;
break;
case MMTIMER_GETCOUNTER:
if (copy_to_user((unsigned long __user *)arg,
(unsigned long *)uv_local_mmr_address(UVH_RTC),
sizeof(unsigned long)))
ret = -EFAULT;
break;
default:
ret = -ENOTTY;
break;
}
return ret;
}
/**
* uv_mmtimer_mmap - maps the clock's registers into userspace
* @file: file structure for the device
* @vma: VMA to map the registers into
*
* Calls remap_pfn_range() to map the clock's registers into
* the calling process' address space.
*/
static int uv_mmtimer_mmap(struct file *file, struct vm_area_struct *vma)
{
unsigned long uv_mmtimer_addr;
if (vma->vm_end - vma->vm_start != PAGE_SIZE)
return -EINVAL;
if (vma->vm_flags & VM_WRITE)
return -EPERM;
if (PAGE_SIZE > (1 << 16))
return -ENOSYS;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
uv_mmtimer_addr = UV_LOCAL_MMR_BASE | UVH_RTC;
uv_mmtimer_addr &= ~(PAGE_SIZE - 1);
uv_mmtimer_addr &= 0xfffffffffffffffUL;
if (remap_pfn_range(vma, vma->vm_start, uv_mmtimer_addr >> PAGE_SHIFT,
PAGE_SIZE, vma->vm_page_prot)) {
printk(KERN_ERR "remap_pfn_range failed in uv_mmtimer_mmap\n");
return -EAGAIN;
}
return 0;
}
static struct miscdevice uv_mmtimer_miscdev = {
MISC_DYNAMIC_MINOR,
UV_MMTIMER_NAME,
&uv_mmtimer_fops
};
/**
* uv_mmtimer_init - device initialization routine
*
* Does initial setup for the uv_mmtimer device.
*/
static int __init uv_mmtimer_init(void)
{
if (!is_uv_system()) {
printk(KERN_ERR "%s: Hardware unsupported\n", UV_MMTIMER_NAME);
return -1;
}
/*
* Sanity check the cycles/sec variable
*/
if (sn_rtc_cycles_per_second < 100000) {
printk(KERN_ERR "%s: unable to determine clock frequency\n",
UV_MMTIMER_NAME);
return -1;
}
uv_mmtimer_femtoperiod = ((unsigned long)1E15 +
sn_rtc_cycles_per_second / 2) /
sn_rtc_cycles_per_second;
if (misc_register(&uv_mmtimer_miscdev)) {
printk(KERN_ERR "%s: failed to register device\n",
UV_MMTIMER_NAME);
return -1;
}
printk(KERN_INFO "%s: v%s, %ld MHz\n", UV_MMTIMER_DESC,
UV_MMTIMER_VERSION,
sn_rtc_cycles_per_second/(unsigned long)1E6);
return 0;
}
module_init(uv_mmtimer_init);
| gpl-2.0 |
rockly703/linux-2.6.28-mini6410 | drivers/pcmcia/m32r_pcc.c | 167 | 17067 | /*
* drivers/pcmcia/m32r_pcc.c
*
* Device driver for the PCMCIA functionality of M32R.
*
* Copyright (c) 2001, 2002, 2003, 2004
* Hiroyuki Kondo, Naoto Sugai, Hayato Fujiwara
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/bitops.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/addrspace.h>
#include <pcmcia/cs_types.h>
#include <pcmcia/ss.h>
#include <pcmcia/cs.h>
/* XXX: should be moved into asm/irq.h */
#define PCC0_IRQ 24
#define PCC1_IRQ 25
#include "m32r_pcc.h"
#define CHAOS_PCC_DEBUG
#ifdef CHAOS_PCC_DEBUG
static volatile u_short dummy_readbuf;
#endif
#define PCC_DEBUG_DBEX
#ifdef CONFIG_PCMCIA_DEBUG
static int m32r_pcc_debug;
module_param(m32r_pcc_debug, int, 0644);
#define debug(lvl, fmt, arg...) do { \
if (m32r_pcc_debug > (lvl)) \
printk(KERN_DEBUG "m32r_pcc: " fmt , ## arg); \
} while (0)
#else
#define debug(n, args...) do { } while (0)
#endif
/* Poll status interval -- 0 means default to interrupt */
static int poll_interval = 0;
typedef enum pcc_space { as_none = 0, as_comm, as_attr, as_io } pcc_as_t;
typedef struct pcc_socket {
u_short type, flags;
struct pcmcia_socket socket;
unsigned int number;
unsigned int ioaddr;
u_long mapaddr;
u_long base; /* PCC register base */
u_char cs_irq, intr;
pccard_io_map io_map[MAX_IO_WIN];
pccard_mem_map mem_map[MAX_WIN];
u_char io_win;
u_char mem_win;
pcc_as_t current_space;
u_char last_iodbex;
#ifdef CHAOS_PCC_DEBUG
u_char last_iosize;
#endif
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *proc;
#endif
} pcc_socket_t;
static int pcc_sockets = 0;
static pcc_socket_t socket[M32R_MAX_PCC] = {
{ 0, }, /* ... */
};
/*====================================================================*/
static unsigned int pcc_get(u_short, unsigned int);
static void pcc_set(u_short, unsigned int , unsigned int );
static DEFINE_SPINLOCK(pcc_lock);
void pcc_iorw(int sock, unsigned long port, void *buf, size_t size, size_t nmemb, int wr, int flag)
{
u_long addr;
u_long flags;
int need_ex;
#ifdef PCC_DEBUG_DBEX
int _dbex;
#endif
pcc_socket_t *t = &socket[sock];
#ifdef CHAOS_PCC_DEBUG
int map_changed = 0;
#endif
/* Need lock ? */
spin_lock_irqsave(&pcc_lock, flags);
/*
* Check if need dbex
*/
need_ex = (size > 1 && flag == 0) ? PCMOD_DBEX : 0;
#ifdef PCC_DEBUG_DBEX
_dbex = need_ex;
need_ex = 0;
#endif
/*
* calculate access address
*/
addr = t->mapaddr + port - t->ioaddr + KSEG1; /* XXX */
/*
* Check current mapping
*/
if (t->current_space != as_io || t->last_iodbex != need_ex) {
u_long cbsz;
/*
* Disable first
*/
pcc_set(sock, PCCR, 0);
/*
* Set mode and io address
*/
cbsz = (t->flags & MAP_16BIT) ? 0 : PCMOD_CBSZ;
pcc_set(sock, PCMOD, PCMOD_AS_IO | cbsz | need_ex);
pcc_set(sock, PCADR, addr & 0x1ff00000);
/*
* Enable and read it
*/
pcc_set(sock, PCCR, 1);
#ifdef CHAOS_PCC_DEBUG
#if 0
map_changed = (t->current_space == as_attr && size == 2); /* XXX */
#else
map_changed = 1;
#endif
#endif
t->current_space = as_io;
}
/*
* access to IO space
*/
if (size == 1) {
/* Byte */
unsigned char *bp = (unsigned char *)buf;
#ifdef CHAOS_DEBUG
if (map_changed) {
dummy_readbuf = readb(addr);
}
#endif
if (wr) {
/* write Byte */
while (nmemb--) {
writeb(*bp++, addr);
}
} else {
/* read Byte */
while (nmemb--) {
*bp++ = readb(addr);
}
}
} else {
/* Word */
unsigned short *bp = (unsigned short *)buf;
#ifdef CHAOS_PCC_DEBUG
if (map_changed) {
dummy_readbuf = readw(addr);
}
#endif
if (wr) {
/* write Word */
while (nmemb--) {
#ifdef PCC_DEBUG_DBEX
if (_dbex) {
unsigned char *cp = (unsigned char *)bp;
unsigned short tmp;
tmp = cp[1] << 8 | cp[0];
writew(tmp, addr);
bp++;
} else
#endif
writew(*bp++, addr);
}
} else {
/* read Word */
while (nmemb--) {
#ifdef PCC_DEBUG_DBEX
if (_dbex) {
unsigned char *cp = (unsigned char *)bp;
unsigned short tmp;
tmp = readw(addr);
cp[0] = tmp & 0xff;
cp[1] = (tmp >> 8) & 0xff;
bp++;
} else
#endif
*bp++ = readw(addr);
}
}
}
#if 1
/* addr is no longer used */
if ((addr = pcc_get(sock, PCIRC)) & PCIRC_BWERR) {
printk("m32r_pcc: BWERR detected : port 0x%04lx : iosize %dbit\n",
port, size * 8);
pcc_set(sock, PCIRC, addr);
}
#endif
/*
* save state
*/
t->last_iosize = size;
t->last_iodbex = need_ex;
/* Need lock ? */
spin_unlock_irqrestore(&pcc_lock,flags);
return;
}
void pcc_ioread(int sock, unsigned long port, void *buf, size_t size, size_t nmemb, int flag) {
pcc_iorw(sock, port, buf, size, nmemb, 0, flag);
}
void pcc_iowrite(int sock, unsigned long port, void *buf, size_t size, size_t nmemb, int flag) {
pcc_iorw(sock, port, buf, size, nmemb, 1, flag);
}
/*====================================================================*/
#define IS_REGISTERED 0x2000
#define IS_ALIVE 0x8000
typedef struct pcc_t {
char *name;
u_short flags;
} pcc_t;
static pcc_t pcc[] = {
{ "xnux2", 0 }, { "xnux2", 0 },
};
static irqreturn_t pcc_interrupt(int, void *);
/*====================================================================*/
static struct timer_list poll_timer;
static unsigned int pcc_get(u_short sock, unsigned int reg)
{
return inl(socket[sock].base + reg);
}
static void pcc_set(u_short sock, unsigned int reg, unsigned int data)
{
outl(data, socket[sock].base + reg);
}
/*======================================================================
See if a card is present, powered up, in IO mode, and already
bound to a (non PC Card) Linux driver. We leave these alone.
We make an exception for cards that seem to be serial devices.
======================================================================*/
static int __init is_alive(u_short sock)
{
unsigned int stat;
unsigned int f;
stat = pcc_get(sock, PCIRC);
f = (stat & (PCIRC_CDIN1 | PCIRC_CDIN2)) >> 16;
if(!f){
printk("m32r_pcc: No Card is detected at socket %d : stat = 0x%08x\n",stat,sock);
return 0;
}
if(f!=3)
printk("m32r_pcc: Insertion fail (%.8x) at socket %d\n",stat,sock);
else
printk("m32r_pcc: Card is Inserted at socket %d(%.8x)\n",sock,stat);
return 0;
}
static void add_pcc_socket(ulong base, int irq, ulong mapaddr,
unsigned int ioaddr)
{
pcc_socket_t *t = &socket[pcc_sockets];
/* add sockets */
t->ioaddr = ioaddr;
t->mapaddr = mapaddr;
t->base = base;
#ifdef CHAOS_PCC_DEBUG
t->flags = MAP_16BIT;
#else
t->flags = 0;
#endif
if (is_alive(pcc_sockets))
t->flags |= IS_ALIVE;
/* add pcc */
if (t->base > 0) {
request_region(t->base, 0x20, "m32r-pcc");
}
printk(KERN_INFO " %s ", pcc[pcc_sockets].name);
printk("pcc at 0x%08lx\n", t->base);
/* Update socket interrupt information, capabilities */
t->socket.features |= (SS_CAP_PCCARD | SS_CAP_STATIC_MAP);
t->socket.map_size = M32R_PCC_MAPSIZE;
t->socket.io_offset = ioaddr; /* use for io access offset */
t->socket.irq_mask = 0;
t->socket.pci_irq = 2 + pcc_sockets; /* XXX */
request_irq(irq, pcc_interrupt, 0, "m32r-pcc", pcc_interrupt);
pcc_sockets++;
return;
}
/*====================================================================*/
static irqreturn_t pcc_interrupt(int irq, void *dev)
{
int i, j, irc;
u_int events, active;
int handled = 0;
debug(4, "m32r: pcc_interrupt(%d)\n", irq);
for (j = 0; j < 20; j++) {
active = 0;
for (i = 0; i < pcc_sockets; i++) {
if ((socket[i].cs_irq != irq) &&
(socket[i].socket.pci_irq != irq))
continue;
handled = 1;
irc = pcc_get(i, PCIRC);
irc >>=16;
debug(2, "m32r-pcc:interrupt: socket %d pcirc 0x%02x ", i, irc);
if (!irc)
continue;
events = (irc) ? SS_DETECT : 0;
events |= (pcc_get(i,PCCR) & PCCR_PCEN) ? SS_READY : 0;
debug(2, " event 0x%02x\n", events);
if (events)
pcmcia_parse_events(&socket[i].socket, events);
active |= events;
active = 0;
}
if (!active) break;
}
if (j == 20)
printk(KERN_NOTICE "m32r-pcc: infinite loop in interrupt handler\n");
debug(4, "m32r-pcc: interrupt done\n");
return IRQ_RETVAL(handled);
} /* pcc_interrupt */
static void pcc_interrupt_wrapper(u_long data)
{
pcc_interrupt(0, NULL);
init_timer(&poll_timer);
poll_timer.expires = jiffies + poll_interval;
add_timer(&poll_timer);
}
/*====================================================================*/
static int _pcc_get_status(u_short sock, u_int *value)
{
u_int status;
status = pcc_get(sock,PCIRC);
*value = ((status & PCIRC_CDIN1) && (status & PCIRC_CDIN2))
? SS_DETECT : 0;
status = pcc_get(sock,PCCR);
#if 0
*value |= (status & PCCR_PCEN) ? SS_READY : 0;
#else
*value |= SS_READY; /* XXX: always */
#endif
status = pcc_get(sock,PCCSIGCR);
*value |= (status & PCCSIGCR_VEN) ? SS_POWERON : 0;
debug(3, "m32r-pcc: GetStatus(%d) = %#4.4x\n", sock, *value);
return 0;
} /* _get_status */
/*====================================================================*/
static int _pcc_set_socket(u_short sock, socket_state_t *state)
{
u_long reg = 0;
debug(3, "m32r-pcc: SetSocket(%d, flags %#3.3x, Vcc %d, Vpp %d, "
"io_irq %d, csc_mask %#2.2x)", sock, state->flags,
state->Vcc, state->Vpp, state->io_irq, state->csc_mask);
if (state->Vcc) {
/*
* 5V only
*/
if (state->Vcc == 50) {
reg |= PCCSIGCR_VEN;
} else {
return -EINVAL;
}
}
if (state->flags & SS_RESET) {
debug(3, ":RESET\n");
reg |= PCCSIGCR_CRST;
}
if (state->flags & SS_OUTPUT_ENA){
debug(3, ":OUTPUT_ENA\n");
/* bit clear */
} else {
reg |= PCCSIGCR_SEN;
}
pcc_set(sock,PCCSIGCR,reg);
#ifdef CONFIG_PCMCIA_DEBUG
if(state->flags & SS_IOCARD){
debug(3, ":IOCARD");
}
if (state->flags & SS_PWR_AUTO) {
debug(3, ":PWR_AUTO");
}
if (state->csc_mask & SS_DETECT)
debug(3, ":csc-SS_DETECT");
if (state->flags & SS_IOCARD) {
if (state->csc_mask & SS_STSCHG)
debug(3, ":STSCHG");
} else {
if (state->csc_mask & SS_BATDEAD)
debug(3, ":BATDEAD");
if (state->csc_mask & SS_BATWARN)
debug(3, ":BATWARN");
if (state->csc_mask & SS_READY)
debug(3, ":READY");
}
debug(3, "\n");
#endif
return 0;
} /* _set_socket */
/*====================================================================*/
static int _pcc_set_io_map(u_short sock, struct pccard_io_map *io)
{
u_char map;
debug(3, "m32r-pcc: SetIOMap(%d, %d, %#2.2x, %d ns, "
"%#x-%#x)\n", sock, io->map, io->flags,
io->speed, io->start, io->stop);
map = io->map;
return 0;
} /* _set_io_map */
/*====================================================================*/
static int _pcc_set_mem_map(u_short sock, struct pccard_mem_map *mem)
{
u_char map = mem->map;
u_long mode;
u_long addr;
pcc_socket_t *t = &socket[sock];
#ifdef CHAOS_PCC_DEBUG
#if 0
pcc_as_t last = t->current_space;
#endif
#endif
debug(3, "m32r-pcc: SetMemMap(%d, %d, %#2.2x, %d ns, "
"%#lx, %#x)\n", sock, map, mem->flags,
mem->speed, mem->static_start, mem->card_start);
/*
* sanity check
*/
if ((map > MAX_WIN) || (mem->card_start > 0x3ffffff)){
return -EINVAL;
}
/*
* de-activate
*/
if ((mem->flags & MAP_ACTIVE) == 0) {
t->current_space = as_none;
return 0;
}
/*
* Disable first
*/
pcc_set(sock, PCCR, 0);
/*
* Set mode
*/
if (mem->flags & MAP_ATTRIB) {
mode = PCMOD_AS_ATTRIB | PCMOD_CBSZ;
t->current_space = as_attr;
} else {
mode = 0; /* common memory */
t->current_space = as_comm;
}
pcc_set(sock, PCMOD, mode);
/*
* Set address
*/
addr = t->mapaddr + (mem->card_start & M32R_PCC_MAPMASK);
pcc_set(sock, PCADR, addr);
mem->static_start = addr + mem->card_start;
/*
* Enable again
*/
pcc_set(sock, PCCR, 1);
#ifdef CHAOS_PCC_DEBUG
#if 0
if (last != as_attr) {
#else
if (1) {
#endif
dummy_readbuf = *(u_char *)(addr + KSEG1);
}
#endif
return 0;
} /* _set_mem_map */
#if 0 /* driver model ordering issue */
/*======================================================================
Routines for accessing socket information and register dumps via
/proc/bus/pccard/...
======================================================================*/
static ssize_t show_info(struct class_device *class_dev, char *buf)
{
pcc_socket_t *s = container_of(class_dev, struct pcc_socket,
socket.dev);
return sprintf(buf, "type: %s\nbase addr: 0x%08lx\n",
pcc[s->type].name, s->base);
}
static ssize_t show_exca(struct class_device *class_dev, char *buf)
{
/* FIXME */
return 0;
}
static CLASS_DEVICE_ATTR(info, S_IRUGO, show_info, NULL);
static CLASS_DEVICE_ATTR(exca, S_IRUGO, show_exca, NULL);
#endif
/*====================================================================*/
/* this is horribly ugly... proper locking needs to be done here at
* some time... */
#define LOCKED(x) do { \
int retval; \
unsigned long flags; \
spin_lock_irqsave(&pcc_lock, flags); \
retval = x; \
spin_unlock_irqrestore(&pcc_lock, flags); \
return retval; \
} while (0)
static int pcc_get_status(struct pcmcia_socket *s, u_int *value)
{
unsigned int sock = container_of(s, struct pcc_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE) {
*value = 0;
return -EINVAL;
}
LOCKED(_pcc_get_status(sock, value));
}
static int pcc_set_socket(struct pcmcia_socket *s, socket_state_t *state)
{
unsigned int sock = container_of(s, struct pcc_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE)
return -EINVAL;
LOCKED(_pcc_set_socket(sock, state));
}
static int pcc_set_io_map(struct pcmcia_socket *s, struct pccard_io_map *io)
{
unsigned int sock = container_of(s, struct pcc_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE)
return -EINVAL;
LOCKED(_pcc_set_io_map(sock, io));
}
static int pcc_set_mem_map(struct pcmcia_socket *s, struct pccard_mem_map *mem)
{
unsigned int sock = container_of(s, struct pcc_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE)
return -EINVAL;
LOCKED(_pcc_set_mem_map(sock, mem));
}
static int pcc_init(struct pcmcia_socket *s)
{
debug(4, "m32r-pcc: init call\n");
return 0;
}
static struct pccard_operations pcc_operations = {
.init = pcc_init,
.get_status = pcc_get_status,
.set_socket = pcc_set_socket,
.set_io_map = pcc_set_io_map,
.set_mem_map = pcc_set_mem_map,
};
/*====================================================================*/
static struct device_driver pcc_driver = {
.name = "pcc",
.bus = &platform_bus_type,
.suspend = pcmcia_socket_dev_suspend,
.resume = pcmcia_socket_dev_resume,
};
static struct platform_device pcc_device = {
.name = "pcc",
.id = 0,
};
/*====================================================================*/
static int __init init_m32r_pcc(void)
{
int i, ret;
ret = driver_register(&pcc_driver);
if (ret)
return ret;
ret = platform_device_register(&pcc_device);
if (ret){
driver_unregister(&pcc_driver);
return ret;
}
printk(KERN_INFO "m32r PCC probe:\n");
pcc_sockets = 0;
add_pcc_socket(M32R_PCC0_BASE, PCC0_IRQ, M32R_PCC0_MAPBASE, 0x1000);
#ifdef CONFIG_M32RPCC_SLOT2
add_pcc_socket(M32R_PCC1_BASE, PCC1_IRQ, M32R_PCC1_MAPBASE, 0x2000);
#endif
if (pcc_sockets == 0) {
printk("socket is not found.\n");
platform_device_unregister(&pcc_device);
driver_unregister(&pcc_driver);
return -ENODEV;
}
/* Set up interrupt handler(s) */
for (i = 0 ; i < pcc_sockets ; i++) {
socket[i].socket.dev.parent = &pcc_device.dev;
socket[i].socket.ops = &pcc_operations;
socket[i].socket.resource_ops = &pccard_static_ops;
socket[i].socket.owner = THIS_MODULE;
socket[i].number = i;
ret = pcmcia_register_socket(&socket[i].socket);
if (!ret)
socket[i].flags |= IS_REGISTERED;
#if 0 /* driver model ordering issue */
class_device_create_file(&socket[i].socket.dev,
&class_device_attr_info);
class_device_create_file(&socket[i].socket.dev,
&class_device_attr_exca);
#endif
}
/* Finally, schedule a polling interrupt */
if (poll_interval != 0) {
poll_timer.function = pcc_interrupt_wrapper;
poll_timer.data = 0;
init_timer(&poll_timer);
poll_timer.expires = jiffies + poll_interval;
add_timer(&poll_timer);
}
return 0;
} /* init_m32r_pcc */
static void __exit exit_m32r_pcc(void)
{
int i;
for (i = 0; i < pcc_sockets; i++)
if (socket[i].flags & IS_REGISTERED)
pcmcia_unregister_socket(&socket[i].socket);
platform_device_unregister(&pcc_device);
if (poll_interval != 0)
del_timer_sync(&poll_timer);
driver_unregister(&pcc_driver);
} /* exit_m32r_pcc */
module_init(init_m32r_pcc);
module_exit(exit_m32r_pcc);
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
| gpl-2.0 |
119/aircam-openwrt | build_dir/linux-gm812x/linux-2.6.28.fa2/drivers/sbus/char/uctrl.c | 167 | 11114 | /* uctrl.c: TS102 Microcontroller interface on Tadpole Sparcbook 3
*
* Copyright 1999 Derrick J Brashear (shadow@dementia.org)
* Copyright 2008 David S. Miller (davem@davemloft.net)
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/smp_lock.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/miscdevice.h>
#include <linux/mm.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
#include <asm/system.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#define UCTRL_MINOR 174
#define DEBUG 1
#ifdef DEBUG
#define dprintk(x) printk x
#else
#define dprintk(x)
#endif
struct uctrl_regs {
u32 uctrl_intr;
u32 uctrl_data;
u32 uctrl_stat;
u32 uctrl_xxx[5];
};
struct ts102_regs {
u32 card_a_intr;
u32 card_a_stat;
u32 card_a_ctrl;
u32 card_a_xxx;
u32 card_b_intr;
u32 card_b_stat;
u32 card_b_ctrl;
u32 card_b_xxx;
u32 uctrl_intr;
u32 uctrl_data;
u32 uctrl_stat;
u32 uctrl_xxx;
u32 ts102_xxx[4];
};
/* Bits for uctrl_intr register */
#define UCTRL_INTR_TXE_REQ 0x01 /* transmit FIFO empty int req */
#define UCTRL_INTR_TXNF_REQ 0x02 /* transmit FIFO not full int req */
#define UCTRL_INTR_RXNE_REQ 0x04 /* receive FIFO not empty int req */
#define UCTRL_INTR_RXO_REQ 0x08 /* receive FIFO overflow int req */
#define UCTRL_INTR_TXE_MSK 0x10 /* transmit FIFO empty mask */
#define UCTRL_INTR_TXNF_MSK 0x20 /* transmit FIFO not full mask */
#define UCTRL_INTR_RXNE_MSK 0x40 /* receive FIFO not empty mask */
#define UCTRL_INTR_RXO_MSK 0x80 /* receive FIFO overflow mask */
/* Bits for uctrl_stat register */
#define UCTRL_STAT_TXE_STA 0x01 /* transmit FIFO empty status */
#define UCTRL_STAT_TXNF_STA 0x02 /* transmit FIFO not full status */
#define UCTRL_STAT_RXNE_STA 0x04 /* receive FIFO not empty status */
#define UCTRL_STAT_RXO_STA 0x08 /* receive FIFO overflow status */
static const char *uctrl_extstatus[16] = {
"main power available",
"internal battery attached",
"external battery attached",
"external VGA attached",
"external keyboard attached",
"external mouse attached",
"lid down",
"internal battery currently charging",
"external battery currently charging",
"internal battery currently discharging",
"external battery currently discharging",
};
/* Everything required for one transaction with the uctrl */
struct uctrl_txn {
u8 opcode;
u8 inbits;
u8 outbits;
u8 *inbuf;
u8 *outbuf;
};
struct uctrl_status {
u8 current_temp; /* 0x07 */
u8 reset_status; /* 0x0b */
u16 event_status; /* 0x0c */
u16 error_status; /* 0x10 */
u16 external_status; /* 0x11, 0x1b */
u8 internal_charge; /* 0x18 */
u8 external_charge; /* 0x19 */
u16 control_lcd; /* 0x20 */
u8 control_bitport; /* 0x21 */
u8 speaker_volume; /* 0x23 */
u8 control_tft_brightness; /* 0x24 */
u8 control_kbd_repeat_delay; /* 0x28 */
u8 control_kbd_repeat_period; /* 0x29 */
u8 control_screen_contrast; /* 0x2F */
};
enum uctrl_opcode {
READ_SERIAL_NUMBER=0x1,
READ_ETHERNET_ADDRESS=0x2,
READ_HARDWARE_VERSION=0x3,
READ_MICROCONTROLLER_VERSION=0x4,
READ_MAX_TEMPERATURE=0x5,
READ_MIN_TEMPERATURE=0x6,
READ_CURRENT_TEMPERATURE=0x7,
READ_SYSTEM_VARIANT=0x8,
READ_POWERON_CYCLES=0x9,
READ_POWERON_SECONDS=0xA,
READ_RESET_STATUS=0xB,
READ_EVENT_STATUS=0xC,
READ_REAL_TIME_CLOCK=0xD,
READ_EXTERNAL_VGA_PORT=0xE,
READ_MICROCONTROLLER_ROM_CHECKSUM=0xF,
READ_ERROR_STATUS=0x10,
READ_EXTERNAL_STATUS=0x11,
READ_USER_CONFIGURATION_AREA=0x12,
READ_MICROCONTROLLER_VOLTAGE=0x13,
READ_INTERNAL_BATTERY_VOLTAGE=0x14,
READ_DCIN_VOLTAGE=0x15,
READ_HORIZONTAL_POINTER_VOLTAGE=0x16,
READ_VERTICAL_POINTER_VOLTAGE=0x17,
READ_INTERNAL_BATTERY_CHARGE_LEVEL=0x18,
READ_EXTERNAL_BATTERY_CHARGE_LEVEL=0x19,
READ_REAL_TIME_CLOCK_ALARM=0x1A,
READ_EVENT_STATUS_NO_RESET=0x1B,
READ_INTERNAL_KEYBOARD_LAYOUT=0x1C,
READ_EXTERNAL_KEYBOARD_LAYOUT=0x1D,
READ_EEPROM_STATUS=0x1E,
CONTROL_LCD=0x20,
CONTROL_BITPORT=0x21,
SPEAKER_VOLUME=0x23,
CONTROL_TFT_BRIGHTNESS=0x24,
CONTROL_WATCHDOG=0x25,
CONTROL_FACTORY_EEPROM_AREA=0x26,
CONTROL_KBD_TIME_UNTIL_REPEAT=0x28,
CONTROL_KBD_TIME_BETWEEN_REPEATS=0x29,
CONTROL_TIMEZONE=0x2A,
CONTROL_MARK_SPACE_RATIO=0x2B,
CONTROL_DIAGNOSTIC_MODE=0x2E,
CONTROL_SCREEN_CONTRAST=0x2F,
RING_BELL=0x30,
SET_DIAGNOSTIC_STATUS=0x32,
CLEAR_KEY_COMBINATION_TABLE=0x33,
PERFORM_SOFTWARE_RESET=0x34,
SET_REAL_TIME_CLOCK=0x35,
RECALIBRATE_POINTING_STICK=0x36,
SET_BELL_FREQUENCY=0x37,
SET_INTERNAL_BATTERY_CHARGE_RATE=0x39,
SET_EXTERNAL_BATTERY_CHARGE_RATE=0x3A,
SET_REAL_TIME_CLOCK_ALARM=0x3B,
READ_EEPROM=0x40,
WRITE_EEPROM=0x41,
WRITE_TO_STATUS_DISPLAY=0x42,
DEFINE_SPECIAL_CHARACTER=0x43,
DEFINE_KEY_COMBINATION_ENTRY=0x50,
DEFINE_STRING_TABLE_ENTRY=0x51,
DEFINE_STATUS_SCREEN_DISPLAY=0x52,
PERFORM_EMU_COMMANDS=0x64,
READ_EMU_REGISTER=0x65,
WRITE_EMU_REGISTER=0x66,
READ_EMU_RAM=0x67,
WRITE_EMU_RAM=0x68,
READ_BQ_REGISTER=0x69,
WRITE_BQ_REGISTER=0x6A,
SET_USER_PASSWORD=0x70,
VERIFY_USER_PASSWORD=0x71,
GET_SYSTEM_PASSWORD_KEY=0x72,
VERIFY_SYSTEM_PASSWORD=0x73,
POWER_OFF=0x82,
POWER_RESTART=0x83,
};
static struct uctrl_driver {
struct uctrl_regs __iomem *regs;
int irq;
int pending;
struct uctrl_status status;
} *global_driver;
static void uctrl_get_event_status(struct uctrl_driver *);
static void uctrl_get_external_status(struct uctrl_driver *);
static int
uctrl_ioctl(struct inode *inode, struct file *file,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
default:
return -EINVAL;
}
return 0;
}
static int
uctrl_open(struct inode *inode, struct file *file)
{
lock_kernel();
uctrl_get_event_status(global_driver);
uctrl_get_external_status(global_driver);
unlock_kernel();
return 0;
}
static irqreturn_t uctrl_interrupt(int irq, void *dev_id)
{
return IRQ_HANDLED;
}
static const struct file_operations uctrl_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.ioctl = uctrl_ioctl,
.open = uctrl_open,
};
static struct miscdevice uctrl_dev = {
UCTRL_MINOR,
"uctrl",
&uctrl_fops
};
/* Wait for space to write, then write to it */
#define WRITEUCTLDATA(value) \
{ \
unsigned int i; \
for (i = 0; i < 10000; i++) { \
if (UCTRL_STAT_TXNF_STA & sbus_readl(&driver->regs->uctrl_stat)) \
break; \
} \
dprintk(("write data 0x%02x\n", value)); \
sbus_writel(value, &driver->regs->uctrl_data); \
}
/* Wait for something to read, read it, then clear the bit */
#define READUCTLDATA(value) \
{ \
unsigned int i; \
value = 0; \
for (i = 0; i < 10000; i++) { \
if ((UCTRL_STAT_RXNE_STA & sbus_readl(&driver->regs->uctrl_stat)) == 0) \
break; \
udelay(1); \
} \
value = sbus_readl(&driver->regs->uctrl_data); \
dprintk(("read data 0x%02x\n", value)); \
sbus_writel(UCTRL_STAT_RXNE_STA, &driver->regs->uctrl_stat); \
}
static void uctrl_do_txn(struct uctrl_driver *driver, struct uctrl_txn *txn)
{
int stat, incnt, outcnt, bytecnt, intr;
u32 byte;
stat = sbus_readl(&driver->regs->uctrl_stat);
intr = sbus_readl(&driver->regs->uctrl_intr);
sbus_writel(stat, &driver->regs->uctrl_stat);
dprintk(("interrupt stat 0x%x int 0x%x\n", stat, intr));
incnt = txn->inbits;
outcnt = txn->outbits;
byte = (txn->opcode << 8);
WRITEUCTLDATA(byte);
bytecnt = 0;
while (incnt > 0) {
byte = (txn->inbuf[bytecnt] << 8);
WRITEUCTLDATA(byte);
incnt--;
bytecnt++;
}
/* Get the ack */
READUCTLDATA(byte);
dprintk(("ack was %x\n", (byte >> 8)));
bytecnt = 0;
while (outcnt > 0) {
READUCTLDATA(byte);
txn->outbuf[bytecnt] = (byte >> 8);
dprintk(("set byte to %02x\n", byte));
outcnt--;
bytecnt++;
}
}
static void uctrl_get_event_status(struct uctrl_driver *driver)
{
struct uctrl_txn txn;
u8 outbits[2];
txn.opcode = READ_EVENT_STATUS;
txn.inbits = 0;
txn.outbits = 2;
txn.inbuf = NULL;
txn.outbuf = outbits;
uctrl_do_txn(driver, &txn);
dprintk(("bytes %x %x\n", (outbits[0] & 0xff), (outbits[1] & 0xff)));
driver->status.event_status =
((outbits[0] & 0xff) << 8) | (outbits[1] & 0xff);
dprintk(("ev is %x\n", driver->status.event_status));
}
static void uctrl_get_external_status(struct uctrl_driver *driver)
{
struct uctrl_txn txn;
u8 outbits[2];
int i, v;
txn.opcode = READ_EXTERNAL_STATUS;
txn.inbits = 0;
txn.outbits = 2;
txn.inbuf = NULL;
txn.outbuf = outbits;
uctrl_do_txn(driver, &txn);
dprintk(("bytes %x %x\n", (outbits[0] & 0xff), (outbits[1] & 0xff)));
driver->status.external_status =
((outbits[0] * 256) + (outbits[1]));
dprintk(("ex is %x\n", driver->status.external_status));
v = driver->status.external_status;
for (i = 0; v != 0; i++, v >>= 1) {
if (v & 1) {
dprintk(("%s%s", " ", uctrl_extstatus[i]));
}
}
dprintk(("\n"));
}
static int __devinit uctrl_probe(struct of_device *op,
const struct of_device_id *match)
{
struct uctrl_driver *p;
int err = -ENOMEM;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (!p) {
printk(KERN_ERR "uctrl: Unable to allocate device struct.\n");
goto out;
}
p->regs = of_ioremap(&op->resource[0], 0,
resource_size(&op->resource[0]),
"uctrl");
if (!p->regs) {
printk(KERN_ERR "uctrl: Unable to map registers.\n");
goto out_free;
}
p->irq = op->irqs[0];
err = request_irq(p->irq, uctrl_interrupt, 0, "uctrl", p);
if (err) {
printk(KERN_ERR "uctrl: Unable to register irq.\n");
goto out_iounmap;
}
err = misc_register(&uctrl_dev);
if (err) {
printk(KERN_ERR "uctrl: Unable to register misc device.\n");
goto out_free_irq;
}
sbus_writel(UCTRL_INTR_RXNE_REQ|UCTRL_INTR_RXNE_MSK, &p->regs->uctrl_intr);
printk(KERN_INFO "%s: uctrl regs[0x%p] (irq %d)\n",
op->node->full_name, p->regs, p->irq);
uctrl_get_event_status(p);
uctrl_get_external_status(p);
dev_set_drvdata(&op->dev, p);
global_driver = p;
out:
return err;
out_free_irq:
free_irq(p->irq, p);
out_iounmap:
of_iounmap(&op->resource[0], p->regs, resource_size(&op->resource[0]));
out_free:
kfree(p);
goto out;
}
static int __devexit uctrl_remove(struct of_device *op)
{
struct uctrl_driver *p = dev_get_drvdata(&op->dev);
if (p) {
misc_deregister(&uctrl_dev);
free_irq(p->irq, p);
of_iounmap(&op->resource[0], p->regs, resource_size(&op->resource[0]));
kfree(p);
}
return 0;
}
static const struct of_device_id uctrl_match[] = {
{
.name = "uctrl",
},
{},
};
MODULE_DEVICE_TABLE(of, uctrl_match);
static struct of_platform_driver uctrl_driver = {
.name = "uctrl",
.match_table = uctrl_match,
.probe = uctrl_probe,
.remove = __devexit_p(uctrl_remove),
};
static int __init uctrl_init(void)
{
return of_register_driver(&uctrl_driver, &of_bus_type);
}
static void __exit uctrl_exit(void)
{
of_unregister_driver(&uctrl_driver);
}
module_init(uctrl_init);
module_exit(uctrl_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Backspace-Dev/htx21 | arch/arm/mach-msm/qdsp6v2/audio_multi_aac.c | 167 | 8076 | /* aac audio output device
*
* Copyright (C) 2008 Google, Inc.
* Copyright (C) 2008 HTC Corporation
* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/msm_audio_aac.h>
#include <mach/socinfo.h>
#include "audio_utils_aio.h"
#undef pr_info
#undef pr_err
#define pr_info(fmt, ...) pr_aud_info(fmt, ##__VA_ARGS__)
#define pr_err(fmt, ...) pr_aud_err(fmt, ##__VA_ARGS__)
#define AUDIO_AAC_DUAL_MONO_INVALID -1
#define PCM_BUFSZ_MIN_AACM ((8*1024) + sizeof(struct dec_meta_out))
#ifdef CONFIG_DEBUG_FS
static const struct file_operations audio_aac_debug_fops = {
.read = audio_aio_debug_read,
.open = audio_aio_debug_open,
};
#endif
static long audio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct q6audio_aio *audio = file->private_data;
int rc = 0;
switch (cmd) {
case AUDIO_START: {
struct asm_aac_cfg aac_cfg;
struct msm_audio_aac_config *aac_config;
uint32_t sbr_ps = 0x00;
aac_config = (struct msm_audio_aac_config *)audio->codec_cfg;
if (audio->feedback == TUNNEL_MODE) {
aac_cfg.sample_rate = aac_config->sample_rate;
aac_cfg.ch_cfg = aac_config->channel_configuration;
} else {
aac_cfg.sample_rate = audio->pcm_cfg.sample_rate;
aac_cfg.ch_cfg = audio->pcm_cfg.channel_count;
}
pr_debug("%s: AUDIO_START session_id[%d]\n", __func__,
audio->ac->session);
if (audio->feedback == NON_TUNNEL_MODE) {
rc = q6asm_enc_cfg_blk_pcm_native(audio->ac,
aac_cfg.sample_rate,
aac_cfg.ch_cfg);
if (rc < 0) {
pr_err("pcm output block config failed\n");
break;
}
}
rc = q6asm_enable_sbrps(audio->ac, sbr_ps);
if (rc < 0)
pr_err("sbr-ps enable failed\n");
if (aac_config->sbr_ps_on_flag)
aac_cfg.aot = AAC_ENC_MODE_EAAC_P;
else if (aac_config->sbr_on_flag)
aac_cfg.aot = AAC_ENC_MODE_AAC_P;
else
aac_cfg.aot = AAC_ENC_MODE_AAC_LC;
switch (aac_config->format) {
case AUDIO_AAC_FORMAT_ADTS:
aac_cfg.format = 0x00;
break;
case AUDIO_AAC_FORMAT_LOAS:
aac_cfg.format = 0x01;
break;
case AUDIO_AAC_FORMAT_ADIF:
aac_cfg.format = 0x02;
break;
default:
case AUDIO_AAC_FORMAT_RAW:
aac_cfg.format = 0x03;
}
aac_cfg.ep_config = aac_config->ep_config;
aac_cfg.section_data_resilience =
aac_config->aac_section_data_resilience_flag;
aac_cfg.scalefactor_data_resilience =
aac_config->aac_scalefactor_data_resilience_flag;
aac_cfg.spectral_data_resilience =
aac_config->aac_spectral_data_resilience_flag;
pr_debug("%s:format=%x aot=%d ch=%d sr=%d\n",
__func__, aac_cfg.format,
aac_cfg.aot, aac_cfg.ch_cfg,
aac_cfg.sample_rate);
rc = q6asm_media_format_block_multi_aac(audio->ac, &aac_cfg);
if (rc < 0) {
pr_err("cmd media format block failed\n");
break;
}
if (!cpu_is_msm8x60()) {
rc = q6asm_set_encdec_chan_map(audio->ac, 2);
if (rc < 0) {
pr_err("%s: cmd set encdec_chan_map failed\n",
__func__);
break;
}
}
rc = audio_aio_enable(audio);
audio->eos_rsp = 0;
audio->eos_flag = 0;
if (!rc) {
audio->enabled = 1;
} else {
audio->enabled = 0;
pr_err("Audio Start procedure failed rc=%d\n", rc);
break;
}
pr_info("%s: AUDIO_START sessionid[%d]enable[%d]\n", __func__,
audio->ac->session,
audio->enabled);
if (audio->stopped == 1)
audio->stopped = 0;
break;
}
case AUDIO_GET_AAC_CONFIG: {
if (copy_to_user((void *)arg, audio->codec_cfg,
sizeof(struct msm_audio_aac_config))) {
rc = -EFAULT;
break;
}
break;
}
case AUDIO_SET_AAC_CONFIG: {
struct msm_audio_aac_config *aac_config;
if (copy_from_user(audio->codec_cfg, (void *)arg,
sizeof(struct msm_audio_aac_config))) {
rc = -EFAULT;
} else {
uint16_t sce_left = 1, sce_right = 2;
aac_config = audio->codec_cfg;
if ((aac_config->dual_mono_mode <
AUDIO_AAC_DUAL_MONO_PL_PR) ||
(aac_config->dual_mono_mode >
AUDIO_AAC_DUAL_MONO_PL_SR)) {
pr_err("%s:AUDIO_SET_AAC_CONFIG: Invalid dual_mono mode =%d\n",
__func__, aac_config->dual_mono_mode);
} else {
pr_debug("%s: AUDIO_SET_AAC_CONFIG: modify dual_mono mode =%d\n",
__func__, aac_config->dual_mono_mode);
switch (aac_config->dual_mono_mode) {
case AUDIO_AAC_DUAL_MONO_PL_PR:
sce_left = 1;
sce_right = 1;
break;
case AUDIO_AAC_DUAL_MONO_SL_SR:
sce_left = 2;
sce_right = 2;
break;
case AUDIO_AAC_DUAL_MONO_SL_PR:
sce_left = 2;
sce_right = 1;
break;
case AUDIO_AAC_DUAL_MONO_PL_SR:
default:
sce_left = 1;
sce_right = 2;
break;
}
rc = q6asm_cfg_dual_mono_aac(audio->ac,
sce_left, sce_right);
if (rc < 0)
pr_err("%s: asm cmd dualmono failed rc=%d\n",
__func__, rc);
} break;
}
break;
}
default:
pr_debug("Calling utils ioctl\n");
rc = audio->codec_ioctl(file, cmd, arg);
}
return rc;
}
static int audio_open(struct inode *inode, struct file *file)
{
struct q6audio_aio *audio = NULL;
int rc = 0;
struct msm_audio_aac_config *aac_config = NULL;
#ifdef CONFIG_DEBUG_FS
char name[sizeof "msm_multi_aac_" + 5];
#endif
audio = kzalloc(sizeof(struct q6audio_aio), GFP_KERNEL);
if (audio == NULL) {
pr_err("Could not allocate memory for aac decode driver\n");
return -ENOMEM;
}
audio->codec_cfg = kzalloc(sizeof(struct msm_audio_aac_config),
GFP_KERNEL);
if (audio->codec_cfg == NULL) {
pr_err("%s: Could not allocate memory for aac config\n",
__func__);
kfree(audio);
return -ENOMEM;
}
aac_config = audio->codec_cfg;
audio->pcm_cfg.buffer_size = PCM_BUFSZ_MIN_AACM;
aac_config->dual_mono_mode = AUDIO_AAC_DUAL_MONO_INVALID;
audio->ac = q6asm_audio_client_alloc((app_cb) q6_audio_cb,
(void *)audio);
if (!audio->ac) {
pr_err("Could not allocate memory for audio client\n");
kfree(audio->codec_cfg);
kfree(audio);
return -ENOMEM;
}
if ((file->f_mode & FMODE_WRITE) && (file->f_mode & FMODE_READ)) {
rc = q6asm_open_read_write(audio->ac, FORMAT_LINEAR_PCM,
FORMAT_MPEG4_MULTI_AAC);
if (rc < 0) {
pr_err("NT mode Open failed rc=%d\n", rc);
rc = -ENODEV;
goto fail;
}
audio->feedback = NON_TUNNEL_MODE;
audio->buf_cfg.meta_info_enable = 0x01;
} else if ((file->f_mode & FMODE_WRITE) &&
!(file->f_mode & FMODE_READ)) {
rc = q6asm_open_write(audio->ac, FORMAT_MPEG4_MULTI_AAC);
if (rc < 0) {
pr_err("T mode Open failed rc=%d\n", rc);
rc = -ENODEV;
goto fail;
}
audio->feedback = TUNNEL_MODE;
audio->buf_cfg.meta_info_enable = 0x00;
} else {
pr_err("Not supported mode\n");
rc = -EACCES;
goto fail;
}
rc = audio_aio_open(audio, file);
#ifdef CONFIG_DEBUG_FS
snprintf(name, sizeof name, "msm_multi_aac_%04x", audio->ac->session);
audio->dentry = debugfs_create_file(name, S_IFREG | S_IRUGO,
NULL, (void *)audio,
&audio_aac_debug_fops);
if (IS_ERR(audio->dentry))
pr_debug("debugfs_create_file failed\n");
#endif
pr_info("%s:AAC 5.1 Decoder OPEN success mode[%d]session[%d]\n",
__func__, audio->feedback, audio->ac->session);
return rc;
fail:
q6asm_audio_client_free(audio->ac);
kfree(audio->codec_cfg);
kfree(audio);
return rc;
}
static const struct file_operations audio_aac_fops = {
.owner = THIS_MODULE,
.open = audio_open,
.release = audio_aio_release,
.unlocked_ioctl = audio_ioctl,
.fsync = audio_aio_fsync,
};
struct miscdevice audio_multiaac_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "msm_multi_aac",
.fops = &audio_aac_fops,
};
static int __init audio_aac_init(void)
{
return misc_register(&audio_multiaac_misc);
}
device_initcall(audio_aac_init);
| gpl-2.0 |
Baastyr/semc-es209ra-kernel | drivers/net/appletalk/ipddp.c | 167 | 8533 | /*
* ipddp.c: IP to Appletalk-IP Encapsulation driver for Linux
* Appletalk-IP to IP Decapsulation driver for Linux
*
* Authors:
* - DDP-IP Encap by: Bradford W. Johnson <johns393@maroon.tc.umn.edu>
* - DDP-IP Decap by: Jay Schulist <jschlst@samba.org>
*
* Derived from:
* - Almost all code already existed in net/appletalk/ddp.c I just
* moved/reorginized it into a driver file. Original IP-over-DDP code
* was done by Bradford W. Johnson <johns393@maroon.tc.umn.edu>
* - skeleton.c: A network driver outline for linux.
* Written 1993-94 by Donald Becker.
* - dummy.c: A dummy net driver. By Nick Holloway.
* - MacGate: A user space Daemon for Appletalk-IP Decap for
* Linux by Jay Schulist <jschlst@samba.org>
*
* 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.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ip.h>
#include <linux/atalk.h>
#include <linux/if_arp.h>
#include <net/route.h>
#include <asm/uaccess.h>
#include "ipddp.h" /* Our stuff */
static const char version[] = KERN_INFO "ipddp.c:v0.01 8/28/97 Bradford W. Johnson <johns393@maroon.tc.umn.edu>\n";
static struct ipddp_route *ipddp_route_list;
#ifdef CONFIG_IPDDP_ENCAP
static int ipddp_mode = IPDDP_ENCAP;
#else
static int ipddp_mode = IPDDP_DECAP;
#endif
/* Index to functions, as function prototypes. */
static int ipddp_xmit(struct sk_buff *skb, struct net_device *dev);
static int ipddp_create(struct ipddp_route *new_rt);
static int ipddp_delete(struct ipddp_route *rt);
static struct ipddp_route* ipddp_find_route(struct ipddp_route *rt);
static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd);
static const struct net_device_ops ipddp_netdev_ops = {
.ndo_start_xmit = ipddp_xmit,
.ndo_do_ioctl = ipddp_ioctl,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static struct net_device * __init ipddp_init(void)
{
static unsigned version_printed;
struct net_device *dev;
int err;
dev = alloc_etherdev(0);
if (!dev)
return ERR_PTR(-ENOMEM);
strcpy(dev->name, "ipddp%d");
if (version_printed++ == 0)
printk(version);
/* Initalize the device structure. */
dev->netdev_ops = &ipddp_netdev_ops;
dev->type = ARPHRD_IPDDP; /* IP over DDP tunnel */
dev->mtu = 585;
dev->flags |= IFF_NOARP;
/*
* The worst case header we will need is currently a
* ethernet header (14 bytes) and a ddp header (sizeof ddpehdr+1)
* We send over SNAP so that takes another 8 bytes.
*/
dev->hard_header_len = 14+8+sizeof(struct ddpehdr)+1;
err = register_netdev(dev);
if (err) {
free_netdev(dev);
return ERR_PTR(err);
}
/* Let the user now what mode we are in */
if(ipddp_mode == IPDDP_ENCAP)
printk("%s: Appletalk-IP Encap. mode by Bradford W. Johnson <johns393@maroon.tc.umn.edu>\n",
dev->name);
if(ipddp_mode == IPDDP_DECAP)
printk("%s: Appletalk-IP Decap. mode by Jay Schulist <jschlst@samba.org>\n",
dev->name);
return dev;
}
/*
* Transmit LLAP/ELAP frame using aarp_send_ddp.
*/
static int ipddp_xmit(struct sk_buff *skb, struct net_device *dev)
{
__be32 paddr = ((struct rtable*)skb->dst)->rt_gateway;
struct ddpehdr *ddp;
struct ipddp_route *rt;
struct atalk_addr *our_addr;
/*
* Find appropriate route to use, based only on IP number.
*/
for(rt = ipddp_route_list; rt != NULL; rt = rt->next)
{
if(rt->ip == paddr)
break;
}
if(rt == NULL)
return 0;
our_addr = atalk_find_dev_addr(rt->dev);
if(ipddp_mode == IPDDP_DECAP)
/*
* Pull off the excess room that should not be there.
* This is due to a hard-header problem. This is the
* quick fix for now though, till it breaks.
*/
skb_pull(skb, 35-(sizeof(struct ddpehdr)+1));
/* Create the Extended DDP header */
ddp = (struct ddpehdr *)skb->data;
ddp->deh_len_hops = htons(skb->len + (1<<10));
ddp->deh_sum = 0;
/*
* For Localtalk we need aarp_send_ddp to strip the
* long DDP header and place a shot DDP header on it.
*/
if(rt->dev->type == ARPHRD_LOCALTLK)
{
ddp->deh_dnet = 0; /* FIXME more hops?? */
ddp->deh_snet = 0;
}
else
{
ddp->deh_dnet = rt->at.s_net; /* FIXME more hops?? */
ddp->deh_snet = our_addr->s_net;
}
ddp->deh_dnode = rt->at.s_node;
ddp->deh_snode = our_addr->s_node;
ddp->deh_dport = 72;
ddp->deh_sport = 72;
*((__u8 *)(ddp+1)) = 22; /* ddp type = IP */
skb->protocol = htons(ETH_P_ATALK); /* Protocol has changed */
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
if(aarp_send_ddp(rt->dev, skb, &rt->at, NULL) < 0)
dev_kfree_skb(skb);
return 0;
}
/*
* Create a routing entry. We first verify that the
* record does not already exist. If it does we return -EEXIST
*/
static int ipddp_create(struct ipddp_route *new_rt)
{
struct ipddp_route *rt = kmalloc(sizeof(*rt), GFP_KERNEL);
if (rt == NULL)
return -ENOMEM;
rt->ip = new_rt->ip;
rt->at = new_rt->at;
rt->next = NULL;
if ((rt->dev = atrtr_get_dev(&rt->at)) == NULL) {
kfree(rt);
return -ENETUNREACH;
}
if (ipddp_find_route(rt)) {
kfree(rt);
return -EEXIST;
}
rt->next = ipddp_route_list;
ipddp_route_list = rt;
return 0;
}
/*
* Delete a route, we only delete a FULL match.
* If route does not exist we return -ENOENT.
*/
static int ipddp_delete(struct ipddp_route *rt)
{
struct ipddp_route **r = &ipddp_route_list;
struct ipddp_route *tmp;
while((tmp = *r) != NULL)
{
if(tmp->ip == rt->ip
&& tmp->at.s_net == rt->at.s_net
&& tmp->at.s_node == rt->at.s_node)
{
*r = tmp->next;
kfree(tmp);
return 0;
}
r = &tmp->next;
}
return (-ENOENT);
}
/*
* Find a routing entry, we only return a FULL match
*/
static struct ipddp_route* ipddp_find_route(struct ipddp_route *rt)
{
struct ipddp_route *f;
for(f = ipddp_route_list; f != NULL; f = f->next)
{
if(f->ip == rt->ip
&& f->at.s_net == rt->at.s_net
&& f->at.s_node == rt->at.s_node)
return (f);
}
return (NULL);
}
static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct ipddp_route __user *rt = ifr->ifr_data;
struct ipddp_route rcp;
if(!capable(CAP_NET_ADMIN))
return -EPERM;
if(copy_from_user(&rcp, rt, sizeof(rcp)))
return -EFAULT;
switch(cmd)
{
case SIOCADDIPDDPRT:
return (ipddp_create(&rcp));
case SIOCFINDIPDDPRT:
if(copy_to_user(rt, ipddp_find_route(&rcp), sizeof(struct ipddp_route)))
return -EFAULT;
return 0;
case SIOCDELIPDDPRT:
return (ipddp_delete(&rcp));
default:
return -EINVAL;
}
}
static struct net_device *dev_ipddp;
MODULE_LICENSE("GPL");
module_param(ipddp_mode, int, 0);
static int __init ipddp_init_module(void)
{
dev_ipddp = ipddp_init();
if (IS_ERR(dev_ipddp))
return PTR_ERR(dev_ipddp);
return 0;
}
static void __exit ipddp_cleanup_module(void)
{
struct ipddp_route *p;
unregister_netdev(dev_ipddp);
free_netdev(dev_ipddp);
while (ipddp_route_list) {
p = ipddp_route_list->next;
kfree(ipddp_route_list);
ipddp_route_list = p;
}
}
module_init(ipddp_init_module);
module_exit(ipddp_cleanup_module);
| gpl-2.0 |
weekend27/redis-3.0-annotated | deps/jemalloc/test/unit/bitmap.c | 423 | 3614 | #include "test/jemalloc_test.h"
#if (LG_BITMAP_MAXBITS > 12)
# define MAXBITS 4500
#else
# define MAXBITS (1U << LG_BITMAP_MAXBITS)
#endif
TEST_BEGIN(test_bitmap_size)
{
size_t i, prev_size;
prev_size = 0;
for (i = 1; i <= MAXBITS; i++) {
size_t size = bitmap_size(i);
assert_true(size >= prev_size,
"Bitmap size is smaller than expected");
prev_size = size;
}
}
TEST_END
TEST_BEGIN(test_bitmap_init)
{
size_t i;
for (i = 1; i <= MAXBITS; i++) {
bitmap_info_t binfo;
bitmap_info_init(&binfo, i);
{
size_t j;
bitmap_t *bitmap = malloc(sizeof(bitmap_t) *
bitmap_info_ngroups(&binfo));
bitmap_init(bitmap, &binfo);
for (j = 0; j < i; j++) {
assert_false(bitmap_get(bitmap, &binfo, j),
"Bit should be unset");
}
free(bitmap);
}
}
}
TEST_END
TEST_BEGIN(test_bitmap_set)
{
size_t i;
for (i = 1; i <= MAXBITS; i++) {
bitmap_info_t binfo;
bitmap_info_init(&binfo, i);
{
size_t j;
bitmap_t *bitmap = malloc(sizeof(bitmap_t) *
bitmap_info_ngroups(&binfo));
bitmap_init(bitmap, &binfo);
for (j = 0; j < i; j++)
bitmap_set(bitmap, &binfo, j);
assert_true(bitmap_full(bitmap, &binfo),
"All bits should be set");
free(bitmap);
}
}
}
TEST_END
TEST_BEGIN(test_bitmap_unset)
{
size_t i;
for (i = 1; i <= MAXBITS; i++) {
bitmap_info_t binfo;
bitmap_info_init(&binfo, i);
{
size_t j;
bitmap_t *bitmap = malloc(sizeof(bitmap_t) *
bitmap_info_ngroups(&binfo));
bitmap_init(bitmap, &binfo);
for (j = 0; j < i; j++)
bitmap_set(bitmap, &binfo, j);
assert_true(bitmap_full(bitmap, &binfo),
"All bits should be set");
for (j = 0; j < i; j++)
bitmap_unset(bitmap, &binfo, j);
for (j = 0; j < i; j++)
bitmap_set(bitmap, &binfo, j);
assert_true(bitmap_full(bitmap, &binfo),
"All bits should be set");
free(bitmap);
}
}
}
TEST_END
TEST_BEGIN(test_bitmap_sfu)
{
size_t i;
for (i = 1; i <= MAXBITS; i++) {
bitmap_info_t binfo;
bitmap_info_init(&binfo, i);
{
ssize_t j;
bitmap_t *bitmap = malloc(sizeof(bitmap_t) *
bitmap_info_ngroups(&binfo));
bitmap_init(bitmap, &binfo);
/* Iteratively set bits starting at the beginning. */
for (j = 0; j < i; j++) {
assert_zd_eq(bitmap_sfu(bitmap, &binfo), j,
"First unset bit should be just after "
"previous first unset bit");
}
assert_true(bitmap_full(bitmap, &binfo),
"All bits should be set");
/*
* Iteratively unset bits starting at the end, and
* verify that bitmap_sfu() reaches the unset bits.
*/
for (j = i - 1; j >= 0; j--) {
bitmap_unset(bitmap, &binfo, j);
assert_zd_eq(bitmap_sfu(bitmap, &binfo), j,
"First unset bit should the bit previously "
"unset");
bitmap_unset(bitmap, &binfo, j);
}
assert_false(bitmap_get(bitmap, &binfo, 0),
"Bit should be unset");
/*
* Iteratively set bits starting at the beginning, and
* verify that bitmap_sfu() looks past them.
*/
for (j = 1; j < i; j++) {
bitmap_set(bitmap, &binfo, j - 1);
assert_zd_eq(bitmap_sfu(bitmap, &binfo), j,
"First unset bit should be just after the "
"bit previously set");
bitmap_unset(bitmap, &binfo, j);
}
assert_zd_eq(bitmap_sfu(bitmap, &binfo), i - 1,
"First unset bit should be the last bit");
assert_true(bitmap_full(bitmap, &binfo),
"All bits should be set");
free(bitmap);
}
}
}
TEST_END
int
main(void)
{
return (test(
test_bitmap_size,
test_bitmap_init,
test_bitmap_set,
test_bitmap_unset,
test_bitmap_sfu));
}
| gpl-2.0 |
ASaifM/orinoco | drivers/clk/mvebu/armada-39x.c | 935 | 4074 | /*
* Marvell Armada 39x SoC clocks
*
* Copyright (C) 2015 Marvell
*
* Gregory CLEMENT <gregory.clement@free-electrons.com>
* Sebastian Hesselbarth <sebastian.hesselbarth@gmail.com>
* Andrew Lunn <andrew@lunn.ch>
* Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/clk-provider.h>
#include <linux/io.h>
#include <linux/of.h>
#include "common.h"
/*
* SARL[14:10] : Ratios between CPU, NBCLK, HCLK and DCLK.
*
* SARL[15] : TCLK frequency
* 0 = 250 MHz
* 1 = 200 MHz
*
* SARH[0] : Reference clock frequency
* 0 = 25 Mhz
* 1 = 40 Mhz
*/
#define SARL 0
#define SARL_A390_TCLK_FREQ_OPT 15
#define SARL_A390_TCLK_FREQ_OPT_MASK 0x1
#define SARL_A390_CPU_DDR_L2_FREQ_OPT 10
#define SARL_A390_CPU_DDR_L2_FREQ_OPT_MASK 0x1F
#define SARH 4
#define SARH_A390_REFCLK_FREQ BIT(0)
static const u32 armada_39x_tclk_frequencies[] __initconst = {
250000000,
200000000,
};
static u32 __init armada_39x_get_tclk_freq(void __iomem *sar)
{
u8 tclk_freq_select;
tclk_freq_select = ((readl(sar + SARL) >> SARL_A390_TCLK_FREQ_OPT) &
SARL_A390_TCLK_FREQ_OPT_MASK);
return armada_39x_tclk_frequencies[tclk_freq_select];
}
static const u32 armada_39x_cpu_frequencies[] __initconst = {
[0x0] = 666 * 1000 * 1000,
[0x2] = 800 * 1000 * 1000,
[0x3] = 800 * 1000 * 1000,
[0x4] = 1066 * 1000 * 1000,
[0x5] = 1066 * 1000 * 1000,
[0x6] = 1200 * 1000 * 1000,
[0x8] = 1332 * 1000 * 1000,
[0xB] = 1600 * 1000 * 1000,
[0xC] = 1600 * 1000 * 1000,
[0x12] = 1800 * 1000 * 1000,
[0x1E] = 1800 * 1000 * 1000,
};
static u32 __init armada_39x_get_cpu_freq(void __iomem *sar)
{
u8 cpu_freq_select;
cpu_freq_select = ((readl(sar + SARL) >> SARL_A390_CPU_DDR_L2_FREQ_OPT) &
SARL_A390_CPU_DDR_L2_FREQ_OPT_MASK);
if (cpu_freq_select >= ARRAY_SIZE(armada_39x_cpu_frequencies)) {
pr_err("Selected CPU frequency (%d) unsupported\n",
cpu_freq_select);
return 0;
}
return armada_39x_cpu_frequencies[cpu_freq_select];
}
enum { A390_CPU_TO_NBCLK, A390_CPU_TO_HCLK, A390_CPU_TO_DCLK };
static const struct coreclk_ratio armada_39x_coreclk_ratios[] __initconst = {
{ .id = A390_CPU_TO_NBCLK, .name = "nbclk" },
{ .id = A390_CPU_TO_HCLK, .name = "hclk" },
{ .id = A390_CPU_TO_DCLK, .name = "dclk" },
};
static void __init armada_39x_get_clk_ratio(
void __iomem *sar, int id, int *mult, int *div)
{
switch (id) {
case A390_CPU_TO_NBCLK:
*mult = 1;
*div = 2;
break;
case A390_CPU_TO_HCLK:
*mult = 1;
*div = 4;
break;
case A390_CPU_TO_DCLK:
*mult = 1;
*div = 2;
break;
}
}
static u32 __init armada_39x_refclk_ratio(void __iomem *sar)
{
if (readl(sar + SARH) & SARH_A390_REFCLK_FREQ)
return 40 * 1000 * 1000;
else
return 25 * 1000 * 1000;
}
static const struct coreclk_soc_desc armada_39x_coreclks = {
.get_tclk_freq = armada_39x_get_tclk_freq,
.get_cpu_freq = armada_39x_get_cpu_freq,
.get_clk_ratio = armada_39x_get_clk_ratio,
.get_refclk_freq = armada_39x_refclk_ratio,
.ratios = armada_39x_coreclk_ratios,
.num_ratios = ARRAY_SIZE(armada_39x_coreclk_ratios),
};
static void __init armada_39x_coreclk_init(struct device_node *np)
{
mvebu_coreclk_setup(np, &armada_39x_coreclks);
}
CLK_OF_DECLARE(armada_39x_core_clk, "marvell,armada-390-core-clock",
armada_39x_coreclk_init);
/*
* Clock Gating Control
*/
static const struct clk_gating_soc_desc armada_39x_gating_desc[] __initconst = {
{ "pex1", NULL, 5 },
{ "pex2", NULL, 6 },
{ "pex3", NULL, 7 },
{ "pex0", NULL, 8 },
{ "usb3h0", NULL, 9 },
{ "sdio", NULL, 17 },
{ "xor0", NULL, 22 },
{ "xor1", NULL, 28 },
{ }
};
static void __init armada_39x_clk_gating_init(struct device_node *np)
{
mvebu_clk_gating_setup(np, armada_39x_gating_desc);
}
CLK_OF_DECLARE(armada_39x_clk_gating, "marvell,armada-390-gating-clock",
armada_39x_clk_gating_init);
| gpl-2.0 |
SolidRun/linux-imx6-3.14 | arch/sparc/kernel/signal32.c | 1191 | 23167 | /* arch/sparc64/kernel/signal32.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1996 Miguel de Icaza (miguel@nuclecu.unam.mx)
* Copyright (C) 1997 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1997,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/binfmts.h>
#include <linux/compat.h>
#include <linux/bitops.h>
#include <linux/tracehook.h>
#include <asm/uaccess.h>
#include <asm/ptrace.h>
#include <asm/pgtable.h>
#include <asm/psrcompat.h>
#include <asm/fpumacro.h>
#include <asm/visasm.h>
#include <asm/compat_signal.h>
#include <asm/switch_to.h>
#include "sigutil.h"
/* This magic should be in g_upper[0] for all upper parts
* to be valid.
*/
#define SIGINFO_EXTRA_V8PLUS_MAGIC 0x130e269
typedef struct {
unsigned int g_upper[8];
unsigned int o_upper[8];
unsigned int asi;
} siginfo_extra_v8plus_t;
struct signal_frame32 {
struct sparc_stackf32 ss;
__siginfo32_t info;
/* __siginfo_fpu_t * */ u32 fpu_save;
unsigned int insns[2];
unsigned int extramask[_COMPAT_NSIG_WORDS - 1];
unsigned int extra_size; /* Should be sizeof(siginfo_extra_v8plus_t) */
/* Only valid if (info.si_regs.psr & (PSR_VERS|PSR_IMPL)) == PSR_V8PLUS */
siginfo_extra_v8plus_t v8plus;
/* __siginfo_rwin_t * */u32 rwin_save;
} __attribute__((aligned(8)));
struct rt_signal_frame32 {
struct sparc_stackf32 ss;
compat_siginfo_t info;
struct pt_regs32 regs;
compat_sigset_t mask;
/* __siginfo_fpu_t * */ u32 fpu_save;
unsigned int insns[2];
compat_stack_t stack;
unsigned int extra_size; /* Should be sizeof(siginfo_extra_v8plus_t) */
/* Only valid if (regs.psr & (PSR_VERS|PSR_IMPL)) == PSR_V8PLUS */
siginfo_extra_v8plus_t v8plus;
/* __siginfo_rwin_t * */u32 rwin_save;
} __attribute__((aligned(8)));
int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from)
{
int err;
if (!access_ok(VERIFY_WRITE, to, sizeof(compat_siginfo_t)))
return -EFAULT;
/* If you change siginfo_t structure, please be sure
this code is fixed accordingly.
It should never copy any pad contained in the structure
to avoid security leaks, but must copy the generic
3 ints plus the relevant union member.
This routine must convert siginfo from 64bit to 32bit as well
at the same time. */
err = __put_user(from->si_signo, &to->si_signo);
err |= __put_user(from->si_errno, &to->si_errno);
err |= __put_user((short)from->si_code, &to->si_code);
if (from->si_code < 0)
err |= __copy_to_user(&to->_sifields._pad, &from->_sifields._pad, SI_PAD_SIZE);
else {
switch (from->si_code >> 16) {
case __SI_TIMER >> 16:
err |= __put_user(from->si_tid, &to->si_tid);
err |= __put_user(from->si_overrun, &to->si_overrun);
err |= __put_user(from->si_int, &to->si_int);
break;
case __SI_CHLD >> 16:
err |= __put_user(from->si_utime, &to->si_utime);
err |= __put_user(from->si_stime, &to->si_stime);
err |= __put_user(from->si_status, &to->si_status);
default:
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
break;
case __SI_FAULT >> 16:
err |= __put_user(from->si_trapno, &to->si_trapno);
err |= __put_user((unsigned long)from->si_addr, &to->si_addr);
break;
case __SI_POLL >> 16:
err |= __put_user(from->si_band, &to->si_band);
err |= __put_user(from->si_fd, &to->si_fd);
break;
case __SI_RT >> 16: /* This is not generated by the kernel as of now. */
case __SI_MESGQ >> 16:
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
err |= __put_user(from->si_int, &to->si_int);
break;
}
}
return err;
}
/* CAUTION: This is just a very minimalist implementation for the
* sake of compat_sys_rt_sigqueueinfo()
*/
int copy_siginfo_from_user32(siginfo_t *to, compat_siginfo_t __user *from)
{
if (!access_ok(VERIFY_WRITE, from, sizeof(compat_siginfo_t)))
return -EFAULT;
if (copy_from_user(to, from, 3*sizeof(int)) ||
copy_from_user(to->_sifields._pad, from->_sifields._pad,
SI_PAD_SIZE))
return -EFAULT;
return 0;
}
void do_sigreturn32(struct pt_regs *regs)
{
struct signal_frame32 __user *sf;
compat_uptr_t fpu_save;
compat_uptr_t rwin_save;
unsigned int psr;
unsigned pc, npc;
sigset_t set;
unsigned seta[_COMPAT_NSIG_WORDS];
int err, i;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
synchronize_user_stack();
regs->u_regs[UREG_FP] &= 0x00000000ffffffffUL;
sf = (struct signal_frame32 __user *) regs->u_regs[UREG_FP];
/* 1. Make sure we are not getting garbage from the user */
if (!access_ok(VERIFY_READ, sf, sizeof(*sf)) ||
(((unsigned long) sf) & 3))
goto segv;
if (get_user(pc, &sf->info.si_regs.pc) ||
__get_user(npc, &sf->info.si_regs.npc))
goto segv;
if ((pc | npc) & 3)
goto segv;
if (test_thread_flag(TIF_32BIT)) {
pc &= 0xffffffff;
npc &= 0xffffffff;
}
regs->tpc = pc;
regs->tnpc = npc;
/* 2. Restore the state */
err = __get_user(regs->y, &sf->info.si_regs.y);
err |= __get_user(psr, &sf->info.si_regs.psr);
for (i = UREG_G1; i <= UREG_I7; i++)
err |= __get_user(regs->u_regs[i], &sf->info.si_regs.u_regs[i]);
if ((psr & (PSR_VERS|PSR_IMPL)) == PSR_V8PLUS) {
err |= __get_user(i, &sf->v8plus.g_upper[0]);
if (i == SIGINFO_EXTRA_V8PLUS_MAGIC) {
unsigned long asi;
for (i = UREG_G1; i <= UREG_I7; i++)
err |= __get_user(((u32 *)regs->u_regs)[2*i], &sf->v8plus.g_upper[i]);
err |= __get_user(asi, &sf->v8plus.asi);
regs->tstate &= ~TSTATE_ASI;
regs->tstate |= ((asi & 0xffUL) << 24UL);
}
}
/* User can only change condition codes in %tstate. */
regs->tstate &= ~(TSTATE_ICC|TSTATE_XCC);
regs->tstate |= psr_to_tstate_icc(psr);
/* Prevent syscall restart. */
pt_regs_clear_syscall(regs);
err |= __get_user(fpu_save, &sf->fpu_save);
if (!err && fpu_save)
err |= restore_fpu_state(regs, compat_ptr(fpu_save));
err |= __get_user(rwin_save, &sf->rwin_save);
if (!err && rwin_save) {
if (restore_rwin_state(compat_ptr(rwin_save)))
goto segv;
}
err |= __get_user(seta[0], &sf->info.si_mask);
err |= copy_from_user(seta+1, &sf->extramask,
(_COMPAT_NSIG_WORDS - 1) * sizeof(unsigned int));
if (err)
goto segv;
switch (_NSIG_WORDS) {
case 4: set.sig[3] = seta[6] + (((long)seta[7]) << 32);
case 3: set.sig[2] = seta[4] + (((long)seta[5]) << 32);
case 2: set.sig[1] = seta[2] + (((long)seta[3]) << 32);
case 1: set.sig[0] = seta[0] + (((long)seta[1]) << 32);
}
set_current_blocked(&set);
return;
segv:
force_sig(SIGSEGV, current);
}
asmlinkage void do_rt_sigreturn32(struct pt_regs *regs)
{
struct rt_signal_frame32 __user *sf;
unsigned int psr, pc, npc;
compat_uptr_t fpu_save;
compat_uptr_t rwin_save;
sigset_t set;
compat_sigset_t seta;
int err, i;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
synchronize_user_stack();
regs->u_regs[UREG_FP] &= 0x00000000ffffffffUL;
sf = (struct rt_signal_frame32 __user *) regs->u_regs[UREG_FP];
/* 1. Make sure we are not getting garbage from the user */
if (!access_ok(VERIFY_READ, sf, sizeof(*sf)) ||
(((unsigned long) sf) & 3))
goto segv;
if (get_user(pc, &sf->regs.pc) ||
__get_user(npc, &sf->regs.npc))
goto segv;
if ((pc | npc) & 3)
goto segv;
if (test_thread_flag(TIF_32BIT)) {
pc &= 0xffffffff;
npc &= 0xffffffff;
}
regs->tpc = pc;
regs->tnpc = npc;
/* 2. Restore the state */
err = __get_user(regs->y, &sf->regs.y);
err |= __get_user(psr, &sf->regs.psr);
for (i = UREG_G1; i <= UREG_I7; i++)
err |= __get_user(regs->u_regs[i], &sf->regs.u_regs[i]);
if ((psr & (PSR_VERS|PSR_IMPL)) == PSR_V8PLUS) {
err |= __get_user(i, &sf->v8plus.g_upper[0]);
if (i == SIGINFO_EXTRA_V8PLUS_MAGIC) {
unsigned long asi;
for (i = UREG_G1; i <= UREG_I7; i++)
err |= __get_user(((u32 *)regs->u_regs)[2*i], &sf->v8plus.g_upper[i]);
err |= __get_user(asi, &sf->v8plus.asi);
regs->tstate &= ~TSTATE_ASI;
regs->tstate |= ((asi & 0xffUL) << 24UL);
}
}
/* User can only change condition codes in %tstate. */
regs->tstate &= ~(TSTATE_ICC|TSTATE_XCC);
regs->tstate |= psr_to_tstate_icc(psr);
/* Prevent syscall restart. */
pt_regs_clear_syscall(regs);
err |= __get_user(fpu_save, &sf->fpu_save);
if (!err && fpu_save)
err |= restore_fpu_state(regs, compat_ptr(fpu_save));
err |= copy_from_user(&seta, &sf->mask, sizeof(compat_sigset_t));
err |= compat_restore_altstack(&sf->stack);
if (err)
goto segv;
err |= __get_user(rwin_save, &sf->rwin_save);
if (!err && rwin_save) {
if (restore_rwin_state(compat_ptr(rwin_save)))
goto segv;
}
switch (_NSIG_WORDS) {
case 4: set.sig[3] = seta.sig[6] + (((long)seta.sig[7]) << 32);
case 3: set.sig[2] = seta.sig[4] + (((long)seta.sig[5]) << 32);
case 2: set.sig[1] = seta.sig[2] + (((long)seta.sig[3]) << 32);
case 1: set.sig[0] = seta.sig[0] + (((long)seta.sig[1]) << 32);
}
set_current_blocked(&set);
return;
segv:
force_sig(SIGSEGV, current);
}
/* Checks if the fp is valid */
static int invalid_frame_pointer(void __user *fp, int fplen)
{
if ((((unsigned long) fp) & 7) || ((unsigned long)fp) > 0x100000000ULL - fplen)
return 1;
return 0;
}
static void __user *get_sigframe(struct ksignal *ksig, struct pt_regs *regs, unsigned long framesize)
{
unsigned long sp;
regs->u_regs[UREG_FP] &= 0x00000000ffffffffUL;
sp = regs->u_regs[UREG_FP];
/*
* If we are on the alternate signal stack and would overflow it, don't.
* Return an always-bogus address instead so we will die with SIGSEGV.
*/
if (on_sig_stack(sp) && !likely(on_sig_stack(sp - framesize)))
return (void __user *) -1L;
/* This is the X/Open sanctioned signal stack switching. */
sp = sigsp(sp, ksig) - framesize;
/* Always align the stack frame. This handles two cases. First,
* sigaltstack need not be mindful of platform specific stack
* alignment. Second, if we took this signal because the stack
* is not aligned properly, we'd like to take the signal cleanly
* and report that.
*/
sp &= ~15UL;
return (void __user *) sp;
}
/* The I-cache flush instruction only works in the primary ASI, which
* right now is the nucleus, aka. kernel space.
*
* Therefore we have to kick the instructions out using the kernel
* side linear mapping of the physical address backing the user
* instructions.
*/
static void flush_signal_insns(unsigned long address)
{
unsigned long pstate, paddr;
pte_t *ptep, pte;
pgd_t *pgdp;
pud_t *pudp;
pmd_t *pmdp;
/* Commit all stores of the instructions we are about to flush. */
wmb();
/* Disable cross-call reception. In this way even a very wide
* munmap() on another cpu can't tear down the page table
* hierarchy from underneath us, since that can't complete
* until the IPI tlb flush returns.
*/
__asm__ __volatile__("rdpr %%pstate, %0" : "=r" (pstate));
__asm__ __volatile__("wrpr %0, %1, %%pstate"
: : "r" (pstate), "i" (PSTATE_IE));
pgdp = pgd_offset(current->mm, address);
if (pgd_none(*pgdp))
goto out_irqs_on;
pudp = pud_offset(pgdp, address);
if (pud_none(*pudp))
goto out_irqs_on;
pmdp = pmd_offset(pudp, address);
if (pmd_none(*pmdp))
goto out_irqs_on;
ptep = pte_offset_map(pmdp, address);
pte = *ptep;
if (!pte_present(pte))
goto out_unmap;
paddr = (unsigned long) page_address(pte_page(pte));
__asm__ __volatile__("flush %0 + %1"
: /* no outputs */
: "r" (paddr),
"r" (address & (PAGE_SIZE - 1))
: "memory");
out_unmap:
pte_unmap(ptep);
out_irqs_on:
__asm__ __volatile__("wrpr %0, 0x0, %%pstate" : : "r" (pstate));
}
static int setup_frame32(struct ksignal *ksig, struct pt_regs *regs,
sigset_t *oldset)
{
struct signal_frame32 __user *sf;
int i, err, wsaved;
void __user *tail;
int sigframe_size;
u32 psr;
unsigned int seta[_COMPAT_NSIG_WORDS];
/* 1. Make sure everything is clean */
synchronize_user_stack();
save_and_clear_fpu();
wsaved = get_thread_wsaved();
sigframe_size = sizeof(*sf);
if (current_thread_info()->fpsaved[0] & FPRS_FEF)
sigframe_size += sizeof(__siginfo_fpu_t);
if (wsaved)
sigframe_size += sizeof(__siginfo_rwin_t);
sf = (struct signal_frame32 __user *)
get_sigframe(ksig, regs, sigframe_size);
if (invalid_frame_pointer(sf, sigframe_size)) {
do_exit(SIGILL);
return -EINVAL;
}
tail = (sf + 1);
/* 2. Save the current process state */
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
err = put_user(regs->tpc, &sf->info.si_regs.pc);
err |= __put_user(regs->tnpc, &sf->info.si_regs.npc);
err |= __put_user(regs->y, &sf->info.si_regs.y);
psr = tstate_to_psr(regs->tstate);
if (current_thread_info()->fpsaved[0] & FPRS_FEF)
psr |= PSR_EF;
err |= __put_user(psr, &sf->info.si_regs.psr);
for (i = 0; i < 16; i++)
err |= __put_user(regs->u_regs[i], &sf->info.si_regs.u_regs[i]);
err |= __put_user(sizeof(siginfo_extra_v8plus_t), &sf->extra_size);
err |= __put_user(SIGINFO_EXTRA_V8PLUS_MAGIC, &sf->v8plus.g_upper[0]);
for (i = 1; i < 16; i++)
err |= __put_user(((u32 *)regs->u_regs)[2*i],
&sf->v8plus.g_upper[i]);
err |= __put_user((regs->tstate & TSTATE_ASI) >> 24UL,
&sf->v8plus.asi);
if (psr & PSR_EF) {
__siginfo_fpu_t __user *fp = tail;
tail += sizeof(*fp);
err |= save_fpu_state(regs, fp);
err |= __put_user((u64)fp, &sf->fpu_save);
} else {
err |= __put_user(0, &sf->fpu_save);
}
if (wsaved) {
__siginfo_rwin_t __user *rwp = tail;
tail += sizeof(*rwp);
err |= save_rwin_state(wsaved, rwp);
err |= __put_user((u64)rwp, &sf->rwin_save);
set_thread_wsaved(0);
} else {
err |= __put_user(0, &sf->rwin_save);
}
switch (_NSIG_WORDS) {
case 4: seta[7] = (oldset->sig[3] >> 32);
seta[6] = oldset->sig[3];
case 3: seta[5] = (oldset->sig[2] >> 32);
seta[4] = oldset->sig[2];
case 2: seta[3] = (oldset->sig[1] >> 32);
seta[2] = oldset->sig[1];
case 1: seta[1] = (oldset->sig[0] >> 32);
seta[0] = oldset->sig[0];
}
err |= __put_user(seta[0], &sf->info.si_mask);
err |= __copy_to_user(sf->extramask, seta + 1,
(_COMPAT_NSIG_WORDS - 1) * sizeof(unsigned int));
if (!wsaved) {
err |= copy_in_user((u32 __user *)sf,
(u32 __user *)(regs->u_regs[UREG_FP]),
sizeof(struct reg_window32));
} else {
struct reg_window *rp;
rp = ¤t_thread_info()->reg_window[wsaved - 1];
for (i = 0; i < 8; i++)
err |= __put_user(rp->locals[i], &sf->ss.locals[i]);
for (i = 0; i < 6; i++)
err |= __put_user(rp->ins[i], &sf->ss.ins[i]);
err |= __put_user(rp->ins[6], &sf->ss.fp);
err |= __put_user(rp->ins[7], &sf->ss.callers_pc);
}
if (err)
return err;
/* 3. signal handler back-trampoline and parameters */
regs->u_regs[UREG_FP] = (unsigned long) sf;
regs->u_regs[UREG_I0] = ksig->sig;
regs->u_regs[UREG_I1] = (unsigned long) &sf->info;
regs->u_regs[UREG_I2] = (unsigned long) &sf->info;
/* 4. signal handler */
regs->tpc = (unsigned long) ksig->ka.sa.sa_handler;
regs->tnpc = (regs->tpc + 4);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
/* 5. return to kernel instructions */
if (ksig->ka.ka_restorer) {
regs->u_regs[UREG_I7] = (unsigned long)ksig->ka.ka_restorer;
} else {
unsigned long address = ((unsigned long)&(sf->insns[0]));
regs->u_regs[UREG_I7] = (unsigned long) (&(sf->insns[0]) - 2);
err = __put_user(0x821020d8, &sf->insns[0]); /*mov __NR_sigreturn, %g1*/
err |= __put_user(0x91d02010, &sf->insns[1]); /*t 0x10*/
if (err)
return err;
flush_signal_insns(address);
}
return 0;
}
static int setup_rt_frame32(struct ksignal *ksig, struct pt_regs *regs,
sigset_t *oldset)
{
struct rt_signal_frame32 __user *sf;
int i, err, wsaved;
void __user *tail;
int sigframe_size;
u32 psr;
compat_sigset_t seta;
/* 1. Make sure everything is clean */
synchronize_user_stack();
save_and_clear_fpu();
wsaved = get_thread_wsaved();
sigframe_size = sizeof(*sf);
if (current_thread_info()->fpsaved[0] & FPRS_FEF)
sigframe_size += sizeof(__siginfo_fpu_t);
if (wsaved)
sigframe_size += sizeof(__siginfo_rwin_t);
sf = (struct rt_signal_frame32 __user *)
get_sigframe(ksig, regs, sigframe_size);
if (invalid_frame_pointer(sf, sigframe_size)) {
do_exit(SIGILL);
return -EINVAL;
}
tail = (sf + 1);
/* 2. Save the current process state */
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
err = put_user(regs->tpc, &sf->regs.pc);
err |= __put_user(regs->tnpc, &sf->regs.npc);
err |= __put_user(regs->y, &sf->regs.y);
psr = tstate_to_psr(regs->tstate);
if (current_thread_info()->fpsaved[0] & FPRS_FEF)
psr |= PSR_EF;
err |= __put_user(psr, &sf->regs.psr);
for (i = 0; i < 16; i++)
err |= __put_user(regs->u_regs[i], &sf->regs.u_regs[i]);
err |= __put_user(sizeof(siginfo_extra_v8plus_t), &sf->extra_size);
err |= __put_user(SIGINFO_EXTRA_V8PLUS_MAGIC, &sf->v8plus.g_upper[0]);
for (i = 1; i < 16; i++)
err |= __put_user(((u32 *)regs->u_regs)[2*i],
&sf->v8plus.g_upper[i]);
err |= __put_user((regs->tstate & TSTATE_ASI) >> 24UL,
&sf->v8plus.asi);
if (psr & PSR_EF) {
__siginfo_fpu_t __user *fp = tail;
tail += sizeof(*fp);
err |= save_fpu_state(regs, fp);
err |= __put_user((u64)fp, &sf->fpu_save);
} else {
err |= __put_user(0, &sf->fpu_save);
}
if (wsaved) {
__siginfo_rwin_t __user *rwp = tail;
tail += sizeof(*rwp);
err |= save_rwin_state(wsaved, rwp);
err |= __put_user((u64)rwp, &sf->rwin_save);
set_thread_wsaved(0);
} else {
err |= __put_user(0, &sf->rwin_save);
}
/* Update the siginfo structure. */
err |= copy_siginfo_to_user32(&sf->info, &ksig->info);
/* Setup sigaltstack */
err |= __compat_save_altstack(&sf->stack, regs->u_regs[UREG_FP]);
switch (_NSIG_WORDS) {
case 4: seta.sig[7] = (oldset->sig[3] >> 32);
seta.sig[6] = oldset->sig[3];
case 3: seta.sig[5] = (oldset->sig[2] >> 32);
seta.sig[4] = oldset->sig[2];
case 2: seta.sig[3] = (oldset->sig[1] >> 32);
seta.sig[2] = oldset->sig[1];
case 1: seta.sig[1] = (oldset->sig[0] >> 32);
seta.sig[0] = oldset->sig[0];
}
err |= __copy_to_user(&sf->mask, &seta, sizeof(compat_sigset_t));
if (!wsaved) {
err |= copy_in_user((u32 __user *)sf,
(u32 __user *)(regs->u_regs[UREG_FP]),
sizeof(struct reg_window32));
} else {
struct reg_window *rp;
rp = ¤t_thread_info()->reg_window[wsaved - 1];
for (i = 0; i < 8; i++)
err |= __put_user(rp->locals[i], &sf->ss.locals[i]);
for (i = 0; i < 6; i++)
err |= __put_user(rp->ins[i], &sf->ss.ins[i]);
err |= __put_user(rp->ins[6], &sf->ss.fp);
err |= __put_user(rp->ins[7], &sf->ss.callers_pc);
}
if (err)
return err;
/* 3. signal handler back-trampoline and parameters */
regs->u_regs[UREG_FP] = (unsigned long) sf;
regs->u_regs[UREG_I0] = ksig->sig;
regs->u_regs[UREG_I1] = (unsigned long) &sf->info;
regs->u_regs[UREG_I2] = (unsigned long) &sf->regs;
/* 4. signal handler */
regs->tpc = (unsigned long) ksig->ka.sa.sa_handler;
regs->tnpc = (regs->tpc + 4);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
/* 5. return to kernel instructions */
if (ksig->ka.ka_restorer)
regs->u_regs[UREG_I7] = (unsigned long)ksig->ka.ka_restorer;
else {
unsigned long address = ((unsigned long)&(sf->insns[0]));
regs->u_regs[UREG_I7] = (unsigned long) (&(sf->insns[0]) - 2);
/* mov __NR_rt_sigreturn, %g1 */
err |= __put_user(0x82102065, &sf->insns[0]);
/* t 0x10 */
err |= __put_user(0x91d02010, &sf->insns[1]);
if (err)
return err;
flush_signal_insns(address);
}
return 0;
}
static inline void handle_signal32(struct ksignal *ksig,
struct pt_regs *regs)
{
sigset_t *oldset = sigmask_to_save();
int err;
if (ksig->ka.sa.sa_flags & SA_SIGINFO)
err = setup_rt_frame32(ksig, regs, oldset);
else
err = setup_frame32(ksig, regs, oldset);
signal_setup_done(err, ksig, 0);
}
static inline void syscall_restart32(unsigned long orig_i0, struct pt_regs *regs,
struct sigaction *sa)
{
switch (regs->u_regs[UREG_I0]) {
case ERESTART_RESTARTBLOCK:
case ERESTARTNOHAND:
no_system_call_restart:
regs->u_regs[UREG_I0] = EINTR;
regs->tstate |= TSTATE_ICARRY;
break;
case ERESTARTSYS:
if (!(sa->sa_flags & SA_RESTART))
goto no_system_call_restart;
/* fallthrough */
case ERESTARTNOINTR:
regs->u_regs[UREG_I0] = orig_i0;
regs->tpc -= 4;
regs->tnpc -= 4;
}
}
/* Note that 'init' is a special process: it doesn't get signals it doesn't
* want to handle. Thus you cannot kill init even with a SIGKILL even by
* mistake.
*/
void do_signal32(struct pt_regs * regs)
{
struct ksignal ksig;
unsigned long orig_i0 = 0;
int restart_syscall = 0;
bool has_handler = get_signal(&ksig);
if (pt_regs_is_syscall(regs) &&
(regs->tstate & (TSTATE_XCARRY | TSTATE_ICARRY))) {
restart_syscall = 1;
orig_i0 = regs->u_regs[UREG_G6];
}
if (has_handler) {
if (restart_syscall)
syscall_restart32(orig_i0, regs, &ksig.ka.sa);
handle_signal32(&ksig, regs);
} else {
if (restart_syscall) {
switch (regs->u_regs[UREG_I0]) {
case ERESTARTNOHAND:
case ERESTARTSYS:
case ERESTARTNOINTR:
/* replay the system call when we are done */
regs->u_regs[UREG_I0] = orig_i0;
regs->tpc -= 4;
regs->tnpc -= 4;
pt_regs_clear_syscall(regs);
case ERESTART_RESTARTBLOCK:
regs->u_regs[UREG_G1] = __NR_restart_syscall;
regs->tpc -= 4;
regs->tnpc -= 4;
pt_regs_clear_syscall(regs);
}
}
restore_saved_sigmask();
}
}
struct sigstack32 {
u32 the_stack;
int cur_status;
};
asmlinkage int do_sys32_sigstack(u32 u_ssptr, u32 u_ossptr, unsigned long sp)
{
struct sigstack32 __user *ssptr =
(struct sigstack32 __user *)((unsigned long)(u_ssptr));
struct sigstack32 __user *ossptr =
(struct sigstack32 __user *)((unsigned long)(u_ossptr));
int ret = -EFAULT;
/* First see if old state is wanted. */
if (ossptr) {
if (put_user(current->sas_ss_sp + current->sas_ss_size,
&ossptr->the_stack) ||
__put_user(on_sig_stack(sp), &ossptr->cur_status))
goto out;
}
/* Now see if we want to update the new state. */
if (ssptr) {
u32 ss_sp;
if (get_user(ss_sp, &ssptr->the_stack))
goto out;
/* If the current stack was set with sigaltstack, don't
* swap stacks while we are on it.
*/
ret = -EPERM;
if (current->sas_ss_sp && on_sig_stack(sp))
goto out;
/* Since we don't know the extent of the stack, and we don't
* track onstack-ness, but rather calculate it, we must
* presume a size. Ho hum this interface is lossy.
*/
current->sas_ss_sp = (unsigned long)ss_sp - SIGSTKSZ;
current->sas_ss_size = SIGSTKSZ;
}
ret = 0;
out:
return ret;
}
| gpl-2.0 |
cphelps76/kernel_lge_mako | net/ipv6/ip6_input.c | 1447 | 8812 | /*
* IPv6 input
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
* Ian P. Morris <I.P.Morris@soton.ac.uk>
*
* Based in linux/net/ipv4/ip_input.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/* Changes
*
* Mitsuru KANDA @USAGI and
* YOSHIFUJI Hideaki @USAGI: Remove ipv6_parse_exthdrs().
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/icmpv6.h>
#include <linux/mroute6.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/transp_v6.h>
#include <net/rawv6.h>
#include <net/ndisc.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/xfrm.h>
inline int ip6_rcv_finish( struct sk_buff *skb)
{
if (skb_dst(skb) == NULL)
ip6_route_input(skb);
return dst_input(skb);
}
int ipv6_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
const struct ipv6hdr *hdr;
u32 pkt_len;
struct inet6_dev *idev;
struct net *net = dev_net(skb->dev);
if (skb->pkt_type == PACKET_OTHERHOST) {
kfree_skb(skb);
return NET_RX_DROP;
}
rcu_read_lock();
idev = __in6_dev_get(skb->dev);
IP6_UPD_PO_STATS_BH(net, idev, IPSTATS_MIB_IN, skb->len);
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL ||
!idev || unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDISCARDS);
goto drop;
}
memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
/*
* Store incoming device index. When the packet will
* be queued, we cannot refer to skb->dev anymore.
*
* BTW, when we send a packet for our own local address on a
* non-loopback interface (e.g. ethX), it is being delivered
* via the loopback interface (lo) here; skb->dev = loopback_dev.
* It, however, should be considered as if it is being
* arrived via the sending interface (ethX), because of the
* nature of scoping architecture. --yoshfuji
*/
IP6CB(skb)->iif = skb_dst(skb) ? ip6_dst_idev(skb_dst(skb))->dev->ifindex : dev->ifindex;
if (unlikely(!pskb_may_pull(skb, sizeof(*hdr))))
goto err;
hdr = ipv6_hdr(skb);
if (hdr->version != 6)
goto err;
/*
* RFC4291 2.5.3
* A packet received on an interface with a destination address
* of loopback must be dropped.
*/
if (!(dev->flags & IFF_LOOPBACK) &&
ipv6_addr_loopback(&hdr->daddr))
goto err;
/* RFC4291 Errata ID: 3480
* Interface-Local scope spans only a single interface on a
* node and is useful only for loopback transmission of
* multicast. Packets with interface-local scope received
* from another node must be discarded.
*/
if (!(skb->pkt_type == PACKET_LOOPBACK ||
dev->flags & IFF_LOOPBACK) &&
ipv6_addr_is_multicast(&hdr->daddr) &&
IPV6_ADDR_MC_SCOPE(&hdr->daddr) == 1)
goto err;
/* RFC4291 2.7
* Nodes must not originate a packet to a multicast address whose scope
* field contains the reserved value 0; if such a packet is received, it
* must be silently dropped.
*/
if (ipv6_addr_is_multicast(&hdr->daddr) &&
IPV6_ADDR_MC_SCOPE(&hdr->daddr) == 0)
goto err;
/*
* RFC4291 2.7
* Multicast addresses must not be used as source addresses in IPv6
* packets or appear in any Routing header.
*/
if (ipv6_addr_is_multicast(&hdr->saddr))
goto err;
skb->transport_header = skb->network_header + sizeof(*hdr);
IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
pkt_len = ntohs(hdr->payload_len);
/* pkt_len may be zero if Jumbo payload option is present */
if (pkt_len || hdr->nexthdr != NEXTHDR_HOP) {
if (pkt_len + sizeof(struct ipv6hdr) > skb->len) {
IP6_INC_STATS_BH(net,
idev, IPSTATS_MIB_INTRUNCATEDPKTS);
goto drop;
}
if (pskb_trim_rcsum(skb, pkt_len + sizeof(struct ipv6hdr))) {
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INHDRERRORS);
goto drop;
}
hdr = ipv6_hdr(skb);
}
if (hdr->nexthdr == NEXTHDR_HOP) {
if (ipv6_parse_hopopts(skb) < 0) {
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INHDRERRORS);
rcu_read_unlock();
return NET_RX_DROP;
}
}
rcu_read_unlock();
/* Must drop socket now because of tproxy. */
skb_orphan(skb);
return NF_HOOK(NFPROTO_IPV6, NF_INET_PRE_ROUTING, skb, dev, NULL,
ip6_rcv_finish);
err:
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INHDRERRORS);
drop:
rcu_read_unlock();
kfree_skb(skb);
return NET_RX_DROP;
}
/*
* Deliver the packet to the host
*/
static int ip6_input_finish(struct sk_buff *skb)
{
const struct inet6_protocol *ipprot;
unsigned int nhoff;
int nexthdr, raw;
u8 hash;
struct inet6_dev *idev;
struct net *net = dev_net(skb_dst(skb)->dev);
/*
* Parse extension headers
*/
rcu_read_lock();
resubmit:
idev = ip6_dst_idev(skb_dst(skb));
if (!pskb_pull(skb, skb_transport_offset(skb)))
goto discard;
nhoff = IP6CB(skb)->nhoff;
nexthdr = skb_network_header(skb)[nhoff];
raw = raw6_local_deliver(skb, nexthdr);
hash = nexthdr & (MAX_INET_PROTOS - 1);
if ((ipprot = rcu_dereference(inet6_protos[hash])) != NULL) {
int ret;
if (ipprot->flags & INET6_PROTO_FINAL) {
const struct ipv6hdr *hdr;
/* Free reference early: we don't need it any more,
and it may hold ip_conntrack module loaded
indefinitely. */
nf_reset(skb);
skb_postpull_rcsum(skb, skb_network_header(skb),
skb_network_header_len(skb));
hdr = ipv6_hdr(skb);
if (ipv6_addr_is_multicast(&hdr->daddr) &&
!ipv6_chk_mcast_addr(skb->dev, &hdr->daddr,
&hdr->saddr) &&
!ipv6_is_mld(skb, nexthdr))
goto discard;
}
if (!(ipprot->flags & INET6_PROTO_NOPOLICY) &&
!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard;
ret = ipprot->handler(skb);
if (ret > 0)
goto resubmit;
else if (ret == 0)
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDELIVERS);
} else {
if (!raw) {
if (xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) {
IP6_INC_STATS_BH(net, idev,
IPSTATS_MIB_INUNKNOWNPROTOS);
icmpv6_send(skb, ICMPV6_PARAMPROB,
ICMPV6_UNK_NEXTHDR, nhoff);
}
} else
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDELIVERS);
kfree_skb(skb);
}
rcu_read_unlock();
return 0;
discard:
IP6_INC_STATS_BH(net, idev, IPSTATS_MIB_INDISCARDS);
rcu_read_unlock();
kfree_skb(skb);
return 0;
}
int ip6_input(struct sk_buff *skb)
{
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_IN, skb, skb->dev, NULL,
ip6_input_finish);
}
int ip6_mc_input(struct sk_buff *skb)
{
const struct ipv6hdr *hdr;
int deliver;
IP6_UPD_PO_STATS_BH(dev_net(skb_dst(skb)->dev),
ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_INMCAST,
skb->len);
hdr = ipv6_hdr(skb);
deliver = ipv6_chk_mcast_addr(skb->dev, &hdr->daddr, NULL);
#ifdef CONFIG_IPV6_MROUTE
/*
* IPv6 multicast router mode is now supported ;)
*/
if (dev_net(skb->dev)->ipv6.devconf_all->mc_forwarding &&
!(ipv6_addr_type(&hdr->daddr) &
(IPV6_ADDR_LOOPBACK|IPV6_ADDR_LINKLOCAL)) &&
likely(!(IP6CB(skb)->flags & IP6SKB_FORWARDED))) {
/*
* Okay, we try to forward - split and duplicate
* packets.
*/
struct sk_buff *skb2;
struct inet6_skb_parm *opt = IP6CB(skb);
/* Check for MLD */
if (unlikely(opt->ra)) {
/* Check if this is a mld message */
u8 *ptr = skb_network_header(skb) + opt->ra;
struct icmp6hdr *icmp6;
u8 nexthdr = hdr->nexthdr;
__be16 frag_off;
int offset;
/* Check if the value of Router Alert
* is for MLD (0x0000).
*/
if ((ptr[2] | ptr[3]) == 0) {
deliver = 0;
if (!ipv6_ext_hdr(nexthdr)) {
/* BUG */
goto out;
}
offset = ipv6_skip_exthdr(skb, sizeof(*hdr),
&nexthdr, &frag_off);
if (offset < 0)
goto out;
if (nexthdr != IPPROTO_ICMPV6)
goto out;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
goto out;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case ICMPV6_MGM_QUERY:
case ICMPV6_MGM_REPORT:
case ICMPV6_MGM_REDUCTION:
case ICMPV6_MLD2_REPORT:
deliver = 1;
break;
}
goto out;
}
/* unknown RA - process it normally */
}
if (deliver)
skb2 = skb_clone(skb, GFP_ATOMIC);
else {
skb2 = skb;
skb = NULL;
}
if (skb2) {
ip6_mr_input(skb2);
}
}
out:
#endif
if (likely(deliver))
ip6_input(skb);
else {
/* discard */
kfree_skb(skb);
}
return 0;
}
| gpl-2.0 |
wujiku/EVO-3D- | arch/arm/mach-at91/board-usb-a9260.c | 1447 | 5382 | /*
* linux/arch/arm/mach-at91/board-usb-a9260.c
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2006 Atmel
* Copyright (C) 2007 Calao-systems
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/clk.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <mach/board.h>
#include <mach/gpio.h>
#include <mach/at91sam9_smc.h>
#include <mach/at91_shdwc.h>
#include "sam9_smc.h"
#include "generic.h"
static void __init ek_map_io(void)
{
/* Initialize processor: 12.000 MHz crystal */
at91sam9260_initialize(12000000);
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* set serial console to ttyS0 (ie, DBGU) */
at91_set_serial_console(0);
}
static void __init ek_init_irq(void)
{
at91sam9260_init_interrupts(NULL);
}
/*
* USB Host port
*/
static struct at91_usbh_data __initdata ek_usbh_data = {
.ports = 2,
};
/*
* USB Device port
*/
static struct at91_udc_data __initdata ek_udc_data = {
.vbus_pin = AT91_PIN_PC5,
.pullup_pin = 0, /* pull-up driven by UDC */
};
/*
* MACB Ethernet device
*/
static struct at91_eth_data __initdata ek_macb_data = {
.phy_irq_pin = AT91_PIN_PA31,
.is_rmii = 1,
};
/*
* NAND flash
*/
static struct mtd_partition __initdata ek_nand_partition[] = {
{
.name = "Uboot & Kernel",
.offset = 0,
.size = SZ_16M,
},
{
.name = "Root FS",
.offset = MTDPART_OFS_NXTBLK,
.size = 120 * SZ_1M,
},
{
.name = "FS",
.offset = MTDPART_OFS_NXTBLK,
.size = 120 * SZ_1M,
}
};
static struct mtd_partition * __init nand_partitions(int size, int *num_partitions)
{
*num_partitions = ARRAY_SIZE(ek_nand_partition);
return ek_nand_partition;
}
static struct atmel_nand_data __initdata ek_nand_data = {
.ale = 21,
.cle = 22,
// .det_pin = ... not connected
.rdy_pin = AT91_PIN_PC13,
.enable_pin = AT91_PIN_PC14,
.partition_info = nand_partitions,
};
static struct sam9_smc_config __initdata ek_nand_smc_config = {
.ncs_read_setup = 0,
.nrd_setup = 1,
.ncs_write_setup = 0,
.nwe_setup = 1,
.ncs_read_pulse = 3,
.nrd_pulse = 3,
.ncs_write_pulse = 3,
.nwe_pulse = 3,
.read_cycle = 5,
.write_cycle = 5,
.mode = AT91_SMC_READMODE | AT91_SMC_WRITEMODE | AT91_SMC_EXNWMODE_DISABLE | AT91_SMC_DBW_8,
.tdf_cycles = 2,
};
static void __init ek_add_device_nand(void)
{
/* configure chip-select 3 (NAND) */
sam9_smc_configure(3, &ek_nand_smc_config);
at91_add_device_nand(&ek_nand_data);
}
/*
* GPIO Buttons
*/
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
static struct gpio_keys_button ek_buttons[] = {
{ /* USER PUSH BUTTON */
.code = KEY_ENTER,
.gpio = AT91_PIN_PB10,
.active_low = 1,
.desc = "user_pb",
.wakeup = 1,
}
};
static struct gpio_keys_platform_data ek_button_data = {
.buttons = ek_buttons,
.nbuttons = ARRAY_SIZE(ek_buttons),
};
static struct platform_device ek_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &ek_button_data,
}
};
static void __init ek_add_device_buttons(void)
{
at91_set_GPIO_periph(AT91_PIN_PB10, 1); /* user push button, pull up enabled */
at91_set_deglitch(AT91_PIN_PB10, 1);
platform_device_register(&ek_button_device);
}
#else
static void __init ek_add_device_buttons(void) {}
#endif
/*
* LEDs
*/
static struct gpio_led ek_leds[] = {
{ /* user_led (green) */
.name = "user_led",
.gpio = AT91_PIN_PB21,
.active_low = 0,
.default_trigger = "heartbeat",
}
};
static void __init ek_board_init(void)
{
/* Serial */
at91_add_device_serial();
/* USB Host */
at91_add_device_usbh(&ek_usbh_data);
/* USB Device */
at91_add_device_udc(&ek_udc_data);
/* NAND */
ek_add_device_nand();
/* I2C */
at91_add_device_i2c(NULL, 0);
/* Ethernet */
at91_add_device_eth(&ek_macb_data);
/* Push Buttons */
ek_add_device_buttons();
/* LEDs */
at91_gpio_leds(ek_leds, ARRAY_SIZE(ek_leds));
/* shutdown controller, wakeup button (5 msec low) */
at91_sys_write(AT91_SHDW_MR, AT91_SHDW_CPTWK0_(10) | AT91_SHDW_WKMODE0_LOW
| AT91_SHDW_RTTWKEN);
}
MACHINE_START(USB_A9260, "CALAO USB_A9260")
/* Maintainer: calao-systems */
.phys_io = AT91_BASE_SYS,
.io_pg_offst = (AT91_VA_BASE_SYS >> 18) & 0xfffc,
.boot_params = AT91_SDRAM_BASE + 0x100,
.timer = &at91sam926x_timer,
.map_io = ek_map_io,
.init_irq = ek_init_irq,
.init_machine = ek_board_init,
MACHINE_END
| gpl-2.0 |
kusl/linux | tools/thermal/tmon/tui.c | 1447 | 16964 | /*
* tui.c ncurses text user interface for TMON program
*
* Copyright (C) 2013 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 or later 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.
*
* Author: Jacob Pan <jacob.jun.pan@linux.intel.com>
*
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ncurses.h>
#include <time.h>
#include <syslog.h>
#include <panel.h>
#include <pthread.h>
#include <signal.h>
#include "tmon.h"
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
#define max(x, y) ({ \
typeof(x) _max1 = (x); \
typeof(y) _max2 = (y); \
(void) (&_max1 == &_max2); \
_max1 > _max2 ? _max1 : _max2; })
static PANEL *data_panel;
static PANEL *dialogue_panel;
static PANEL *top;
static WINDOW *title_bar_window;
static WINDOW *tz_sensor_window;
static WINDOW *cooling_device_window;
static WINDOW *control_window;
static WINDOW *status_bar_window;
static WINDOW *thermal_data_window;
static WINDOW *dialogue_window;
char status_bar_slots[10][40];
static void draw_hbar(WINDOW *win, int y, int start, int len,
unsigned long pattern, bool end);
static int maxx, maxy;
static int maxwidth = 200;
#define TITLE_BAR_HIGHT 1
#define SENSOR_WIN_HIGHT 4 /* one row for tz name, one for trip points */
/* daemon mode flag (set by startup parameter -d) */
static int tui_disabled;
static void close_panel(PANEL *p)
{
if (p) {
del_panel(p);
p = NULL;
}
}
static void close_window(WINDOW *win)
{
if (win) {
delwin(win);
win = NULL;
}
}
void close_windows(void)
{
if (tui_disabled)
return;
/* must delete panels before their attached windows */
if (dialogue_window)
close_panel(dialogue_panel);
if (cooling_device_window)
close_panel(data_panel);
close_window(title_bar_window);
close_window(tz_sensor_window);
close_window(status_bar_window);
close_window(cooling_device_window);
close_window(control_window);
close_window(thermal_data_window);
close_window(dialogue_window);
}
void write_status_bar(int x, char *line)
{
mvwprintw(status_bar_window, 0, x, "%s", line);
wrefresh(status_bar_window);
}
/* wrap at 5 */
#define DIAG_DEV_ROWS 5
/*
* list cooling devices + "set temp" entry; wraps after 5 rows, if they fit
*/
static int diag_dev_rows(void)
{
int entries = ptdata.nr_cooling_dev + 1;
int rows = max(DIAG_DEV_ROWS, (entries + 1) / 2);
return min(rows, entries);
}
void setup_windows(void)
{
int y_begin = 1;
if (tui_disabled)
return;
getmaxyx(stdscr, maxy, maxx);
resizeterm(maxy, maxx);
title_bar_window = subwin(stdscr, TITLE_BAR_HIGHT, maxx, 0, 0);
y_begin += TITLE_BAR_HIGHT;
tz_sensor_window = subwin(stdscr, SENSOR_WIN_HIGHT, maxx, y_begin, 0);
y_begin += SENSOR_WIN_HIGHT;
cooling_device_window = subwin(stdscr, ptdata.nr_cooling_dev + 3, maxx,
y_begin, 0);
y_begin += ptdata.nr_cooling_dev + 3; /* 2 lines for border */
/* two lines to show borders, one line per tz show trip point position
* and value.
* dialogue window is a pop-up, when needed it lays on top of cdev win
*/
dialogue_window = subwin(stdscr, diag_dev_rows() + 5, maxx-50,
DIAG_Y, DIAG_X);
thermal_data_window = subwin(stdscr, ptdata.nr_tz_sensor *
NR_LINES_TZDATA + 3, maxx, y_begin, 0);
y_begin += ptdata.nr_tz_sensor * NR_LINES_TZDATA + 3;
control_window = subwin(stdscr, 4, maxx, y_begin, 0);
scrollok(cooling_device_window, TRUE);
maxwidth = maxx - 18;
status_bar_window = subwin(stdscr, 1, maxx, maxy-1, 0);
strcpy(status_bar_slots[0], " Ctrl-c - Quit ");
strcpy(status_bar_slots[1], " TAB - Tuning ");
wmove(status_bar_window, 1, 30);
/* prepare panels for dialogue, if panel already created then we must
* be doing resizing, so just replace windows with new ones, old ones
* should have been deleted by close_window
*/
data_panel = new_panel(cooling_device_window);
if (!data_panel)
syslog(LOG_DEBUG, "No data panel\n");
else {
if (dialogue_window) {
dialogue_panel = new_panel(dialogue_window);
if (!dialogue_panel)
syslog(LOG_DEBUG, "No dialogue panel\n");
else {
/* Set up the user pointer to the next panel*/
set_panel_userptr(data_panel, dialogue_panel);
set_panel_userptr(dialogue_panel, data_panel);
top = data_panel;
}
} else
syslog(LOG_INFO, "no dialogue win, term too small\n");
}
doupdate();
werase(stdscr);
refresh();
}
void resize_handler(int sig)
{
/* start over when term gets resized, but first we clean up */
close_windows();
endwin();
refresh();
clear();
getmaxyx(stdscr, maxy, maxx); /* get the new screen size */
setup_windows();
/* rate limit */
sleep(1);
syslog(LOG_DEBUG, "SIG %d, term resized to %d x %d\n",
sig, maxy, maxx);
signal(SIGWINCH, resize_handler);
}
const char cdev_title[] = " COOLING DEVICES ";
void show_cooling_device(void)
{
int i, j, x, y = 0;
if (tui_disabled || !cooling_device_window)
return;
werase(cooling_device_window);
wattron(cooling_device_window, A_BOLD);
mvwprintw(cooling_device_window, 1, 1,
"ID Cooling Dev Cur Max Thermal Zone Binding");
wattroff(cooling_device_window, A_BOLD);
for (j = 0; j < ptdata.nr_cooling_dev; j++) {
/* draw cooling device list on the left in the order of
* cooling device instances. skip unused idr.
*/
mvwprintw(cooling_device_window, j + 2, 1,
"%02d %12.12s%6d %6d",
ptdata.cdi[j].instance,
ptdata.cdi[j].type,
ptdata.cdi[j].cur_state,
ptdata.cdi[j].max_state);
}
/* show cdev binding, y is the global cooling device instance */
for (i = 0; i < ptdata.nr_tz_sensor; i++) {
int tz_inst = ptdata.tzi[i].instance;
for (j = 0; j < ptdata.nr_cooling_dev; j++) {
int cdev_inst;
y = j;
x = tz_inst * TZONE_RECORD_SIZE + TZ_LEFT_ALIGN;
draw_hbar(cooling_device_window, y+2, x,
TZONE_RECORD_SIZE-1, ACS_VLINE, false);
/* draw a column of spaces to separate thermal zones */
mvwprintw(cooling_device_window, y+2, x-1, " ");
if (ptdata.tzi[i].cdev_binding) {
cdev_inst = ptdata.cdi[j].instance;
unsigned long trip_binding =
ptdata.tzi[i].trip_binding[cdev_inst];
int k = 0; /* per zone trip point id that
* binded to this cdev, one to
* many possible based on the
* binding bitmask.
*/
syslog(LOG_DEBUG,
"bind tz%d cdev%d tp%lx %d cdev%lx\n",
i, j, trip_binding, y,
ptdata.tzi[i].cdev_binding);
/* draw each trip binding for the cdev */
while (trip_binding >>= 1) {
k++;
if (!(trip_binding & 1))
continue;
/* draw '*' to show binding */
mvwprintw(cooling_device_window,
y + 2,
x + ptdata.tzi[i].nr_trip_pts -
k - 1, "*");
}
}
}
}
/* draw border after data so that border will not be messed up
* even there is not enough space for all the data to be shown
*/
wborder(cooling_device_window, 0, 0, 0, 0, 0, 0, 0, 0);
wattron(cooling_device_window, A_BOLD);
mvwprintw(cooling_device_window, 0, maxx/2 - sizeof(cdev_title),
cdev_title);
wattroff(cooling_device_window, A_BOLD);
wrefresh(cooling_device_window);
}
const char DIAG_TITLE[] = "[ TUNABLES ]";
void show_dialogue(void)
{
int j, x = 0, y = 0;
int rows, cols;
WINDOW *w = dialogue_window;
if (tui_disabled || !w)
return;
getmaxyx(w, rows, cols);
/* Silence compiler 'unused' warnings */
(void)cols;
werase(w);
box(w, 0, 0);
mvwprintw(w, 0, maxx/4, DIAG_TITLE);
/* list all the available tunables */
for (j = 0; j <= ptdata.nr_cooling_dev; j++) {
y = j % diag_dev_rows();
if (y == 0 && j != 0)
x += 20;
if (j == ptdata.nr_cooling_dev)
/* save last choice for target temp */
mvwprintw(w, y+1, x+1, "%C-%.12s", 'A'+j, "Set Temp");
else
mvwprintw(w, y+1, x+1, "%C-%.10s-%2d", 'A'+j,
ptdata.cdi[j].type, ptdata.cdi[j].instance);
}
wattron(w, A_BOLD);
mvwprintw(w, diag_dev_rows()+1, 1, "Enter Choice [A-Z]?");
wattroff(w, A_BOLD);
/* print legend at the bottom line */
mvwprintw(w, rows - 2, 1,
"Legend: A=Active, P=Passive, C=Critical");
wrefresh(dialogue_window);
}
void write_dialogue_win(char *buf, int y, int x)
{
WINDOW *w = dialogue_window;
mvwprintw(w, y, x, "%s", buf);
}
const char control_title[] = " CONTROLS ";
void show_control_w(void)
{
unsigned long state;
get_ctrl_state(&state);
if (tui_disabled || !control_window)
return;
werase(control_window);
mvwprintw(control_window, 1, 1,
"PID gain: kp=%2.2f ki=%2.2f kd=%2.2f Output %2.2f",
p_param.kp, p_param.ki, p_param.kd, p_param.y_k);
mvwprintw(control_window, 2, 1,
"Target Temp: %2.1fC, Zone: %d, Control Device: %.12s",
p_param.t_target, target_thermal_zone, ctrl_cdev);
/* draw border last such that everything is within boundary */
wborder(control_window, 0, 0, 0, 0, 0, 0, 0, 0);
wattron(control_window, A_BOLD);
mvwprintw(control_window, 0, maxx/2 - sizeof(control_title),
control_title);
wattroff(control_window, A_BOLD);
wrefresh(control_window);
}
void initialize_curses(void)
{
if (tui_disabled)
return;
initscr();
start_color();
keypad(stdscr, TRUE); /* enable keyboard mapping */
nonl(); /* tell curses not to do NL->CR/NL on output */
cbreak(); /* take input chars one at a time */
noecho(); /* dont echo input */
curs_set(0); /* turn off cursor */
use_default_colors();
init_pair(PT_COLOR_DEFAULT, COLOR_WHITE, COLOR_BLACK);
init_pair(PT_COLOR_HEADER_BAR, COLOR_BLACK, COLOR_WHITE);
init_pair(PT_COLOR_ERROR, COLOR_BLACK, COLOR_RED);
init_pair(PT_COLOR_RED, COLOR_WHITE, COLOR_RED);
init_pair(PT_COLOR_YELLOW, COLOR_WHITE, COLOR_YELLOW);
init_pair(PT_COLOR_GREEN, COLOR_WHITE, COLOR_GREEN);
init_pair(PT_COLOR_BLUE, COLOR_WHITE, COLOR_BLUE);
init_pair(PT_COLOR_BRIGHT, COLOR_WHITE, COLOR_BLACK);
}
void show_title_bar(void)
{
int i;
int x = 0;
if (tui_disabled || !title_bar_window)
return;
wattrset(title_bar_window, COLOR_PAIR(PT_COLOR_HEADER_BAR));
wbkgd(title_bar_window, COLOR_PAIR(PT_COLOR_HEADER_BAR));
werase(title_bar_window);
mvwprintw(title_bar_window, 0, 0,
" TMON v%s", VERSION);
wrefresh(title_bar_window);
werase(status_bar_window);
for (i = 0; i < 10; i++) {
if (strlen(status_bar_slots[i]) == 0)
continue;
wattron(status_bar_window, A_REVERSE);
mvwprintw(status_bar_window, 0, x, "%s", status_bar_slots[i]);
wattroff(status_bar_window, A_REVERSE);
x += strlen(status_bar_slots[i]) + 1;
}
wrefresh(status_bar_window);
}
static void handle_input_val(int ch)
{
char buf[32];
int val;
char path[256];
WINDOW *w = dialogue_window;
echo();
keypad(w, TRUE);
wgetnstr(w, buf, 31);
val = atoi(buf);
if (ch == ptdata.nr_cooling_dev) {
snprintf(buf, 31, "Invalid Temp %d! %d-%d", val,
MIN_CTRL_TEMP, MAX_CTRL_TEMP);
if (val < MIN_CTRL_TEMP || val > MAX_CTRL_TEMP)
write_status_bar(40, buf);
else {
p_param.t_target = val;
snprintf(buf, 31, "Set New Target Temp %d", val);
write_status_bar(40, buf);
}
} else {
snprintf(path, 256, "%s/%s%d", THERMAL_SYSFS,
CDEV, ptdata.cdi[ch].instance);
sysfs_set_ulong(path, "cur_state", val);
}
noecho();
dialogue_on = 0;
show_data_w();
show_control_w();
top = (PANEL *)panel_userptr(top);
top_panel(top);
}
static void handle_input_choice(int ch)
{
char buf[48];
int base = 0;
int cdev_id = 0;
if ((ch >= 'A' && ch <= 'A' + ptdata.nr_cooling_dev) ||
(ch >= 'a' && ch <= 'a' + ptdata.nr_cooling_dev)) {
base = (ch < 'a') ? 'A' : 'a';
cdev_id = ch - base;
if (ptdata.nr_cooling_dev == cdev_id)
snprintf(buf, sizeof(buf), "New Target Temp:");
else
snprintf(buf, sizeof(buf), "New Value for %.10s-%2d: ",
ptdata.cdi[cdev_id].type,
ptdata.cdi[cdev_id].instance);
write_dialogue_win(buf, diag_dev_rows() + 2, 2);
handle_input_val(cdev_id);
} else {
snprintf(buf, sizeof(buf), "Invalid selection %d", ch);
write_dialogue_win(buf, 8, 2);
}
}
void *handle_tui_events(void *arg)
{
int ch;
keypad(cooling_device_window, TRUE);
while ((ch = wgetch(cooling_device_window)) != EOF) {
if (tmon_exit)
break;
/* when term size is too small, no dialogue panels are set.
* we need to filter out such cases.
*/
if (!data_panel || !dialogue_panel ||
!cooling_device_window ||
!dialogue_window) {
continue;
}
pthread_mutex_lock(&input_lock);
if (dialogue_on) {
handle_input_choice(ch);
/* top panel filter */
if (ch == 'q' || ch == 'Q')
ch = 0;
}
switch (ch) {
case KEY_LEFT:
box(cooling_device_window, 10, 0);
break;
case 9: /* TAB */
top = (PANEL *)panel_userptr(top);
top_panel(top);
if (top == dialogue_panel) {
dialogue_on = 1;
show_dialogue();
} else {
dialogue_on = 0;
/* force refresh */
show_data_w();
show_control_w();
}
break;
case 'q':
case 'Q':
tmon_exit = 1;
break;
}
update_panels();
doupdate();
pthread_mutex_unlock(&input_lock);
}
if (arg)
*(int *)arg = 0; /* make gcc happy */
return NULL;
}
/* draw a horizontal bar in given pattern */
static void draw_hbar(WINDOW *win, int y, int start, int len, unsigned long ptn,
bool end)
{
mvwaddch(win, y, start, ptn);
whline(win, ptn, len);
if (end)
mvwaddch(win, y, MAX_DISP_TEMP+TDATA_LEFT, ']');
}
static char trip_type_to_char(int type)
{
switch (type) {
case THERMAL_TRIP_CRITICAL: return 'C';
case THERMAL_TRIP_HOT: return 'H';
case THERMAL_TRIP_PASSIVE: return 'P';
case THERMAL_TRIP_ACTIVE: return 'A';
default:
return '?';
}
}
/* fill a string with trip point type and value in one line
* e.g. P(56) C(106)
* maintain the distance one degree per char
*/
static void draw_tp_line(int tz, int y)
{
int j;
int x;
for (j = 0; j < ptdata.tzi[tz].nr_trip_pts; j++) {
x = ptdata.tzi[tz].tp[j].temp / 1000;
mvwprintw(thermal_data_window, y + 0, x + TDATA_LEFT,
"%c%d", trip_type_to_char(ptdata.tzi[tz].tp[j].type),
x);
syslog(LOG_INFO, "%s:tz %d tp %d temp = %lu\n", __func__,
tz, j, ptdata.tzi[tz].tp[j].temp);
}
}
const char data_win_title[] = " THERMAL DATA ";
void show_data_w(void)
{
int i;
if (tui_disabled || !thermal_data_window)
return;
werase(thermal_data_window);
wattron(thermal_data_window, A_BOLD);
mvwprintw(thermal_data_window, 0, maxx/2 - sizeof(data_win_title),
data_win_title);
wattroff(thermal_data_window, A_BOLD);
/* draw a line as ruler */
for (i = 10; i < MAX_DISP_TEMP; i += 10)
mvwprintw(thermal_data_window, 1, i+TDATA_LEFT, "%2d", i);
for (i = 0; i < ptdata.nr_tz_sensor; i++) {
int temp = trec[cur_thermal_record].temp[i] / 1000;
int y = 0;
y = i * NR_LINES_TZDATA + 2;
/* y at tz temp data line */
mvwprintw(thermal_data_window, y, 1, "%6.6s%2d:[%3d][",
ptdata.tzi[i].type,
ptdata.tzi[i].instance, temp);
draw_hbar(thermal_data_window, y, TDATA_LEFT, temp, ACS_RARROW,
true);
draw_tp_line(i, y);
}
wborder(thermal_data_window, 0, 0, 0, 0, 0, 0, 0, 0);
wrefresh(thermal_data_window);
}
const char tz_title[] = "THERMAL ZONES(SENSORS)";
void show_sensors_w(void)
{
int i, j;
char buffer[512];
if (tui_disabled || !tz_sensor_window)
return;
werase(tz_sensor_window);
memset(buffer, 0, sizeof(buffer));
wattron(tz_sensor_window, A_BOLD);
mvwprintw(tz_sensor_window, 1, 1, "Thermal Zones:");
wattroff(tz_sensor_window, A_BOLD);
mvwprintw(tz_sensor_window, 1, TZ_LEFT_ALIGN, "%s", buffer);
/* fill trip points for each tzone */
wattron(tz_sensor_window, A_BOLD);
mvwprintw(tz_sensor_window, 2, 1, "Trip Points:");
wattroff(tz_sensor_window, A_BOLD);
/* draw trip point from low to high for each tz */
for (i = 0; i < ptdata.nr_tz_sensor; i++) {
int inst = ptdata.tzi[i].instance;
mvwprintw(tz_sensor_window, 1,
TZ_LEFT_ALIGN+TZONE_RECORD_SIZE * inst, "%.9s%02d",
ptdata.tzi[i].type, ptdata.tzi[i].instance);
for (j = ptdata.tzi[i].nr_trip_pts - 1; j >= 0; j--) {
/* loop through all trip points */
char type;
int tp_pos;
/* reverse the order here since trips are sorted
* in ascending order in terms of temperature.
*/
tp_pos = ptdata.tzi[i].nr_trip_pts - j - 1;
type = trip_type_to_char(ptdata.tzi[i].tp[j].type);
mvwaddch(tz_sensor_window, 2,
inst * TZONE_RECORD_SIZE + TZ_LEFT_ALIGN +
tp_pos, type);
syslog(LOG_DEBUG, "draw tz %d tp %d ch:%c\n",
inst, j, type);
}
}
wborder(tz_sensor_window, 0, 0, 0, 0, 0, 0, 0, 0);
wattron(tz_sensor_window, A_BOLD);
mvwprintw(tz_sensor_window, 0, maxx/2 - sizeof(tz_title), tz_title);
wattroff(tz_sensor_window, A_BOLD);
wrefresh(tz_sensor_window);
}
void disable_tui(void)
{
tui_disabled = 1;
}
| gpl-2.0 |
byeonggon/project-pika-lynx | arch/powerpc/sysdev/ppc4xx_soc.c | 3751 | 6114 | /*
* IBM/AMCC PPC4xx SoC setup code
*
* Copyright 2008 DENX Software Engineering, Stefan Roese <sr@denx.de>
*
* L2 cache routines cloned from arch/ppc/syslib/ibm440gx_common.c which is:
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
* Copyright (c) 2003 - 2006 Zultys Technologies
*
* 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/stddef.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/of_platform.h>
#include <asm/dcr.h>
#include <asm/dcr-regs.h>
#include <asm/reg.h>
static u32 dcrbase_l2c;
/*
* L2-cache
*/
/* Issue L2C diagnostic command */
static inline u32 l2c_diag(u32 addr)
{
mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, addr);
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_DIAG);
while (!(mfdcr(dcrbase_l2c + DCRN_L2C0_SR) & L2C_SR_CC))
;
return mfdcr(dcrbase_l2c + DCRN_L2C0_DATA);
}
static irqreturn_t l2c_error_handler(int irq, void *dev)
{
u32 sr = mfdcr(dcrbase_l2c + DCRN_L2C0_SR);
if (sr & L2C_SR_CPE) {
/* Read cache trapped address */
u32 addr = l2c_diag(0x42000000);
printk(KERN_EMERG "L2C: Cache Parity Error, addr[16:26] = 0x%08x\n",
addr);
}
if (sr & L2C_SR_TPE) {
/* Read tag trapped address */
u32 addr = l2c_diag(0x82000000) >> 16;
printk(KERN_EMERG "L2C: Tag Parity Error, addr[16:26] = 0x%08x\n",
addr);
}
/* Clear parity errors */
if (sr & (L2C_SR_CPE | L2C_SR_TPE)){
mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, 0);
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_CCP | L2C_CMD_CTE);
} else {
printk(KERN_EMERG "L2C: LRU error\n");
}
return IRQ_HANDLED;
}
static int __init ppc4xx_l2c_probe(void)
{
struct device_node *np;
u32 r;
unsigned long flags;
int irq;
const u32 *dcrreg;
u32 dcrbase_isram;
int len;
const u32 *prop;
u32 l2_size;
np = of_find_compatible_node(NULL, NULL, "ibm,l2-cache");
if (!np)
return 0;
/* Get l2 cache size */
prop = of_get_property(np, "cache-size", NULL);
if (prop == NULL) {
printk(KERN_ERR "%s: Can't get cache-size!\n", np->full_name);
of_node_put(np);
return -ENODEV;
}
l2_size = prop[0];
/* Map DCRs */
dcrreg = of_get_property(np, "dcr-reg", &len);
if (!dcrreg || (len != 4 * sizeof(u32))) {
printk(KERN_ERR "%s: Can't get DCR register base !",
np->full_name);
of_node_put(np);
return -ENODEV;
}
dcrbase_isram = dcrreg[0];
dcrbase_l2c = dcrreg[2];
/* Get and map irq number from device tree */
irq = irq_of_parse_and_map(np, 0);
if (irq == NO_IRQ) {
printk(KERN_ERR "irq_of_parse_and_map failed\n");
of_node_put(np);
return -ENODEV;
}
/* Install error handler */
if (request_irq(irq, l2c_error_handler, IRQF_DISABLED, "L2C", 0) < 0) {
printk(KERN_ERR "Cannot install L2C error handler"
", cache is not enabled\n");
of_node_put(np);
return -ENODEV;
}
local_irq_save(flags);
asm volatile ("sync" ::: "memory");
/* Disable SRAM */
mtdcr(dcrbase_isram + DCRN_SRAM0_DPC,
mfdcr(dcrbase_isram + DCRN_SRAM0_DPC) & ~SRAM_DPC_ENABLE);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB0CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB0CR) & ~SRAM_SBCR_BU_MASK);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB1CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB1CR) & ~SRAM_SBCR_BU_MASK);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB2CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB2CR) & ~SRAM_SBCR_BU_MASK);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB3CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB3CR) & ~SRAM_SBCR_BU_MASK);
/* Enable L2_MODE without ICU/DCU */
r = mfdcr(dcrbase_l2c + DCRN_L2C0_CFG) &
~(L2C_CFG_ICU | L2C_CFG_DCU | L2C_CFG_SS_MASK);
r |= L2C_CFG_L2M | L2C_CFG_SS_256;
mtdcr(dcrbase_l2c + DCRN_L2C0_CFG, r);
mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, 0);
/* Hardware Clear Command */
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_HCC);
while (!(mfdcr(dcrbase_l2c + DCRN_L2C0_SR) & L2C_SR_CC))
;
/* Clear Cache Parity and Tag Errors */
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_CCP | L2C_CMD_CTE);
/* Enable 64G snoop region starting at 0 */
r = mfdcr(dcrbase_l2c + DCRN_L2C0_SNP0) &
~(L2C_SNP_BA_MASK | L2C_SNP_SSR_MASK);
r |= L2C_SNP_SSR_32G | L2C_SNP_ESR;
mtdcr(dcrbase_l2c + DCRN_L2C0_SNP0, r);
r = mfdcr(dcrbase_l2c + DCRN_L2C0_SNP1) &
~(L2C_SNP_BA_MASK | L2C_SNP_SSR_MASK);
r |= 0x80000000 | L2C_SNP_SSR_32G | L2C_SNP_ESR;
mtdcr(dcrbase_l2c + DCRN_L2C0_SNP1, r);
asm volatile ("sync" ::: "memory");
/* Enable ICU/DCU ports */
r = mfdcr(dcrbase_l2c + DCRN_L2C0_CFG);
r &= ~(L2C_CFG_DCW_MASK | L2C_CFG_PMUX_MASK | L2C_CFG_PMIM
| L2C_CFG_TPEI | L2C_CFG_CPEI | L2C_CFG_NAM | L2C_CFG_NBRM);
r |= L2C_CFG_ICU | L2C_CFG_DCU | L2C_CFG_TPC | L2C_CFG_CPC | L2C_CFG_FRAN
| L2C_CFG_CPIM | L2C_CFG_TPIM | L2C_CFG_LIM | L2C_CFG_SMCM;
/* Check for 460EX/GT special handling */
if (of_device_is_compatible(np, "ibm,l2-cache-460ex") ||
of_device_is_compatible(np, "ibm,l2-cache-460gt"))
r |= L2C_CFG_RDBW;
mtdcr(dcrbase_l2c + DCRN_L2C0_CFG, r);
asm volatile ("sync; isync" ::: "memory");
local_irq_restore(flags);
printk(KERN_INFO "%dk L2-cache enabled\n", l2_size >> 10);
of_node_put(np);
return 0;
}
arch_initcall(ppc4xx_l2c_probe);
/*
* Apply a system reset. Alternatively a board specific value may be
* provided via the "reset-type" property in the cpu node.
*/
void ppc4xx_reset_system(char *cmd)
{
struct device_node *np;
u32 reset_type = DBCR0_RST_SYSTEM;
const u32 *prop;
np = of_find_node_by_type(NULL, "cpu");
if (np) {
prop = of_get_property(np, "reset-type", NULL);
/*
* Check if property exists and if it is in range:
* 1 - PPC4xx core reset
* 2 - PPC4xx chip reset
* 3 - PPC4xx system reset (default)
*/
if ((prop) && ((prop[0] >= 1) && (prop[0] <= 3)))
reset_type = prop[0] << 28;
}
mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) | reset_type);
while (1)
; /* Just in case the reset doesn't work */
}
| gpl-2.0 |
blindcozy/kernel-zenfone-4 | drivers/input/touchscreen/atmel_tsadcc.c | 5031 | 11352 | /*
* Atmel Touch Screen Driver
*
* Copyright (c) 2008 ATMEL
* Copyright (c) 2008 Dan Liang
* Copyright (c) 2008 TimeSys Corporation
* Copyright (c) 2008 Justin Waters
*
* Based on touchscreen code from 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/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <mach/board.h>
#include <mach/cpu.h>
/* Register definitions based on AT91SAM9RL64 preliminary draft datasheet */
#define ATMEL_TSADCC_CR 0x00 /* Control register */
#define ATMEL_TSADCC_SWRST (1 << 0) /* Software Reset*/
#define ATMEL_TSADCC_START (1 << 1) /* Start conversion */
#define ATMEL_TSADCC_MR 0x04 /* Mode register */
#define ATMEL_TSADCC_TSAMOD (3 << 0) /* ADC mode */
#define ATMEL_TSADCC_TSAMOD_ADC_ONLY_MODE (0x0) /* ADC Mode */
#define ATMEL_TSADCC_TSAMOD_TS_ONLY_MODE (0x1) /* Touch Screen Only Mode */
#define ATMEL_TSADCC_LOWRES (1 << 4) /* Resolution selection */
#define ATMEL_TSADCC_SLEEP (1 << 5) /* Sleep mode */
#define ATMEL_TSADCC_PENDET (1 << 6) /* Pen Detect selection */
#define ATMEL_TSADCC_PRES (1 << 7) /* Pressure Measurement Selection */
#define ATMEL_TSADCC_PRESCAL (0x3f << 8) /* Prescalar Rate Selection */
#define ATMEL_TSADCC_EPRESCAL (0xff << 8) /* Prescalar Rate Selection (Extended) */
#define ATMEL_TSADCC_STARTUP (0x7f << 16) /* Start Up time */
#define ATMEL_TSADCC_SHTIM (0xf << 24) /* Sample & Hold time */
#define ATMEL_TSADCC_PENDBC (0xf << 28) /* Pen Detect debouncing time */
#define ATMEL_TSADCC_TRGR 0x08 /* Trigger register */
#define ATMEL_TSADCC_TRGMOD (7 << 0) /* Trigger mode */
#define ATMEL_TSADCC_TRGMOD_NONE (0 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_RISING (1 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_FALLING (2 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_ANY (3 << 0)
#define ATMEL_TSADCC_TRGMOD_PENDET (4 << 0)
#define ATMEL_TSADCC_TRGMOD_PERIOD (5 << 0)
#define ATMEL_TSADCC_TRGMOD_CONTINUOUS (6 << 0)
#define ATMEL_TSADCC_TRGPER (0xffff << 16) /* Trigger period */
#define ATMEL_TSADCC_TSR 0x0C /* Touch Screen register */
#define ATMEL_TSADCC_TSFREQ (0xf << 0) /* TS Frequency in Interleaved mode */
#define ATMEL_TSADCC_TSSHTIM (0xf << 24) /* Sample & Hold time */
#define ATMEL_TSADCC_CHER 0x10 /* Channel Enable register */
#define ATMEL_TSADCC_CHDR 0x14 /* Channel Disable register */
#define ATMEL_TSADCC_CHSR 0x18 /* Channel Status register */
#define ATMEL_TSADCC_CH(n) (1 << (n)) /* Channel number */
#define ATMEL_TSADCC_SR 0x1C /* Status register */
#define ATMEL_TSADCC_EOC(n) (1 << ((n)+0)) /* End of conversion for channel N */
#define ATMEL_TSADCC_OVRE(n) (1 << ((n)+8)) /* Overrun error for channel N */
#define ATMEL_TSADCC_DRDY (1 << 16) /* Data Ready */
#define ATMEL_TSADCC_GOVRE (1 << 17) /* General Overrun Error */
#define ATMEL_TSADCC_ENDRX (1 << 18) /* End of RX Buffer */
#define ATMEL_TSADCC_RXBUFF (1 << 19) /* TX Buffer full */
#define ATMEL_TSADCC_PENCNT (1 << 20) /* Pen contact */
#define ATMEL_TSADCC_NOCNT (1 << 21) /* No contact */
#define ATMEL_TSADCC_LCDR 0x20 /* Last Converted Data register */
#define ATMEL_TSADCC_DATA (0x3ff << 0) /* Channel data */
#define ATMEL_TSADCC_IER 0x24 /* Interrupt Enable register */
#define ATMEL_TSADCC_IDR 0x28 /* Interrupt Disable register */
#define ATMEL_TSADCC_IMR 0x2C /* Interrupt Mask register */
#define ATMEL_TSADCC_CDR0 0x30 /* Channel Data 0 */
#define ATMEL_TSADCC_CDR1 0x34 /* Channel Data 1 */
#define ATMEL_TSADCC_CDR2 0x38 /* Channel Data 2 */
#define ATMEL_TSADCC_CDR3 0x3C /* Channel Data 3 */
#define ATMEL_TSADCC_CDR4 0x40 /* Channel Data 4 */
#define ATMEL_TSADCC_CDR5 0x44 /* Channel Data 5 */
#define ATMEL_TSADCC_XPOS 0x50
#define ATMEL_TSADCC_Z1DAT 0x54
#define ATMEL_TSADCC_Z2DAT 0x58
#define PRESCALER_VAL(x) ((x) >> 8)
#define ADC_DEFAULT_CLOCK 100000
struct atmel_tsadcc {
struct input_dev *input;
char phys[32];
struct clk *clk;
int irq;
unsigned int prev_absx;
unsigned int prev_absy;
unsigned char bufferedmeasure;
};
static void __iomem *tsc_base;
#define atmel_tsadcc_read(reg) __raw_readl(tsc_base + (reg))
#define atmel_tsadcc_write(reg, val) __raw_writel((val), tsc_base + (reg))
static irqreturn_t atmel_tsadcc_interrupt(int irq, void *dev)
{
struct atmel_tsadcc *ts_dev = (struct atmel_tsadcc *)dev;
struct input_dev *input_dev = ts_dev->input;
unsigned int status;
unsigned int reg;
status = atmel_tsadcc_read(ATMEL_TSADCC_SR);
status &= atmel_tsadcc_read(ATMEL_TSADCC_IMR);
if (status & ATMEL_TSADCC_NOCNT) {
/* Contact lost */
reg = atmel_tsadcc_read(ATMEL_TSADCC_MR) | ATMEL_TSADCC_PENDBC;
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR, ATMEL_TSADCC_TRGMOD_NONE);
atmel_tsadcc_write(ATMEL_TSADCC_IDR,
ATMEL_TSADCC_EOC(3) | ATMEL_TSADCC_NOCNT);
atmel_tsadcc_write(ATMEL_TSADCC_IER, ATMEL_TSADCC_PENCNT);
input_report_key(input_dev, BTN_TOUCH, 0);
ts_dev->bufferedmeasure = 0;
input_sync(input_dev);
} else if (status & ATMEL_TSADCC_PENCNT) {
/* Pen detected */
reg = atmel_tsadcc_read(ATMEL_TSADCC_MR);
reg &= ~ATMEL_TSADCC_PENDBC;
atmel_tsadcc_write(ATMEL_TSADCC_IDR, ATMEL_TSADCC_PENCNT);
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_IER,
ATMEL_TSADCC_EOC(3) | ATMEL_TSADCC_NOCNT);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR,
ATMEL_TSADCC_TRGMOD_PERIOD | (0x0FFF << 16));
} else if (status & ATMEL_TSADCC_EOC(3)) {
/* Conversion finished */
if (ts_dev->bufferedmeasure) {
/* Last measurement is always discarded, since it can
* be erroneous.
* Always report previous measurement */
input_report_abs(input_dev, ABS_X, ts_dev->prev_absx);
input_report_abs(input_dev, ABS_Y, ts_dev->prev_absy);
input_report_key(input_dev, BTN_TOUCH, 1);
input_sync(input_dev);
} else
ts_dev->bufferedmeasure = 1;
/* Now make new measurement */
ts_dev->prev_absx = atmel_tsadcc_read(ATMEL_TSADCC_CDR3) << 10;
ts_dev->prev_absx /= atmel_tsadcc_read(ATMEL_TSADCC_CDR2);
ts_dev->prev_absy = atmel_tsadcc_read(ATMEL_TSADCC_CDR1) << 10;
ts_dev->prev_absy /= atmel_tsadcc_read(ATMEL_TSADCC_CDR0);
}
return IRQ_HANDLED;
}
/*
* The functions for inserting/removing us as a module.
*/
static int __devinit atmel_tsadcc_probe(struct platform_device *pdev)
{
struct atmel_tsadcc *ts_dev;
struct input_dev *input_dev;
struct resource *res;
struct at91_tsadcc_data *pdata = pdev->dev.platform_data;
int err = 0;
unsigned int prsc;
unsigned int reg;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "no mmio resource defined.\n");
return -ENXIO;
}
/* Allocate memory for device */
ts_dev = kzalloc(sizeof(struct atmel_tsadcc), GFP_KERNEL);
if (!ts_dev) {
dev_err(&pdev->dev, "failed to allocate memory.\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, ts_dev);
input_dev = input_allocate_device();
if (!input_dev) {
dev_err(&pdev->dev, "failed to allocate input device.\n");
err = -EBUSY;
goto err_free_mem;
}
ts_dev->irq = platform_get_irq(pdev, 0);
if (ts_dev->irq < 0) {
dev_err(&pdev->dev, "no irq ID is designated.\n");
err = -ENODEV;
goto err_free_dev;
}
if (!request_mem_region(res->start, resource_size(res),
"atmel tsadcc regs")) {
dev_err(&pdev->dev, "resources is unavailable.\n");
err = -EBUSY;
goto err_free_dev;
}
tsc_base = ioremap(res->start, resource_size(res));
if (!tsc_base) {
dev_err(&pdev->dev, "failed to map registers.\n");
err = -ENOMEM;
goto err_release_mem;
}
err = request_irq(ts_dev->irq, atmel_tsadcc_interrupt, 0,
pdev->dev.driver->name, ts_dev);
if (err) {
dev_err(&pdev->dev, "failed to allocate irq.\n");
goto err_unmap_regs;
}
ts_dev->clk = clk_get(&pdev->dev, "tsc_clk");
if (IS_ERR(ts_dev->clk)) {
dev_err(&pdev->dev, "failed to get ts_clk\n");
err = PTR_ERR(ts_dev->clk);
goto err_free_irq;
}
ts_dev->input = input_dev;
ts_dev->bufferedmeasure = 0;
snprintf(ts_dev->phys, sizeof(ts_dev->phys),
"%s/input0", dev_name(&pdev->dev));
input_dev->name = "atmel touch screen controller";
input_dev->phys = ts_dev->phys;
input_dev->dev.parent = &pdev->dev;
__set_bit(EV_ABS, input_dev->evbit);
input_set_abs_params(input_dev, ABS_X, 0, 0x3FF, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0, 0x3FF, 0, 0);
input_set_capability(input_dev, EV_KEY, BTN_TOUCH);
/* clk_enable() always returns 0, no need to check it */
clk_enable(ts_dev->clk);
prsc = clk_get_rate(ts_dev->clk);
dev_info(&pdev->dev, "Master clock is set at: %d Hz\n", prsc);
if (!pdata)
goto err_fail;
if (!pdata->adc_clock)
pdata->adc_clock = ADC_DEFAULT_CLOCK;
prsc = (prsc / (2 * pdata->adc_clock)) - 1;
/* saturate if this value is too high */
if (cpu_is_at91sam9rl()) {
if (prsc > PRESCALER_VAL(ATMEL_TSADCC_PRESCAL))
prsc = PRESCALER_VAL(ATMEL_TSADCC_PRESCAL);
} else {
if (prsc > PRESCALER_VAL(ATMEL_TSADCC_EPRESCAL))
prsc = PRESCALER_VAL(ATMEL_TSADCC_EPRESCAL);
}
dev_info(&pdev->dev, "Prescaler is set at: %d\n", prsc);
reg = ATMEL_TSADCC_TSAMOD_TS_ONLY_MODE |
((0x00 << 5) & ATMEL_TSADCC_SLEEP) | /* Normal Mode */
((0x01 << 6) & ATMEL_TSADCC_PENDET) | /* Enable Pen Detect */
(prsc << 8) |
((0x26 << 16) & ATMEL_TSADCC_STARTUP) |
((pdata->pendet_debounce << 28) & ATMEL_TSADCC_PENDBC);
atmel_tsadcc_write(ATMEL_TSADCC_CR, ATMEL_TSADCC_SWRST);
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR, ATMEL_TSADCC_TRGMOD_NONE);
atmel_tsadcc_write(ATMEL_TSADCC_TSR,
(pdata->ts_sample_hold_time << 24) & ATMEL_TSADCC_TSSHTIM);
atmel_tsadcc_read(ATMEL_TSADCC_SR);
atmel_tsadcc_write(ATMEL_TSADCC_IER, ATMEL_TSADCC_PENCNT);
/* All went ok, so register to the input system */
err = input_register_device(input_dev);
if (err)
goto err_fail;
return 0;
err_fail:
clk_disable(ts_dev->clk);
clk_put(ts_dev->clk);
err_free_irq:
free_irq(ts_dev->irq, ts_dev);
err_unmap_regs:
iounmap(tsc_base);
err_release_mem:
release_mem_region(res->start, resource_size(res));
err_free_dev:
input_free_device(input_dev);
err_free_mem:
kfree(ts_dev);
return err;
}
static int __devexit atmel_tsadcc_remove(struct platform_device *pdev)
{
struct atmel_tsadcc *ts_dev = dev_get_drvdata(&pdev->dev);
struct resource *res;
free_irq(ts_dev->irq, ts_dev);
input_unregister_device(ts_dev->input);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
iounmap(tsc_base);
release_mem_region(res->start, resource_size(res));
clk_disable(ts_dev->clk);
clk_put(ts_dev->clk);
kfree(ts_dev);
return 0;
}
static struct platform_driver atmel_tsadcc_driver = {
.probe = atmel_tsadcc_probe,
.remove = __devexit_p(atmel_tsadcc_remove),
.driver = {
.name = "atmel_tsadcc",
},
};
module_platform_driver(atmel_tsadcc_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Atmel TouchScreen Driver");
MODULE_AUTHOR("Dan Liang <dan.liang@atmel.com>");
| gpl-2.0 |
DirtyUnicorns/android_kernel_htc_m4 | drivers/input/touchscreen/atmel_tsadcc.c | 5031 | 11352 | /*
* Atmel Touch Screen Driver
*
* Copyright (c) 2008 ATMEL
* Copyright (c) 2008 Dan Liang
* Copyright (c) 2008 TimeSys Corporation
* Copyright (c) 2008 Justin Waters
*
* Based on touchscreen code from 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/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <mach/board.h>
#include <mach/cpu.h>
/* Register definitions based on AT91SAM9RL64 preliminary draft datasheet */
#define ATMEL_TSADCC_CR 0x00 /* Control register */
#define ATMEL_TSADCC_SWRST (1 << 0) /* Software Reset*/
#define ATMEL_TSADCC_START (1 << 1) /* Start conversion */
#define ATMEL_TSADCC_MR 0x04 /* Mode register */
#define ATMEL_TSADCC_TSAMOD (3 << 0) /* ADC mode */
#define ATMEL_TSADCC_TSAMOD_ADC_ONLY_MODE (0x0) /* ADC Mode */
#define ATMEL_TSADCC_TSAMOD_TS_ONLY_MODE (0x1) /* Touch Screen Only Mode */
#define ATMEL_TSADCC_LOWRES (1 << 4) /* Resolution selection */
#define ATMEL_TSADCC_SLEEP (1 << 5) /* Sleep mode */
#define ATMEL_TSADCC_PENDET (1 << 6) /* Pen Detect selection */
#define ATMEL_TSADCC_PRES (1 << 7) /* Pressure Measurement Selection */
#define ATMEL_TSADCC_PRESCAL (0x3f << 8) /* Prescalar Rate Selection */
#define ATMEL_TSADCC_EPRESCAL (0xff << 8) /* Prescalar Rate Selection (Extended) */
#define ATMEL_TSADCC_STARTUP (0x7f << 16) /* Start Up time */
#define ATMEL_TSADCC_SHTIM (0xf << 24) /* Sample & Hold time */
#define ATMEL_TSADCC_PENDBC (0xf << 28) /* Pen Detect debouncing time */
#define ATMEL_TSADCC_TRGR 0x08 /* Trigger register */
#define ATMEL_TSADCC_TRGMOD (7 << 0) /* Trigger mode */
#define ATMEL_TSADCC_TRGMOD_NONE (0 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_RISING (1 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_FALLING (2 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_ANY (3 << 0)
#define ATMEL_TSADCC_TRGMOD_PENDET (4 << 0)
#define ATMEL_TSADCC_TRGMOD_PERIOD (5 << 0)
#define ATMEL_TSADCC_TRGMOD_CONTINUOUS (6 << 0)
#define ATMEL_TSADCC_TRGPER (0xffff << 16) /* Trigger period */
#define ATMEL_TSADCC_TSR 0x0C /* Touch Screen register */
#define ATMEL_TSADCC_TSFREQ (0xf << 0) /* TS Frequency in Interleaved mode */
#define ATMEL_TSADCC_TSSHTIM (0xf << 24) /* Sample & Hold time */
#define ATMEL_TSADCC_CHER 0x10 /* Channel Enable register */
#define ATMEL_TSADCC_CHDR 0x14 /* Channel Disable register */
#define ATMEL_TSADCC_CHSR 0x18 /* Channel Status register */
#define ATMEL_TSADCC_CH(n) (1 << (n)) /* Channel number */
#define ATMEL_TSADCC_SR 0x1C /* Status register */
#define ATMEL_TSADCC_EOC(n) (1 << ((n)+0)) /* End of conversion for channel N */
#define ATMEL_TSADCC_OVRE(n) (1 << ((n)+8)) /* Overrun error for channel N */
#define ATMEL_TSADCC_DRDY (1 << 16) /* Data Ready */
#define ATMEL_TSADCC_GOVRE (1 << 17) /* General Overrun Error */
#define ATMEL_TSADCC_ENDRX (1 << 18) /* End of RX Buffer */
#define ATMEL_TSADCC_RXBUFF (1 << 19) /* TX Buffer full */
#define ATMEL_TSADCC_PENCNT (1 << 20) /* Pen contact */
#define ATMEL_TSADCC_NOCNT (1 << 21) /* No contact */
#define ATMEL_TSADCC_LCDR 0x20 /* Last Converted Data register */
#define ATMEL_TSADCC_DATA (0x3ff << 0) /* Channel data */
#define ATMEL_TSADCC_IER 0x24 /* Interrupt Enable register */
#define ATMEL_TSADCC_IDR 0x28 /* Interrupt Disable register */
#define ATMEL_TSADCC_IMR 0x2C /* Interrupt Mask register */
#define ATMEL_TSADCC_CDR0 0x30 /* Channel Data 0 */
#define ATMEL_TSADCC_CDR1 0x34 /* Channel Data 1 */
#define ATMEL_TSADCC_CDR2 0x38 /* Channel Data 2 */
#define ATMEL_TSADCC_CDR3 0x3C /* Channel Data 3 */
#define ATMEL_TSADCC_CDR4 0x40 /* Channel Data 4 */
#define ATMEL_TSADCC_CDR5 0x44 /* Channel Data 5 */
#define ATMEL_TSADCC_XPOS 0x50
#define ATMEL_TSADCC_Z1DAT 0x54
#define ATMEL_TSADCC_Z2DAT 0x58
#define PRESCALER_VAL(x) ((x) >> 8)
#define ADC_DEFAULT_CLOCK 100000
struct atmel_tsadcc {
struct input_dev *input;
char phys[32];
struct clk *clk;
int irq;
unsigned int prev_absx;
unsigned int prev_absy;
unsigned char bufferedmeasure;
};
static void __iomem *tsc_base;
#define atmel_tsadcc_read(reg) __raw_readl(tsc_base + (reg))
#define atmel_tsadcc_write(reg, val) __raw_writel((val), tsc_base + (reg))
static irqreturn_t atmel_tsadcc_interrupt(int irq, void *dev)
{
struct atmel_tsadcc *ts_dev = (struct atmel_tsadcc *)dev;
struct input_dev *input_dev = ts_dev->input;
unsigned int status;
unsigned int reg;
status = atmel_tsadcc_read(ATMEL_TSADCC_SR);
status &= atmel_tsadcc_read(ATMEL_TSADCC_IMR);
if (status & ATMEL_TSADCC_NOCNT) {
/* Contact lost */
reg = atmel_tsadcc_read(ATMEL_TSADCC_MR) | ATMEL_TSADCC_PENDBC;
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR, ATMEL_TSADCC_TRGMOD_NONE);
atmel_tsadcc_write(ATMEL_TSADCC_IDR,
ATMEL_TSADCC_EOC(3) | ATMEL_TSADCC_NOCNT);
atmel_tsadcc_write(ATMEL_TSADCC_IER, ATMEL_TSADCC_PENCNT);
input_report_key(input_dev, BTN_TOUCH, 0);
ts_dev->bufferedmeasure = 0;
input_sync(input_dev);
} else if (status & ATMEL_TSADCC_PENCNT) {
/* Pen detected */
reg = atmel_tsadcc_read(ATMEL_TSADCC_MR);
reg &= ~ATMEL_TSADCC_PENDBC;
atmel_tsadcc_write(ATMEL_TSADCC_IDR, ATMEL_TSADCC_PENCNT);
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_IER,
ATMEL_TSADCC_EOC(3) | ATMEL_TSADCC_NOCNT);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR,
ATMEL_TSADCC_TRGMOD_PERIOD | (0x0FFF << 16));
} else if (status & ATMEL_TSADCC_EOC(3)) {
/* Conversion finished */
if (ts_dev->bufferedmeasure) {
/* Last measurement is always discarded, since it can
* be erroneous.
* Always report previous measurement */
input_report_abs(input_dev, ABS_X, ts_dev->prev_absx);
input_report_abs(input_dev, ABS_Y, ts_dev->prev_absy);
input_report_key(input_dev, BTN_TOUCH, 1);
input_sync(input_dev);
} else
ts_dev->bufferedmeasure = 1;
/* Now make new measurement */
ts_dev->prev_absx = atmel_tsadcc_read(ATMEL_TSADCC_CDR3) << 10;
ts_dev->prev_absx /= atmel_tsadcc_read(ATMEL_TSADCC_CDR2);
ts_dev->prev_absy = atmel_tsadcc_read(ATMEL_TSADCC_CDR1) << 10;
ts_dev->prev_absy /= atmel_tsadcc_read(ATMEL_TSADCC_CDR0);
}
return IRQ_HANDLED;
}
/*
* The functions for inserting/removing us as a module.
*/
static int __devinit atmel_tsadcc_probe(struct platform_device *pdev)
{
struct atmel_tsadcc *ts_dev;
struct input_dev *input_dev;
struct resource *res;
struct at91_tsadcc_data *pdata = pdev->dev.platform_data;
int err = 0;
unsigned int prsc;
unsigned int reg;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "no mmio resource defined.\n");
return -ENXIO;
}
/* Allocate memory for device */
ts_dev = kzalloc(sizeof(struct atmel_tsadcc), GFP_KERNEL);
if (!ts_dev) {
dev_err(&pdev->dev, "failed to allocate memory.\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, ts_dev);
input_dev = input_allocate_device();
if (!input_dev) {
dev_err(&pdev->dev, "failed to allocate input device.\n");
err = -EBUSY;
goto err_free_mem;
}
ts_dev->irq = platform_get_irq(pdev, 0);
if (ts_dev->irq < 0) {
dev_err(&pdev->dev, "no irq ID is designated.\n");
err = -ENODEV;
goto err_free_dev;
}
if (!request_mem_region(res->start, resource_size(res),
"atmel tsadcc regs")) {
dev_err(&pdev->dev, "resources is unavailable.\n");
err = -EBUSY;
goto err_free_dev;
}
tsc_base = ioremap(res->start, resource_size(res));
if (!tsc_base) {
dev_err(&pdev->dev, "failed to map registers.\n");
err = -ENOMEM;
goto err_release_mem;
}
err = request_irq(ts_dev->irq, atmel_tsadcc_interrupt, 0,
pdev->dev.driver->name, ts_dev);
if (err) {
dev_err(&pdev->dev, "failed to allocate irq.\n");
goto err_unmap_regs;
}
ts_dev->clk = clk_get(&pdev->dev, "tsc_clk");
if (IS_ERR(ts_dev->clk)) {
dev_err(&pdev->dev, "failed to get ts_clk\n");
err = PTR_ERR(ts_dev->clk);
goto err_free_irq;
}
ts_dev->input = input_dev;
ts_dev->bufferedmeasure = 0;
snprintf(ts_dev->phys, sizeof(ts_dev->phys),
"%s/input0", dev_name(&pdev->dev));
input_dev->name = "atmel touch screen controller";
input_dev->phys = ts_dev->phys;
input_dev->dev.parent = &pdev->dev;
__set_bit(EV_ABS, input_dev->evbit);
input_set_abs_params(input_dev, ABS_X, 0, 0x3FF, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0, 0x3FF, 0, 0);
input_set_capability(input_dev, EV_KEY, BTN_TOUCH);
/* clk_enable() always returns 0, no need to check it */
clk_enable(ts_dev->clk);
prsc = clk_get_rate(ts_dev->clk);
dev_info(&pdev->dev, "Master clock is set at: %d Hz\n", prsc);
if (!pdata)
goto err_fail;
if (!pdata->adc_clock)
pdata->adc_clock = ADC_DEFAULT_CLOCK;
prsc = (prsc / (2 * pdata->adc_clock)) - 1;
/* saturate if this value is too high */
if (cpu_is_at91sam9rl()) {
if (prsc > PRESCALER_VAL(ATMEL_TSADCC_PRESCAL))
prsc = PRESCALER_VAL(ATMEL_TSADCC_PRESCAL);
} else {
if (prsc > PRESCALER_VAL(ATMEL_TSADCC_EPRESCAL))
prsc = PRESCALER_VAL(ATMEL_TSADCC_EPRESCAL);
}
dev_info(&pdev->dev, "Prescaler is set at: %d\n", prsc);
reg = ATMEL_TSADCC_TSAMOD_TS_ONLY_MODE |
((0x00 << 5) & ATMEL_TSADCC_SLEEP) | /* Normal Mode */
((0x01 << 6) & ATMEL_TSADCC_PENDET) | /* Enable Pen Detect */
(prsc << 8) |
((0x26 << 16) & ATMEL_TSADCC_STARTUP) |
((pdata->pendet_debounce << 28) & ATMEL_TSADCC_PENDBC);
atmel_tsadcc_write(ATMEL_TSADCC_CR, ATMEL_TSADCC_SWRST);
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR, ATMEL_TSADCC_TRGMOD_NONE);
atmel_tsadcc_write(ATMEL_TSADCC_TSR,
(pdata->ts_sample_hold_time << 24) & ATMEL_TSADCC_TSSHTIM);
atmel_tsadcc_read(ATMEL_TSADCC_SR);
atmel_tsadcc_write(ATMEL_TSADCC_IER, ATMEL_TSADCC_PENCNT);
/* All went ok, so register to the input system */
err = input_register_device(input_dev);
if (err)
goto err_fail;
return 0;
err_fail:
clk_disable(ts_dev->clk);
clk_put(ts_dev->clk);
err_free_irq:
free_irq(ts_dev->irq, ts_dev);
err_unmap_regs:
iounmap(tsc_base);
err_release_mem:
release_mem_region(res->start, resource_size(res));
err_free_dev:
input_free_device(input_dev);
err_free_mem:
kfree(ts_dev);
return err;
}
static int __devexit atmel_tsadcc_remove(struct platform_device *pdev)
{
struct atmel_tsadcc *ts_dev = dev_get_drvdata(&pdev->dev);
struct resource *res;
free_irq(ts_dev->irq, ts_dev);
input_unregister_device(ts_dev->input);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
iounmap(tsc_base);
release_mem_region(res->start, resource_size(res));
clk_disable(ts_dev->clk);
clk_put(ts_dev->clk);
kfree(ts_dev);
return 0;
}
static struct platform_driver atmel_tsadcc_driver = {
.probe = atmel_tsadcc_probe,
.remove = __devexit_p(atmel_tsadcc_remove),
.driver = {
.name = "atmel_tsadcc",
},
};
module_platform_driver(atmel_tsadcc_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Atmel TouchScreen Driver");
MODULE_AUTHOR("Dan Liang <dan.liang@atmel.com>");
| gpl-2.0 |
Shaaan/android_kernel_samsung_u8500-common | drivers/misc/akm8975.c | 6567 | 16798 | /* drivers/misc/akm8975.c - akm8975 compass driver
*
* Copyright (C) 2007-2008 HTC Corporation.
* Author: Hou-Kun Chen <houkun.chen@gmail.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* Revised by AKM 2009/04/02
* Revised by Motorola 2010/05/27
*
*/
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/miscdevice.h>
#include <linux/gpio.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/freezer.h>
#include <linux/akm8975.h>
#include <linux/earlysuspend.h>
#define AK8975DRV_CALL_DBG 0
#if AK8975DRV_CALL_DBG
#define FUNCDBG(msg) pr_err("%s:%s\n", __func__, msg);
#else
#define FUNCDBG(msg)
#endif
#define AK8975DRV_DATA_DBG 0
#define MAX_FAILURE_COUNT 10
struct akm8975_data {
struct i2c_client *this_client;
struct akm8975_platform_data *pdata;
struct input_dev *input_dev;
struct work_struct work;
struct mutex flags_lock;
#ifdef CONFIG_HAS_EARLYSUSPEND
struct early_suspend early_suspend;
#endif
};
/*
* Because misc devices can not carry a pointer from driver register to
* open, we keep this global. This limits the driver to a single instance.
*/
struct akm8975_data *akmd_data;
static DECLARE_WAIT_QUEUE_HEAD(open_wq);
static atomic_t open_flag;
static short m_flag;
static short a_flag;
static short t_flag;
static short mv_flag;
static short akmd_delay;
static ssize_t akm8975_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
return sprintf(buf, "%u\n", i2c_smbus_read_byte_data(client,
AK8975_REG_CNTL));
}
static ssize_t akm8975_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned long val;
strict_strtoul(buf, 10, &val);
if (val > 0xff)
return -EINVAL;
i2c_smbus_write_byte_data(client, AK8975_REG_CNTL, val);
return count;
}
static DEVICE_ATTR(akm_ms1, S_IWUSR | S_IRUGO, akm8975_show, akm8975_store);
static int akm8975_i2c_rxdata(struct akm8975_data *akm, char *buf, int length)
{
struct i2c_msg msgs[] = {
{
.addr = akm->this_client->addr,
.flags = 0,
.len = 1,
.buf = buf,
},
{
.addr = akm->this_client->addr,
.flags = I2C_M_RD,
.len = length,
.buf = buf,
},
};
FUNCDBG("called");
if (i2c_transfer(akm->this_client->adapter, msgs, 2) < 0) {
pr_err("akm8975_i2c_rxdata: transfer error\n");
return EIO;
} else
return 0;
}
static int akm8975_i2c_txdata(struct akm8975_data *akm, char *buf, int length)
{
struct i2c_msg msgs[] = {
{
.addr = akm->this_client->addr,
.flags = 0,
.len = length,
.buf = buf,
},
};
FUNCDBG("called");
if (i2c_transfer(akm->this_client->adapter, msgs, 1) < 0) {
pr_err("akm8975_i2c_txdata: transfer error\n");
return -EIO;
} else
return 0;
}
static void akm8975_ecs_report_value(struct akm8975_data *akm, short *rbuf)
{
struct akm8975_data *data = i2c_get_clientdata(akm->this_client);
FUNCDBG("called");
#if AK8975DRV_DATA_DBG
pr_info("akm8975_ecs_report_value: yaw = %d, pitch = %d, roll = %d\n",
rbuf[0], rbuf[1], rbuf[2]);
pr_info("tmp = %d, m_stat= %d, g_stat=%d\n", rbuf[3], rbuf[4], rbuf[5]);
pr_info("Acceleration: x = %d LSB, y = %d LSB, z = %d LSB\n",
rbuf[6], rbuf[7], rbuf[8]);
pr_info("Magnetic: x = %d LSB, y = %d LSB, z = %d LSB\n\n",
rbuf[9], rbuf[10], rbuf[11]);
#endif
mutex_lock(&akm->flags_lock);
/* Report magnetic sensor information */
if (m_flag) {
input_report_abs(data->input_dev, ABS_RX, rbuf[0]);
input_report_abs(data->input_dev, ABS_RY, rbuf[1]);
input_report_abs(data->input_dev, ABS_RZ, rbuf[2]);
input_report_abs(data->input_dev, ABS_RUDDER, rbuf[4]);
}
/* Report acceleration sensor information */
if (a_flag) {
input_report_abs(data->input_dev, ABS_X, rbuf[6]);
input_report_abs(data->input_dev, ABS_Y, rbuf[7]);
input_report_abs(data->input_dev, ABS_Z, rbuf[8]);
input_report_abs(data->input_dev, ABS_WHEEL, rbuf[5]);
}
/* Report temperature information */
if (t_flag)
input_report_abs(data->input_dev, ABS_THROTTLE, rbuf[3]);
if (mv_flag) {
input_report_abs(data->input_dev, ABS_HAT0X, rbuf[9]);
input_report_abs(data->input_dev, ABS_HAT0Y, rbuf[10]);
input_report_abs(data->input_dev, ABS_BRAKE, rbuf[11]);
}
mutex_unlock(&akm->flags_lock);
input_sync(data->input_dev);
}
static void akm8975_ecs_close_done(struct akm8975_data *akm)
{
FUNCDBG("called");
mutex_lock(&akm->flags_lock);
m_flag = 1;
a_flag = 1;
t_flag = 1;
mv_flag = 1;
mutex_unlock(&akm->flags_lock);
}
static int akm_aot_open(struct inode *inode, struct file *file)
{
int ret = -1;
FUNCDBG("called");
if (atomic_cmpxchg(&open_flag, 0, 1) == 0) {
wake_up(&open_wq);
ret = 0;
}
ret = nonseekable_open(inode, file);
if (ret)
return ret;
file->private_data = akmd_data;
return ret;
}
static int akm_aot_release(struct inode *inode, struct file *file)
{
FUNCDBG("called");
atomic_set(&open_flag, 0);
wake_up(&open_wq);
return 0;
}
static int akm_aot_ioctl(struct inode *inode, struct file *file,
unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *) arg;
short flag;
struct akm8975_data *akm = file->private_data;
FUNCDBG("called");
switch (cmd) {
case ECS_IOCTL_APP_SET_MFLAG:
case ECS_IOCTL_APP_SET_AFLAG:
case ECS_IOCTL_APP_SET_MVFLAG:
if (copy_from_user(&flag, argp, sizeof(flag)))
return -EFAULT;
if (flag < 0 || flag > 1)
return -EINVAL;
break;
case ECS_IOCTL_APP_SET_DELAY:
if (copy_from_user(&flag, argp, sizeof(flag)))
return -EFAULT;
break;
default:
break;
}
mutex_lock(&akm->flags_lock);
switch (cmd) {
case ECS_IOCTL_APP_SET_MFLAG:
m_flag = flag;
break;
case ECS_IOCTL_APP_GET_MFLAG:
flag = m_flag;
break;
case ECS_IOCTL_APP_SET_AFLAG:
a_flag = flag;
break;
case ECS_IOCTL_APP_GET_AFLAG:
flag = a_flag;
break;
case ECS_IOCTL_APP_SET_MVFLAG:
mv_flag = flag;
break;
case ECS_IOCTL_APP_GET_MVFLAG:
flag = mv_flag;
break;
case ECS_IOCTL_APP_SET_DELAY:
akmd_delay = flag;
break;
case ECS_IOCTL_APP_GET_DELAY:
flag = akmd_delay;
break;
default:
return -ENOTTY;
}
mutex_unlock(&akm->flags_lock);
switch (cmd) {
case ECS_IOCTL_APP_GET_MFLAG:
case ECS_IOCTL_APP_GET_AFLAG:
case ECS_IOCTL_APP_GET_MVFLAG:
case ECS_IOCTL_APP_GET_DELAY:
if (copy_to_user(argp, &flag, sizeof(flag)))
return -EFAULT;
break;
default:
break;
}
return 0;
}
static int akmd_open(struct inode *inode, struct file *file)
{
int err = 0;
FUNCDBG("called");
err = nonseekable_open(inode, file);
if (err)
return err;
file->private_data = akmd_data;
return 0;
}
static int akmd_release(struct inode *inode, struct file *file)
{
struct akm8975_data *akm = file->private_data;
FUNCDBG("called");
akm8975_ecs_close_done(akm);
return 0;
}
static int akmd_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *) arg;
char rwbuf[16];
int ret = -1;
int status;
short value[12];
short delay;
struct akm8975_data *akm = file->private_data;
FUNCDBG("called");
switch (cmd) {
case ECS_IOCTL_READ:
case ECS_IOCTL_WRITE:
if (copy_from_user(&rwbuf, argp, sizeof(rwbuf)))
return -EFAULT;
break;
case ECS_IOCTL_SET_YPR:
if (copy_from_user(&value, argp, sizeof(value)))
return -EFAULT;
break;
default:
break;
}
switch (cmd) {
case ECS_IOCTL_READ:
if (rwbuf[0] < 1)
return -EINVAL;
ret = akm8975_i2c_rxdata(akm, &rwbuf[1], rwbuf[0]);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_WRITE:
if (rwbuf[0] < 2)
return -EINVAL;
ret = akm8975_i2c_txdata(akm, &rwbuf[1], rwbuf[0]);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_SET_YPR:
akm8975_ecs_report_value(akm, value);
break;
case ECS_IOCTL_GET_OPEN_STATUS:
wait_event_interruptible(open_wq,
(atomic_read(&open_flag) != 0));
status = atomic_read(&open_flag);
break;
case ECS_IOCTL_GET_CLOSE_STATUS:
wait_event_interruptible(open_wq,
(atomic_read(&open_flag) == 0));
status = atomic_read(&open_flag);
break;
case ECS_IOCTL_GET_DELAY:
delay = akmd_delay;
break;
default:
FUNCDBG("Unknown cmd\n");
return -ENOTTY;
}
switch (cmd) {
case ECS_IOCTL_READ:
if (copy_to_user(argp, &rwbuf, sizeof(rwbuf)))
return -EFAULT;
break;
case ECS_IOCTL_GET_OPEN_STATUS:
case ECS_IOCTL_GET_CLOSE_STATUS:
if (copy_to_user(argp, &status, sizeof(status)))
return -EFAULT;
break;
case ECS_IOCTL_GET_DELAY:
if (copy_to_user(argp, &delay, sizeof(delay)))
return -EFAULT;
break;
default:
break;
}
return 0;
}
/* needed to clear the int. pin */
static void akm_work_func(struct work_struct *work)
{
struct akm8975_data *akm =
container_of(work, struct akm8975_data, work);
FUNCDBG("called");
enable_irq(akm->this_client->irq);
}
static irqreturn_t akm8975_interrupt(int irq, void *dev_id)
{
struct akm8975_data *akm = dev_id;
FUNCDBG("called");
disable_irq_nosync(akm->this_client->irq);
schedule_work(&akm->work);
return IRQ_HANDLED;
}
static int akm8975_power_off(struct akm8975_data *akm)
{
#if AK8975DRV_CALL_DBG
pr_info("%s\n", __func__);
#endif
if (akm->pdata->power_off)
akm->pdata->power_off();
return 0;
}
static int akm8975_power_on(struct akm8975_data *akm)
{
int err;
#if AK8975DRV_CALL_DBG
pr_info("%s\n", __func__);
#endif
if (akm->pdata->power_on) {
err = akm->pdata->power_on();
if (err < 0)
return err;
}
return 0;
}
static int akm8975_suspend(struct i2c_client *client, pm_message_t mesg)
{
struct akm8975_data *akm = i2c_get_clientdata(client);
#if AK8975DRV_CALL_DBG
pr_info("%s\n", __func__);
#endif
/* TO DO: might need more work after power mgmt
is enabled */
return akm8975_power_off(akm);
}
static int akm8975_resume(struct i2c_client *client)
{
struct akm8975_data *akm = i2c_get_clientdata(client);
#if AK8975DRV_CALL_DBG
pr_info("%s\n", __func__);
#endif
/* TO DO: might need more work after power mgmt
is enabled */
return akm8975_power_on(akm);
}
#ifdef CONFIG_HAS_EARLYSUSPEND
static void akm8975_early_suspend(struct early_suspend *handler)
{
struct akm8975_data *akm;
akm = container_of(handler, struct akm8975_data, early_suspend);
#if AK8975DRV_CALL_DBG
pr_info("%s\n", __func__);
#endif
akm8975_suspend(akm->this_client, PMSG_SUSPEND);
}
static void akm8975_early_resume(struct early_suspend *handler)
{
struct akm8975_data *akm;
akm = container_of(handler, struct akm8975_data, early_suspend);
#if AK8975DRV_CALL_DBG
pr_info("%s\n", __func__);
#endif
akm8975_resume(akm->this_client);
}
#endif
static int akm8975_init_client(struct i2c_client *client)
{
struct akm8975_data *data;
int ret;
data = i2c_get_clientdata(client);
ret = request_irq(client->irq, akm8975_interrupt, IRQF_TRIGGER_RISING,
"akm8975", data);
if (ret < 0) {
pr_err("akm8975_init_client: request irq failed\n");
goto err;
}
init_waitqueue_head(&open_wq);
mutex_lock(&data->flags_lock);
m_flag = 1;
a_flag = 1;
t_flag = 1;
mv_flag = 1;
mutex_unlock(&data->flags_lock);
return 0;
err:
return ret;
}
static const struct file_operations akmd_fops = {
.owner = THIS_MODULE,
.open = akmd_open,
.release = akmd_release,
.ioctl = akmd_ioctl,
};
static const struct file_operations akm_aot_fops = {
.owner = THIS_MODULE,
.open = akm_aot_open,
.release = akm_aot_release,
.ioctl = akm_aot_ioctl,
};
static struct miscdevice akm_aot_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "akm8975_aot",
.fops = &akm_aot_fops,
};
static struct miscdevice akmd_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "akm8975_dev",
.fops = &akmd_fops,
};
int akm8975_probe(struct i2c_client *client,
const struct i2c_device_id *devid)
{
struct akm8975_data *akm;
int err;
FUNCDBG("called");
if (client->dev.platform_data == NULL) {
dev_err(&client->dev, "platform data is NULL. exiting.\n");
err = -ENODEV;
goto exit_platform_data_null;
}
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
dev_err(&client->dev, "platform data is NULL. exiting.\n");
err = -ENODEV;
goto exit_check_functionality_failed;
}
akm = kzalloc(sizeof(struct akm8975_data), GFP_KERNEL);
if (!akm) {
dev_err(&client->dev,
"failed to allocate memory for module data\n");
err = -ENOMEM;
goto exit_alloc_data_failed;
}
akm->pdata = client->dev.platform_data;
mutex_init(&akm->flags_lock);
INIT_WORK(&akm->work, akm_work_func);
i2c_set_clientdata(client, akm);
err = akm8975_power_on(akm);
if (err < 0)
goto exit_power_on_failed;
akm8975_init_client(client);
akm->this_client = client;
akmd_data = akm;
akm->input_dev = input_allocate_device();
if (!akm->input_dev) {
err = -ENOMEM;
dev_err(&akm->this_client->dev,
"input device allocate failed\n");
goto exit_input_dev_alloc_failed;
}
set_bit(EV_ABS, akm->input_dev->evbit);
/* yaw */
input_set_abs_params(akm->input_dev, ABS_RX, 0, 23040, 0, 0);
/* pitch */
input_set_abs_params(akm->input_dev, ABS_RY, -11520, 11520, 0, 0);
/* roll */
input_set_abs_params(akm->input_dev, ABS_RZ, -5760, 5760, 0, 0);
/* x-axis acceleration */
input_set_abs_params(akm->input_dev, ABS_X, -5760, 5760, 0, 0);
/* y-axis acceleration */
input_set_abs_params(akm->input_dev, ABS_Y, -5760, 5760, 0, 0);
/* z-axis acceleration */
input_set_abs_params(akm->input_dev, ABS_Z, -5760, 5760, 0, 0);
/* temparature */
input_set_abs_params(akm->input_dev, ABS_THROTTLE, -30, 85, 0, 0);
/* status of magnetic sensor */
input_set_abs_params(akm->input_dev, ABS_RUDDER, 0, 3, 0, 0);
/* status of acceleration sensor */
input_set_abs_params(akm->input_dev, ABS_WHEEL, 0, 3, 0, 0);
/* x-axis of raw magnetic vector */
input_set_abs_params(akm->input_dev, ABS_HAT0X, -20480, 20479, 0, 0);
/* y-axis of raw magnetic vector */
input_set_abs_params(akm->input_dev, ABS_HAT0Y, -20480, 20479, 0, 0);
/* z-axis of raw magnetic vector */
input_set_abs_params(akm->input_dev, ABS_BRAKE, -20480, 20479, 0, 0);
akm->input_dev->name = "compass";
err = input_register_device(akm->input_dev);
if (err) {
pr_err("akm8975_probe: Unable to register input device: %s\n",
akm->input_dev->name);
goto exit_input_register_device_failed;
}
err = misc_register(&akmd_device);
if (err) {
pr_err("akm8975_probe: akmd_device register failed\n");
goto exit_misc_device_register_failed;
}
err = misc_register(&akm_aot_device);
if (err) {
pr_err("akm8975_probe: akm_aot_device register failed\n");
goto exit_misc_device_register_failed;
}
err = device_create_file(&client->dev, &dev_attr_akm_ms1);
#ifdef CONFIG_HAS_EARLYSUSPEND
akm->early_suspend.suspend = akm8975_early_suspend;
akm->early_suspend.resume = akm8975_early_resume;
register_early_suspend(&akm->early_suspend);
#endif
return 0;
exit_misc_device_register_failed:
exit_input_register_device_failed:
input_free_device(akm->input_dev);
exit_input_dev_alloc_failed:
akm8975_power_off(akm);
exit_power_on_failed:
kfree(akm);
exit_alloc_data_failed:
exit_check_functionality_failed:
exit_platform_data_null:
return err;
}
static int __devexit akm8975_remove(struct i2c_client *client)
{
struct akm8975_data *akm = i2c_get_clientdata(client);
FUNCDBG("called");
free_irq(client->irq, NULL);
input_unregister_device(akm->input_dev);
misc_deregister(&akmd_device);
misc_deregister(&akm_aot_device);
akm8975_power_off(akm);
kfree(akm);
return 0;
}
static const struct i2c_device_id akm8975_id[] = {
{ "akm8975", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, akm8975_id);
static struct i2c_driver akm8975_driver = {
.probe = akm8975_probe,
.remove = akm8975_remove,
#ifndef CONFIG_HAS_EARLYSUSPEND
.resume = akm8975_resume,
.suspend = akm8975_suspend,
#endif
.id_table = akm8975_id,
.driver = {
.name = "akm8975",
},
};
static int __init akm8975_init(void)
{
pr_info("AK8975 compass driver: init\n");
FUNCDBG("AK8975 compass driver: init\n");
return i2c_add_driver(&akm8975_driver);
}
static void __exit akm8975_exit(void)
{
FUNCDBG("AK8975 compass driver: exit\n");
i2c_del_driver(&akm8975_driver);
}
module_init(akm8975_init);
module_exit(akm8975_exit);
MODULE_AUTHOR("Hou-Kun Chen <hk_chen@htc.com>");
MODULE_DESCRIPTION("AK8975 compass driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
flar2/m8-Sense-5.0.1 | fs/affs/bitmap.c | 9127 | 9001 | /*
* linux/fs/affs/bitmap.c
*
* (c) 1996 Hans-Joachim Widmaier
*
* bitmap.c contains the code that handles all bitmap related stuff -
* block allocation, deallocation, calculation of free space.
*/
#include <linux/slab.h>
#include "affs.h"
/* This is, of course, shamelessly stolen from fs/minix */
static const int nibblemap[] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4 };
static u32
affs_count_free_bits(u32 blocksize, const void *data)
{
const u32 *map;
u32 free;
u32 tmp;
map = data;
free = 0;
for (blocksize /= 4; blocksize > 0; blocksize--) {
tmp = *map++;
while (tmp) {
free += nibblemap[tmp & 0xf];
tmp >>= 4;
}
}
return free;
}
u32
affs_count_free_blocks(struct super_block *sb)
{
struct affs_bm_info *bm;
u32 free;
int i;
pr_debug("AFFS: count_free_blocks()\n");
if (sb->s_flags & MS_RDONLY)
return 0;
mutex_lock(&AFFS_SB(sb)->s_bmlock);
bm = AFFS_SB(sb)->s_bitmap;
free = 0;
for (i = AFFS_SB(sb)->s_bmap_count; i > 0; bm++, i--)
free += bm->bm_free;
mutex_unlock(&AFFS_SB(sb)->s_bmlock);
return free;
}
void
affs_free_block(struct super_block *sb, u32 block)
{
struct affs_sb_info *sbi = AFFS_SB(sb);
struct affs_bm_info *bm;
struct buffer_head *bh;
u32 blk, bmap, bit, mask, tmp;
__be32 *data;
pr_debug("AFFS: free_block(%u)\n", block);
if (block > sbi->s_partition_size)
goto err_range;
blk = block - sbi->s_reserved;
bmap = blk / sbi->s_bmap_bits;
bit = blk % sbi->s_bmap_bits;
bm = &sbi->s_bitmap[bmap];
mutex_lock(&sbi->s_bmlock);
bh = sbi->s_bmap_bh;
if (sbi->s_last_bmap != bmap) {
affs_brelse(bh);
bh = affs_bread(sb, bm->bm_key);
if (!bh)
goto err_bh_read;
sbi->s_bmap_bh = bh;
sbi->s_last_bmap = bmap;
}
mask = 1 << (bit & 31);
data = (__be32 *)bh->b_data + bit / 32 + 1;
/* mark block free */
tmp = be32_to_cpu(*data);
if (tmp & mask)
goto err_free;
*data = cpu_to_be32(tmp | mask);
/* fix checksum */
tmp = be32_to_cpu(*(__be32 *)bh->b_data);
*(__be32 *)bh->b_data = cpu_to_be32(tmp - mask);
mark_buffer_dirty(bh);
sb->s_dirt = 1;
bm->bm_free++;
mutex_unlock(&sbi->s_bmlock);
return;
err_free:
affs_warning(sb,"affs_free_block","Trying to free block %u which is already free", block);
mutex_unlock(&sbi->s_bmlock);
return;
err_bh_read:
affs_error(sb,"affs_free_block","Cannot read bitmap block %u", bm->bm_key);
sbi->s_bmap_bh = NULL;
sbi->s_last_bmap = ~0;
mutex_unlock(&sbi->s_bmlock);
return;
err_range:
affs_error(sb, "affs_free_block","Block %u outside partition", block);
return;
}
/*
* Allocate a block in the given allocation zone.
* Since we have to byte-swap the bitmap on little-endian
* machines, this is rather expensive. Therefore we will
* preallocate up to 16 blocks from the same word, if
* possible. We are not doing preallocations in the
* header zone, though.
*/
u32
affs_alloc_block(struct inode *inode, u32 goal)
{
struct super_block *sb;
struct affs_sb_info *sbi;
struct affs_bm_info *bm;
struct buffer_head *bh;
__be32 *data, *enddata;
u32 blk, bmap, bit, mask, mask2, tmp;
int i;
sb = inode->i_sb;
sbi = AFFS_SB(sb);
pr_debug("AFFS: balloc(inode=%lu,goal=%u): ", inode->i_ino, goal);
if (AFFS_I(inode)->i_pa_cnt) {
pr_debug("%d\n", AFFS_I(inode)->i_lastalloc+1);
AFFS_I(inode)->i_pa_cnt--;
return ++AFFS_I(inode)->i_lastalloc;
}
if (!goal || goal > sbi->s_partition_size) {
if (goal)
affs_warning(sb, "affs_balloc", "invalid goal %d", goal);
//if (!AFFS_I(inode)->i_last_block)
// affs_warning(sb, "affs_balloc", "no last alloc block");
goal = sbi->s_reserved;
}
blk = goal - sbi->s_reserved;
bmap = blk / sbi->s_bmap_bits;
bm = &sbi->s_bitmap[bmap];
mutex_lock(&sbi->s_bmlock);
if (bm->bm_free)
goto find_bmap_bit;
find_bmap:
/* search for the next bmap buffer with free bits */
i = sbi->s_bmap_count;
do {
if (--i < 0)
goto err_full;
bmap++;
bm++;
if (bmap < sbi->s_bmap_count)
continue;
/* restart search at zero */
bmap = 0;
bm = sbi->s_bitmap;
} while (!bm->bm_free);
blk = bmap * sbi->s_bmap_bits;
find_bmap_bit:
bh = sbi->s_bmap_bh;
if (sbi->s_last_bmap != bmap) {
affs_brelse(bh);
bh = affs_bread(sb, bm->bm_key);
if (!bh)
goto err_bh_read;
sbi->s_bmap_bh = bh;
sbi->s_last_bmap = bmap;
}
/* find an unused block in this bitmap block */
bit = blk % sbi->s_bmap_bits;
data = (__be32 *)bh->b_data + bit / 32 + 1;
enddata = (__be32 *)((u8 *)bh->b_data + sb->s_blocksize);
mask = ~0UL << (bit & 31);
blk &= ~31UL;
tmp = be32_to_cpu(*data);
if (tmp & mask)
goto find_bit;
/* scan the rest of the buffer */
do {
blk += 32;
if (++data >= enddata)
/* didn't find something, can only happen
* if scan didn't start at 0, try next bmap
*/
goto find_bmap;
} while (!*data);
tmp = be32_to_cpu(*data);
mask = ~0;
find_bit:
/* finally look for a free bit in the word */
bit = ffs(tmp & mask) - 1;
blk += bit + sbi->s_reserved;
mask2 = mask = 1 << (bit & 31);
AFFS_I(inode)->i_lastalloc = blk;
/* prealloc as much as possible within this word */
while ((mask2 <<= 1)) {
if (!(tmp & mask2))
break;
AFFS_I(inode)->i_pa_cnt++;
mask |= mask2;
}
bm->bm_free -= AFFS_I(inode)->i_pa_cnt + 1;
*data = cpu_to_be32(tmp & ~mask);
/* fix checksum */
tmp = be32_to_cpu(*(__be32 *)bh->b_data);
*(__be32 *)bh->b_data = cpu_to_be32(tmp + mask);
mark_buffer_dirty(bh);
sb->s_dirt = 1;
mutex_unlock(&sbi->s_bmlock);
pr_debug("%d\n", blk);
return blk;
err_bh_read:
affs_error(sb,"affs_read_block","Cannot read bitmap block %u", bm->bm_key);
sbi->s_bmap_bh = NULL;
sbi->s_last_bmap = ~0;
err_full:
mutex_unlock(&sbi->s_bmlock);
pr_debug("failed\n");
return 0;
}
int affs_init_bitmap(struct super_block *sb, int *flags)
{
struct affs_bm_info *bm;
struct buffer_head *bmap_bh = NULL, *bh = NULL;
__be32 *bmap_blk;
u32 size, blk, end, offset, mask;
int i, res = 0;
struct affs_sb_info *sbi = AFFS_SB(sb);
if (*flags & MS_RDONLY)
return 0;
if (!AFFS_ROOT_TAIL(sb, sbi->s_root_bh)->bm_flag) {
printk(KERN_NOTICE "AFFS: Bitmap invalid - mounting %s read only\n",
sb->s_id);
*flags |= MS_RDONLY;
return 0;
}
sbi->s_last_bmap = ~0;
sbi->s_bmap_bh = NULL;
sbi->s_bmap_bits = sb->s_blocksize * 8 - 32;
sbi->s_bmap_count = (sbi->s_partition_size - sbi->s_reserved +
sbi->s_bmap_bits - 1) / sbi->s_bmap_bits;
size = sbi->s_bmap_count * sizeof(*bm);
bm = sbi->s_bitmap = kzalloc(size, GFP_KERNEL);
if (!sbi->s_bitmap) {
printk(KERN_ERR "AFFS: Bitmap allocation failed\n");
return -ENOMEM;
}
bmap_blk = (__be32 *)sbi->s_root_bh->b_data;
blk = sb->s_blocksize / 4 - 49;
end = blk + 25;
for (i = sbi->s_bmap_count; i > 0; bm++, i--) {
affs_brelse(bh);
bm->bm_key = be32_to_cpu(bmap_blk[blk]);
bh = affs_bread(sb, bm->bm_key);
if (!bh) {
printk(KERN_ERR "AFFS: Cannot read bitmap\n");
res = -EIO;
goto out;
}
if (affs_checksum_block(sb, bh)) {
printk(KERN_WARNING "AFFS: Bitmap %u invalid - mounting %s read only.\n",
bm->bm_key, sb->s_id);
*flags |= MS_RDONLY;
goto out;
}
pr_debug("AFFS: read bitmap block %d: %d\n", blk, bm->bm_key);
bm->bm_free = affs_count_free_bits(sb->s_blocksize - 4, bh->b_data + 4);
/* Don't try read the extension if this is the last block,
* but we also need the right bm pointer below
*/
if (++blk < end || i == 1)
continue;
if (bmap_bh)
affs_brelse(bmap_bh);
bmap_bh = affs_bread(sb, be32_to_cpu(bmap_blk[blk]));
if (!bmap_bh) {
printk(KERN_ERR "AFFS: Cannot read bitmap extension\n");
res = -EIO;
goto out;
}
bmap_blk = (__be32 *)bmap_bh->b_data;
blk = 0;
end = sb->s_blocksize / 4 - 1;
}
offset = (sbi->s_partition_size - sbi->s_reserved) % sbi->s_bmap_bits;
mask = ~(0xFFFFFFFFU << (offset & 31));
pr_debug("last word: %d %d %d\n", offset, offset / 32 + 1, mask);
offset = offset / 32 + 1;
if (mask) {
u32 old, new;
/* Mark unused bits in the last word as allocated */
old = be32_to_cpu(((__be32 *)bh->b_data)[offset]);
new = old & mask;
//if (old != new) {
((__be32 *)bh->b_data)[offset] = cpu_to_be32(new);
/* fix checksum */
//new -= old;
//old = be32_to_cpu(*(__be32 *)bh->b_data);
//*(__be32 *)bh->b_data = cpu_to_be32(old - new);
//mark_buffer_dirty(bh);
//}
/* correct offset for the bitmap count below */
//offset++;
}
while (++offset < sb->s_blocksize / 4)
((__be32 *)bh->b_data)[offset] = 0;
((__be32 *)bh->b_data)[0] = 0;
((__be32 *)bh->b_data)[0] = cpu_to_be32(-affs_checksum_block(sb, bh));
mark_buffer_dirty(bh);
/* recalculate bitmap count for last block */
bm--;
bm->bm_free = affs_count_free_bits(sb->s_blocksize - 4, bh->b_data + 4);
out:
affs_brelse(bh);
affs_brelse(bmap_bh);
return res;
}
void affs_free_bitmap(struct super_block *sb)
{
struct affs_sb_info *sbi = AFFS_SB(sb);
if (!sbi->s_bitmap)
return;
affs_brelse(sbi->s_bmap_bh);
sbi->s_bmap_bh = NULL;
sbi->s_last_bmap = ~0;
kfree(sbi->s_bitmap);
sbi->s_bitmap = NULL;
}
| gpl-2.0 |
NoelMacwan/SXDNickiDS | drivers/infiniband/hw/mthca/mthca_catas.c | 9639 | 5347 | /*
* Copyright (c) 2005 Cisco Systems. 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/jiffies.h>
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include "mthca_dev.h"
enum {
MTHCA_CATAS_POLL_INTERVAL = 5 * HZ,
MTHCA_CATAS_TYPE_INTERNAL = 0,
MTHCA_CATAS_TYPE_UPLINK = 3,
MTHCA_CATAS_TYPE_DDR = 4,
MTHCA_CATAS_TYPE_PARITY = 5,
};
static DEFINE_SPINLOCK(catas_lock);
static LIST_HEAD(catas_list);
static struct workqueue_struct *catas_wq;
static struct work_struct catas_work;
static int catas_reset_disable;
module_param_named(catas_reset_disable, catas_reset_disable, int, 0644);
MODULE_PARM_DESC(catas_reset_disable, "disable reset on catastrophic event if nonzero");
static void catas_reset(struct work_struct *work)
{
struct mthca_dev *dev, *tmpdev;
LIST_HEAD(tlist);
int ret;
mutex_lock(&mthca_device_mutex);
spin_lock_irq(&catas_lock);
list_splice_init(&catas_list, &tlist);
spin_unlock_irq(&catas_lock);
list_for_each_entry_safe(dev, tmpdev, &tlist, catas_err.list) {
struct pci_dev *pdev = dev->pdev;
ret = __mthca_restart_one(dev->pdev);
/* 'dev' now is not valid */
if (ret)
printk(KERN_ERR "mthca %s: Reset failed (%d)\n",
pci_name(pdev), ret);
else {
struct mthca_dev *d = pci_get_drvdata(pdev);
mthca_dbg(d, "Reset succeeded\n");
}
}
mutex_unlock(&mthca_device_mutex);
}
static void handle_catas(struct mthca_dev *dev)
{
struct ib_event event;
unsigned long flags;
const char *type;
int i;
event.device = &dev->ib_dev;
event.event = IB_EVENT_DEVICE_FATAL;
event.element.port_num = 0;
dev->active = false;
ib_dispatch_event(&event);
switch (swab32(readl(dev->catas_err.map)) >> 24) {
case MTHCA_CATAS_TYPE_INTERNAL:
type = "internal error";
break;
case MTHCA_CATAS_TYPE_UPLINK:
type = "uplink bus error";
break;
case MTHCA_CATAS_TYPE_DDR:
type = "DDR data error";
break;
case MTHCA_CATAS_TYPE_PARITY:
type = "internal parity error";
break;
default:
type = "unknown error";
break;
}
mthca_err(dev, "Catastrophic error detected: %s\n", type);
for (i = 0; i < dev->catas_err.size; ++i)
mthca_err(dev, " buf[%02x]: %08x\n",
i, swab32(readl(dev->catas_err.map + i)));
if (catas_reset_disable)
return;
spin_lock_irqsave(&catas_lock, flags);
list_add(&dev->catas_err.list, &catas_list);
queue_work(catas_wq, &catas_work);
spin_unlock_irqrestore(&catas_lock, flags);
}
static void poll_catas(unsigned long dev_ptr)
{
struct mthca_dev *dev = (struct mthca_dev *) dev_ptr;
int i;
for (i = 0; i < dev->catas_err.size; ++i)
if (readl(dev->catas_err.map + i)) {
handle_catas(dev);
return;
}
mod_timer(&dev->catas_err.timer,
round_jiffies(jiffies + MTHCA_CATAS_POLL_INTERVAL));
}
void mthca_start_catas_poll(struct mthca_dev *dev)
{
phys_addr_t addr;
init_timer(&dev->catas_err.timer);
dev->catas_err.map = NULL;
addr = pci_resource_start(dev->pdev, 0) +
((pci_resource_len(dev->pdev, 0) - 1) &
dev->catas_err.addr);
dev->catas_err.map = ioremap(addr, dev->catas_err.size * 4);
if (!dev->catas_err.map) {
mthca_warn(dev, "couldn't map catastrophic error region "
"at 0x%llx/0x%x\n", (unsigned long long) addr,
dev->catas_err.size * 4);
return;
}
dev->catas_err.timer.data = (unsigned long) dev;
dev->catas_err.timer.function = poll_catas;
dev->catas_err.timer.expires = jiffies + MTHCA_CATAS_POLL_INTERVAL;
INIT_LIST_HEAD(&dev->catas_err.list);
add_timer(&dev->catas_err.timer);
}
void mthca_stop_catas_poll(struct mthca_dev *dev)
{
del_timer_sync(&dev->catas_err.timer);
if (dev->catas_err.map)
iounmap(dev->catas_err.map);
spin_lock_irq(&catas_lock);
list_del(&dev->catas_err.list);
spin_unlock_irq(&catas_lock);
}
int __init mthca_catas_init(void)
{
INIT_WORK(&catas_work, catas_reset);
catas_wq = create_singlethread_workqueue("mthca_catas");
if (!catas_wq)
return -ENOMEM;
return 0;
}
void mthca_catas_cleanup(void)
{
destroy_workqueue(catas_wq);
}
| gpl-2.0 |
fat-tire/omap | drivers/usb/misc/sisusbvga/sisusb_con.c | 11431 | 36803 | /*
* sisusb - usb kernel driver for SiS315(E) based USB2VGA dongles
*
* VGA text mode console part
*
* Copyright (C) 2005 by Thomas Winischhofer, Vienna, Austria
*
* If distributed as part of the Linux kernel, this code is licensed under the
* terms of the GPL v2.
*
* Otherwise, the following license terms apply:
*
* * Redistribution and use in source and binary forms, with or without
* * modification, are permitted provided that the following conditions
* * are met:
* * 1) Redistributions of source code must retain the above copyright
* * notice, this list of conditions and the following disclaimer.
* * 2) Redistributions in binary form must reproduce the above copyright
* * notice, this list of conditions and the following disclaimer in the
* * documentation and/or other materials provided with the distribution.
* * 3) The name of the author may not be used to endorse or promote products
* * derived from this software without specific psisusbr written permission.
* *
* * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESSED 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.
*
* Author: Thomas Winischhofer <thomas@winischhofer.net>
*
* Portions based on vgacon.c which are
* Created 28 Sep 1997 by Geert Uytterhoeven
* Rewritten by Martin Mares <mj@ucw.cz>, July 1998
* based on code Copyright (C) 1991, 1992 Linus Torvalds
* 1995 Jay Estabrook
*
* A note on using in_atomic() in here: We can't handle console
* calls from non-schedulable context due to our USB-dependend
* nature. For now, this driver just ignores any calls if it
* detects this state.
*
*/
#include <linux/mutex.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/fs.h>
#include <linux/usb.h>
#include <linux/tty.h>
#include <linux/console.h>
#include <linux/string.h>
#include <linux/kd.h>
#include <linux/init.h>
#include <linux/vt_kern.h>
#include <linux/selection.h>
#include <linux/spinlock.h>
#include <linux/kref.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/vmalloc.h>
#include "sisusb.h"
#include "sisusb_init.h"
#ifdef INCL_SISUSB_CON
#define sisusbcon_writew(val, addr) (*(addr) = (val))
#define sisusbcon_readw(addr) (*(addr))
#define sisusbcon_memmovew(d, s, c) memmove(d, s, c)
#define sisusbcon_memcpyw(d, s, c) memcpy(d, s, c)
/* vc_data -> sisusb conversion table */
static struct sisusb_usb_data *mysisusbs[MAX_NR_CONSOLES];
/* Forward declaration */
static const struct consw sisusb_con;
static inline void
sisusbcon_memsetw(u16 *s, u16 c, unsigned int count)
{
count /= 2;
while (count--)
sisusbcon_writew(c, s++);
}
static inline void
sisusb_initialize(struct sisusb_usb_data *sisusb)
{
/* Reset cursor and start address */
if (sisusb_setidxreg(sisusb, SISCR, 0x0c, 0x00))
return;
if (sisusb_setidxreg(sisusb, SISCR, 0x0d, 0x00))
return;
if (sisusb_setidxreg(sisusb, SISCR, 0x0e, 0x00))
return;
sisusb_setidxreg(sisusb, SISCR, 0x0f, 0x00);
}
static inline void
sisusbcon_set_start_address(struct sisusb_usb_data *sisusb, struct vc_data *c)
{
sisusb->cur_start_addr = (c->vc_visible_origin - sisusb->scrbuf) / 2;
sisusb_setidxreg(sisusb, SISCR, 0x0c, (sisusb->cur_start_addr >> 8));
sisusb_setidxreg(sisusb, SISCR, 0x0d, (sisusb->cur_start_addr & 0xff));
}
void
sisusb_set_cursor(struct sisusb_usb_data *sisusb, unsigned int location)
{
if (sisusb->sisusb_cursor_loc == location)
return;
sisusb->sisusb_cursor_loc = location;
/* Hardware bug: Text cursor appears twice or not at all
* at some positions. Work around it with the cursor skew
* bits.
*/
if ((location & 0x0007) == 0x0007) {
sisusb->bad_cursor_pos = 1;
location--;
if (sisusb_setidxregandor(sisusb, SISCR, 0x0b, 0x1f, 0x20))
return;
} else if (sisusb->bad_cursor_pos) {
if (sisusb_setidxregand(sisusb, SISCR, 0x0b, 0x1f))
return;
sisusb->bad_cursor_pos = 0;
}
if (sisusb_setidxreg(sisusb, SISCR, 0x0e, (location >> 8)))
return;
sisusb_setidxreg(sisusb, SISCR, 0x0f, (location & 0xff));
}
static inline struct sisusb_usb_data *
sisusb_get_sisusb(unsigned short console)
{
return mysisusbs[console];
}
static inline int
sisusb_sisusb_valid(struct sisusb_usb_data *sisusb)
{
if (!sisusb->present || !sisusb->ready || !sisusb->sisusb_dev)
return 0;
return 1;
}
static struct sisusb_usb_data *
sisusb_get_sisusb_lock_and_check(unsigned short console)
{
struct sisusb_usb_data *sisusb;
/* We can't handle console calls in non-schedulable
* context due to our locks and the USB transport.
* So we simply ignore them. This should only affect
* some calls to printk.
*/
if (in_atomic())
return NULL;
if (!(sisusb = sisusb_get_sisusb(console)))
return NULL;
mutex_lock(&sisusb->lock);
if (!sisusb_sisusb_valid(sisusb) ||
!sisusb->havethisconsole[console]) {
mutex_unlock(&sisusb->lock);
return NULL;
}
return sisusb;
}
static int
sisusb_is_inactive(struct vc_data *c, struct sisusb_usb_data *sisusb)
{
if (sisusb->is_gfx ||
sisusb->textmodedestroyed ||
c->vc_mode != KD_TEXT)
return 1;
return 0;
}
/* con_startup console interface routine */
static const char *
sisusbcon_startup(void)
{
return "SISUSBCON";
}
/* con_init console interface routine */
static void
sisusbcon_init(struct vc_data *c, int init)
{
struct sisusb_usb_data *sisusb;
int cols, rows;
/* This is called by take_over_console(),
* ie by us/under our control. It is
* only called after text mode and fonts
* are set up/restored.
*/
if (!(sisusb = sisusb_get_sisusb(c->vc_num)))
return;
mutex_lock(&sisusb->lock);
if (!sisusb_sisusb_valid(sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
c->vc_can_do_color = 1;
c->vc_complement_mask = 0x7700;
c->vc_hi_font_mask = sisusb->current_font_512 ? 0x0800 : 0;
sisusb->haveconsole = 1;
sisusb->havethisconsole[c->vc_num] = 1;
/* We only support 640x400 */
c->vc_scan_lines = 400;
c->vc_font.height = sisusb->current_font_height;
/* We only support width = 8 */
cols = 80;
rows = c->vc_scan_lines / c->vc_font.height;
/* Increment usage count for our sisusb.
* Doing so saves us from upping/downing
* the disconnect semaphore; we can't
* lose our sisusb until this is undone
* in con_deinit. For all other console
* interface functions, it suffices to
* use sisusb->lock and do a quick check
* of sisusb for device disconnection.
*/
kref_get(&sisusb->kref);
if (!*c->vc_uni_pagedir_loc)
con_set_default_unimap(c);
mutex_unlock(&sisusb->lock);
if (init) {
c->vc_cols = cols;
c->vc_rows = rows;
} else
vc_resize(c, cols, rows);
}
/* con_deinit console interface routine */
static void
sisusbcon_deinit(struct vc_data *c)
{
struct sisusb_usb_data *sisusb;
int i;
/* This is called by take_over_console()
* and others, ie not under our control.
*/
if (!(sisusb = sisusb_get_sisusb(c->vc_num)))
return;
mutex_lock(&sisusb->lock);
/* Clear ourselves in mysisusbs */
mysisusbs[c->vc_num] = NULL;
sisusb->havethisconsole[c->vc_num] = 0;
/* Free our font buffer if all consoles are gone */
if (sisusb->font_backup) {
for(i = 0; i < MAX_NR_CONSOLES; i++) {
if (sisusb->havethisconsole[c->vc_num])
break;
}
if (i == MAX_NR_CONSOLES) {
vfree(sisusb->font_backup);
sisusb->font_backup = NULL;
}
}
mutex_unlock(&sisusb->lock);
/* decrement the usage count on our sisusb */
kref_put(&sisusb->kref, sisusb_delete);
}
/* interface routine */
static u8
sisusbcon_build_attr(struct vc_data *c, u8 color, u8 intensity,
u8 blink, u8 underline, u8 reverse, u8 unused)
{
u8 attr = color;
if (underline)
attr = (attr & 0xf0) | c->vc_ulcolor;
else if (intensity == 0)
attr = (attr & 0xf0) | c->vc_halfcolor;
if (reverse)
attr = ((attr) & 0x88) |
((((attr) >> 4) |
((attr) << 4)) & 0x77);
if (blink)
attr ^= 0x80;
if (intensity == 2)
attr ^= 0x08;
return attr;
}
/* Interface routine */
static void
sisusbcon_invert_region(struct vc_data *vc, u16 *p, int count)
{
/* Invert a region. This is called with a pointer
* to the console's internal screen buffer. So we
* simply do the inversion there and rely on
* a call to putc(s) to update the real screen.
*/
while (count--) {
u16 a = sisusbcon_readw(p);
a = ((a) & 0x88ff) |
(((a) & 0x7000) >> 4) |
(((a) & 0x0700) << 4);
sisusbcon_writew(a, p++);
}
}
#define SISUSB_VADDR(x,y) \
((u16 *)c->vc_origin + \
(y) * sisusb->sisusb_num_columns + \
(x))
#define SISUSB_HADDR(x,y) \
((u16 *)(sisusb->vrambase + (c->vc_origin - sisusb->scrbuf)) + \
(y) * sisusb->sisusb_num_columns + \
(x))
/* Interface routine */
static void
sisusbcon_putc(struct vc_data *c, int ch, int y, int x)
{
struct sisusb_usb_data *sisusb;
ssize_t written;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
sisusb_copy_memory(sisusb, (char *)SISUSB_VADDR(x, y),
(long)SISUSB_HADDR(x, y), 2, &written);
mutex_unlock(&sisusb->lock);
}
/* Interface routine */
static void
sisusbcon_putcs(struct vc_data *c, const unsigned short *s,
int count, int y, int x)
{
struct sisusb_usb_data *sisusb;
ssize_t written;
u16 *dest;
int i;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return;
/* sisusb->lock is down */
/* Need to put the characters into the buffer ourselves,
* because the vt does this AFTER calling us.
*/
dest = SISUSB_VADDR(x, y);
for (i = count; i > 0; i--)
sisusbcon_writew(sisusbcon_readw(s++), dest++);
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
sisusb_copy_memory(sisusb, (char *)SISUSB_VADDR(x, y),
(long)SISUSB_HADDR(x, y), count * 2, &written);
mutex_unlock(&sisusb->lock);
}
/* Interface routine */
static void
sisusbcon_clear(struct vc_data *c, int y, int x, int height, int width)
{
struct sisusb_usb_data *sisusb;
u16 eattr = c->vc_video_erase_char;
ssize_t written;
int i, length, cols;
u16 *dest;
if (width <= 0 || height <= 0)
return;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return;
/* sisusb->lock is down */
/* Need to clear buffer ourselves, because the vt does
* this AFTER calling us.
*/
dest = SISUSB_VADDR(x, y);
cols = sisusb->sisusb_num_columns;
if (width > cols)
width = cols;
if (x == 0 && width >= c->vc_cols) {
sisusbcon_memsetw(dest, eattr, height * cols * 2);
} else {
for (i = height; i > 0; i--, dest += cols)
sisusbcon_memsetw(dest, eattr, width * 2);
}
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
length = ((height * cols) - x - (cols - width - x)) * 2;
sisusb_copy_memory(sisusb, (unsigned char *)SISUSB_VADDR(x, y),
(long)SISUSB_HADDR(x, y), length, &written);
mutex_unlock(&sisusb->lock);
}
/* Interface routine */
static void
sisusbcon_bmove(struct vc_data *c, int sy, int sx,
int dy, int dx, int height, int width)
{
struct sisusb_usb_data *sisusb;
ssize_t written;
int cols, length;
if (width <= 0 || height <= 0)
return;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return;
/* sisusb->lock is down */
cols = sisusb->sisusb_num_columns;
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
length = ((height * cols) - dx - (cols - width - dx)) * 2;
sisusb_copy_memory(sisusb, (unsigned char *)SISUSB_VADDR(dx, dy),
(long)SISUSB_HADDR(dx, dy), length, &written);
mutex_unlock(&sisusb->lock);
}
/* interface routine */
static int
sisusbcon_switch(struct vc_data *c)
{
struct sisusb_usb_data *sisusb;
ssize_t written;
int length;
/* Returnvalue 0 means we have fully restored screen,
* and vt doesn't need to call do_update_region().
* Returnvalue != 0 naturally means the opposite.
*/
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return 0;
/* sisusb->lock is down */
/* Don't write to screen if in gfx mode */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return 0;
}
/* That really should not happen. It would mean we are
* being called while the vc is using its private buffer
* as origin.
*/
if (c->vc_origin == (unsigned long)c->vc_screenbuf) {
mutex_unlock(&sisusb->lock);
dev_dbg(&sisusb->sisusb_dev->dev, "ASSERT ORIGIN != SCREENBUF!\n");
return 0;
}
/* Check that we don't copy too much */
length = min((int)c->vc_screenbuf_size,
(int)(sisusb->scrbuf + sisusb->scrbuf_size - c->vc_origin));
/* Restore the screen contents */
sisusbcon_memcpyw((u16 *)c->vc_origin, (u16 *)c->vc_screenbuf,
length);
sisusb_copy_memory(sisusb, (unsigned char *)c->vc_origin,
(long)SISUSB_HADDR(0, 0),
length, &written);
mutex_unlock(&sisusb->lock);
return 0;
}
/* interface routine */
static void
sisusbcon_save_screen(struct vc_data *c)
{
struct sisusb_usb_data *sisusb;
int length;
/* Save the current screen contents to vc's private
* buffer.
*/
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
/* Check that we don't copy too much */
length = min((int)c->vc_screenbuf_size,
(int)(sisusb->scrbuf + sisusb->scrbuf_size - c->vc_origin));
/* Save the screen contents to vc's private buffer */
sisusbcon_memcpyw((u16 *)c->vc_screenbuf, (u16 *)c->vc_origin,
length);
mutex_unlock(&sisusb->lock);
}
/* interface routine */
static int
sisusbcon_set_palette(struct vc_data *c, unsigned char *table)
{
struct sisusb_usb_data *sisusb;
int i, j;
/* Return value not used by vt */
if (!CON_IS_VISIBLE(c))
return -EINVAL;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return -EINVAL;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return -EINVAL;
}
for (i = j = 0; i < 16; i++) {
if (sisusb_setreg(sisusb, SISCOLIDX, table[i]))
break;
if (sisusb_setreg(sisusb, SISCOLDATA, c->vc_palette[j++] >> 2))
break;
if (sisusb_setreg(sisusb, SISCOLDATA, c->vc_palette[j++] >> 2))
break;
if (sisusb_setreg(sisusb, SISCOLDATA, c->vc_palette[j++] >> 2))
break;
}
mutex_unlock(&sisusb->lock);
return 0;
}
/* interface routine */
static int
sisusbcon_blank(struct vc_data *c, int blank, int mode_switch)
{
struct sisusb_usb_data *sisusb;
u8 sr1, cr17, pmreg, cr63;
ssize_t written;
int ret = 0;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return 0;
/* sisusb->lock is down */
if (mode_switch)
sisusb->is_gfx = blank ? 1 : 0;
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return 0;
}
switch (blank) {
case 1: /* Normal blanking: Clear screen */
case -1:
sisusbcon_memsetw((u16 *)c->vc_origin,
c->vc_video_erase_char,
c->vc_screenbuf_size);
sisusb_copy_memory(sisusb,
(unsigned char *)c->vc_origin,
(u32)(sisusb->vrambase +
(c->vc_origin - sisusb->scrbuf)),
c->vc_screenbuf_size, &written);
sisusb->con_blanked = 1;
ret = 1;
break;
default: /* VESA blanking */
switch (blank) {
case 0: /* Unblank */
sr1 = 0x00;
cr17 = 0x80;
pmreg = 0x00;
cr63 = 0x00;
ret = 1;
sisusb->con_blanked = 0;
break;
case VESA_VSYNC_SUSPEND + 1:
sr1 = 0x20;
cr17 = 0x80;
pmreg = 0x80;
cr63 = 0x40;
break;
case VESA_HSYNC_SUSPEND + 1:
sr1 = 0x20;
cr17 = 0x80;
pmreg = 0x40;
cr63 = 0x40;
break;
case VESA_POWERDOWN + 1:
sr1 = 0x20;
cr17 = 0x00;
pmreg = 0xc0;
cr63 = 0x40;
break;
default:
mutex_unlock(&sisusb->lock);
return -EINVAL;
}
sisusb_setidxregandor(sisusb, SISSR, 0x01, ~0x20, sr1);
sisusb_setidxregandor(sisusb, SISCR, 0x17, 0x7f, cr17);
sisusb_setidxregandor(sisusb, SISSR, 0x1f, 0x3f, pmreg);
sisusb_setidxregandor(sisusb, SISCR, 0x63, 0xbf, cr63);
}
mutex_unlock(&sisusb->lock);
return ret;
}
/* interface routine */
static int
sisusbcon_scrolldelta(struct vc_data *c, int lines)
{
struct sisusb_usb_data *sisusb;
int margin = c->vc_size_row * 4;
int ul, we, p, st;
/* The return value does not seem to be used */
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return 0;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return 0;
}
if (!lines) /* Turn scrollback off */
c->vc_visible_origin = c->vc_origin;
else {
if (sisusb->con_rolled_over >
(c->vc_scr_end - sisusb->scrbuf) + margin) {
ul = c->vc_scr_end - sisusb->scrbuf;
we = sisusb->con_rolled_over + c->vc_size_row;
} else {
ul = 0;
we = sisusb->scrbuf_size;
}
p = (c->vc_visible_origin - sisusb->scrbuf - ul + we) % we +
lines * c->vc_size_row;
st = (c->vc_origin - sisusb->scrbuf - ul + we) % we;
if (st < 2 * margin)
margin = 0;
if (p < margin)
p = 0;
if (p > st - margin)
p = st;
c->vc_visible_origin = sisusb->scrbuf + (p + ul) % we;
}
sisusbcon_set_start_address(sisusb, c);
mutex_unlock(&sisusb->lock);
return 1;
}
/* Interface routine */
static void
sisusbcon_cursor(struct vc_data *c, int mode)
{
struct sisusb_usb_data *sisusb;
int from, to, baseline;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return;
}
if (c->vc_origin != c->vc_visible_origin) {
c->vc_visible_origin = c->vc_origin;
sisusbcon_set_start_address(sisusb, c);
}
if (mode == CM_ERASE) {
sisusb_setidxregor(sisusb, SISCR, 0x0a, 0x20);
sisusb->sisusb_cursor_size_to = -1;
mutex_unlock(&sisusb->lock);
return;
}
sisusb_set_cursor(sisusb, (c->vc_pos - sisusb->scrbuf) / 2);
baseline = c->vc_font.height - (c->vc_font.height < 10 ? 1 : 2);
switch (c->vc_cursor_type & 0x0f) {
case CUR_BLOCK: from = 1;
to = c->vc_font.height;
break;
case CUR_TWO_THIRDS: from = c->vc_font.height / 3;
to = baseline;
break;
case CUR_LOWER_HALF: from = c->vc_font.height / 2;
to = baseline;
break;
case CUR_LOWER_THIRD: from = (c->vc_font.height * 2) / 3;
to = baseline;
break;
case CUR_NONE: from = 31;
to = 30;
break;
default:
case CUR_UNDERLINE: from = baseline - 1;
to = baseline;
break;
}
if (sisusb->sisusb_cursor_size_from != from ||
sisusb->sisusb_cursor_size_to != to) {
sisusb_setidxreg(sisusb, SISCR, 0x0a, from);
sisusb_setidxregandor(sisusb, SISCR, 0x0b, 0xe0, to);
sisusb->sisusb_cursor_size_from = from;
sisusb->sisusb_cursor_size_to = to;
}
mutex_unlock(&sisusb->lock);
}
static int
sisusbcon_scroll_area(struct vc_data *c, struct sisusb_usb_data *sisusb,
int t, int b, int dir, int lines)
{
int cols = sisusb->sisusb_num_columns;
int length = ((b - t) * cols) * 2;
u16 eattr = c->vc_video_erase_char;
ssize_t written;
/* sisusb->lock is down */
/* Scroll an area which does not match the
* visible screen's dimensions. This needs
* to be done separately, as it does not
* use hardware panning.
*/
switch (dir) {
case SM_UP:
sisusbcon_memmovew(SISUSB_VADDR(0, t),
SISUSB_VADDR(0, t + lines),
(b - t - lines) * cols * 2);
sisusbcon_memsetw(SISUSB_VADDR(0, b - lines), eattr,
lines * cols * 2);
break;
case SM_DOWN:
sisusbcon_memmovew(SISUSB_VADDR(0, t + lines),
SISUSB_VADDR(0, t),
(b - t - lines) * cols * 2);
sisusbcon_memsetw(SISUSB_VADDR(0, t), eattr,
lines * cols * 2);
break;
}
sisusb_copy_memory(sisusb, (char *)SISUSB_VADDR(0, t),
(long)SISUSB_HADDR(0, t), length, &written);
mutex_unlock(&sisusb->lock);
return 1;
}
/* Interface routine */
static int
sisusbcon_scroll(struct vc_data *c, int t, int b, int dir, int lines)
{
struct sisusb_usb_data *sisusb;
u16 eattr = c->vc_video_erase_char;
ssize_t written;
int copyall = 0;
unsigned long oldorigin;
unsigned int delta = lines * c->vc_size_row;
u32 originoffset;
/* Returning != 0 means we have done the scrolling successfully.
* Returning 0 makes vt do the scrolling on its own.
* Note that con_scroll is only called if the console is
* visible. In that case, the origin should be our buffer,
* not the vt's private one.
*/
if (!lines)
return 1;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return 0;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb)) {
mutex_unlock(&sisusb->lock);
return 0;
}
/* Special case */
if (t || b != c->vc_rows)
return sisusbcon_scroll_area(c, sisusb, t, b, dir, lines);
if (c->vc_origin != c->vc_visible_origin) {
c->vc_visible_origin = c->vc_origin;
sisusbcon_set_start_address(sisusb, c);
}
/* limit amount to maximum realistic size */
if (lines > c->vc_rows)
lines = c->vc_rows;
oldorigin = c->vc_origin;
switch (dir) {
case SM_UP:
if (c->vc_scr_end + delta >=
sisusb->scrbuf + sisusb->scrbuf_size) {
sisusbcon_memcpyw((u16 *)sisusb->scrbuf,
(u16 *)(oldorigin + delta),
c->vc_screenbuf_size - delta);
c->vc_origin = sisusb->scrbuf;
sisusb->con_rolled_over = oldorigin - sisusb->scrbuf;
copyall = 1;
} else
c->vc_origin += delta;
sisusbcon_memsetw(
(u16 *)(c->vc_origin + c->vc_screenbuf_size - delta),
eattr, delta);
break;
case SM_DOWN:
if (oldorigin - delta < sisusb->scrbuf) {
sisusbcon_memmovew((u16 *)(sisusb->scrbuf +
sisusb->scrbuf_size -
c->vc_screenbuf_size +
delta),
(u16 *)oldorigin,
c->vc_screenbuf_size - delta);
c->vc_origin = sisusb->scrbuf +
sisusb->scrbuf_size -
c->vc_screenbuf_size;
sisusb->con_rolled_over = 0;
copyall = 1;
} else
c->vc_origin -= delta;
c->vc_scr_end = c->vc_origin + c->vc_screenbuf_size;
scr_memsetw((u16 *)(c->vc_origin), eattr, delta);
break;
}
originoffset = (u32)(c->vc_origin - sisusb->scrbuf);
if (copyall)
sisusb_copy_memory(sisusb,
(char *)c->vc_origin,
(u32)(sisusb->vrambase + originoffset),
c->vc_screenbuf_size, &written);
else if (dir == SM_UP)
sisusb_copy_memory(sisusb,
(char *)c->vc_origin + c->vc_screenbuf_size - delta,
(u32)sisusb->vrambase + originoffset +
c->vc_screenbuf_size - delta,
delta, &written);
else
sisusb_copy_memory(sisusb,
(char *)c->vc_origin,
(u32)(sisusb->vrambase + originoffset),
delta, &written);
c->vc_scr_end = c->vc_origin + c->vc_screenbuf_size;
c->vc_visible_origin = c->vc_origin;
sisusbcon_set_start_address(sisusb, c);
c->vc_pos = c->vc_pos - oldorigin + c->vc_origin;
mutex_unlock(&sisusb->lock);
return 1;
}
/* Interface routine */
static int
sisusbcon_set_origin(struct vc_data *c)
{
struct sisusb_usb_data *sisusb;
/* Returning != 0 means we were successful.
* Returning 0 will vt make to use its own
* screenbuffer as the origin.
*/
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return 0;
/* sisusb->lock is down */
if (sisusb_is_inactive(c, sisusb) || sisusb->con_blanked) {
mutex_unlock(&sisusb->lock);
return 0;
}
c->vc_origin = c->vc_visible_origin = sisusb->scrbuf;
sisusbcon_set_start_address(sisusb, c);
sisusb->con_rolled_over = 0;
mutex_unlock(&sisusb->lock);
return 1;
}
/* Interface routine */
static int
sisusbcon_resize(struct vc_data *c, unsigned int newcols, unsigned int newrows,
unsigned int user)
{
struct sisusb_usb_data *sisusb;
int fh;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return -ENODEV;
fh = sisusb->current_font_height;
mutex_unlock(&sisusb->lock);
/* We are quite unflexible as regards resizing. The vt code
* handles sizes where the line length isn't equal the pitch
* quite badly. As regards the rows, our panning tricks only
* work well if the number of rows equals the visible number
* of rows.
*/
if (newcols != 80 || c->vc_scan_lines / fh != newrows)
return -EINVAL;
return 0;
}
int
sisusbcon_do_font_op(struct sisusb_usb_data *sisusb, int set, int slot,
u8 *arg, int cmapsz, int ch512, int dorecalc,
struct vc_data *c, int fh, int uplock)
{
int font_select = 0x00, i, err = 0;
u32 offset = 0;
u8 dummy;
/* sisusb->lock is down */
/*
* The default font is kept in slot 0.
* A user font is loaded in slot 2 (256 ch)
* or 2+3 (512 ch).
*/
if ((slot != 0 && slot != 2) || !fh) {
if (uplock)
mutex_unlock(&sisusb->lock);
return -EINVAL;
}
if (set)
sisusb->font_slot = slot;
/* Default font is always 256 */
if (slot == 0)
ch512 = 0;
else
offset = 4 * cmapsz;
font_select = (slot == 0) ? 0x00 : (ch512 ? 0x0e : 0x0a);
err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x01); /* Reset */
err |= sisusb_setidxreg(sisusb, SISSR, 0x02, 0x04); /* Write to plane 2 */
err |= sisusb_setidxreg(sisusb, SISSR, 0x04, 0x07); /* Memory mode a0-bf */
err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x03); /* Reset */
if (err)
goto font_op_error;
err |= sisusb_setidxreg(sisusb, SISGR, 0x04, 0x03); /* Select plane read 2 */
err |= sisusb_setidxreg(sisusb, SISGR, 0x05, 0x00); /* Disable odd/even */
err |= sisusb_setidxreg(sisusb, SISGR, 0x06, 0x00); /* Address range a0-bf */
if (err)
goto font_op_error;
if (arg) {
if (set)
for (i = 0; i < cmapsz; i++) {
err |= sisusb_writeb(sisusb,
sisusb->vrambase + offset + i,
arg[i]);
if (err)
break;
}
else
for (i = 0; i < cmapsz; i++) {
err |= sisusb_readb(sisusb,
sisusb->vrambase + offset + i,
&arg[i]);
if (err)
break;
}
/*
* In 512-character mode, the character map is not contiguous if
* we want to remain EGA compatible -- which we do
*/
if (ch512) {
if (set)
for (i = 0; i < cmapsz; i++) {
err |= sisusb_writeb(sisusb,
sisusb->vrambase + offset +
(2 * cmapsz) + i,
arg[cmapsz + i]);
if (err)
break;
}
else
for (i = 0; i < cmapsz; i++) {
err |= sisusb_readb(sisusb,
sisusb->vrambase + offset +
(2 * cmapsz) + i,
&arg[cmapsz + i]);
if (err)
break;
}
}
}
if (err)
goto font_op_error;
err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x01); /* Reset */
err |= sisusb_setidxreg(sisusb, SISSR, 0x02, 0x03); /* Write to planes 0+1 */
err |= sisusb_setidxreg(sisusb, SISSR, 0x04, 0x03); /* Memory mode a0-bf */
if (set)
sisusb_setidxreg(sisusb, SISSR, 0x03, font_select);
err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x03); /* Reset end */
if (err)
goto font_op_error;
err |= sisusb_setidxreg(sisusb, SISGR, 0x04, 0x00); /* Select plane read 0 */
err |= sisusb_setidxreg(sisusb, SISGR, 0x05, 0x10); /* Enable odd/even */
err |= sisusb_setidxreg(sisusb, SISGR, 0x06, 0x06); /* Address range b8-bf */
if (err)
goto font_op_error;
if ((set) && (ch512 != sisusb->current_font_512)) {
/* Font is shared among all our consoles.
* And so is the hi_font_mask.
*/
for (i = 0; i < MAX_NR_CONSOLES; i++) {
struct vc_data *d = vc_cons[i].d;
if (d && d->vc_sw == &sisusb_con)
d->vc_hi_font_mask = ch512 ? 0x0800 : 0;
}
sisusb->current_font_512 = ch512;
/* color plane enable register:
256-char: enable intensity bit
512-char: disable intensity bit */
sisusb_getreg(sisusb, SISINPSTAT, &dummy);
sisusb_setreg(sisusb, SISAR, 0x12);
sisusb_setreg(sisusb, SISAR, ch512 ? 0x07 : 0x0f);
sisusb_getreg(sisusb, SISINPSTAT, &dummy);
sisusb_setreg(sisusb, SISAR, 0x20);
sisusb_getreg(sisusb, SISINPSTAT, &dummy);
}
if (dorecalc) {
/*
* Adjust the screen to fit a font of a certain height
*/
unsigned char ovr, vde, fsr;
int rows = 0, maxscan = 0;
if (c) {
/* Number of video rows */
rows = c->vc_scan_lines / fh;
/* Scan lines to actually display-1 */
maxscan = rows * fh - 1;
/*printk(KERN_DEBUG "sisusb recalc rows %d maxscan %d fh %d sl %d\n",
rows, maxscan, fh, c->vc_scan_lines);*/
sisusb_getidxreg(sisusb, SISCR, 0x07, &ovr);
vde = maxscan & 0xff;
ovr = (ovr & 0xbd) |
((maxscan & 0x100) >> 7) |
((maxscan & 0x200) >> 3);
sisusb_setidxreg(sisusb, SISCR, 0x07, ovr);
sisusb_setidxreg(sisusb, SISCR, 0x12, vde);
}
sisusb_getidxreg(sisusb, SISCR, 0x09, &fsr);
fsr = (fsr & 0xe0) | (fh - 1);
sisusb_setidxreg(sisusb, SISCR, 0x09, fsr);
sisusb->current_font_height = fh;
sisusb->sisusb_cursor_size_from = -1;
sisusb->sisusb_cursor_size_to = -1;
}
if (uplock)
mutex_unlock(&sisusb->lock);
if (dorecalc && c) {
int rows = c->vc_scan_lines / fh;
/* Now adjust our consoles' size */
for (i = 0; i < MAX_NR_CONSOLES; i++) {
struct vc_data *vc = vc_cons[i].d;
if (vc && vc->vc_sw == &sisusb_con) {
if (CON_IS_VISIBLE(vc)) {
vc->vc_sw->con_cursor(vc, CM_DRAW);
}
vc->vc_font.height = fh;
vc_resize(vc, 0, rows);
}
}
}
return 0;
font_op_error:
if (uplock)
mutex_unlock(&sisusb->lock);
return -EIO;
}
/* Interface routine */
static int
sisusbcon_font_set(struct vc_data *c, struct console_font *font,
unsigned flags)
{
struct sisusb_usb_data *sisusb;
unsigned charcount = font->charcount;
if (font->width != 8 || (charcount != 256 && charcount != 512))
return -EINVAL;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return -ENODEV;
/* sisusb->lock is down */
/* Save the user-provided font into a buffer. This
* is used for restoring text mode after quitting
* from X and for the con_getfont routine.
*/
if (sisusb->font_backup) {
if (sisusb->font_backup_size < charcount) {
vfree(sisusb->font_backup);
sisusb->font_backup = NULL;
}
}
if (!sisusb->font_backup)
sisusb->font_backup = vmalloc(charcount * 32);
if (sisusb->font_backup) {
memcpy(sisusb->font_backup, font->data, charcount * 32);
sisusb->font_backup_size = charcount;
sisusb->font_backup_height = font->height;
sisusb->font_backup_512 = (charcount == 512) ? 1 : 0;
}
/* do_font_op ups sisusb->lock */
return sisusbcon_do_font_op(sisusb, 1, 2, font->data,
8192, (charcount == 512),
(!(flags & KD_FONT_FLAG_DONT_RECALC)) ? 1 : 0,
c, font->height, 1);
}
/* Interface routine */
static int
sisusbcon_font_get(struct vc_data *c, struct console_font *font)
{
struct sisusb_usb_data *sisusb;
if (!(sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num)))
return -ENODEV;
/* sisusb->lock is down */
font->width = 8;
font->height = c->vc_font.height;
font->charcount = 256;
if (!font->data) {
mutex_unlock(&sisusb->lock);
return 0;
}
if (!sisusb->font_backup) {
mutex_unlock(&sisusb->lock);
return -ENODEV;
}
/* Copy 256 chars only, like vgacon */
memcpy(font->data, sisusb->font_backup, 256 * 32);
mutex_unlock(&sisusb->lock);
return 0;
}
/*
* The console `switch' structure for the sisusb console
*/
static const struct consw sisusb_con = {
.owner = THIS_MODULE,
.con_startup = sisusbcon_startup,
.con_init = sisusbcon_init,
.con_deinit = sisusbcon_deinit,
.con_clear = sisusbcon_clear,
.con_putc = sisusbcon_putc,
.con_putcs = sisusbcon_putcs,
.con_cursor = sisusbcon_cursor,
.con_scroll = sisusbcon_scroll,
.con_bmove = sisusbcon_bmove,
.con_switch = sisusbcon_switch,
.con_blank = sisusbcon_blank,
.con_font_set = sisusbcon_font_set,
.con_font_get = sisusbcon_font_get,
.con_set_palette = sisusbcon_set_palette,
.con_scrolldelta = sisusbcon_scrolldelta,
.con_build_attr = sisusbcon_build_attr,
.con_invert_region = sisusbcon_invert_region,
.con_set_origin = sisusbcon_set_origin,
.con_save_screen = sisusbcon_save_screen,
.con_resize = sisusbcon_resize,
};
/* Our very own dummy console driver */
static const char *sisusbdummycon_startup(void)
{
return "SISUSBVGADUMMY";
}
static void sisusbdummycon_init(struct vc_data *vc, int init)
{
vc->vc_can_do_color = 1;
if (init) {
vc->vc_cols = 80;
vc->vc_rows = 25;
} else
vc_resize(vc, 80, 25);
}
static int sisusbdummycon_dummy(void)
{
return 0;
}
#define SISUSBCONDUMMY (void *)sisusbdummycon_dummy
static const struct consw sisusb_dummy_con = {
.owner = THIS_MODULE,
.con_startup = sisusbdummycon_startup,
.con_init = sisusbdummycon_init,
.con_deinit = SISUSBCONDUMMY,
.con_clear = SISUSBCONDUMMY,
.con_putc = SISUSBCONDUMMY,
.con_putcs = SISUSBCONDUMMY,
.con_cursor = SISUSBCONDUMMY,
.con_scroll = SISUSBCONDUMMY,
.con_bmove = SISUSBCONDUMMY,
.con_switch = SISUSBCONDUMMY,
.con_blank = SISUSBCONDUMMY,
.con_font_set = SISUSBCONDUMMY,
.con_font_get = SISUSBCONDUMMY,
.con_font_default = SISUSBCONDUMMY,
.con_font_copy = SISUSBCONDUMMY,
.con_set_palette = SISUSBCONDUMMY,
.con_scrolldelta = SISUSBCONDUMMY,
};
int
sisusb_console_init(struct sisusb_usb_data *sisusb, int first, int last)
{
int i, ret;
mutex_lock(&sisusb->lock);
/* Erm.. that should not happen */
if (sisusb->haveconsole || !sisusb->SiS_Pr) {
mutex_unlock(&sisusb->lock);
return 1;
}
sisusb->con_first = first;
sisusb->con_last = last;
if (first > last ||
first > MAX_NR_CONSOLES ||
last > MAX_NR_CONSOLES) {
mutex_unlock(&sisusb->lock);
return 1;
}
/* If gfxcore not initialized or no consoles given, quit graciously */
if (!sisusb->gfxinit || first < 1 || last < 1) {
mutex_unlock(&sisusb->lock);
return 0;
}
sisusb->sisusb_cursor_loc = -1;
sisusb->sisusb_cursor_size_from = -1;
sisusb->sisusb_cursor_size_to = -1;
/* Set up text mode (and upload default font) */
if (sisusb_reset_text_mode(sisusb, 1)) {
mutex_unlock(&sisusb->lock);
dev_err(&sisusb->sisusb_dev->dev, "Failed to set up text mode\n");
return 1;
}
/* Initialize some gfx registers */
sisusb_initialize(sisusb);
for (i = first - 1; i <= last - 1; i++) {
/* Save sisusb for our interface routines */
mysisusbs[i] = sisusb;
}
/* Initial console setup */
sisusb->sisusb_num_columns = 80;
/* Use a 32K buffer (matches b8000-bffff area) */
sisusb->scrbuf_size = 32 * 1024;
/* Allocate screen buffer */
if (!(sisusb->scrbuf = (unsigned long)vmalloc(sisusb->scrbuf_size))) {
mutex_unlock(&sisusb->lock);
dev_err(&sisusb->sisusb_dev->dev, "Failed to allocate screen buffer\n");
return 1;
}
mutex_unlock(&sisusb->lock);
/* Now grab the desired console(s) */
ret = take_over_console(&sisusb_con, first - 1, last - 1, 0);
if (!ret)
sisusb->haveconsole = 1;
else {
for (i = first - 1; i <= last - 1; i++)
mysisusbs[i] = NULL;
}
return ret;
}
void
sisusb_console_exit(struct sisusb_usb_data *sisusb)
{
int i;
/* This is called if the device is disconnected
* and while disconnect and lock semaphores
* are up. This should be save because we
* can't lose our sisusb any other way but by
* disconnection (and hence, the disconnect
* sema is for protecting all other access
* functions from disconnection, not the
* other way round).
*/
/* Now what do we do in case of disconnection:
* One alternative would be to simply call
* give_up_console(). Nah, not a good idea.
* give_up_console() is obviously buggy as it
* only discards the consw pointer from the
* driver_map, but doesn't adapt vc->vc_sw
* of the affected consoles. Hence, the next
* call to any of the console functions will
* eventually take a trip to oops county.
* Also, give_up_console for some reason
* doesn't decrement our module refcount.
* Instead, we switch our consoles to a private
* dummy console. This, of course, keeps our
* refcount up as well, but it works perfectly.
*/
if (sisusb->haveconsole) {
for (i = 0; i < MAX_NR_CONSOLES; i++)
if (sisusb->havethisconsole[i])
take_over_console(&sisusb_dummy_con, i, i, 0);
/* At this point, con_deinit for all our
* consoles is executed by take_over_console().
*/
sisusb->haveconsole = 0;
}
vfree((void *)sisusb->scrbuf);
sisusb->scrbuf = 0;
vfree(sisusb->font_backup);
sisusb->font_backup = NULL;
}
void __init sisusb_init_concode(void)
{
int i;
for (i = 0; i < MAX_NR_CONSOLES; i++)
mysisusbs[i] = NULL;
}
#endif /* INCL_CON */
| gpl-2.0 |
jokersax/Photon-blur-kernel | arch/alpha/lib/memcpy.c | 13735 | 4108 | /*
* linux/arch/alpha/lib/memcpy.c
*
* Copyright (C) 1995 Linus Torvalds
*/
/*
* This is a reasonably optimized memcpy() routine.
*/
/*
* Note that the C code is written to be optimized into good assembly. However,
* at this point gcc is unable to sanely compile "if (n >= 0)", resulting in a
* explicit compare against 0 (instead of just using the proper "blt reg, xx" or
* "bge reg, xx"). I hope alpha-gcc will be fixed to notice this eventually..
*/
#include <linux/types.h>
/*
* This should be done in one go with ldq_u*2/mask/stq_u. Do it
* with a macro so that we can fix it up later..
*/
#define ALIGN_DEST_TO8_UP(d,s,n) \
while (d & 7) { \
if (n <= 0) return; \
n--; \
*(char *) d = *(char *) s; \
d++; s++; \
}
#define ALIGN_DEST_TO8_DN(d,s,n) \
while (d & 7) { \
if (n <= 0) return; \
n--; \
d--; s--; \
*(char *) d = *(char *) s; \
}
/*
* This should similarly be done with ldq_u*2/mask/stq. The destination
* is aligned, but we don't fill in a full quad-word
*/
#define DO_REST_UP(d,s,n) \
while (n > 0) { \
n--; \
*(char *) d = *(char *) s; \
d++; s++; \
}
#define DO_REST_DN(d,s,n) \
while (n > 0) { \
n--; \
d--; s--; \
*(char *) d = *(char *) s; \
}
/*
* This should be done with ldq/mask/stq. The source and destination are
* aligned, but we don't fill in a full quad-word
*/
#define DO_REST_ALIGNED_UP(d,s,n) DO_REST_UP(d,s,n)
#define DO_REST_ALIGNED_DN(d,s,n) DO_REST_DN(d,s,n)
/*
* This does unaligned memory copies. We want to avoid storing to
* an unaligned address, as that would do a read-modify-write cycle.
* We also want to avoid double-reading the unaligned reads.
*
* Note the ordering to try to avoid load (and address generation) latencies.
*/
static inline void __memcpy_unaligned_up (unsigned long d, unsigned long s,
long n)
{
ALIGN_DEST_TO8_UP(d,s,n);
n -= 8; /* to avoid compare against 8 in the loop */
if (n >= 0) {
unsigned long low_word, high_word;
__asm__("ldq_u %0,%1":"=r" (low_word):"m" (*(unsigned long *) s));
do {
unsigned long tmp;
__asm__("ldq_u %0,%1":"=r" (high_word):"m" (*(unsigned long *)(s+8)));
n -= 8;
__asm__("extql %1,%2,%0"
:"=r" (low_word)
:"r" (low_word), "r" (s));
__asm__("extqh %1,%2,%0"
:"=r" (tmp)
:"r" (high_word), "r" (s));
s += 8;
*(unsigned long *) d = low_word | tmp;
d += 8;
low_word = high_word;
} while (n >= 0);
}
n += 8;
DO_REST_UP(d,s,n);
}
static inline void __memcpy_unaligned_dn (unsigned long d, unsigned long s,
long n)
{
/* I don't understand AXP assembler well enough for this. -Tim */
s += n;
d += n;
while (n--)
* (char *) --d = * (char *) --s;
}
/*
* Hmm.. Strange. The __asm__ here is there to make gcc use an integer register
* for the load-store. I don't know why, but it would seem that using a floating
* point register for the move seems to slow things down (very small difference,
* though).
*
* Note the ordering to try to avoid load (and address generation) latencies.
*/
static inline void __memcpy_aligned_up (unsigned long d, unsigned long s,
long n)
{
ALIGN_DEST_TO8_UP(d,s,n);
n -= 8;
while (n >= 0) {
unsigned long tmp;
__asm__("ldq %0,%1":"=r" (tmp):"m" (*(unsigned long *) s));
n -= 8;
s += 8;
*(unsigned long *) d = tmp;
d += 8;
}
n += 8;
DO_REST_ALIGNED_UP(d,s,n);
}
static inline void __memcpy_aligned_dn (unsigned long d, unsigned long s,
long n)
{
s += n;
d += n;
ALIGN_DEST_TO8_DN(d,s,n);
n -= 8;
while (n >= 0) {
unsigned long tmp;
s -= 8;
__asm__("ldq %0,%1":"=r" (tmp):"m" (*(unsigned long *) s));
n -= 8;
d -= 8;
*(unsigned long *) d = tmp;
}
n += 8;
DO_REST_ALIGNED_DN(d,s,n);
}
void * memcpy(void * dest, const void *src, size_t n)
{
if (!(((unsigned long) dest ^ (unsigned long) src) & 7)) {
__memcpy_aligned_up ((unsigned long) dest, (unsigned long) src,
n);
return dest;
}
__memcpy_unaligned_up ((unsigned long) dest, (unsigned long) src, n);
return dest;
}
/* For backward modules compatibility, define __memcpy. */
asm("__memcpy = memcpy; .globl __memcpy");
| gpl-2.0 |
jmztaylor/android_kernel_htc_k2plccl | arch/powerpc/math-emu/fmsub.c | 13735 | 1123 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
int
fmsub(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (B_c != FP_CLS_NAN)
B_s ^= 1;
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_D(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
bizcuite/Archos_Gen8_Linaro_kernel | drivers/isdn/mISDN/dsp_tones.c | 168 | 17252 | /*
* Audio support data for ISDN4Linux.
*
* Copyright Andreas Eversberg (jolly@eversberg.eu)
*
* 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 DATA_S sample_silence
#define SIZE_S (&sizeof_silence)
#define DATA_GA sample_german_all
#define SIZE_GA (&sizeof_german_all)
#define DATA_GO sample_german_old
#define SIZE_GO (&sizeof_german_old)
#define DATA_DT sample_american_dialtone
#define SIZE_DT (&sizeof_american_dialtone)
#define DATA_RI sample_american_ringing
#define SIZE_RI (&sizeof_american_ringing)
#define DATA_BU sample_american_busy
#define SIZE_BU (&sizeof_american_busy)
#define DATA_S1 sample_special1
#define SIZE_S1 (&sizeof_special1)
#define DATA_S2 sample_special2
#define SIZE_S2 (&sizeof_special2)
#define DATA_S3 sample_special3
#define SIZE_S3 (&sizeof_special3)
/***************/
/* tones loops */
/***************/
/* all tones are alaw encoded */
/* the last sample+1 is in phase with the first sample. the error is low */
static u8 sample_german_all[] = {
0x80, 0xab, 0x81, 0x6d, 0xfd, 0xdd, 0x5d, 0x9d,
0x4d, 0xd1, 0x89, 0x88, 0xd0, 0x4c, 0x9c, 0x5c,
0xdc, 0xfc, 0x6c,
0x80, 0xab, 0x81, 0x6d, 0xfd, 0xdd, 0x5d, 0x9d,
0x4d, 0xd1, 0x89, 0x88, 0xd0, 0x4c, 0x9c, 0x5c,
0xdc, 0xfc, 0x6c,
0x80, 0xab, 0x81, 0x6d, 0xfd, 0xdd, 0x5d, 0x9d,
0x4d, 0xd1, 0x89, 0x88, 0xd0, 0x4c, 0x9c, 0x5c,
0xdc, 0xfc, 0x6c,
0x80, 0xab, 0x81, 0x6d, 0xfd, 0xdd, 0x5d, 0x9d,
0x4d, 0xd1, 0x89, 0x88, 0xd0, 0x4c, 0x9c, 0x5c,
0xdc, 0xfc, 0x6c,
};
static u32 sizeof_german_all = sizeof(sample_german_all);
static u8 sample_german_old[] = {
0xec, 0x68, 0xe1, 0x6d, 0x6d, 0x91, 0x51, 0xed,
0x6d, 0x01, 0x1e, 0x10, 0x0c, 0x90, 0x60, 0x70,
0x8c,
0xec, 0x68, 0xe1, 0x6d, 0x6d, 0x91, 0x51, 0xed,
0x6d, 0x01, 0x1e, 0x10, 0x0c, 0x90, 0x60, 0x70,
0x8c,
0xec, 0x68, 0xe1, 0x6d, 0x6d, 0x91, 0x51, 0xed,
0x6d, 0x01, 0x1e, 0x10, 0x0c, 0x90, 0x60, 0x70,
0x8c,
0xec, 0x68, 0xe1, 0x6d, 0x6d, 0x91, 0x51, 0xed,
0x6d, 0x01, 0x1e, 0x10, 0x0c, 0x90, 0x60, 0x70,
0x8c,
};
static u32 sizeof_german_old = sizeof(sample_german_old);
static u8 sample_american_dialtone[] = {
0x2a, 0x18, 0x90, 0x6c, 0x4c, 0xbc, 0x4c, 0x6c,
0x10, 0x58, 0x32, 0xb9, 0x31, 0x2d, 0x8d, 0x0d,
0x8d, 0x2d, 0x31, 0x99, 0x0f, 0x28, 0x60, 0xf0,
0xd0, 0x50, 0xd0, 0x30, 0x60, 0x08, 0x8e, 0x67,
0x09, 0x19, 0x21, 0xe1, 0xd9, 0xb9, 0x29, 0x67,
0x83, 0x02, 0xce, 0xbe, 0xee, 0x1a, 0x1b, 0xef,
0xbf, 0xcf, 0x03, 0x82, 0x66, 0x28, 0xb8, 0xd8,
0xe0, 0x20, 0x18, 0x08, 0x66, 0x8f, 0x09, 0x61,
0x31, 0xd1, 0x51, 0xd1, 0xf1, 0x61, 0x29, 0x0e,
0x98, 0x30, 0x2c, 0x8c, 0x0c, 0x8c, 0x2c, 0x30,
0xb8, 0x33, 0x59, 0x11, 0x6d, 0x4d, 0xbd, 0x4d,
0x6d, 0x91, 0x19,
};
static u32 sizeof_american_dialtone = sizeof(sample_american_dialtone);
static u8 sample_american_ringing[] = {
0x2a, 0xe0, 0xac, 0x0c, 0xbc, 0x4c, 0x8c, 0x90,
0x48, 0xc7, 0xc1, 0xed, 0xcd, 0x4d, 0xcd, 0xed,
0xc1, 0xb7, 0x08, 0x30, 0xec, 0xcc, 0xcc, 0x8c,
0x10, 0x58, 0x1a, 0x99, 0x71, 0xed, 0x8d, 0x8d,
0x2d, 0x41, 0x89, 0x9e, 0x20, 0x70, 0x2c, 0xec,
0x2c, 0x70, 0x20, 0x86, 0x77, 0xe1, 0x31, 0x11,
0xd1, 0xf1, 0x81, 0x09, 0xa3, 0x56, 0x58, 0x00,
0x40, 0xc0, 0x60, 0x38, 0x46, 0x43, 0x57, 0x39,
0xd9, 0x59, 0x99, 0xc9, 0x77, 0x2f, 0x2e, 0xc6,
0xd6, 0x28, 0xd6, 0x36, 0x26, 0x2e, 0x8a, 0xa3,
0x43, 0x63, 0x4b, 0x4a, 0x62, 0x42, 0xa2, 0x8b,
0x2f, 0x27, 0x37, 0xd7, 0x29, 0xd7, 0xc7, 0x2f,
0x2e, 0x76, 0xc8, 0x98, 0x58, 0xd8, 0x38, 0x56,
0x42, 0x47, 0x39, 0x61, 0xc1, 0x41, 0x01, 0x59,
0x57, 0xa2, 0x08, 0x80, 0xf0, 0xd0, 0x10, 0x30,
0xe0, 0x76, 0x87, 0x21, 0x71, 0x2d, 0xed, 0x2d,
0x71, 0x21, 0x9f, 0x88, 0x40, 0x2c, 0x8c, 0x8c,
0xec, 0x70, 0x98, 0x1b, 0x59, 0x11, 0x8d, 0xcd,
0xcd, 0xed, 0x31, 0x09, 0xb6, 0xc0, 0xec, 0xcc,
0x4c, 0xcc, 0xec, 0xc0, 0xc6, 0x49, 0x91, 0x8d,
0x4d, 0xbd, 0x0d, 0xad, 0xe1,
};
static u32 sizeof_american_ringing = sizeof(sample_american_ringing);
static u8 sample_american_busy[] = {
0x2a, 0x00, 0x6c, 0x4c, 0x4c, 0x6c, 0xb0, 0x66,
0x99, 0x11, 0x6d, 0x8d, 0x2d, 0x41, 0xd7, 0x96,
0x60, 0xf0, 0x70, 0x40, 0x58, 0xf6, 0x53, 0x57,
0x09, 0x89, 0xd7, 0x5f, 0xe3, 0x2a, 0xe3, 0x5f,
0xd7, 0x89, 0x09, 0x57, 0x53, 0xf6, 0x58, 0x40,
0x70, 0xf0, 0x60, 0x96, 0xd7, 0x41, 0x2d, 0x8d,
0x6d, 0x11, 0x99, 0x66, 0xb0, 0x6c, 0x4c, 0x4c,
0x6c, 0x00, 0x2a, 0x01, 0x6d, 0x4d, 0x4d, 0x6d,
0xb1, 0x67, 0x98, 0x10, 0x6c, 0x8c, 0x2c, 0x40,
0xd6, 0x97, 0x61, 0xf1, 0x71, 0x41, 0x59, 0xf7,
0x52, 0x56, 0x08, 0x88, 0xd6, 0x5e, 0xe2, 0x2a,
0xe2, 0x5e, 0xd6, 0x88, 0x08, 0x56, 0x52, 0xf7,
0x59, 0x41, 0x71, 0xf1, 0x61, 0x97, 0xd6, 0x40,
0x2c, 0x8c, 0x6c, 0x10, 0x98, 0x67, 0xb1, 0x6d,
0x4d, 0x4d, 0x6d, 0x01,
};
static u32 sizeof_american_busy = sizeof(sample_american_busy);
static u8 sample_special1[] = {
0x2a, 0x2c, 0xbc, 0x6c, 0xd6, 0x71, 0xbd, 0x0d,
0xd9, 0x80, 0xcc, 0x4c, 0x40, 0x39, 0x0d, 0xbd,
0x11, 0x86, 0xec, 0xbc, 0xec, 0x0e, 0x51, 0xbd,
0x8d, 0x89, 0x30, 0x4c, 0xcc, 0xe0, 0xe1, 0xcd,
0x4d, 0x31, 0x88, 0x8c, 0xbc, 0x50, 0x0f, 0xed,
0xbd, 0xed, 0x87, 0x10, 0xbc, 0x0c, 0x38, 0x41,
0x4d, 0xcd, 0x81, 0xd8, 0x0c, 0xbc, 0x70, 0xd7,
0x6d, 0xbd, 0x2d,
};
static u32 sizeof_special1 = sizeof(sample_special1);
static u8 sample_special2[] = {
0x2a, 0xcc, 0x8c, 0xd7, 0x4d, 0x2d, 0x18, 0xbc,
0x10, 0xc1, 0xbd, 0xc1, 0x10, 0xbc, 0x18, 0x2d,
0x4d, 0xd7, 0x8c, 0xcc, 0x2a, 0xcd, 0x8d, 0xd6,
0x4c, 0x2c, 0x19, 0xbd, 0x11, 0xc0, 0xbc, 0xc0,
0x11, 0xbd, 0x19, 0x2c, 0x4c, 0xd6, 0x8d, 0xcd,
0x2a, 0xcc, 0x8c, 0xd7, 0x4d, 0x2d, 0x18, 0xbc,
0x10, 0xc1, 0xbd, 0xc1, 0x10, 0xbc, 0x18, 0x2d,
0x4d, 0xd7, 0x8c, 0xcc, 0x2a, 0xcd, 0x8d, 0xd6,
0x4c, 0x2c, 0x19, 0xbd, 0x11, 0xc0, 0xbc, 0xc0,
0x11, 0xbd, 0x19, 0x2c, 0x4c, 0xd6, 0x8d, 0xcd,
};
static u32 sizeof_special2 = sizeof(sample_special2);
static u8 sample_special3[] = {
0x2a, 0xbc, 0x18, 0xcd, 0x11, 0x2c, 0x8c, 0xc1,
0x4d, 0xd6, 0xbc, 0xd6, 0x4d, 0xc1, 0x8c, 0x2c,
0x11, 0xcd, 0x18, 0xbc, 0x2a, 0xbd, 0x19, 0xcc,
0x10, 0x2d, 0x8d, 0xc0, 0x4c, 0xd7, 0xbd, 0xd7,
0x4c, 0xc0, 0x8d, 0x2d, 0x10, 0xcc, 0x19, 0xbd,
0x2a, 0xbc, 0x18, 0xcd, 0x11, 0x2c, 0x8c, 0xc1,
0x4d, 0xd6, 0xbc, 0xd6, 0x4d, 0xc1, 0x8c, 0x2c,
0x11, 0xcd, 0x18, 0xbc, 0x2a, 0xbd, 0x19, 0xcc,
0x10, 0x2d, 0x8d, 0xc0, 0x4c, 0xd7, 0xbd, 0xd7,
0x4c, 0xc0, 0x8d, 0x2d, 0x10, 0xcc, 0x19, 0xbd,
};
static u32 sizeof_special3 = sizeof(sample_special3);
static u8 sample_silence[] = {
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
};
static u32 sizeof_silence = sizeof(sample_silence);
struct tones_samples {
u32 *len;
u8 *data;
};
static struct
tones_samples samples[] = {
{&sizeof_german_all, sample_german_all},
{&sizeof_german_old, sample_german_old},
{&sizeof_american_dialtone, sample_american_dialtone},
{&sizeof_american_ringing, sample_american_ringing},
{&sizeof_american_busy, sample_american_busy},
{&sizeof_special1, sample_special1},
{&sizeof_special2, sample_special2},
{&sizeof_special3, sample_special3},
{NULL, NULL},
};
/***********************************
* generate ulaw from alaw samples *
***********************************/
void
dsp_audio_generate_ulaw_samples(void)
{
int i, j;
i = 0;
while (samples[i].len) {
j = 0;
while (j < (*samples[i].len)) {
samples[i].data[j] =
dsp_audio_alaw_to_ulaw[samples[i].data[j]];
j++;
}
i++;
}
}
/****************************
* tone sequence definition *
****************************/
static struct pattern {
int tone;
u8 *data[10];
u32 *siz[10];
u32 seq[10];
} pattern[] = {
{TONE_GERMAN_DIALTONE,
{DATA_GA, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GA, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{1900, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_OLDDIALTONE,
{DATA_GO, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GO, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{1998, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_AMERICAN_DIALTONE,
{DATA_DT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_DT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{8000, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_DIALPBX,
{DATA_GA, DATA_S, DATA_GA, DATA_S, DATA_GA, DATA_S, NULL, NULL, NULL, NULL},
{SIZE_GA, SIZE_S, SIZE_GA, SIZE_S, SIZE_GA, SIZE_S, NULL, NULL, NULL, NULL},
{2000, 2000, 2000, 2000, 2000, 12000, 0, 0, 0, 0} },
{TONE_GERMAN_OLDDIALPBX,
{DATA_GO, DATA_S, DATA_GO, DATA_S, DATA_GO, DATA_S, NULL, NULL, NULL, NULL},
{SIZE_GO, SIZE_S, SIZE_GO, SIZE_S, SIZE_GO, SIZE_S, NULL, NULL, NULL, NULL},
{2000, 2000, 2000, 2000, 2000, 12000, 0, 0, 0, 0} },
{TONE_AMERICAN_DIALPBX,
{DATA_DT, DATA_S, DATA_DT, DATA_S, DATA_DT, DATA_S, NULL, NULL, NULL, NULL},
{SIZE_DT, SIZE_S, SIZE_DT, SIZE_S, SIZE_DT, SIZE_S, NULL, NULL, NULL, NULL},
{2000, 2000, 2000, 2000, 2000, 12000, 0, 0, 0, 0} },
{TONE_GERMAN_RINGING,
{DATA_GA, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GA, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{8000, 32000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_OLDRINGING,
{DATA_GO, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GO, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{8000, 40000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_AMERICAN_RINGING,
{DATA_RI, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_RI, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{8000, 32000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_RINGPBX,
{DATA_GA, DATA_S, DATA_GA, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GA, SIZE_S, SIZE_GA, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL},
{4000, 4000, 4000, 28000, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_OLDRINGPBX,
{DATA_GO, DATA_S, DATA_GO, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GO, SIZE_S, SIZE_GO, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL},
{4000, 4000, 4000, 28000, 0, 0, 0, 0, 0, 0} },
{TONE_AMERICAN_RINGPBX,
{DATA_RI, DATA_S, DATA_RI, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_RI, SIZE_S, SIZE_RI, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL},
{4000, 4000, 4000, 28000, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_BUSY,
{DATA_GA, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GA, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{4000, 4000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_OLDBUSY,
{DATA_GO, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GO, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{1000, 5000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_AMERICAN_BUSY,
{DATA_BU, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_BU, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{4000, 4000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_HANGUP,
{DATA_GA, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GA, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{4000, 4000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_OLDHANGUP,
{DATA_GO, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GO, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{1000, 5000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_AMERICAN_HANGUP,
{DATA_DT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_DT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{8000, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_SPECIAL_INFO,
{DATA_S1, DATA_S2, DATA_S3, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_S1, SIZE_S2, SIZE_S3, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL},
{2666, 2666, 2666, 8002, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_GASSENBESETZT,
{DATA_GA, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GA, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{2000, 2000, 0, 0, 0, 0, 0, 0, 0, 0} },
{TONE_GERMAN_AUFSCHALTTON,
{DATA_GO, DATA_S, DATA_GO, DATA_S, NULL, NULL, NULL, NULL, NULL, NULL},
{SIZE_GO, SIZE_S, SIZE_GO, SIZE_S, NULL, NULL, NULL, NULL, NULL, NULL},
{1000, 5000, 1000, 17000, 0, 0, 0, 0, 0, 0} },
{0,
{NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
};
/******************
* copy tone data *
******************/
/* an sk_buff is generated from the number of samples needed.
* the count will be changed and may begin from 0 each pattern period.
* the clue is to precalculate the pointers and legths to use only one
* memcpy per function call, or two memcpy if the tone sequence changes.
*
* pattern - the type of the pattern
* count - the sample from the beginning of the pattern (phase)
* len - the number of bytes
*
* return - the sk_buff with the sample
*
* if tones has finished (e.g. knocking tone), dsp->tones is turned off
*/
void dsp_tone_copy(struct dsp *dsp, u8 *data, int len)
{
int index, count, start, num;
struct pattern *pat;
struct dsp_tone *tone = &dsp->tone;
/* if we have no tone, we copy silence */
if (!tone->tone) {
memset(data, dsp_silence, len);
return;
}
/* process pattern */
pat = (struct pattern *)tone->pattern;
/* points to the current pattern */
index = tone->index; /* gives current sequence index */
count = tone->count; /* gives current sample */
/* copy sample */
while (len) {
/* find sample to start with */
while (42) {
/* warp arround */
if (!pat->seq[index]) {
count = 0;
index = 0;
}
/* check if we are currently playing this tone */
if (count < pat->seq[index])
break;
if (dsp_debug & DEBUG_DSP_TONE)
printk(KERN_DEBUG "%s: reaching next sequence "
"(index=%d)\n", __func__, index);
count -= pat->seq[index];
index++;
}
/* calculate start and number of samples */
start = count % (*(pat->siz[index]));
num = len;
if (num+count > pat->seq[index])
num = pat->seq[index] - count;
if (num+start > (*(pat->siz[index])))
num = (*(pat->siz[index])) - start;
/* copy memory */
memcpy(data, pat->data[index]+start, num);
/* reduce length */
data += num;
count += num;
len -= num;
}
tone->index = index;
tone->count = count;
/* return sk_buff */
return;
}
/*******************************
* send HW message to hfc card *
*******************************/
static void
dsp_tone_hw_message(struct dsp *dsp, u8 *sample, int len)
{
struct sk_buff *nskb;
/* unlocking is not required, because we don't expect a response */
nskb = _alloc_mISDN_skb(PH_CONTROL_REQ,
(len)?HFC_SPL_LOOP_ON:HFC_SPL_LOOP_OFF, len, sample,
GFP_ATOMIC);
if (nskb) {
if (dsp->ch.peer) {
if (dsp->ch.recv(dsp->ch.peer, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
}
/*****************
* timer expires *
*****************/
void
dsp_tone_timeout(void *arg)
{
struct dsp *dsp = arg;
struct dsp_tone *tone = &dsp->tone;
struct pattern *pat = (struct pattern *)tone->pattern;
int index = tone->index;
if (!tone->tone)
return;
index++;
if (!pat->seq[index])
index = 0;
tone->index = index;
/* set next tone */
if (pat->data[index] == DATA_S)
dsp_tone_hw_message(dsp, NULL, 0);
else
dsp_tone_hw_message(dsp, pat->data[index], *(pat->siz[index]));
/* set timer */
init_timer(&tone->tl);
tone->tl.expires = jiffies + (pat->seq[index] * HZ) / 8000;
add_timer(&tone->tl);
}
/********************
* set/release tone *
********************/
/*
* tones are relaized by streaming or by special loop commands if supported
* by hardware. when hardware is used, the patterns will be controlled by
* timers.
*/
int
dsp_tone(struct dsp *dsp, int tone)
{
struct pattern *pat;
int i;
struct dsp_tone *tonet = &dsp->tone;
tonet->software = 0;
tonet->hardware = 0;
/* we turn off the tone */
if (!tone) {
if (dsp->features.hfc_loops)
if (timer_pending(&tonet->tl))
del_timer(&tonet->tl);
if (dsp->features.hfc_loops)
dsp_tone_hw_message(dsp, NULL, 0);
tonet->tone = 0;
return 0;
}
pat = NULL;
i = 0;
while (pattern[i].tone) {
if (pattern[i].tone == tone) {
pat = &pattern[i];
break;
}
i++;
}
if (!pat) {
printk(KERN_WARNING "dsp: given tone 0x%x is invalid\n", tone);
return -EINVAL;
}
if (dsp_debug & DEBUG_DSP_TONE)
printk(KERN_DEBUG "%s: now starting tone %d (index=%d)\n",
__func__, tone, 0);
tonet->tone = tone;
tonet->pattern = pat;
tonet->index = 0;
tonet->count = 0;
if (dsp->features.hfc_loops) {
tonet->hardware = 1;
/* set first tone */
dsp_tone_hw_message(dsp, pat->data[0], *(pat->siz[0]));
/* set timer */
if (timer_pending(&tonet->tl))
del_timer(&tonet->tl);
init_timer(&tonet->tl);
tonet->tl.expires = jiffies + (pat->seq[0] * HZ) / 8000;
add_timer(&tonet->tl);
} else {
tonet->software = 1;
}
return 0;
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | external/icu4c/common/ustrenum.cpp | 168 | 8579 | /*
**********************************************************************
* Copyright (c) 2002-2010, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: November 11 2002
* Since: ICU 2.4
**********************************************************************
*/
#include <typeinfo> // for 'typeid' to work
#include "unicode/ustring.h"
#include "unicode/strenum.h"
#include "unicode/putil.h"
#include "uenumimp.h"
#include "ustrenum.h"
#include "cstring.h"
#include "cmemory.h"
#include "uassert.h"
U_NAMESPACE_BEGIN
// StringEnumeration implementation ---------------------------------------- ***
StringEnumeration::StringEnumeration()
: chars(charsBuffer), charsCapacity(sizeof(charsBuffer)) {
}
StringEnumeration::~StringEnumeration() {
if (chars != NULL && chars != charsBuffer) {
uprv_free(chars);
}
}
// StringEnumeration base class clone() default implementation, does not clone
StringEnumeration *
StringEnumeration::clone() const {
return NULL;
}
const char *
StringEnumeration::next(int32_t *resultLength, UErrorCode &status) {
const UnicodeString *s=snext(status);
if(s!=NULL) {
unistr=*s;
ensureCharsCapacity(unistr.length()+1, status);
if(U_SUCCESS(status)) {
if(resultLength!=NULL) {
*resultLength=unistr.length();
}
unistr.extract(0, INT32_MAX, chars, charsCapacity, US_INV);
return chars;
}
}
return NULL;
}
const UChar *
StringEnumeration::unext(int32_t *resultLength, UErrorCode &status) {
const UnicodeString *s=snext(status);
if(s!=NULL) {
unistr=*s;
if(U_SUCCESS(status)) {
if(resultLength!=NULL) {
*resultLength=unistr.length();
}
return unistr.getTerminatedBuffer();
}
}
return NULL;
}
void
StringEnumeration::ensureCharsCapacity(int32_t capacity, UErrorCode &status) {
if(U_SUCCESS(status) && capacity>charsCapacity) {
if(capacity<(charsCapacity+charsCapacity/2)) {
// avoid allocation thrashing
capacity=charsCapacity+charsCapacity/2;
}
if(chars!=charsBuffer) {
uprv_free(chars);
}
chars=(char *)uprv_malloc(capacity);
if(chars==NULL) {
chars=charsBuffer;
charsCapacity=sizeof(charsBuffer);
status=U_MEMORY_ALLOCATION_ERROR;
} else {
charsCapacity=capacity;
}
}
}
UnicodeString *
StringEnumeration::setChars(const char *s, int32_t length, UErrorCode &status) {
if(U_SUCCESS(status) && s!=NULL) {
if(length<0) {
length=(int32_t)uprv_strlen(s);
}
UChar *buffer=unistr.getBuffer(length+1);
if(buffer!=NULL) {
u_charsToUChars(s, buffer, length);
buffer[length]=0;
unistr.releaseBuffer(length);
return &unistr;
} else {
status=U_MEMORY_ALLOCATION_ERROR;
}
}
return NULL;
}
UBool
StringEnumeration::operator==(const StringEnumeration& that)const {
return typeid(*this) == typeid(that);
}
UBool
StringEnumeration::operator!=(const StringEnumeration& that)const {
return !operator==(that);
}
// UStringEnumeration implementation --------------------------------------- ***
UStringEnumeration::UStringEnumeration(UEnumeration* _uenum) :
uenum(_uenum) {
U_ASSERT(_uenum != 0);
}
UStringEnumeration::~UStringEnumeration() {
uenum_close(uenum);
}
int32_t UStringEnumeration::count(UErrorCode& status) const {
return uenum_count(uenum, &status);
}
const UnicodeString* UStringEnumeration::snext(UErrorCode& status) {
int32_t length;
const UChar* str = uenum_unext(uenum, &length, &status);
if (str == 0 || U_FAILURE(status)) {
return 0;
}
return &unistr.setTo(str, length);
}
void UStringEnumeration::reset(UErrorCode& status) {
uenum_reset(uenum, &status);
}
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UStringEnumeration)
U_NAMESPACE_END
// C wrapper --------------------------------------------------------------- ***
#define THIS(en) ((U_NAMESPACE_QUALIFIER StringEnumeration*)(en->context))
U_CDECL_BEGIN
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static void U_CALLCONV
ustrenum_close(UEnumeration* en) {
delete THIS(en);
uprv_free(en);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static int32_t U_CALLCONV
ustrenum_count(UEnumeration* en,
UErrorCode* ec)
{
return THIS(en)->count(*ec);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static const UChar* U_CALLCONV
ustrenum_unext(UEnumeration* en,
int32_t* resultLength,
UErrorCode* ec)
{
return THIS(en)->unext(resultLength, *ec);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static const char* U_CALLCONV
ustrenum_next(UEnumeration* en,
int32_t* resultLength,
UErrorCode* ec)
{
return THIS(en)->next(resultLength, *ec);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static void U_CALLCONV
ustrenum_reset(UEnumeration* en,
UErrorCode* ec)
{
THIS(en)->reset(*ec);
}
/**
* Pseudo-vtable for UEnumeration wrapper around StringEnumeration.
* The StringEnumeration pointer will be stored in 'context'.
*/
static const UEnumeration USTRENUM_VT = {
NULL,
NULL, // store StringEnumeration pointer here
ustrenum_close,
ustrenum_count,
ustrenum_unext,
ustrenum_next,
ustrenum_reset
};
U_CDECL_END
/**
* Given a StringEnumeration, wrap it in a UEnumeration. The
* StringEnumeration is adopted; after this call, the caller must not
* delete it (regardless of error status).
*/
U_CAPI UEnumeration* U_EXPORT2
uenum_openFromStringEnumeration(U_NAMESPACE_QUALIFIER StringEnumeration* adopted, UErrorCode* ec) {
UEnumeration* result = NULL;
if (U_SUCCESS(*ec) && adopted != NULL) {
result = (UEnumeration*) uprv_malloc(sizeof(UEnumeration));
if (result == NULL) {
*ec = U_MEMORY_ALLOCATION_ERROR;
} else {
uprv_memcpy(result, &USTRENUM_VT, sizeof(USTRENUM_VT));
result->context = adopted;
}
}
if (result == NULL) {
delete adopted;
}
return result;
}
// C wrapper --------------------------------------------------------------- ***
U_CDECL_BEGIN
typedef struct UCharStringEnumeration {
UEnumeration uenum;
int32_t index, count;
} UCharStringEnumeration;
static void U_CALLCONV
ucharstrenum_close(UEnumeration* en) {
uprv_free(en);
}
static int32_t U_CALLCONV
ucharstrenum_count(UEnumeration* en,
UErrorCode* /*ec*/) {
return ((UCharStringEnumeration*)en)->count;
}
static const char* U_CALLCONV
ucharstrenum_next(UEnumeration* en,
int32_t* resultLength,
UErrorCode* /*ec*/) {
UCharStringEnumeration *e = (UCharStringEnumeration*) en;
if (e->index >= e->count) {
return NULL;
}
const char* result = ((const char**)e->uenum.context)[e->index++];
if (resultLength) {
*resultLength = (int32_t)uprv_strlen(result);
}
return result;
}
static void U_CALLCONV
ucharstrenum_reset(UEnumeration* en,
UErrorCode* /*ec*/) {
((UCharStringEnumeration*)en)->index = 0;
}
static const UEnumeration UCHARSTRENUM_VT = {
NULL,
NULL, // store StringEnumeration pointer here
ucharstrenum_close,
ucharstrenum_count,
uenum_unextDefault,
ucharstrenum_next,
ucharstrenum_reset
};
U_CDECL_END
U_CAPI UEnumeration* U_EXPORT2
uenum_openCharStringsEnumeration(const char* const* strings, int32_t count,
UErrorCode* ec) {
UCharStringEnumeration* result = NULL;
if (U_SUCCESS(*ec) && count >= 0 && (count == 0 || strings != 0)) {
result = (UCharStringEnumeration*) uprv_malloc(sizeof(UCharStringEnumeration));
if (result == NULL) {
*ec = U_MEMORY_ALLOCATION_ERROR;
} else {
U_ASSERT((char*)result==(char*)(&result->uenum));
uprv_memcpy(result, &UCHARSTRENUM_VT, sizeof(UCHARSTRENUM_VT));
result->uenum.context = (void*)strings;
result->index = 0;
result->count = count;
}
}
return (UEnumeration*) result;
}
| gpl-2.0 |
rgwan/gcc | gcc/testsuite/gcc.c-torture/execute/pr51933.c | 168 | 1219 | /* PR rtl-optimization/51933 */
static signed char v1;
static unsigned char v2[256], v3[256];
__attribute__((noclone, noinline)) void
foo (void)
{
#if defined(__s390__) && !defined(__zarch__)
/* S/390 31 bit cannot deal with more than one literal pool
reference per insn. */
asm volatile ("" : : "g" (&v1) : "memory");
asm volatile ("" : : "g" (&v2[0]));
asm volatile ("" : : "g" (&v3[0]));
#else
asm volatile ("" : : "g" (&v1), "g" (&v2[0]), "g" (&v3[0]) : "memory");
#endif
}
__attribute__((noclone, noinline)) int
bar (const int x, const unsigned short *y, char *z)
{
int i;
unsigned short u;
if (!v1)
foo ();
for (i = 0; i < x; i++)
{
u = y[i];
z[i] = u < 0x0100 ? v2[u] : v3[u & 0xff];
}
z[x] = '\0';
return x;
}
int
main (void)
{
char buf[18];
unsigned short s[18];
unsigned char c[18] = "abcdefghijklmnopq";
int i;
for (i = 0; i < 256; i++)
{
v2[i] = i;
v3[i] = i + 1;
}
for (i = 0; i < 18; i++)
s[i] = c[i];
s[5] |= 0x600;
s[6] |= 0x500;
s[11] |= 0x2000;
s[15] |= 0x500;
foo ();
if (bar (17, s, buf) != 17
|| __builtin_memcmp (buf, "abcdeghhijkmmnoqq", 18) != 0)
__builtin_abort ();
return 0;
}
| gpl-2.0 |
zzpu/linux-stack | drivers/net/ethernet/oki-semi/pch_gbe/pch_gbe_main.c | 168 | 80849 | /*
* Copyright (C) 1999 - 2010 Intel Corporation.
* Copyright (C) 2010 - 2012 LAPIS SEMICONDUCTOR CO., LTD.
*
* This code was derived from the Intel e1000e Linux driver.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "pch_gbe.h"
#include "pch_gbe_api.h"
#include <linux/module.h>
#include <linux/net_tstamp.h>
#include <linux/ptp_classify.h>
#include <linux/gpio.h>
#define DRV_VERSION "1.01"
const char pch_driver_version[] = DRV_VERSION;
#define PCI_DEVICE_ID_INTEL_IOH1_GBE 0x8802 /* Pci device ID */
#define PCH_GBE_MAR_ENTRIES 16
#define PCH_GBE_SHORT_PKT 64
#define DSC_INIT16 0xC000
#define PCH_GBE_DMA_ALIGN 0
#define PCH_GBE_DMA_PADDING 2
#define PCH_GBE_WATCHDOG_PERIOD (5 * HZ) /* watchdog time */
#define PCH_GBE_COPYBREAK_DEFAULT 256
#define PCH_GBE_PCI_BAR 1
#define PCH_GBE_RESERVE_MEMORY 0x200000 /* 2MB */
/* Macros for ML7223 */
#define PCI_VENDOR_ID_ROHM 0x10db
#define PCI_DEVICE_ID_ROHM_ML7223_GBE 0x8013
/* Macros for ML7831 */
#define PCI_DEVICE_ID_ROHM_ML7831_GBE 0x8802
#define PCH_GBE_TX_WEIGHT 64
#define PCH_GBE_RX_WEIGHT 64
#define PCH_GBE_RX_BUFFER_WRITE 16
/* Initialize the wake-on-LAN settings */
#define PCH_GBE_WL_INIT_SETTING (PCH_GBE_WLC_MP)
#define PCH_GBE_MAC_RGMII_CTRL_SETTING ( \
PCH_GBE_CHIP_TYPE_INTERNAL | \
PCH_GBE_RGMII_MODE_RGMII \
)
/* Ethertype field values */
#define PCH_GBE_MAX_RX_BUFFER_SIZE 0x2880
#define PCH_GBE_MAX_JUMBO_FRAME_SIZE 10318
#define PCH_GBE_FRAME_SIZE_2048 2048
#define PCH_GBE_FRAME_SIZE_4096 4096
#define PCH_GBE_FRAME_SIZE_8192 8192
#define PCH_GBE_GET_DESC(R, i, type) (&(((struct type *)((R).desc))[i]))
#define PCH_GBE_RX_DESC(R, i) PCH_GBE_GET_DESC(R, i, pch_gbe_rx_desc)
#define PCH_GBE_TX_DESC(R, i) PCH_GBE_GET_DESC(R, i, pch_gbe_tx_desc)
#define PCH_GBE_DESC_UNUSED(R) \
((((R)->next_to_clean > (R)->next_to_use) ? 0 : (R)->count) + \
(R)->next_to_clean - (R)->next_to_use - 1)
/* Pause packet value */
#define PCH_GBE_PAUSE_PKT1_VALUE 0x00C28001
#define PCH_GBE_PAUSE_PKT2_VALUE 0x00000100
#define PCH_GBE_PAUSE_PKT4_VALUE 0x01000888
#define PCH_GBE_PAUSE_PKT5_VALUE 0x0000FFFF
/* This defines the bits that are set in the Interrupt Mask
* Set/Read Register. Each bit is documented below:
* o RXT0 = Receiver Timer Interrupt (ring 0)
* o TXDW = Transmit Descriptor Written Back
* o RXDMT0 = Receive Descriptor Minimum Threshold hit (ring 0)
* o RXSEQ = Receive Sequence Error
* o LSC = Link Status Change
*/
#define PCH_GBE_INT_ENABLE_MASK ( \
PCH_GBE_INT_RX_DMA_CMPLT | \
PCH_GBE_INT_RX_DSC_EMP | \
PCH_GBE_INT_RX_FIFO_ERR | \
PCH_GBE_INT_WOL_DET | \
PCH_GBE_INT_TX_CMPLT \
)
#define PCH_GBE_INT_DISABLE_ALL 0
/* Macros for ieee1588 */
/* 0x40 Time Synchronization Channel Control Register Bits */
#define MASTER_MODE (1<<0)
#define SLAVE_MODE (0)
#define V2_MODE (1<<31)
#define CAP_MODE0 (0)
#define CAP_MODE2 (1<<17)
/* 0x44 Time Synchronization Channel Event Register Bits */
#define TX_SNAPSHOT_LOCKED (1<<0)
#define RX_SNAPSHOT_LOCKED (1<<1)
#define PTP_L4_MULTICAST_SA "01:00:5e:00:01:81"
#define PTP_L2_MULTICAST_SA "01:1b:19:00:00:00"
#define MINNOW_PHY_RESET_GPIO 13
static unsigned int copybreak __read_mostly = PCH_GBE_COPYBREAK_DEFAULT;
static int pch_gbe_mdio_read(struct net_device *netdev, int addr, int reg);
static void pch_gbe_mdio_write(struct net_device *netdev, int addr, int reg,
int data);
static void pch_gbe_set_multi(struct net_device *netdev);
static int pch_ptp_match(struct sk_buff *skb, u16 uid_hi, u32 uid_lo, u16 seqid)
{
u8 *data = skb->data;
unsigned int offset;
u16 *hi, *id;
u32 lo;
if (ptp_classify_raw(skb) == PTP_CLASS_NONE)
return 0;
offset = ETH_HLEN + IPV4_HLEN(data) + UDP_HLEN;
if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(seqid))
return 0;
hi = (u16 *)(data + offset + OFF_PTP_SOURCE_UUID);
id = (u16 *)(data + offset + OFF_PTP_SEQUENCE_ID);
memcpy(&lo, &hi[1], sizeof(lo));
return (uid_hi == *hi &&
uid_lo == lo &&
seqid == *id);
}
static void
pch_rx_timestamp(struct pch_gbe_adapter *adapter, struct sk_buff *skb)
{
struct skb_shared_hwtstamps *shhwtstamps;
struct pci_dev *pdev;
u64 ns;
u32 hi, lo, val;
u16 uid, seq;
if (!adapter->hwts_rx_en)
return;
/* Get ieee1588's dev information */
pdev = adapter->ptp_pdev;
val = pch_ch_event_read(pdev);
if (!(val & RX_SNAPSHOT_LOCKED))
return;
lo = pch_src_uuid_lo_read(pdev);
hi = pch_src_uuid_hi_read(pdev);
uid = hi & 0xffff;
seq = (hi >> 16) & 0xffff;
if (!pch_ptp_match(skb, htons(uid), htonl(lo), htons(seq)))
goto out;
ns = pch_rx_snap_read(pdev);
shhwtstamps = skb_hwtstamps(skb);
memset(shhwtstamps, 0, sizeof(*shhwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(ns);
out:
pch_ch_event_write(pdev, RX_SNAPSHOT_LOCKED);
}
static void
pch_tx_timestamp(struct pch_gbe_adapter *adapter, struct sk_buff *skb)
{
struct skb_shared_hwtstamps shhwtstamps;
struct pci_dev *pdev;
struct skb_shared_info *shtx;
u64 ns;
u32 cnt, val;
shtx = skb_shinfo(skb);
if (likely(!(shtx->tx_flags & SKBTX_HW_TSTAMP && adapter->hwts_tx_en)))
return;
shtx->tx_flags |= SKBTX_IN_PROGRESS;
/* Get ieee1588's dev information */
pdev = adapter->ptp_pdev;
/*
* This really stinks, but we have to poll for the Tx time stamp.
*/
for (cnt = 0; cnt < 100; cnt++) {
val = pch_ch_event_read(pdev);
if (val & TX_SNAPSHOT_LOCKED)
break;
udelay(1);
}
if (!(val & TX_SNAPSHOT_LOCKED)) {
shtx->tx_flags &= ~SKBTX_IN_PROGRESS;
return;
}
ns = pch_tx_snap_read(pdev);
memset(&shhwtstamps, 0, sizeof(shhwtstamps));
shhwtstamps.hwtstamp = ns_to_ktime(ns);
skb_tstamp_tx(skb, &shhwtstamps);
pch_ch_event_write(pdev, TX_SNAPSHOT_LOCKED);
}
static int hwtstamp_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct hwtstamp_config cfg;
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pci_dev *pdev;
u8 station[20];
if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
return -EFAULT;
if (cfg.flags) /* reserved for future extensions */
return -EINVAL;
/* Get ieee1588's dev information */
pdev = adapter->ptp_pdev;
if (cfg.tx_type != HWTSTAMP_TX_OFF && cfg.tx_type != HWTSTAMP_TX_ON)
return -ERANGE;
switch (cfg.rx_filter) {
case HWTSTAMP_FILTER_NONE:
adapter->hwts_rx_en = 0;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
adapter->hwts_rx_en = 0;
pch_ch_control_write(pdev, SLAVE_MODE | CAP_MODE0);
break;
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
adapter->hwts_rx_en = 1;
pch_ch_control_write(pdev, MASTER_MODE | CAP_MODE0);
break;
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
adapter->hwts_rx_en = 1;
pch_ch_control_write(pdev, V2_MODE | CAP_MODE2);
strcpy(station, PTP_L4_MULTICAST_SA);
pch_set_station_address(station, pdev);
break;
case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
adapter->hwts_rx_en = 1;
pch_ch_control_write(pdev, V2_MODE | CAP_MODE2);
strcpy(station, PTP_L2_MULTICAST_SA);
pch_set_station_address(station, pdev);
break;
default:
return -ERANGE;
}
adapter->hwts_tx_en = cfg.tx_type == HWTSTAMP_TX_ON;
/* Clear out any old time stamps. */
pch_ch_event_write(pdev, TX_SNAPSHOT_LOCKED | RX_SNAPSHOT_LOCKED);
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
static inline void pch_gbe_mac_load_mac_addr(struct pch_gbe_hw *hw)
{
iowrite32(0x01, &hw->reg->MAC_ADDR_LOAD);
}
/**
* pch_gbe_mac_read_mac_addr - Read MAC address
* @hw: Pointer to the HW structure
* Returns:
* 0: Successful.
*/
s32 pch_gbe_mac_read_mac_addr(struct pch_gbe_hw *hw)
{
struct pch_gbe_adapter *adapter = pch_gbe_hw_to_adapter(hw);
u32 adr1a, adr1b;
adr1a = ioread32(&hw->reg->mac_adr[0].high);
adr1b = ioread32(&hw->reg->mac_adr[0].low);
hw->mac.addr[0] = (u8)(adr1a & 0xFF);
hw->mac.addr[1] = (u8)((adr1a >> 8) & 0xFF);
hw->mac.addr[2] = (u8)((adr1a >> 16) & 0xFF);
hw->mac.addr[3] = (u8)((adr1a >> 24) & 0xFF);
hw->mac.addr[4] = (u8)(adr1b & 0xFF);
hw->mac.addr[5] = (u8)((adr1b >> 8) & 0xFF);
netdev_dbg(adapter->netdev, "hw->mac.addr : %pM\n", hw->mac.addr);
return 0;
}
/**
* pch_gbe_wait_clr_bit - Wait to clear a bit
* @reg: Pointer of register
* @busy: Busy bit
*/
static void pch_gbe_wait_clr_bit(void *reg, u32 bit)
{
u32 tmp;
/* wait busy */
tmp = 1000;
while ((ioread32(reg) & bit) && --tmp)
cpu_relax();
if (!tmp)
pr_err("Error: busy bit is not cleared\n");
}
/**
* pch_gbe_mac_mar_set - Set MAC address register
* @hw: Pointer to the HW structure
* @addr: Pointer to the MAC address
* @index: MAC address array register
*/
static void pch_gbe_mac_mar_set(struct pch_gbe_hw *hw, u8 * addr, u32 index)
{
struct pch_gbe_adapter *adapter = pch_gbe_hw_to_adapter(hw);
u32 mar_low, mar_high, adrmask;
netdev_dbg(adapter->netdev, "index : 0x%x\n", index);
/*
* HW expects these in little endian so we reverse the byte order
* from network order (big endian) to little endian
*/
mar_high = ((u32) addr[0] | ((u32) addr[1] << 8) |
((u32) addr[2] << 16) | ((u32) addr[3] << 24));
mar_low = ((u32) addr[4] | ((u32) addr[5] << 8));
/* Stop the MAC Address of index. */
adrmask = ioread32(&hw->reg->ADDR_MASK);
iowrite32((adrmask | (0x0001 << index)), &hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
/* Set the MAC address to the MAC address 1A/1B register */
iowrite32(mar_high, &hw->reg->mac_adr[index].high);
iowrite32(mar_low, &hw->reg->mac_adr[index].low);
/* Start the MAC address of index */
iowrite32((adrmask & ~(0x0001 << index)), &hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
}
/**
* pch_gbe_mac_reset_hw - Reset hardware
* @hw: Pointer to the HW structure
*/
static void pch_gbe_mac_reset_hw(struct pch_gbe_hw *hw)
{
/* Read the MAC address. and store to the private data */
pch_gbe_mac_read_mac_addr(hw);
iowrite32(PCH_GBE_ALL_RST, &hw->reg->RESET);
#ifdef PCH_GBE_MAC_IFOP_RGMII
iowrite32(PCH_GBE_MODE_GMII_ETHER, &hw->reg->MODE);
#endif
pch_gbe_wait_clr_bit(&hw->reg->RESET, PCH_GBE_ALL_RST);
/* Setup the receive addresses */
pch_gbe_mac_mar_set(hw, hw->mac.addr, 0);
return;
}
static void pch_gbe_disable_mac_rx(struct pch_gbe_hw *hw)
{
u32 rctl;
/* Disables Receive MAC */
rctl = ioread32(&hw->reg->MAC_RX_EN);
iowrite32((rctl & ~PCH_GBE_MRE_MAC_RX_EN), &hw->reg->MAC_RX_EN);
}
static void pch_gbe_enable_mac_rx(struct pch_gbe_hw *hw)
{
u32 rctl;
/* Enables Receive MAC */
rctl = ioread32(&hw->reg->MAC_RX_EN);
iowrite32((rctl | PCH_GBE_MRE_MAC_RX_EN), &hw->reg->MAC_RX_EN);
}
/**
* pch_gbe_mac_init_rx_addrs - Initialize receive address's
* @hw: Pointer to the HW structure
* @mar_count: Receive address registers
*/
static void pch_gbe_mac_init_rx_addrs(struct pch_gbe_hw *hw, u16 mar_count)
{
u32 i;
/* Setup the receive address */
pch_gbe_mac_mar_set(hw, hw->mac.addr, 0);
/* Zero out the other receive addresses */
for (i = 1; i < mar_count; i++) {
iowrite32(0, &hw->reg->mac_adr[i].high);
iowrite32(0, &hw->reg->mac_adr[i].low);
}
iowrite32(0xFFFE, &hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
}
/**
* pch_gbe_mac_mc_addr_list_update - Update Multicast addresses
* @hw: Pointer to the HW structure
* @mc_addr_list: Array of multicast addresses to program
* @mc_addr_count: Number of multicast addresses to program
* @mar_used_count: The first MAC Address register free to program
* @mar_total_num: Total number of supported MAC Address Registers
*/
static void pch_gbe_mac_mc_addr_list_update(struct pch_gbe_hw *hw,
u8 *mc_addr_list, u32 mc_addr_count,
u32 mar_used_count, u32 mar_total_num)
{
u32 i, adrmask;
/* Load the first set of multicast addresses into the exact
* filters (RAR). If there are not enough to fill the RAR
* array, clear the filters.
*/
for (i = mar_used_count; i < mar_total_num; i++) {
if (mc_addr_count) {
pch_gbe_mac_mar_set(hw, mc_addr_list, i);
mc_addr_count--;
mc_addr_list += ETH_ALEN;
} else {
/* Clear MAC address mask */
adrmask = ioread32(&hw->reg->ADDR_MASK);
iowrite32((adrmask | (0x0001 << i)),
&hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
/* Clear MAC address */
iowrite32(0, &hw->reg->mac_adr[i].high);
iowrite32(0, &hw->reg->mac_adr[i].low);
}
}
}
/**
* pch_gbe_mac_force_mac_fc - Force the MAC's flow control settings
* @hw: Pointer to the HW structure
* Returns:
* 0: Successful.
* Negative value: Failed.
*/
s32 pch_gbe_mac_force_mac_fc(struct pch_gbe_hw *hw)
{
struct pch_gbe_adapter *adapter = pch_gbe_hw_to_adapter(hw);
struct pch_gbe_mac_info *mac = &hw->mac;
u32 rx_fctrl;
netdev_dbg(adapter->netdev, "mac->fc = %u\n", mac->fc);
rx_fctrl = ioread32(&hw->reg->RX_FCTRL);
switch (mac->fc) {
case PCH_GBE_FC_NONE:
rx_fctrl &= ~PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = false;
break;
case PCH_GBE_FC_RX_PAUSE:
rx_fctrl |= PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = false;
break;
case PCH_GBE_FC_TX_PAUSE:
rx_fctrl &= ~PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = true;
break;
case PCH_GBE_FC_FULL:
rx_fctrl |= PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = true;
break;
default:
netdev_err(adapter->netdev,
"Flow control param set incorrectly\n");
return -EINVAL;
}
if (mac->link_duplex == DUPLEX_HALF)
rx_fctrl &= ~PCH_GBE_FL_CTRL_EN;
iowrite32(rx_fctrl, &hw->reg->RX_FCTRL);
netdev_dbg(adapter->netdev,
"RX_FCTRL reg : 0x%08x mac->tx_fc_enable : %d\n",
ioread32(&hw->reg->RX_FCTRL), mac->tx_fc_enable);
return 0;
}
/**
* pch_gbe_mac_set_wol_event - Set wake-on-lan event
* @hw: Pointer to the HW structure
* @wu_evt: Wake up event
*/
static void pch_gbe_mac_set_wol_event(struct pch_gbe_hw *hw, u32 wu_evt)
{
struct pch_gbe_adapter *adapter = pch_gbe_hw_to_adapter(hw);
u32 addr_mask;
netdev_dbg(adapter->netdev, "wu_evt : 0x%08x ADDR_MASK reg : 0x%08x\n",
wu_evt, ioread32(&hw->reg->ADDR_MASK));
if (wu_evt) {
/* Set Wake-On-Lan address mask */
addr_mask = ioread32(&hw->reg->ADDR_MASK);
iowrite32(addr_mask, &hw->reg->WOL_ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->WOL_ADDR_MASK, PCH_GBE_WLA_BUSY);
iowrite32(0, &hw->reg->WOL_ST);
iowrite32((wu_evt | PCH_GBE_WLC_WOL_MODE), &hw->reg->WOL_CTRL);
iowrite32(0x02, &hw->reg->TCPIP_ACC);
iowrite32(PCH_GBE_INT_ENABLE_MASK, &hw->reg->INT_EN);
} else {
iowrite32(0, &hw->reg->WOL_CTRL);
iowrite32(0, &hw->reg->WOL_ST);
}
return;
}
/**
* pch_gbe_mac_ctrl_miim - Control MIIM interface
* @hw: Pointer to the HW structure
* @addr: Address of PHY
* @dir: Operetion. (Write or Read)
* @reg: Access register of PHY
* @data: Write data.
*
* Returns: Read date.
*/
u16 pch_gbe_mac_ctrl_miim(struct pch_gbe_hw *hw, u32 addr, u32 dir, u32 reg,
u16 data)
{
struct pch_gbe_adapter *adapter = pch_gbe_hw_to_adapter(hw);
u32 data_out = 0;
unsigned int i;
unsigned long flags;
spin_lock_irqsave(&hw->miim_lock, flags);
for (i = 100; i; --i) {
if ((ioread32(&hw->reg->MIIM) & PCH_GBE_MIIM_OPER_READY))
break;
udelay(20);
}
if (i == 0) {
netdev_err(adapter->netdev, "pch-gbe.miim won't go Ready\n");
spin_unlock_irqrestore(&hw->miim_lock, flags);
return 0; /* No way to indicate timeout error */
}
iowrite32(((reg << PCH_GBE_MIIM_REG_ADDR_SHIFT) |
(addr << PCH_GBE_MIIM_PHY_ADDR_SHIFT) |
dir | data), &hw->reg->MIIM);
for (i = 0; i < 100; i++) {
udelay(20);
data_out = ioread32(&hw->reg->MIIM);
if ((data_out & PCH_GBE_MIIM_OPER_READY))
break;
}
spin_unlock_irqrestore(&hw->miim_lock, flags);
netdev_dbg(adapter->netdev, "PHY %s: reg=%d, data=0x%04X\n",
dir == PCH_GBE_MIIM_OPER_READ ? "READ" : "WRITE", reg,
dir == PCH_GBE_MIIM_OPER_READ ? data_out : data);
return (u16) data_out;
}
/**
* pch_gbe_mac_set_pause_packet - Set pause packet
* @hw: Pointer to the HW structure
*/
static void pch_gbe_mac_set_pause_packet(struct pch_gbe_hw *hw)
{
struct pch_gbe_adapter *adapter = pch_gbe_hw_to_adapter(hw);
unsigned long tmp2, tmp3;
/* Set Pause packet */
tmp2 = hw->mac.addr[1];
tmp2 = (tmp2 << 8) | hw->mac.addr[0];
tmp2 = PCH_GBE_PAUSE_PKT2_VALUE | (tmp2 << 16);
tmp3 = hw->mac.addr[5];
tmp3 = (tmp3 << 8) | hw->mac.addr[4];
tmp3 = (tmp3 << 8) | hw->mac.addr[3];
tmp3 = (tmp3 << 8) | hw->mac.addr[2];
iowrite32(PCH_GBE_PAUSE_PKT1_VALUE, &hw->reg->PAUSE_PKT1);
iowrite32(tmp2, &hw->reg->PAUSE_PKT2);
iowrite32(tmp3, &hw->reg->PAUSE_PKT3);
iowrite32(PCH_GBE_PAUSE_PKT4_VALUE, &hw->reg->PAUSE_PKT4);
iowrite32(PCH_GBE_PAUSE_PKT5_VALUE, &hw->reg->PAUSE_PKT5);
/* Transmit Pause Packet */
iowrite32(PCH_GBE_PS_PKT_RQ, &hw->reg->PAUSE_REQ);
netdev_dbg(adapter->netdev,
"PAUSE_PKT1-5 reg : 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
ioread32(&hw->reg->PAUSE_PKT1),
ioread32(&hw->reg->PAUSE_PKT2),
ioread32(&hw->reg->PAUSE_PKT3),
ioread32(&hw->reg->PAUSE_PKT4),
ioread32(&hw->reg->PAUSE_PKT5));
return;
}
/**
* pch_gbe_alloc_queues - Allocate memory for all rings
* @adapter: Board private structure to initialize
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_alloc_queues(struct pch_gbe_adapter *adapter)
{
adapter->tx_ring = devm_kzalloc(&adapter->pdev->dev,
sizeof(*adapter->tx_ring), GFP_KERNEL);
if (!adapter->tx_ring)
return -ENOMEM;
adapter->rx_ring = devm_kzalloc(&adapter->pdev->dev,
sizeof(*adapter->rx_ring), GFP_KERNEL);
if (!adapter->rx_ring)
return -ENOMEM;
return 0;
}
/**
* pch_gbe_init_stats - Initialize status
* @adapter: Board private structure to initialize
*/
static void pch_gbe_init_stats(struct pch_gbe_adapter *adapter)
{
memset(&adapter->stats, 0, sizeof(adapter->stats));
return;
}
/**
* pch_gbe_init_phy - Initialize PHY
* @adapter: Board private structure to initialize
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_init_phy(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 addr;
u16 bmcr, stat;
/* Discover phy addr by searching addrs in order {1,0,2,..., 31} */
for (addr = 0; addr < PCH_GBE_PHY_REGS_LEN; addr++) {
adapter->mii.phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr;
bmcr = pch_gbe_mdio_read(netdev, adapter->mii.phy_id, MII_BMCR);
stat = pch_gbe_mdio_read(netdev, adapter->mii.phy_id, MII_BMSR);
stat = pch_gbe_mdio_read(netdev, adapter->mii.phy_id, MII_BMSR);
if (!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0))))
break;
}
adapter->hw.phy.addr = adapter->mii.phy_id;
netdev_dbg(netdev, "phy_addr = %d\n", adapter->mii.phy_id);
if (addr == PCH_GBE_PHY_REGS_LEN)
return -EAGAIN;
/* Selected the phy and isolate the rest */
for (addr = 0; addr < PCH_GBE_PHY_REGS_LEN; addr++) {
if (addr != adapter->mii.phy_id) {
pch_gbe_mdio_write(netdev, addr, MII_BMCR,
BMCR_ISOLATE);
} else {
bmcr = pch_gbe_mdio_read(netdev, addr, MII_BMCR);
pch_gbe_mdio_write(netdev, addr, MII_BMCR,
bmcr & ~BMCR_ISOLATE);
}
}
/* MII setup */
adapter->mii.phy_id_mask = 0x1F;
adapter->mii.reg_num_mask = 0x1F;
adapter->mii.dev = adapter->netdev;
adapter->mii.mdio_read = pch_gbe_mdio_read;
adapter->mii.mdio_write = pch_gbe_mdio_write;
adapter->mii.supports_gmii = mii_check_gmii_support(&adapter->mii);
return 0;
}
/**
* pch_gbe_mdio_read - The read function for mii
* @netdev: Network interface device structure
* @addr: Phy ID
* @reg: Access location
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_mdio_read(struct net_device *netdev, int addr, int reg)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
return pch_gbe_mac_ctrl_miim(hw, addr, PCH_GBE_HAL_MIIM_READ, reg,
(u16) 0);
}
/**
* pch_gbe_mdio_write - The write function for mii
* @netdev: Network interface device structure
* @addr: Phy ID (not used)
* @reg: Access location
* @data: Write data
*/
static void pch_gbe_mdio_write(struct net_device *netdev,
int addr, int reg, int data)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
pch_gbe_mac_ctrl_miim(hw, addr, PCH_GBE_HAL_MIIM_WRITE, reg, data);
}
/**
* pch_gbe_reset_task - Reset processing at the time of transmission timeout
* @work: Pointer of board private structure
*/
static void pch_gbe_reset_task(struct work_struct *work)
{
struct pch_gbe_adapter *adapter;
adapter = container_of(work, struct pch_gbe_adapter, reset_task);
rtnl_lock();
pch_gbe_reinit_locked(adapter);
rtnl_unlock();
}
/**
* pch_gbe_reinit_locked- Re-initialization
* @adapter: Board private structure
*/
void pch_gbe_reinit_locked(struct pch_gbe_adapter *adapter)
{
pch_gbe_down(adapter);
pch_gbe_up(adapter);
}
/**
* pch_gbe_reset - Reset GbE
* @adapter: Board private structure
*/
void pch_gbe_reset(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
pch_gbe_mac_reset_hw(&adapter->hw);
/* reprogram multicast address register after reset */
pch_gbe_set_multi(netdev);
/* Setup the receive address. */
pch_gbe_mac_init_rx_addrs(&adapter->hw, PCH_GBE_MAR_ENTRIES);
if (pch_gbe_hal_init_hw(&adapter->hw))
netdev_err(netdev, "Hardware Error\n");
}
/**
* pch_gbe_free_irq - Free an interrupt
* @adapter: Board private structure
*/
static void pch_gbe_free_irq(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
free_irq(adapter->pdev->irq, netdev);
if (adapter->have_msi) {
pci_disable_msi(adapter->pdev);
netdev_dbg(netdev, "call pci_disable_msi\n");
}
}
/**
* pch_gbe_irq_disable - Mask off interrupt generation on the NIC
* @adapter: Board private structure
*/
static void pch_gbe_irq_disable(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
atomic_inc(&adapter->irq_sem);
iowrite32(0, &hw->reg->INT_EN);
ioread32(&hw->reg->INT_ST);
synchronize_irq(adapter->pdev->irq);
netdev_dbg(adapter->netdev, "INT_EN reg : 0x%08x\n",
ioread32(&hw->reg->INT_EN));
}
/**
* pch_gbe_irq_enable - Enable default interrupt generation settings
* @adapter: Board private structure
*/
static void pch_gbe_irq_enable(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
if (likely(atomic_dec_and_test(&adapter->irq_sem)))
iowrite32(PCH_GBE_INT_ENABLE_MASK, &hw->reg->INT_EN);
ioread32(&hw->reg->INT_ST);
netdev_dbg(adapter->netdev, "INT_EN reg : 0x%08x\n",
ioread32(&hw->reg->INT_EN));
}
/**
* pch_gbe_setup_tctl - configure the Transmit control registers
* @adapter: Board private structure
*/
static void pch_gbe_setup_tctl(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 tx_mode, tcpip;
tx_mode = PCH_GBE_TM_LONG_PKT |
PCH_GBE_TM_ST_AND_FD |
PCH_GBE_TM_SHORT_PKT |
PCH_GBE_TM_TH_TX_STRT_8 |
PCH_GBE_TM_TH_ALM_EMP_4 | PCH_GBE_TM_TH_ALM_FULL_8;
iowrite32(tx_mode, &hw->reg->TX_MODE);
tcpip = ioread32(&hw->reg->TCPIP_ACC);
tcpip |= PCH_GBE_TX_TCPIPACC_EN;
iowrite32(tcpip, &hw->reg->TCPIP_ACC);
return;
}
/**
* pch_gbe_configure_tx - Configure Transmit Unit after Reset
* @adapter: Board private structure
*/
static void pch_gbe_configure_tx(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 tdba, tdlen, dctrl;
netdev_dbg(adapter->netdev, "dma addr = 0x%08llx size = 0x%08x\n",
(unsigned long long)adapter->tx_ring->dma,
adapter->tx_ring->size);
/* Setup the HW Tx Head and Tail descriptor pointers */
tdba = adapter->tx_ring->dma;
tdlen = adapter->tx_ring->size - 0x10;
iowrite32(tdba, &hw->reg->TX_DSC_BASE);
iowrite32(tdlen, &hw->reg->TX_DSC_SIZE);
iowrite32(tdba, &hw->reg->TX_DSC_SW_P);
/* Enables Transmission DMA */
dctrl = ioread32(&hw->reg->DMA_CTRL);
dctrl |= PCH_GBE_TX_DMA_EN;
iowrite32(dctrl, &hw->reg->DMA_CTRL);
}
/**
* pch_gbe_setup_rctl - Configure the receive control registers
* @adapter: Board private structure
*/
static void pch_gbe_setup_rctl(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 rx_mode, tcpip;
rx_mode = PCH_GBE_ADD_FIL_EN | PCH_GBE_MLT_FIL_EN |
PCH_GBE_RH_ALM_EMP_4 | PCH_GBE_RH_ALM_FULL_4 | PCH_GBE_RH_RD_TRG_8;
iowrite32(rx_mode, &hw->reg->RX_MODE);
tcpip = ioread32(&hw->reg->TCPIP_ACC);
tcpip |= PCH_GBE_RX_TCPIPACC_OFF;
tcpip &= ~PCH_GBE_RX_TCPIPACC_EN;
iowrite32(tcpip, &hw->reg->TCPIP_ACC);
return;
}
/**
* pch_gbe_configure_rx - Configure Receive Unit after Reset
* @adapter: Board private structure
*/
static void pch_gbe_configure_rx(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 rdba, rdlen, rxdma;
netdev_dbg(adapter->netdev, "dma adr = 0x%08llx size = 0x%08x\n",
(unsigned long long)adapter->rx_ring->dma,
adapter->rx_ring->size);
pch_gbe_mac_force_mac_fc(hw);
pch_gbe_disable_mac_rx(hw);
/* Disables Receive DMA */
rxdma = ioread32(&hw->reg->DMA_CTRL);
rxdma &= ~PCH_GBE_RX_DMA_EN;
iowrite32(rxdma, &hw->reg->DMA_CTRL);
netdev_dbg(adapter->netdev,
"MAC_RX_EN reg = 0x%08x DMA_CTRL reg = 0x%08x\n",
ioread32(&hw->reg->MAC_RX_EN),
ioread32(&hw->reg->DMA_CTRL));
/* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring */
rdba = adapter->rx_ring->dma;
rdlen = adapter->rx_ring->size - 0x10;
iowrite32(rdba, &hw->reg->RX_DSC_BASE);
iowrite32(rdlen, &hw->reg->RX_DSC_SIZE);
iowrite32((rdba + rdlen), &hw->reg->RX_DSC_SW_P);
}
/**
* pch_gbe_unmap_and_free_tx_resource - Unmap and free tx socket buffer
* @adapter: Board private structure
* @buffer_info: Buffer information structure
*/
static void pch_gbe_unmap_and_free_tx_resource(
struct pch_gbe_adapter *adapter, struct pch_gbe_buffer *buffer_info)
{
if (buffer_info->mapped) {
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
buffer_info->mapped = false;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
}
/**
* pch_gbe_unmap_and_free_rx_resource - Unmap and free rx socket buffer
* @adapter: Board private structure
* @buffer_info: Buffer information structure
*/
static void pch_gbe_unmap_and_free_rx_resource(
struct pch_gbe_adapter *adapter,
struct pch_gbe_buffer *buffer_info)
{
if (buffer_info->mapped) {
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_FROM_DEVICE);
buffer_info->mapped = false;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
}
/**
* pch_gbe_clean_tx_ring - Free Tx Buffers
* @adapter: Board private structure
* @tx_ring: Ring to be cleaned
*/
static void pch_gbe_clean_tx_ring(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
pch_gbe_unmap_and_free_tx_resource(adapter, buffer_info);
}
netdev_dbg(adapter->netdev,
"call pch_gbe_unmap_and_free_tx_resource() %d count\n", i);
size = (unsigned long)sizeof(struct pch_gbe_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
iowrite32(tx_ring->dma, &hw->reg->TX_DSC_HW_P);
iowrite32((tx_ring->size - 0x10), &hw->reg->TX_DSC_SIZE);
}
/**
* pch_gbe_clean_rx_ring - Free Rx Buffers
* @adapter: Board private structure
* @rx_ring: Ring to free buffers from
*/
static void
pch_gbe_clean_rx_ring(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
pch_gbe_unmap_and_free_rx_resource(adapter, buffer_info);
}
netdev_dbg(adapter->netdev,
"call pch_gbe_unmap_and_free_rx_resource() %d count\n", i);
size = (unsigned long)sizeof(struct pch_gbe_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
iowrite32(rx_ring->dma, &hw->reg->RX_DSC_HW_P);
iowrite32((rx_ring->size - 0x10), &hw->reg->RX_DSC_SIZE);
}
static void pch_gbe_set_rgmii_ctrl(struct pch_gbe_adapter *adapter, u16 speed,
u16 duplex)
{
struct pch_gbe_hw *hw = &adapter->hw;
unsigned long rgmii = 0;
/* Set the RGMII control. */
#ifdef PCH_GBE_MAC_IFOP_RGMII
switch (speed) {
case SPEED_10:
rgmii = (PCH_GBE_RGMII_RATE_2_5M |
PCH_GBE_MAC_RGMII_CTRL_SETTING);
break;
case SPEED_100:
rgmii = (PCH_GBE_RGMII_RATE_25M |
PCH_GBE_MAC_RGMII_CTRL_SETTING);
break;
case SPEED_1000:
rgmii = (PCH_GBE_RGMII_RATE_125M |
PCH_GBE_MAC_RGMII_CTRL_SETTING);
break;
}
iowrite32(rgmii, &hw->reg->RGMII_CTRL);
#else /* GMII */
rgmii = 0;
iowrite32(rgmii, &hw->reg->RGMII_CTRL);
#endif
}
static void pch_gbe_set_mode(struct pch_gbe_adapter *adapter, u16 speed,
u16 duplex)
{
struct net_device *netdev = adapter->netdev;
struct pch_gbe_hw *hw = &adapter->hw;
unsigned long mode = 0;
/* Set the communication mode */
switch (speed) {
case SPEED_10:
mode = PCH_GBE_MODE_MII_ETHER;
netdev->tx_queue_len = 10;
break;
case SPEED_100:
mode = PCH_GBE_MODE_MII_ETHER;
netdev->tx_queue_len = 100;
break;
case SPEED_1000:
mode = PCH_GBE_MODE_GMII_ETHER;
break;
}
if (duplex == DUPLEX_FULL)
mode |= PCH_GBE_MODE_FULL_DUPLEX;
else
mode |= PCH_GBE_MODE_HALF_DUPLEX;
iowrite32(mode, &hw->reg->MODE);
}
/**
* pch_gbe_watchdog - Watchdog process
* @data: Board private structure
*/
static void pch_gbe_watchdog(unsigned long data)
{
struct pch_gbe_adapter *adapter = (struct pch_gbe_adapter *)data;
struct net_device *netdev = adapter->netdev;
struct pch_gbe_hw *hw = &adapter->hw;
netdev_dbg(netdev, "right now = %ld\n", jiffies);
pch_gbe_update_stats(adapter);
if ((mii_link_ok(&adapter->mii)) && (!netif_carrier_ok(netdev))) {
struct ethtool_cmd cmd = { .cmd = ETHTOOL_GSET };
netdev->tx_queue_len = adapter->tx_queue_len;
/* mii library handles link maintenance tasks */
if (mii_ethtool_gset(&adapter->mii, &cmd)) {
netdev_err(netdev, "ethtool get setting Error\n");
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies +
PCH_GBE_WATCHDOG_PERIOD));
return;
}
hw->mac.link_speed = ethtool_cmd_speed(&cmd);
hw->mac.link_duplex = cmd.duplex;
/* Set the RGMII control. */
pch_gbe_set_rgmii_ctrl(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
/* Set the communication mode */
pch_gbe_set_mode(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
netdev_dbg(netdev,
"Link is Up %d Mbps %s-Duplex\n",
hw->mac.link_speed,
cmd.duplex == DUPLEX_FULL ? "Full" : "Half");
netif_carrier_on(netdev);
netif_wake_queue(netdev);
} else if ((!mii_link_ok(&adapter->mii)) &&
(netif_carrier_ok(netdev))) {
netdev_dbg(netdev, "NIC Link is Down\n");
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_HALF;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + PCH_GBE_WATCHDOG_PERIOD));
}
/**
* pch_gbe_tx_queue - Carry out queuing of the transmission data
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring structure
* @skb: Sockt buffer structure
*/
static void pch_gbe_tx_queue(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring,
struct sk_buff *skb)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_tx_desc *tx_desc;
struct pch_gbe_buffer *buffer_info;
struct sk_buff *tmp_skb;
unsigned int frame_ctrl;
unsigned int ring_num;
/*-- Set frame control --*/
frame_ctrl = 0;
if (unlikely(skb->len < PCH_GBE_SHORT_PKT))
frame_ctrl |= PCH_GBE_TXD_CTRL_APAD;
if (skb->ip_summed == CHECKSUM_NONE)
frame_ctrl |= PCH_GBE_TXD_CTRL_TCPIP_ACC_OFF;
/* Performs checksum processing */
/*
* It is because the hardware accelerator does not support a checksum,
* when the received data size is less than 64 bytes.
*/
if (skb->len < PCH_GBE_SHORT_PKT && skb->ip_summed != CHECKSUM_NONE) {
frame_ctrl |= PCH_GBE_TXD_CTRL_APAD |
PCH_GBE_TXD_CTRL_TCPIP_ACC_OFF;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
unsigned int offset;
offset = skb_transport_offset(skb);
if (iph->protocol == IPPROTO_TCP) {
skb->csum = 0;
tcp_hdr(skb)->check = 0;
skb->csum = skb_checksum(skb, offset,
skb->len - offset, 0);
tcp_hdr(skb)->check =
csum_tcpudp_magic(iph->saddr,
iph->daddr,
skb->len - offset,
IPPROTO_TCP,
skb->csum);
} else if (iph->protocol == IPPROTO_UDP) {
skb->csum = 0;
udp_hdr(skb)->check = 0;
skb->csum =
skb_checksum(skb, offset,
skb->len - offset, 0);
udp_hdr(skb)->check =
csum_tcpudp_magic(iph->saddr,
iph->daddr,
skb->len - offset,
IPPROTO_UDP,
skb->csum);
}
}
}
ring_num = tx_ring->next_to_use;
if (unlikely((ring_num + 1) == tx_ring->count))
tx_ring->next_to_use = 0;
else
tx_ring->next_to_use = ring_num + 1;
buffer_info = &tx_ring->buffer_info[ring_num];
tmp_skb = buffer_info->skb;
/* [Header:14][payload] ---> [Header:14][paddong:2][payload] */
memcpy(tmp_skb->data, skb->data, ETH_HLEN);
tmp_skb->data[ETH_HLEN] = 0x00;
tmp_skb->data[ETH_HLEN + 1] = 0x00;
tmp_skb->len = skb->len;
memcpy(&tmp_skb->data[ETH_HLEN + 2], &skb->data[ETH_HLEN],
(skb->len - ETH_HLEN));
/*-- Set Buffer information --*/
buffer_info->length = tmp_skb->len;
buffer_info->dma = dma_map_single(&adapter->pdev->dev, tmp_skb->data,
buffer_info->length,
DMA_TO_DEVICE);
if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
netdev_err(adapter->netdev, "TX DMA map failed\n");
buffer_info->dma = 0;
buffer_info->time_stamp = 0;
tx_ring->next_to_use = ring_num;
return;
}
buffer_info->mapped = true;
buffer_info->time_stamp = jiffies;
/*-- Set Tx descriptor --*/
tx_desc = PCH_GBE_TX_DESC(*tx_ring, ring_num);
tx_desc->buffer_addr = (buffer_info->dma);
tx_desc->length = (tmp_skb->len);
tx_desc->tx_words_eob = ((tmp_skb->len + 3));
tx_desc->tx_frame_ctrl = (frame_ctrl);
tx_desc->gbec_status = (DSC_INIT16);
if (unlikely(++ring_num == tx_ring->count))
ring_num = 0;
/* Update software pointer of TX descriptor */
iowrite32(tx_ring->dma +
(int)sizeof(struct pch_gbe_tx_desc) * ring_num,
&hw->reg->TX_DSC_SW_P);
pch_tx_timestamp(adapter, skb);
dev_kfree_skb_any(skb);
}
/**
* pch_gbe_update_stats - Update the board statistics counters
* @adapter: Board private structure
*/
void pch_gbe_update_stats(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_hw_stats *stats = &adapter->stats;
unsigned long flags;
/*
* Prevent stats update while adapter is being reset, or if the pci
* connection is down.
*/
if ((pdev->error_state) && (pdev->error_state != pci_channel_io_normal))
return;
spin_lock_irqsave(&adapter->stats_lock, flags);
/* Update device status "adapter->stats" */
stats->rx_errors = stats->rx_crc_errors + stats->rx_frame_errors;
stats->tx_errors = stats->tx_length_errors +
stats->tx_aborted_errors +
stats->tx_carrier_errors + stats->tx_timeout_count;
/* Update network device status "adapter->net_stats" */
netdev->stats.rx_packets = stats->rx_packets;
netdev->stats.rx_bytes = stats->rx_bytes;
netdev->stats.rx_dropped = stats->rx_dropped;
netdev->stats.tx_packets = stats->tx_packets;
netdev->stats.tx_bytes = stats->tx_bytes;
netdev->stats.tx_dropped = stats->tx_dropped;
/* Fill out the OS statistics structure */
netdev->stats.multicast = stats->multicast;
netdev->stats.collisions = stats->collisions;
/* Rx Errors */
netdev->stats.rx_errors = stats->rx_errors;
netdev->stats.rx_crc_errors = stats->rx_crc_errors;
netdev->stats.rx_frame_errors = stats->rx_frame_errors;
/* Tx Errors */
netdev->stats.tx_errors = stats->tx_errors;
netdev->stats.tx_aborted_errors = stats->tx_aborted_errors;
netdev->stats.tx_carrier_errors = stats->tx_carrier_errors;
spin_unlock_irqrestore(&adapter->stats_lock, flags);
}
static void pch_gbe_disable_dma_rx(struct pch_gbe_hw *hw)
{
u32 rxdma;
/* Disable Receive DMA */
rxdma = ioread32(&hw->reg->DMA_CTRL);
rxdma &= ~PCH_GBE_RX_DMA_EN;
iowrite32(rxdma, &hw->reg->DMA_CTRL);
}
static void pch_gbe_enable_dma_rx(struct pch_gbe_hw *hw)
{
u32 rxdma;
/* Enables Receive DMA */
rxdma = ioread32(&hw->reg->DMA_CTRL);
rxdma |= PCH_GBE_RX_DMA_EN;
iowrite32(rxdma, &hw->reg->DMA_CTRL);
}
/**
* pch_gbe_intr - Interrupt Handler
* @irq: Interrupt number
* @data: Pointer to a network interface device structure
* Returns:
* - IRQ_HANDLED: Our interrupt
* - IRQ_NONE: Not our interrupt
*/
static irqreturn_t pch_gbe_intr(int irq, void *data)
{
struct net_device *netdev = data;
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
u32 int_st;
u32 int_en;
/* Check request status */
int_st = ioread32(&hw->reg->INT_ST);
int_st = int_st & ioread32(&hw->reg->INT_EN);
/* When request status is no interruption factor */
if (unlikely(!int_st))
return IRQ_NONE; /* Not our interrupt. End processing. */
netdev_dbg(netdev, "%s occur int_st = 0x%08x\n", __func__, int_st);
if (int_st & PCH_GBE_INT_RX_FRAME_ERR)
adapter->stats.intr_rx_frame_err_count++;
if (int_st & PCH_GBE_INT_RX_FIFO_ERR)
if (!adapter->rx_stop_flag) {
adapter->stats.intr_rx_fifo_err_count++;
netdev_dbg(netdev, "Rx fifo over run\n");
adapter->rx_stop_flag = true;
int_en = ioread32(&hw->reg->INT_EN);
iowrite32((int_en & ~PCH_GBE_INT_RX_FIFO_ERR),
&hw->reg->INT_EN);
pch_gbe_disable_dma_rx(&adapter->hw);
int_st |= ioread32(&hw->reg->INT_ST);
int_st = int_st & ioread32(&hw->reg->INT_EN);
}
if (int_st & PCH_GBE_INT_RX_DMA_ERR)
adapter->stats.intr_rx_dma_err_count++;
if (int_st & PCH_GBE_INT_TX_FIFO_ERR)
adapter->stats.intr_tx_fifo_err_count++;
if (int_st & PCH_GBE_INT_TX_DMA_ERR)
adapter->stats.intr_tx_dma_err_count++;
if (int_st & PCH_GBE_INT_TCPIP_ERR)
adapter->stats.intr_tcpip_err_count++;
/* When Rx descriptor is empty */
if ((int_st & PCH_GBE_INT_RX_DSC_EMP)) {
adapter->stats.intr_rx_dsc_empty_count++;
netdev_dbg(netdev, "Rx descriptor is empty\n");
int_en = ioread32(&hw->reg->INT_EN);
iowrite32((int_en & ~PCH_GBE_INT_RX_DSC_EMP), &hw->reg->INT_EN);
if (hw->mac.tx_fc_enable) {
/* Set Pause packet */
pch_gbe_mac_set_pause_packet(hw);
}
}
/* When request status is Receive interruption */
if ((int_st & (PCH_GBE_INT_RX_DMA_CMPLT | PCH_GBE_INT_TX_CMPLT)) ||
(adapter->rx_stop_flag)) {
if (likely(napi_schedule_prep(&adapter->napi))) {
/* Enable only Rx Descriptor empty */
atomic_inc(&adapter->irq_sem);
int_en = ioread32(&hw->reg->INT_EN);
int_en &=
~(PCH_GBE_INT_RX_DMA_CMPLT | PCH_GBE_INT_TX_CMPLT);
iowrite32(int_en, &hw->reg->INT_EN);
/* Start polling for NAPI */
__napi_schedule(&adapter->napi);
}
}
netdev_dbg(netdev, "return = 0x%08x INT_EN reg = 0x%08x\n",
IRQ_HANDLED, ioread32(&hw->reg->INT_EN));
return IRQ_HANDLED;
}
/**
* pch_gbe_alloc_rx_buffers - Replace used receive buffers; legacy & extended
* @adapter: Board private structure
* @rx_ring: Rx descriptor ring
* @cleaned_count: Cleaned count
*/
static void
pch_gbe_alloc_rx_buffers(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring, int cleaned_count)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_rx_desc *rx_desc;
struct pch_gbe_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz;
bufsz = adapter->rx_buffer_len + NET_IP_ALIGN;
i = rx_ring->next_to_use;
while ((cleaned_count--)) {
buffer_info = &rx_ring->buffer_info[i];
skb = netdev_alloc_skb(netdev, bufsz);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->stats.rx_alloc_buff_failed++;
break;
}
/* align */
skb_reserve(skb, NET_IP_ALIGN);
buffer_info->skb = skb;
buffer_info->dma = dma_map_single(&pdev->dev,
buffer_info->rx_buffer,
buffer_info->length,
DMA_FROM_DEVICE);
if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
dev_kfree_skb(skb);
buffer_info->skb = NULL;
buffer_info->dma = 0;
adapter->stats.rx_alloc_buff_failed++;
break; /* while !buffer_info->skb */
}
buffer_info->mapped = true;
rx_desc = PCH_GBE_RX_DESC(*rx_ring, i);
rx_desc->buffer_addr = (buffer_info->dma);
rx_desc->gbec_status = DSC_INIT16;
netdev_dbg(netdev,
"i = %d buffer_info->dma = 0x08%llx buffer_info->length = 0x%x\n",
i, (unsigned long long)buffer_info->dma,
buffer_info->length);
if (unlikely(++i == rx_ring->count))
i = 0;
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
iowrite32(rx_ring->dma +
(int)sizeof(struct pch_gbe_rx_desc) * i,
&hw->reg->RX_DSC_SW_P);
}
return;
}
static int
pch_gbe_alloc_rx_buffers_pool(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring, int cleaned_count)
{
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_buffer *buffer_info;
unsigned int i;
unsigned int bufsz;
unsigned int size;
bufsz = adapter->rx_buffer_len;
size = rx_ring->count * bufsz + PCH_GBE_RESERVE_MEMORY;
rx_ring->rx_buff_pool =
dma_zalloc_coherent(&pdev->dev, size,
&rx_ring->rx_buff_pool_logic, GFP_KERNEL);
if (!rx_ring->rx_buff_pool)
return -ENOMEM;
rx_ring->rx_buff_pool_size = size;
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
buffer_info->rx_buffer = rx_ring->rx_buff_pool + bufsz * i;
buffer_info->length = bufsz;
}
return 0;
}
/**
* pch_gbe_alloc_tx_buffers - Allocate transmit buffers
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring
*/
static void pch_gbe_alloc_tx_buffers(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pch_gbe_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz;
struct pch_gbe_tx_desc *tx_desc;
bufsz =
adapter->hw.mac.max_frame_size + PCH_GBE_DMA_ALIGN + NET_IP_ALIGN;
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
skb = netdev_alloc_skb(adapter->netdev, bufsz);
skb_reserve(skb, PCH_GBE_DMA_ALIGN);
buffer_info->skb = skb;
tx_desc = PCH_GBE_TX_DESC(*tx_ring, i);
tx_desc->gbec_status = (DSC_INIT16);
}
return;
}
/**
* pch_gbe_clean_tx - Reclaim resources after transmit completes
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring
* Returns:
* true: Cleaned the descriptor
* false: Not cleaned the descriptor
*/
static bool
pch_gbe_clean_tx(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pch_gbe_tx_desc *tx_desc;
struct pch_gbe_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int cleaned_count = 0;
bool cleaned = false;
int unused, thresh;
netdev_dbg(adapter->netdev, "next_to_clean : %d\n",
tx_ring->next_to_clean);
i = tx_ring->next_to_clean;
tx_desc = PCH_GBE_TX_DESC(*tx_ring, i);
netdev_dbg(adapter->netdev, "gbec_status:0x%04x dma_status:0x%04x\n",
tx_desc->gbec_status, tx_desc->dma_status);
unused = PCH_GBE_DESC_UNUSED(tx_ring);
thresh = tx_ring->count - PCH_GBE_TX_WEIGHT;
if ((tx_desc->gbec_status == DSC_INIT16) && (unused < thresh))
{ /* current marked clean, tx queue filling up, do extra clean */
int j, k;
if (unused < 8) { /* tx queue nearly full */
netdev_dbg(adapter->netdev,
"clean_tx: transmit queue warning (%x,%x) unused=%d\n",
tx_ring->next_to_clean, tx_ring->next_to_use,
unused);
}
/* current marked clean, scan for more that need cleaning. */
k = i;
for (j = 0; j < PCH_GBE_TX_WEIGHT; j++)
{
tx_desc = PCH_GBE_TX_DESC(*tx_ring, k);
if (tx_desc->gbec_status != DSC_INIT16) break; /*found*/
if (++k >= tx_ring->count) k = 0; /*increment, wrap*/
}
if (j < PCH_GBE_TX_WEIGHT) {
netdev_dbg(adapter->netdev,
"clean_tx: unused=%d loops=%d found tx_desc[%x,%x:%x].gbec_status=%04x\n",
unused, j, i, k, tx_ring->next_to_use,
tx_desc->gbec_status);
i = k; /*found one to clean, usu gbec_status==2000.*/
}
}
while ((tx_desc->gbec_status & DSC_INIT16) == 0x0000) {
netdev_dbg(adapter->netdev, "gbec_status:0x%04x\n",
tx_desc->gbec_status);
buffer_info = &tx_ring->buffer_info[i];
skb = buffer_info->skb;
cleaned = true;
if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_ABT)) {
adapter->stats.tx_aborted_errors++;
netdev_err(adapter->netdev, "Transfer Abort Error\n");
} else if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_CRSER)
) {
adapter->stats.tx_carrier_errors++;
netdev_err(adapter->netdev,
"Transfer Carrier Sense Error\n");
} else if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_EXCOL)
) {
adapter->stats.tx_aborted_errors++;
netdev_err(adapter->netdev,
"Transfer Collision Abort Error\n");
} else if ((tx_desc->gbec_status &
(PCH_GBE_TXD_GMAC_STAT_SNGCOL |
PCH_GBE_TXD_GMAC_STAT_MLTCOL))) {
adapter->stats.collisions++;
adapter->stats.tx_packets++;
adapter->stats.tx_bytes += skb->len;
netdev_dbg(adapter->netdev, "Transfer Collision\n");
} else if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_CMPLT)
) {
adapter->stats.tx_packets++;
adapter->stats.tx_bytes += skb->len;
}
if (buffer_info->mapped) {
netdev_dbg(adapter->netdev,
"unmap buffer_info->dma : %d\n", i);
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
buffer_info->mapped = false;
}
if (buffer_info->skb) {
netdev_dbg(adapter->netdev,
"trim buffer_info->skb : %d\n", i);
skb_trim(buffer_info->skb, 0);
}
tx_desc->gbec_status = DSC_INIT16;
if (unlikely(++i == tx_ring->count))
i = 0;
tx_desc = PCH_GBE_TX_DESC(*tx_ring, i);
/* weight of a sort for tx, to avoid endless transmit cleanup */
if (cleaned_count++ == PCH_GBE_TX_WEIGHT) {
cleaned = false;
break;
}
}
netdev_dbg(adapter->netdev,
"called pch_gbe_unmap_and_free_tx_resource() %d count\n",
cleaned_count);
if (cleaned_count > 0) { /*skip this if nothing cleaned*/
/* Recover from running out of Tx resources in xmit_frame */
netif_tx_lock(adapter->netdev);
if (unlikely(cleaned && (netif_queue_stopped(adapter->netdev))))
{
netif_wake_queue(adapter->netdev);
adapter->stats.tx_restart_count++;
netdev_dbg(adapter->netdev, "Tx wake queue\n");
}
tx_ring->next_to_clean = i;
netdev_dbg(adapter->netdev, "next_to_clean : %d\n",
tx_ring->next_to_clean);
netif_tx_unlock(adapter->netdev);
}
return cleaned;
}
/**
* pch_gbe_clean_rx - Send received data up the network stack; legacy
* @adapter: Board private structure
* @rx_ring: Rx descriptor ring
* @work_done: Completed count
* @work_to_do: Request count
* Returns:
* true: Cleaned the descriptor
* false: Not cleaned the descriptor
*/
static bool
pch_gbe_clean_rx(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring,
int *work_done, int work_to_do)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_buffer *buffer_info;
struct pch_gbe_rx_desc *rx_desc;
u32 length;
unsigned int i;
unsigned int cleaned_count = 0;
bool cleaned = false;
struct sk_buff *skb;
u8 dma_status;
u16 gbec_status;
u32 tcp_ip_status;
i = rx_ring->next_to_clean;
while (*work_done < work_to_do) {
/* Check Rx descriptor status */
rx_desc = PCH_GBE_RX_DESC(*rx_ring, i);
if (rx_desc->gbec_status == DSC_INIT16)
break;
cleaned = true;
cleaned_count++;
dma_status = rx_desc->dma_status;
gbec_status = rx_desc->gbec_status;
tcp_ip_status = rx_desc->tcp_ip_status;
rx_desc->gbec_status = DSC_INIT16;
buffer_info = &rx_ring->buffer_info[i];
skb = buffer_info->skb;
buffer_info->skb = NULL;
/* unmap dma */
dma_unmap_single(&pdev->dev, buffer_info->dma,
buffer_info->length, DMA_FROM_DEVICE);
buffer_info->mapped = false;
netdev_dbg(netdev,
"RxDecNo = 0x%04x Status[DMA:0x%02x GBE:0x%04x TCP:0x%08x] BufInf = 0x%p\n",
i, dma_status, gbec_status, tcp_ip_status,
buffer_info);
/* Error check */
if (unlikely(gbec_status & PCH_GBE_RXD_GMAC_STAT_NOTOCTAL)) {
adapter->stats.rx_frame_errors++;
netdev_err(netdev, "Receive Not Octal Error\n");
} else if (unlikely(gbec_status &
PCH_GBE_RXD_GMAC_STAT_NBLERR)) {
adapter->stats.rx_frame_errors++;
netdev_err(netdev, "Receive Nibble Error\n");
} else if (unlikely(gbec_status &
PCH_GBE_RXD_GMAC_STAT_CRCERR)) {
adapter->stats.rx_crc_errors++;
netdev_err(netdev, "Receive CRC Error\n");
} else {
/* get receive length */
/* length convert[-3], length includes FCS length */
length = (rx_desc->rx_words_eob) - 3 - ETH_FCS_LEN;
if (rx_desc->rx_words_eob & 0x02)
length = length - 4;
/*
* buffer_info->rx_buffer: [Header:14][payload]
* skb->data: [Reserve:2][Header:14][payload]
*/
memcpy(skb->data, buffer_info->rx_buffer, length);
/* update status of driver */
adapter->stats.rx_bytes += length;
adapter->stats.rx_packets++;
if ((gbec_status & PCH_GBE_RXD_GMAC_STAT_MARMLT))
adapter->stats.multicast++;
/* Write meta date of skb */
skb_put(skb, length);
pch_rx_timestamp(adapter, skb);
skb->protocol = eth_type_trans(skb, netdev);
if (tcp_ip_status & PCH_GBE_RXD_ACC_STAT_TCPIPOK)
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb->ip_summed = CHECKSUM_NONE;
napi_gro_receive(&adapter->napi, skb);
(*work_done)++;
netdev_dbg(netdev,
"Receive skb->ip_summed: %d length: %d\n",
skb->ip_summed, length);
}
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= PCH_GBE_RX_BUFFER_WRITE)) {
pch_gbe_alloc_rx_buffers(adapter, rx_ring,
cleaned_count);
cleaned_count = 0;
}
if (++i == rx_ring->count)
i = 0;
}
rx_ring->next_to_clean = i;
if (cleaned_count)
pch_gbe_alloc_rx_buffers(adapter, rx_ring, cleaned_count);
return cleaned;
}
/**
* pch_gbe_setup_tx_resources - Allocate Tx resources (Descriptors)
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring (for a specific queue) to setup
* Returns:
* 0: Successfully
* Negative value: Failed
*/
int pch_gbe_setup_tx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_tx_desc *tx_desc;
int size;
int desNo;
size = (int)sizeof(struct pch_gbe_buffer) * tx_ring->count;
tx_ring->buffer_info = vzalloc(size);
if (!tx_ring->buffer_info)
return -ENOMEM;
tx_ring->size = tx_ring->count * (int)sizeof(struct pch_gbe_tx_desc);
tx_ring->desc = dma_zalloc_coherent(&pdev->dev, tx_ring->size,
&tx_ring->dma, GFP_KERNEL);
if (!tx_ring->desc) {
vfree(tx_ring->buffer_info);
return -ENOMEM;
}
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
for (desNo = 0; desNo < tx_ring->count; desNo++) {
tx_desc = PCH_GBE_TX_DESC(*tx_ring, desNo);
tx_desc->gbec_status = DSC_INIT16;
}
netdev_dbg(adapter->netdev,
"tx_ring->desc = 0x%p tx_ring->dma = 0x%08llx next_to_clean = 0x%08x next_to_use = 0x%08x\n",
tx_ring->desc, (unsigned long long)tx_ring->dma,
tx_ring->next_to_clean, tx_ring->next_to_use);
return 0;
}
/**
* pch_gbe_setup_rx_resources - Allocate Rx resources (Descriptors)
* @adapter: Board private structure
* @rx_ring: Rx descriptor ring (for a specific queue) to setup
* Returns:
* 0: Successfully
* Negative value: Failed
*/
int pch_gbe_setup_rx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_rx_desc *rx_desc;
int size;
int desNo;
size = (int)sizeof(struct pch_gbe_buffer) * rx_ring->count;
rx_ring->buffer_info = vzalloc(size);
if (!rx_ring->buffer_info)
return -ENOMEM;
rx_ring->size = rx_ring->count * (int)sizeof(struct pch_gbe_rx_desc);
rx_ring->desc = dma_zalloc_coherent(&pdev->dev, rx_ring->size,
&rx_ring->dma, GFP_KERNEL);
if (!rx_ring->desc) {
vfree(rx_ring->buffer_info);
return -ENOMEM;
}
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
for (desNo = 0; desNo < rx_ring->count; desNo++) {
rx_desc = PCH_GBE_RX_DESC(*rx_ring, desNo);
rx_desc->gbec_status = DSC_INIT16;
}
netdev_dbg(adapter->netdev,
"rx_ring->desc = 0x%p rx_ring->dma = 0x%08llx next_to_clean = 0x%08x next_to_use = 0x%08x\n",
rx_ring->desc, (unsigned long long)rx_ring->dma,
rx_ring->next_to_clean, rx_ring->next_to_use);
return 0;
}
/**
* pch_gbe_free_tx_resources - Free Tx Resources
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring for a specific queue
*/
void pch_gbe_free_tx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
pch_gbe_clean_tx_ring(adapter, tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
pci_free_consistent(pdev, tx_ring->size, tx_ring->desc, tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* pch_gbe_free_rx_resources - Free Rx Resources
* @adapter: Board private structure
* @rx_ring: Ring to clean the resources from
*/
void pch_gbe_free_rx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
pch_gbe_clean_rx_ring(adapter, rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
pci_free_consistent(pdev, rx_ring->size, rx_ring->desc, rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* pch_gbe_request_irq - Allocate an interrupt line
* @adapter: Board private structure
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_request_irq(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err;
int flags;
flags = IRQF_SHARED;
adapter->have_msi = false;
err = pci_enable_msi(adapter->pdev);
netdev_dbg(netdev, "call pci_enable_msi\n");
if (err) {
netdev_dbg(netdev, "call pci_enable_msi - Error: %d\n", err);
} else {
flags = 0;
adapter->have_msi = true;
}
err = request_irq(adapter->pdev->irq, &pch_gbe_intr,
flags, netdev->name, netdev);
if (err)
netdev_err(netdev, "Unable to allocate interrupt Error: %d\n",
err);
netdev_dbg(netdev,
"adapter->have_msi : %d flags : 0x%04x return : 0x%04x\n",
adapter->have_msi, flags, err);
return err;
}
/**
* pch_gbe_up - Up GbE network device
* @adapter: Board private structure
* Returns:
* 0: Successfully
* Negative value: Failed
*/
int pch_gbe_up(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pch_gbe_tx_ring *tx_ring = adapter->tx_ring;
struct pch_gbe_rx_ring *rx_ring = adapter->rx_ring;
int err = -EINVAL;
/* Ensure we have a valid MAC */
if (!is_valid_ether_addr(adapter->hw.mac.addr)) {
netdev_err(netdev, "Error: Invalid MAC address\n");
goto out;
}
/* hardware has been reset, we need to reload some things */
pch_gbe_set_multi(netdev);
pch_gbe_setup_tctl(adapter);
pch_gbe_configure_tx(adapter);
pch_gbe_setup_rctl(adapter);
pch_gbe_configure_rx(adapter);
err = pch_gbe_request_irq(adapter);
if (err) {
netdev_err(netdev,
"Error: can't bring device up - irq request failed\n");
goto out;
}
err = pch_gbe_alloc_rx_buffers_pool(adapter, rx_ring, rx_ring->count);
if (err) {
netdev_err(netdev,
"Error: can't bring device up - alloc rx buffers pool failed\n");
goto freeirq;
}
pch_gbe_alloc_tx_buffers(adapter, tx_ring);
pch_gbe_alloc_rx_buffers(adapter, rx_ring, rx_ring->count);
adapter->tx_queue_len = netdev->tx_queue_len;
pch_gbe_enable_dma_rx(&adapter->hw);
pch_gbe_enable_mac_rx(&adapter->hw);
mod_timer(&adapter->watchdog_timer, jiffies);
napi_enable(&adapter->napi);
pch_gbe_irq_enable(adapter);
netif_start_queue(adapter->netdev);
return 0;
freeirq:
pch_gbe_free_irq(adapter);
out:
return err;
}
/**
* pch_gbe_down - Down GbE network device
* @adapter: Board private structure
*/
void pch_gbe_down(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_rx_ring *rx_ring = adapter->rx_ring;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
napi_disable(&adapter->napi);
atomic_set(&adapter->irq_sem, 0);
pch_gbe_irq_disable(adapter);
pch_gbe_free_irq(adapter);
del_timer_sync(&adapter->watchdog_timer);
netdev->tx_queue_len = adapter->tx_queue_len;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
if ((pdev->error_state) && (pdev->error_state != pci_channel_io_normal))
pch_gbe_reset(adapter);
pch_gbe_clean_tx_ring(adapter, adapter->tx_ring);
pch_gbe_clean_rx_ring(adapter, adapter->rx_ring);
pci_free_consistent(adapter->pdev, rx_ring->rx_buff_pool_size,
rx_ring->rx_buff_pool, rx_ring->rx_buff_pool_logic);
rx_ring->rx_buff_pool_logic = 0;
rx_ring->rx_buff_pool_size = 0;
rx_ring->rx_buff_pool = NULL;
}
/**
* pch_gbe_sw_init - Initialize general software structures (struct pch_gbe_adapter)
* @adapter: Board private structure to initialize
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_sw_init(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_2048;
hw->mac.max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN;
hw->mac.min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
/* Initialize the hardware-specific values */
if (pch_gbe_hal_setup_init_funcs(hw)) {
netdev_err(netdev, "Hardware Initialization Failure\n");
return -EIO;
}
if (pch_gbe_alloc_queues(adapter)) {
netdev_err(netdev, "Unable to allocate memory for queues\n");
return -ENOMEM;
}
spin_lock_init(&adapter->hw.miim_lock);
spin_lock_init(&adapter->stats_lock);
spin_lock_init(&adapter->ethtool_lock);
atomic_set(&adapter->irq_sem, 0);
pch_gbe_irq_disable(adapter);
pch_gbe_init_stats(adapter);
netdev_dbg(netdev,
"rx_buffer_len : %d mac.min_frame_size : %d mac.max_frame_size : %d\n",
(u32) adapter->rx_buffer_len,
hw->mac.min_frame_size, hw->mac.max_frame_size);
return 0;
}
/**
* pch_gbe_open - Called when a network interface is made active
* @netdev: Network interface device structure
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_open(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
int err;
/* allocate transmit descriptors */
err = pch_gbe_setup_tx_resources(adapter, adapter->tx_ring);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = pch_gbe_setup_rx_resources(adapter, adapter->rx_ring);
if (err)
goto err_setup_rx;
pch_gbe_hal_power_up_phy(hw);
err = pch_gbe_up(adapter);
if (err)
goto err_up;
netdev_dbg(netdev, "Success End\n");
return 0;
err_up:
if (!adapter->wake_up_evt)
pch_gbe_hal_power_down_phy(hw);
pch_gbe_free_rx_resources(adapter, adapter->rx_ring);
err_setup_rx:
pch_gbe_free_tx_resources(adapter, adapter->tx_ring);
err_setup_tx:
pch_gbe_reset(adapter);
netdev_err(netdev, "Error End\n");
return err;
}
/**
* pch_gbe_stop - Disables a network interface
* @netdev: Network interface device structure
* Returns:
* 0: Successfully
*/
static int pch_gbe_stop(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
pch_gbe_down(adapter);
if (!adapter->wake_up_evt)
pch_gbe_hal_power_down_phy(hw);
pch_gbe_free_tx_resources(adapter, adapter->tx_ring);
pch_gbe_free_rx_resources(adapter, adapter->rx_ring);
return 0;
}
/**
* pch_gbe_xmit_frame - Packet transmitting start
* @skb: Socket buffer structure
* @netdev: Network interface device structure
* Returns:
* - NETDEV_TX_OK: Normal end
* - NETDEV_TX_BUSY: Error end
*/
static int pch_gbe_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_tx_ring *tx_ring = adapter->tx_ring;
if (unlikely(!PCH_GBE_DESC_UNUSED(tx_ring))) {
netif_stop_queue(netdev);
netdev_dbg(netdev,
"Return : BUSY next_to use : 0x%08x next_to clean : 0x%08x\n",
tx_ring->next_to_use, tx_ring->next_to_clean);
return NETDEV_TX_BUSY;
}
/* CRC,ITAG no support */
pch_gbe_tx_queue(adapter, tx_ring, skb);
return NETDEV_TX_OK;
}
/**
* pch_gbe_get_stats - Get System Network Statistics
* @netdev: Network interface device structure
* Returns: The current stats
*/
static struct net_device_stats *pch_gbe_get_stats(struct net_device *netdev)
{
/* only return the current stats */
return &netdev->stats;
}
/**
* pch_gbe_set_multi - Multicast and Promiscuous mode set
* @netdev: Network interface device structure
*/
static void pch_gbe_set_multi(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u8 *mta_list;
u32 rctl;
int i;
int mc_count;
netdev_dbg(netdev, "netdev->flags : 0x%08x\n", netdev->flags);
/* Check for Promiscuous and All Multicast modes */
rctl = ioread32(&hw->reg->RX_MODE);
mc_count = netdev_mc_count(netdev);
if ((netdev->flags & IFF_PROMISC)) {
rctl &= ~PCH_GBE_ADD_FIL_EN;
rctl &= ~PCH_GBE_MLT_FIL_EN;
} else if ((netdev->flags & IFF_ALLMULTI)) {
/* all the multicasting receive permissions */
rctl |= PCH_GBE_ADD_FIL_EN;
rctl &= ~PCH_GBE_MLT_FIL_EN;
} else {
if (mc_count >= PCH_GBE_MAR_ENTRIES) {
/* all the multicasting receive permissions */
rctl |= PCH_GBE_ADD_FIL_EN;
rctl &= ~PCH_GBE_MLT_FIL_EN;
} else {
rctl |= (PCH_GBE_ADD_FIL_EN | PCH_GBE_MLT_FIL_EN);
}
}
iowrite32(rctl, &hw->reg->RX_MODE);
if (mc_count >= PCH_GBE_MAR_ENTRIES)
return;
mta_list = kmalloc(mc_count * ETH_ALEN, GFP_ATOMIC);
if (!mta_list)
return;
/* The shared function expects a packed array of only addresses. */
i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i == mc_count)
break;
memcpy(mta_list + (i++ * ETH_ALEN), &ha->addr, ETH_ALEN);
}
pch_gbe_mac_mc_addr_list_update(hw, mta_list, i, 1,
PCH_GBE_MAR_ENTRIES);
kfree(mta_list);
netdev_dbg(netdev,
"RX_MODE reg(check bit31,30 ADD,MLT) : 0x%08x netdev->mc_count : 0x%08x\n",
ioread32(&hw->reg->RX_MODE), mc_count);
}
/**
* pch_gbe_set_mac - Change the Ethernet Address of the NIC
* @netdev: Network interface device structure
* @addr: Pointer to an address structure
* Returns:
* 0: Successfully
* -EADDRNOTAVAIL: Failed
*/
static int pch_gbe_set_mac(struct net_device *netdev, void *addr)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct sockaddr *skaddr = addr;
int ret_val;
if (!is_valid_ether_addr(skaddr->sa_data)) {
ret_val = -EADDRNOTAVAIL;
} else {
memcpy(netdev->dev_addr, skaddr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac.addr, skaddr->sa_data, netdev->addr_len);
pch_gbe_mac_mar_set(&adapter->hw, adapter->hw.mac.addr, 0);
ret_val = 0;
}
netdev_dbg(netdev, "ret_val : 0x%08x\n", ret_val);
netdev_dbg(netdev, "dev_addr : %pM\n", netdev->dev_addr);
netdev_dbg(netdev, "mac_addr : %pM\n", adapter->hw.mac.addr);
netdev_dbg(netdev, "MAC_ADR1AB reg : 0x%08x 0x%08x\n",
ioread32(&adapter->hw.reg->mac_adr[0].high),
ioread32(&adapter->hw.reg->mac_adr[0].low));
return ret_val;
}
/**
* pch_gbe_change_mtu - Change the Maximum Transfer Unit
* @netdev: Network interface device structure
* @new_mtu: New value for maximum frame size
* Returns:
* 0: Successfully
* -EINVAL: Failed
*/
static int pch_gbe_change_mtu(struct net_device *netdev, int new_mtu)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
int max_frame;
unsigned long old_rx_buffer_len = adapter->rx_buffer_len;
int err;
max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN;
if ((max_frame < ETH_ZLEN + ETH_FCS_LEN) ||
(max_frame > PCH_GBE_MAX_JUMBO_FRAME_SIZE)) {
netdev_err(netdev, "Invalid MTU setting\n");
return -EINVAL;
}
if (max_frame <= PCH_GBE_FRAME_SIZE_2048)
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_2048;
else if (max_frame <= PCH_GBE_FRAME_SIZE_4096)
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_4096;
else if (max_frame <= PCH_GBE_FRAME_SIZE_8192)
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_8192;
else
adapter->rx_buffer_len = PCH_GBE_MAX_RX_BUFFER_SIZE;
if (netif_running(netdev)) {
pch_gbe_down(adapter);
err = pch_gbe_up(adapter);
if (err) {
adapter->rx_buffer_len = old_rx_buffer_len;
pch_gbe_up(adapter);
return err;
} else {
netdev->mtu = new_mtu;
adapter->hw.mac.max_frame_size = max_frame;
}
} else {
pch_gbe_reset(adapter);
netdev->mtu = new_mtu;
adapter->hw.mac.max_frame_size = max_frame;
}
netdev_dbg(netdev,
"max_frame : %d rx_buffer_len : %d mtu : %d max_frame_size : %d\n",
max_frame, (u32) adapter->rx_buffer_len, netdev->mtu,
adapter->hw.mac.max_frame_size);
return 0;
}
/**
* pch_gbe_set_features - Reset device after features changed
* @netdev: Network interface device structure
* @features: New features
* Returns:
* 0: HW state updated successfully
*/
static int pch_gbe_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
netdev_features_t changed = features ^ netdev->features;
if (!(changed & NETIF_F_RXCSUM))
return 0;
if (netif_running(netdev))
pch_gbe_reinit_locked(adapter);
else
pch_gbe_reset(adapter);
return 0;
}
/**
* pch_gbe_ioctl - Controls register through a MII interface
* @netdev: Network interface device structure
* @ifr: Pointer to ifr structure
* @cmd: Control command
* Returns:
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
netdev_dbg(netdev, "cmd : 0x%04x\n", cmd);
if (cmd == SIOCSHWTSTAMP)
return hwtstamp_ioctl(netdev, ifr, cmd);
return generic_mii_ioctl(&adapter->mii, if_mii(ifr), cmd, NULL);
}
/**
* pch_gbe_tx_timeout - Respond to a Tx Hang
* @netdev: Network interface device structure
*/
static void pch_gbe_tx_timeout(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->stats.tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
/**
* pch_gbe_napi_poll - NAPI receive and transfer polling callback
* @napi: Pointer of polling device struct
* @budget: The maximum number of a packet
* Returns:
* false: Exit the polling mode
* true: Continue the polling mode
*/
static int pch_gbe_napi_poll(struct napi_struct *napi, int budget)
{
struct pch_gbe_adapter *adapter =
container_of(napi, struct pch_gbe_adapter, napi);
int work_done = 0;
bool poll_end_flag = false;
bool cleaned = false;
netdev_dbg(adapter->netdev, "budget : %d\n", budget);
pch_gbe_clean_rx(adapter, adapter->rx_ring, &work_done, budget);
cleaned = pch_gbe_clean_tx(adapter, adapter->tx_ring);
if (cleaned)
work_done = budget;
/* If no Tx and not enough Rx work done,
* exit the polling mode
*/
if (work_done < budget)
poll_end_flag = true;
if (poll_end_flag) {
napi_complete(napi);
pch_gbe_irq_enable(adapter);
}
if (adapter->rx_stop_flag) {
adapter->rx_stop_flag = false;
pch_gbe_enable_dma_rx(&adapter->hw);
}
netdev_dbg(adapter->netdev,
"poll_end_flag : %d work_done : %d budget : %d\n",
poll_end_flag, work_done, budget);
return work_done;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/**
* pch_gbe_netpoll - Used by things like netconsole to send skbs
* @netdev: Network interface device structure
*/
static void pch_gbe_netpoll(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
disable_irq(adapter->pdev->irq);
pch_gbe_intr(adapter->pdev->irq, netdev);
enable_irq(adapter->pdev->irq);
}
#endif
static const struct net_device_ops pch_gbe_netdev_ops = {
.ndo_open = pch_gbe_open,
.ndo_stop = pch_gbe_stop,
.ndo_start_xmit = pch_gbe_xmit_frame,
.ndo_get_stats = pch_gbe_get_stats,
.ndo_set_mac_address = pch_gbe_set_mac,
.ndo_tx_timeout = pch_gbe_tx_timeout,
.ndo_change_mtu = pch_gbe_change_mtu,
.ndo_set_features = pch_gbe_set_features,
.ndo_do_ioctl = pch_gbe_ioctl,
.ndo_set_rx_mode = pch_gbe_set_multi,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = pch_gbe_netpoll,
#endif
};
static pci_ers_result_t pch_gbe_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (netif_running(netdev))
pch_gbe_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
static pci_ers_result_t pch_gbe_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
if (pci_enable_device(pdev)) {
netdev_err(netdev, "Cannot re-enable PCI device after reset\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D0, 0);
pch_gbe_hal_power_up_phy(hw);
pch_gbe_reset(adapter);
/* Clear wake up status */
pch_gbe_mac_set_wol_event(hw, 0);
return PCI_ERS_RESULT_RECOVERED;
}
static void pch_gbe_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev)) {
if (pch_gbe_up(adapter)) {
netdev_dbg(netdev,
"can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
}
static int __pch_gbe_suspend(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
u32 wufc = adapter->wake_up_evt;
int retval = 0;
netif_device_detach(netdev);
if (netif_running(netdev))
pch_gbe_down(adapter);
if (wufc) {
pch_gbe_set_multi(netdev);
pch_gbe_setup_rctl(adapter);
pch_gbe_configure_rx(adapter);
pch_gbe_set_rgmii_ctrl(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
pch_gbe_set_mode(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
pch_gbe_mac_set_wol_event(hw, wufc);
pci_disable_device(pdev);
} else {
pch_gbe_hal_power_down_phy(hw);
pch_gbe_mac_set_wol_event(hw, wufc);
pci_disable_device(pdev);
}
return retval;
}
#ifdef CONFIG_PM
static int pch_gbe_suspend(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
return __pch_gbe_suspend(pdev);
}
static int pch_gbe_resume(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
u32 err;
err = pci_enable_device(pdev);
if (err) {
netdev_err(netdev, "Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pch_gbe_hal_power_up_phy(hw);
pch_gbe_reset(adapter);
/* Clear wake on lan control and status */
pch_gbe_mac_set_wol_event(hw, 0);
if (netif_running(netdev))
pch_gbe_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif /* CONFIG_PM */
static void pch_gbe_shutdown(struct pci_dev *pdev)
{
__pch_gbe_suspend(pdev);
if (system_state == SYSTEM_POWER_OFF) {
pci_wake_from_d3(pdev, true);
pci_set_power_state(pdev, PCI_D3hot);
}
}
static void pch_gbe_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
cancel_work_sync(&adapter->reset_task);
unregister_netdev(netdev);
pch_gbe_hal_phy_hw_reset(&adapter->hw);
free_netdev(netdev);
}
static int pch_gbe_probe(struct pci_dev *pdev,
const struct pci_device_id *pci_id)
{
struct net_device *netdev;
struct pch_gbe_adapter *adapter;
int ret;
ret = pcim_enable_device(pdev);
if (ret)
return ret;
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64))
|| pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
ret = pci_set_consistent_dma_mask(pdev,
DMA_BIT_MASK(32));
if (ret) {
dev_err(&pdev->dev, "ERR: No usable DMA "
"configuration, aborting\n");
return ret;
}
}
}
ret = pcim_iomap_regions(pdev, 1 << PCH_GBE_PCI_BAR, pci_name(pdev));
if (ret) {
dev_err(&pdev->dev,
"ERR: Can't reserve PCI I/O and memory resources\n");
return ret;
}
pci_set_master(pdev);
netdev = alloc_etherdev((int)sizeof(struct pch_gbe_adapter));
if (!netdev)
return -ENOMEM;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
adapter->hw.reg = pcim_iomap_table(pdev)[PCH_GBE_PCI_BAR];
adapter->pdata = (struct pch_gbe_privdata *)pci_id->driver_data;
if (adapter->pdata && adapter->pdata->platform_init)
adapter->pdata->platform_init(pdev);
adapter->ptp_pdev = pci_get_bus_and_slot(adapter->pdev->bus->number,
PCI_DEVFN(12, 4));
netdev->netdev_ops = &pch_gbe_netdev_ops;
netdev->watchdog_timeo = PCH_GBE_WATCHDOG_PERIOD;
netif_napi_add(netdev, &adapter->napi,
pch_gbe_napi_poll, PCH_GBE_RX_WEIGHT);
netdev->hw_features = NETIF_F_RXCSUM |
NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
netdev->features = netdev->hw_features;
pch_gbe_set_ethtool_ops(netdev);
pch_gbe_mac_load_mac_addr(&adapter->hw);
pch_gbe_mac_reset_hw(&adapter->hw);
/* setup the private structure */
ret = pch_gbe_sw_init(adapter);
if (ret)
goto err_free_netdev;
/* Initialize PHY */
ret = pch_gbe_init_phy(adapter);
if (ret) {
dev_err(&pdev->dev, "PHY initialize error\n");
goto err_free_adapter;
}
pch_gbe_hal_get_bus_info(&adapter->hw);
/* Read the MAC address. and store to the private data */
ret = pch_gbe_hal_read_mac_addr(&adapter->hw);
if (ret) {
dev_err(&pdev->dev, "MAC address Read Error\n");
goto err_free_adapter;
}
memcpy(netdev->dev_addr, adapter->hw.mac.addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->dev_addr)) {
/*
* If the MAC is invalid (or just missing), display a warning
* but do not abort setting up the device. pch_gbe_up will
* prevent the interface from being brought up until a valid MAC
* is set.
*/
dev_err(&pdev->dev, "Invalid MAC address, "
"interface disabled.\n");
}
setup_timer(&adapter->watchdog_timer, pch_gbe_watchdog,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, pch_gbe_reset_task);
pch_gbe_check_options(adapter);
/* initialize the wol settings based on the eeprom settings */
adapter->wake_up_evt = PCH_GBE_WL_INIT_SETTING;
dev_info(&pdev->dev, "MAC address : %pM\n", netdev->dev_addr);
/* reset the hardware with the new settings */
pch_gbe_reset(adapter);
ret = register_netdev(netdev);
if (ret)
goto err_free_adapter;
/* tell the stack to leave us alone until pch_gbe_open() is called */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
dev_dbg(&pdev->dev, "PCH Network Connection\n");
/* Disable hibernation on certain platforms */
if (adapter->pdata && adapter->pdata->phy_disable_hibernate)
pch_gbe_phy_disable_hibernate(&adapter->hw);
device_set_wakeup_enable(&pdev->dev, 1);
return 0;
err_free_adapter:
pch_gbe_hal_phy_hw_reset(&adapter->hw);
err_free_netdev:
free_netdev(netdev);
return ret;
}
/* The AR803X PHY on the MinnowBoard requires a physical pin to be toggled to
* ensure it is awake for probe and init. Request the line and reset the PHY.
*/
static int pch_gbe_minnow_platform_init(struct pci_dev *pdev)
{
unsigned long flags = GPIOF_DIR_OUT | GPIOF_INIT_HIGH | GPIOF_EXPORT;
unsigned gpio = MINNOW_PHY_RESET_GPIO;
int ret;
ret = devm_gpio_request_one(&pdev->dev, gpio, flags,
"minnow_phy_reset");
if (ret) {
dev_err(&pdev->dev,
"ERR: Can't request PHY reset GPIO line '%d'\n", gpio);
return ret;
}
gpio_set_value(gpio, 0);
usleep_range(1250, 1500);
gpio_set_value(gpio, 1);
usleep_range(1250, 1500);
return ret;
}
static struct pch_gbe_privdata pch_gbe_minnow_privdata = {
.phy_tx_clk_delay = true,
.phy_disable_hibernate = true,
.platform_init = pch_gbe_minnow_platform_init,
};
static const struct pci_device_id pch_gbe_pcidev_id[] = {
{.vendor = PCI_VENDOR_ID_INTEL,
.device = PCI_DEVICE_ID_INTEL_IOH1_GBE,
.subvendor = PCI_VENDOR_ID_CIRCUITCO,
.subdevice = PCI_SUBSYSTEM_ID_CIRCUITCO_MINNOWBOARD,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00),
.driver_data = (kernel_ulong_t)&pch_gbe_minnow_privdata
},
{.vendor = PCI_VENDOR_ID_INTEL,
.device = PCI_DEVICE_ID_INTEL_IOH1_GBE,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00)
},
{.vendor = PCI_VENDOR_ID_ROHM,
.device = PCI_DEVICE_ID_ROHM_ML7223_GBE,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00)
},
{.vendor = PCI_VENDOR_ID_ROHM,
.device = PCI_DEVICE_ID_ROHM_ML7831_GBE,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00)
},
/* required last entry */
{0}
};
#ifdef CONFIG_PM
static const struct dev_pm_ops pch_gbe_pm_ops = {
.suspend = pch_gbe_suspend,
.resume = pch_gbe_resume,
.freeze = pch_gbe_suspend,
.thaw = pch_gbe_resume,
.poweroff = pch_gbe_suspend,
.restore = pch_gbe_resume,
};
#endif
static const struct pci_error_handlers pch_gbe_err_handler = {
.error_detected = pch_gbe_io_error_detected,
.slot_reset = pch_gbe_io_slot_reset,
.resume = pch_gbe_io_resume
};
static struct pci_driver pch_gbe_driver = {
.name = KBUILD_MODNAME,
.id_table = pch_gbe_pcidev_id,
.probe = pch_gbe_probe,
.remove = pch_gbe_remove,
#ifdef CONFIG_PM
.driver.pm = &pch_gbe_pm_ops,
#endif
.shutdown = pch_gbe_shutdown,
.err_handler = &pch_gbe_err_handler
};
static int __init pch_gbe_init_module(void)
{
int ret;
pr_info("EG20T PCH Gigabit Ethernet Driver - version %s\n",DRV_VERSION);
ret = pci_register_driver(&pch_gbe_driver);
if (copybreak != PCH_GBE_COPYBREAK_DEFAULT) {
if (copybreak == 0) {
pr_info("copybreak disabled\n");
} else {
pr_info("copybreak enabled for packets <= %u bytes\n",
copybreak);
}
}
return ret;
}
static void __exit pch_gbe_exit_module(void)
{
pci_unregister_driver(&pch_gbe_driver);
}
module_init(pch_gbe_init_module);
module_exit(pch_gbe_exit_module);
MODULE_DESCRIPTION("EG20T PCH Gigabit ethernet Driver");
MODULE_AUTHOR("LAPIS SEMICONDUCTOR, <tshimizu818@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DEVICE_TABLE(pci, pch_gbe_pcidev_id);
module_param(copybreak, uint, 0644);
MODULE_PARM_DESC(copybreak,
"Maximum size of packet that is copied to a new buffer on receive");
/* pch_gbe_main.c */
| gpl-2.0 |
xerpi/linux | drivers/ssb/driver_chipcommon_pmu.c | 1192 | 22408 | /*
* Sonics Silicon Backplane
* Broadcom ChipCommon Power Management Unit driver
*
* Copyright 2009, Michael Buesch <m@bues.ch>
* Copyright 2007, Broadcom Corporation
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/ssb/ssb.h>
#include <linux/ssb/ssb_regs.h>
#include <linux/ssb/ssb_driver_chipcommon.h>
#include <linux/delay.h>
#include <linux/export.h>
#ifdef CONFIG_BCM47XX
#include <linux/bcm47xx_nvram.h>
#endif
#include "ssb_private.h"
static u32 ssb_chipco_pll_read(struct ssb_chipcommon *cc, u32 offset)
{
chipco_write32(cc, SSB_CHIPCO_PLLCTL_ADDR, offset);
return chipco_read32(cc, SSB_CHIPCO_PLLCTL_DATA);
}
static void ssb_chipco_pll_write(struct ssb_chipcommon *cc,
u32 offset, u32 value)
{
chipco_write32(cc, SSB_CHIPCO_PLLCTL_ADDR, offset);
chipco_write32(cc, SSB_CHIPCO_PLLCTL_DATA, value);
}
static void ssb_chipco_regctl_maskset(struct ssb_chipcommon *cc,
u32 offset, u32 mask, u32 set)
{
u32 value;
chipco_read32(cc, SSB_CHIPCO_REGCTL_ADDR);
chipco_write32(cc, SSB_CHIPCO_REGCTL_ADDR, offset);
chipco_read32(cc, SSB_CHIPCO_REGCTL_ADDR);
value = chipco_read32(cc, SSB_CHIPCO_REGCTL_DATA);
value &= mask;
value |= set;
chipco_write32(cc, SSB_CHIPCO_REGCTL_DATA, value);
chipco_read32(cc, SSB_CHIPCO_REGCTL_DATA);
}
struct pmu0_plltab_entry {
u16 freq; /* Crystal frequency in kHz.*/
u8 xf; /* Crystal frequency value for PMU control */
u8 wb_int;
u32 wb_frac;
};
static const struct pmu0_plltab_entry pmu0_plltab[] = {
{ .freq = 12000, .xf = 1, .wb_int = 73, .wb_frac = 349525, },
{ .freq = 13000, .xf = 2, .wb_int = 67, .wb_frac = 725937, },
{ .freq = 14400, .xf = 3, .wb_int = 61, .wb_frac = 116508, },
{ .freq = 15360, .xf = 4, .wb_int = 57, .wb_frac = 305834, },
{ .freq = 16200, .xf = 5, .wb_int = 54, .wb_frac = 336579, },
{ .freq = 16800, .xf = 6, .wb_int = 52, .wb_frac = 399457, },
{ .freq = 19200, .xf = 7, .wb_int = 45, .wb_frac = 873813, },
{ .freq = 19800, .xf = 8, .wb_int = 44, .wb_frac = 466033, },
{ .freq = 20000, .xf = 9, .wb_int = 44, .wb_frac = 0, },
{ .freq = 25000, .xf = 10, .wb_int = 70, .wb_frac = 419430, },
{ .freq = 26000, .xf = 11, .wb_int = 67, .wb_frac = 725937, },
{ .freq = 30000, .xf = 12, .wb_int = 58, .wb_frac = 699050, },
{ .freq = 38400, .xf = 13, .wb_int = 45, .wb_frac = 873813, },
{ .freq = 40000, .xf = 14, .wb_int = 45, .wb_frac = 0, },
};
#define SSB_PMU0_DEFAULT_XTALFREQ 20000
static const struct pmu0_plltab_entry * pmu0_plltab_find_entry(u32 crystalfreq)
{
const struct pmu0_plltab_entry *e;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(pmu0_plltab); i++) {
e = &pmu0_plltab[i];
if (e->freq == crystalfreq)
return e;
}
return NULL;
}
/* Tune the PLL to the crystal speed. crystalfreq is in kHz. */
static void ssb_pmu0_pllinit_r0(struct ssb_chipcommon *cc,
u32 crystalfreq)
{
struct ssb_bus *bus = cc->dev->bus;
const struct pmu0_plltab_entry *e = NULL;
u32 pmuctl, tmp, pllctl;
unsigned int i;
if (crystalfreq)
e = pmu0_plltab_find_entry(crystalfreq);
if (!e)
e = pmu0_plltab_find_entry(SSB_PMU0_DEFAULT_XTALFREQ);
BUG_ON(!e);
crystalfreq = e->freq;
cc->pmu.crystalfreq = e->freq;
/* Check if the PLL already is programmed to this frequency. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
if (((pmuctl & SSB_CHIPCO_PMU_CTL_XTALFREQ) >> SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) == e->xf) {
/* We're already there... */
return;
}
ssb_info("Programming PLL to %u.%03u MHz\n",
crystalfreq / 1000, crystalfreq % 1000);
/* First turn the PLL off. */
switch (bus->chip_id) {
case 0x4328:
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK,
~(1 << SSB_PMURES_4328_BB_PLL_PU));
chipco_mask32(cc, SSB_CHIPCO_PMU_MAXRES_MSK,
~(1 << SSB_PMURES_4328_BB_PLL_PU));
break;
case 0x5354:
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK,
~(1 << SSB_PMURES_5354_BB_PLL_PU));
chipco_mask32(cc, SSB_CHIPCO_PMU_MAXRES_MSK,
~(1 << SSB_PMURES_5354_BB_PLL_PU));
break;
default:
SSB_WARN_ON(1);
}
for (i = 1500; i; i--) {
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (!(tmp & SSB_CHIPCO_CLKCTLST_HAVEHT))
break;
udelay(10);
}
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (tmp & SSB_CHIPCO_CLKCTLST_HAVEHT)
ssb_emerg("Failed to turn the PLL off!\n");
/* Set PDIV in PLL control 0. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU0_PLLCTL0);
if (crystalfreq >= SSB_PMU0_PLLCTL0_PDIV_FREQ)
pllctl |= SSB_PMU0_PLLCTL0_PDIV_MSK;
else
pllctl &= ~SSB_PMU0_PLLCTL0_PDIV_MSK;
ssb_chipco_pll_write(cc, SSB_PMU0_PLLCTL0, pllctl);
/* Set WILD in PLL control 1. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU0_PLLCTL1);
pllctl &= ~SSB_PMU0_PLLCTL1_STOPMOD;
pllctl &= ~(SSB_PMU0_PLLCTL1_WILD_IMSK | SSB_PMU0_PLLCTL1_WILD_FMSK);
pllctl |= ((u32)e->wb_int << SSB_PMU0_PLLCTL1_WILD_IMSK_SHIFT) & SSB_PMU0_PLLCTL1_WILD_IMSK;
pllctl |= ((u32)e->wb_frac << SSB_PMU0_PLLCTL1_WILD_FMSK_SHIFT) & SSB_PMU0_PLLCTL1_WILD_FMSK;
if (e->wb_frac == 0)
pllctl |= SSB_PMU0_PLLCTL1_STOPMOD;
ssb_chipco_pll_write(cc, SSB_PMU0_PLLCTL1, pllctl);
/* Set WILD in PLL control 2. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU0_PLLCTL2);
pllctl &= ~SSB_PMU0_PLLCTL2_WILD_IMSKHI;
pllctl |= (((u32)e->wb_int >> 4) << SSB_PMU0_PLLCTL2_WILD_IMSKHI_SHIFT) & SSB_PMU0_PLLCTL2_WILD_IMSKHI;
ssb_chipco_pll_write(cc, SSB_PMU0_PLLCTL2, pllctl);
/* Set the crystalfrequency and the divisor. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
pmuctl &= ~SSB_CHIPCO_PMU_CTL_ILP_DIV;
pmuctl |= (((crystalfreq + 127) / 128 - 1) << SSB_CHIPCO_PMU_CTL_ILP_DIV_SHIFT)
& SSB_CHIPCO_PMU_CTL_ILP_DIV;
pmuctl &= ~SSB_CHIPCO_PMU_CTL_XTALFREQ;
pmuctl |= ((u32)e->xf << SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) & SSB_CHIPCO_PMU_CTL_XTALFREQ;
chipco_write32(cc, SSB_CHIPCO_PMU_CTL, pmuctl);
}
struct pmu1_plltab_entry {
u16 freq; /* Crystal frequency in kHz.*/
u8 xf; /* Crystal frequency value for PMU control */
u8 ndiv_int;
u32 ndiv_frac;
u8 p1div;
u8 p2div;
};
static const struct pmu1_plltab_entry pmu1_plltab[] = {
{ .freq = 12000, .xf = 1, .p1div = 3, .p2div = 22, .ndiv_int = 0x9, .ndiv_frac = 0xFFFFEF, },
{ .freq = 13000, .xf = 2, .p1div = 1, .p2div = 6, .ndiv_int = 0xb, .ndiv_frac = 0x483483, },
{ .freq = 14400, .xf = 3, .p1div = 1, .p2div = 10, .ndiv_int = 0xa, .ndiv_frac = 0x1C71C7, },
{ .freq = 15360, .xf = 4, .p1div = 1, .p2div = 5, .ndiv_int = 0xb, .ndiv_frac = 0x755555, },
{ .freq = 16200, .xf = 5, .p1div = 1, .p2div = 10, .ndiv_int = 0x5, .ndiv_frac = 0x6E9E06, },
{ .freq = 16800, .xf = 6, .p1div = 1, .p2div = 10, .ndiv_int = 0x5, .ndiv_frac = 0x3CF3CF, },
{ .freq = 19200, .xf = 7, .p1div = 1, .p2div = 9, .ndiv_int = 0x5, .ndiv_frac = 0x17B425, },
{ .freq = 19800, .xf = 8, .p1div = 1, .p2div = 11, .ndiv_int = 0x4, .ndiv_frac = 0xA57EB, },
{ .freq = 20000, .xf = 9, .p1div = 1, .p2div = 11, .ndiv_int = 0x4, .ndiv_frac = 0, },
{ .freq = 24000, .xf = 10, .p1div = 3, .p2div = 11, .ndiv_int = 0xa, .ndiv_frac = 0, },
{ .freq = 25000, .xf = 11, .p1div = 5, .p2div = 16, .ndiv_int = 0xb, .ndiv_frac = 0, },
{ .freq = 26000, .xf = 12, .p1div = 1, .p2div = 2, .ndiv_int = 0x10, .ndiv_frac = 0xEC4EC4, },
{ .freq = 30000, .xf = 13, .p1div = 3, .p2div = 8, .ndiv_int = 0xb, .ndiv_frac = 0, },
{ .freq = 38400, .xf = 14, .p1div = 1, .p2div = 5, .ndiv_int = 0x4, .ndiv_frac = 0x955555, },
{ .freq = 40000, .xf = 15, .p1div = 1, .p2div = 2, .ndiv_int = 0xb, .ndiv_frac = 0, },
};
#define SSB_PMU1_DEFAULT_XTALFREQ 15360
static const struct pmu1_plltab_entry * pmu1_plltab_find_entry(u32 crystalfreq)
{
const struct pmu1_plltab_entry *e;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(pmu1_plltab); i++) {
e = &pmu1_plltab[i];
if (e->freq == crystalfreq)
return e;
}
return NULL;
}
/* Tune the PLL to the crystal speed. crystalfreq is in kHz. */
static void ssb_pmu1_pllinit_r0(struct ssb_chipcommon *cc,
u32 crystalfreq)
{
struct ssb_bus *bus = cc->dev->bus;
const struct pmu1_plltab_entry *e = NULL;
u32 buffer_strength = 0;
u32 tmp, pllctl, pmuctl;
unsigned int i;
if (bus->chip_id == 0x4312) {
/* We do not touch the BCM4312 PLL and assume
* the default crystal settings work out-of-the-box. */
cc->pmu.crystalfreq = 20000;
return;
}
if (crystalfreq)
e = pmu1_plltab_find_entry(crystalfreq);
if (!e)
e = pmu1_plltab_find_entry(SSB_PMU1_DEFAULT_XTALFREQ);
BUG_ON(!e);
crystalfreq = e->freq;
cc->pmu.crystalfreq = e->freq;
/* Check if the PLL already is programmed to this frequency. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
if (((pmuctl & SSB_CHIPCO_PMU_CTL_XTALFREQ) >> SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) == e->xf) {
/* We're already there... */
return;
}
ssb_info("Programming PLL to %u.%03u MHz\n",
crystalfreq / 1000, crystalfreq % 1000);
/* First turn the PLL off. */
switch (bus->chip_id) {
case 0x4325:
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK,
~((1 << SSB_PMURES_4325_BBPLL_PWRSW_PU) |
(1 << SSB_PMURES_4325_HT_AVAIL)));
chipco_mask32(cc, SSB_CHIPCO_PMU_MAXRES_MSK,
~((1 << SSB_PMURES_4325_BBPLL_PWRSW_PU) |
(1 << SSB_PMURES_4325_HT_AVAIL)));
/* Adjust the BBPLL to 2 on all channels later. */
buffer_strength = 0x222222;
break;
default:
SSB_WARN_ON(1);
}
for (i = 1500; i; i--) {
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (!(tmp & SSB_CHIPCO_CLKCTLST_HAVEHT))
break;
udelay(10);
}
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (tmp & SSB_CHIPCO_CLKCTLST_HAVEHT)
ssb_emerg("Failed to turn the PLL off!\n");
/* Set p1div and p2div. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL0);
pllctl &= ~(SSB_PMU1_PLLCTL0_P1DIV | SSB_PMU1_PLLCTL0_P2DIV);
pllctl |= ((u32)e->p1div << SSB_PMU1_PLLCTL0_P1DIV_SHIFT) & SSB_PMU1_PLLCTL0_P1DIV;
pllctl |= ((u32)e->p2div << SSB_PMU1_PLLCTL0_P2DIV_SHIFT) & SSB_PMU1_PLLCTL0_P2DIV;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL0, pllctl);
/* Set ndiv int and ndiv mode */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL2);
pllctl &= ~(SSB_PMU1_PLLCTL2_NDIVINT | SSB_PMU1_PLLCTL2_NDIVMODE);
pllctl |= ((u32)e->ndiv_int << SSB_PMU1_PLLCTL2_NDIVINT_SHIFT) & SSB_PMU1_PLLCTL2_NDIVINT;
pllctl |= (1 << SSB_PMU1_PLLCTL2_NDIVMODE_SHIFT) & SSB_PMU1_PLLCTL2_NDIVMODE;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL2, pllctl);
/* Set ndiv frac */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL3);
pllctl &= ~SSB_PMU1_PLLCTL3_NDIVFRAC;
pllctl |= ((u32)e->ndiv_frac << SSB_PMU1_PLLCTL3_NDIVFRAC_SHIFT) & SSB_PMU1_PLLCTL3_NDIVFRAC;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL3, pllctl);
/* Change the drive strength, if required. */
if (buffer_strength) {
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL5);
pllctl &= ~SSB_PMU1_PLLCTL5_CLKDRV;
pllctl |= (buffer_strength << SSB_PMU1_PLLCTL5_CLKDRV_SHIFT) & SSB_PMU1_PLLCTL5_CLKDRV;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL5, pllctl);
}
/* Tune the crystalfreq and the divisor. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
pmuctl &= ~(SSB_CHIPCO_PMU_CTL_ILP_DIV | SSB_CHIPCO_PMU_CTL_XTALFREQ);
pmuctl |= ((((u32)e->freq + 127) / 128 - 1) << SSB_CHIPCO_PMU_CTL_ILP_DIV_SHIFT)
& SSB_CHIPCO_PMU_CTL_ILP_DIV;
pmuctl |= ((u32)e->xf << SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) & SSB_CHIPCO_PMU_CTL_XTALFREQ;
chipco_write32(cc, SSB_CHIPCO_PMU_CTL, pmuctl);
}
static void ssb_pmu_pll_init(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
u32 crystalfreq = 0; /* in kHz. 0 = keep default freq. */
if (bus->bustype == SSB_BUSTYPE_SSB) {
#ifdef CONFIG_BCM47XX
char buf[20];
if (bcm47xx_nvram_getenv("xtalfreq", buf, sizeof(buf)) >= 0)
crystalfreq = simple_strtoul(buf, NULL, 0);
#endif
}
switch (bus->chip_id) {
case 0x4312:
case 0x4325:
ssb_pmu1_pllinit_r0(cc, crystalfreq);
break;
case 0x4328:
ssb_pmu0_pllinit_r0(cc, crystalfreq);
break;
case 0x5354:
if (crystalfreq == 0)
crystalfreq = 25000;
ssb_pmu0_pllinit_r0(cc, crystalfreq);
break;
case 0x4322:
if (cc->pmu.rev == 2) {
chipco_write32(cc, SSB_CHIPCO_PLLCTL_ADDR, 0x0000000A);
chipco_write32(cc, SSB_CHIPCO_PLLCTL_DATA, 0x380005C0);
}
break;
case 43222:
break;
default:
ssb_err("ERROR: PLL init unknown for device %04X\n",
bus->chip_id);
}
}
struct pmu_res_updown_tab_entry {
u8 resource; /* The resource number */
u16 updown; /* The updown value */
};
enum pmu_res_depend_tab_task {
PMU_RES_DEP_SET = 1,
PMU_RES_DEP_ADD,
PMU_RES_DEP_REMOVE,
};
struct pmu_res_depend_tab_entry {
u8 resource; /* The resource number */
u8 task; /* SET | ADD | REMOVE */
u32 depend; /* The depend mask */
};
static const struct pmu_res_updown_tab_entry pmu_res_updown_tab_4328a0[] = {
{ .resource = SSB_PMURES_4328_EXT_SWITCHER_PWM, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_BB_SWITCHER_PWM, .updown = 0x1F01, },
{ .resource = SSB_PMURES_4328_BB_SWITCHER_BURST, .updown = 0x010F, },
{ .resource = SSB_PMURES_4328_BB_EXT_SWITCHER_BURST, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_ILP_REQUEST, .updown = 0x0202, },
{ .resource = SSB_PMURES_4328_RADIO_SWITCHER_PWM, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_RADIO_SWITCHER_BURST, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_ROM_SWITCH, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_PA_REF_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_RADIO_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_AFE_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_PLL_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_BG_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_TX_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_RX_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_XTAL_PU, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_XTAL_EN, .updown = 0xA001, },
{ .resource = SSB_PMURES_4328_BB_PLL_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_RF_PLL_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_BB_PLL_PU, .updown = 0x0701, },
};
static const struct pmu_res_depend_tab_entry pmu_res_depend_tab_4328a0[] = {
{
/* Adjust ILP Request to avoid forcing EXT/BB into burst mode. */
.resource = SSB_PMURES_4328_ILP_REQUEST,
.task = PMU_RES_DEP_SET,
.depend = ((1 << SSB_PMURES_4328_EXT_SWITCHER_PWM) |
(1 << SSB_PMURES_4328_BB_SWITCHER_PWM)),
},
};
static const struct pmu_res_updown_tab_entry pmu_res_updown_tab_4325a0[] = {
{ .resource = SSB_PMURES_4325_XTAL_PU, .updown = 0x1501, },
};
static const struct pmu_res_depend_tab_entry pmu_res_depend_tab_4325a0[] = {
{
/* Adjust HT-Available dependencies. */
.resource = SSB_PMURES_4325_HT_AVAIL,
.task = PMU_RES_DEP_ADD,
.depend = ((1 << SSB_PMURES_4325_RX_PWRSW_PU) |
(1 << SSB_PMURES_4325_TX_PWRSW_PU) |
(1 << SSB_PMURES_4325_LOGEN_PWRSW_PU) |
(1 << SSB_PMURES_4325_AFE_PWRSW_PU)),
},
};
static void ssb_pmu_resources_init(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
u32 min_msk = 0, max_msk = 0;
unsigned int i;
const struct pmu_res_updown_tab_entry *updown_tab = NULL;
unsigned int updown_tab_size = 0;
const struct pmu_res_depend_tab_entry *depend_tab = NULL;
unsigned int depend_tab_size = 0;
switch (bus->chip_id) {
case 0x4312:
min_msk = 0xCBB;
break;
case 0x4322:
case 43222:
/* We keep the default settings:
* min_msk = 0xCBB
* max_msk = 0x7FFFF
*/
break;
case 0x4325:
/* Power OTP down later. */
min_msk = (1 << SSB_PMURES_4325_CBUCK_BURST) |
(1 << SSB_PMURES_4325_LNLDO2_PU);
if (chipco_read32(cc, SSB_CHIPCO_CHIPSTAT) &
SSB_CHIPCO_CHST_4325_PMUTOP_2B)
min_msk |= (1 << SSB_PMURES_4325_CLDO_CBUCK_BURST);
/* The PLL may turn on, if it decides so. */
max_msk = 0xFFFFF;
updown_tab = pmu_res_updown_tab_4325a0;
updown_tab_size = ARRAY_SIZE(pmu_res_updown_tab_4325a0);
depend_tab = pmu_res_depend_tab_4325a0;
depend_tab_size = ARRAY_SIZE(pmu_res_depend_tab_4325a0);
break;
case 0x4328:
min_msk = (1 << SSB_PMURES_4328_EXT_SWITCHER_PWM) |
(1 << SSB_PMURES_4328_BB_SWITCHER_PWM) |
(1 << SSB_PMURES_4328_XTAL_EN);
/* The PLL may turn on, if it decides so. */
max_msk = 0xFFFFF;
updown_tab = pmu_res_updown_tab_4328a0;
updown_tab_size = ARRAY_SIZE(pmu_res_updown_tab_4328a0);
depend_tab = pmu_res_depend_tab_4328a0;
depend_tab_size = ARRAY_SIZE(pmu_res_depend_tab_4328a0);
break;
case 0x5354:
/* The PLL may turn on, if it decides so. */
max_msk = 0xFFFFF;
break;
default:
ssb_err("ERROR: PMU resource config unknown for device %04X\n",
bus->chip_id);
}
if (updown_tab) {
for (i = 0; i < updown_tab_size; i++) {
chipco_write32(cc, SSB_CHIPCO_PMU_RES_TABSEL,
updown_tab[i].resource);
chipco_write32(cc, SSB_CHIPCO_PMU_RES_UPDNTM,
updown_tab[i].updown);
}
}
if (depend_tab) {
for (i = 0; i < depend_tab_size; i++) {
chipco_write32(cc, SSB_CHIPCO_PMU_RES_TABSEL,
depend_tab[i].resource);
switch (depend_tab[i].task) {
case PMU_RES_DEP_SET:
chipco_write32(cc, SSB_CHIPCO_PMU_RES_DEPMSK,
depend_tab[i].depend);
break;
case PMU_RES_DEP_ADD:
chipco_set32(cc, SSB_CHIPCO_PMU_RES_DEPMSK,
depend_tab[i].depend);
break;
case PMU_RES_DEP_REMOVE:
chipco_mask32(cc, SSB_CHIPCO_PMU_RES_DEPMSK,
~(depend_tab[i].depend));
break;
default:
SSB_WARN_ON(1);
}
}
}
/* Set the resource masks. */
if (min_msk)
chipco_write32(cc, SSB_CHIPCO_PMU_MINRES_MSK, min_msk);
if (max_msk)
chipco_write32(cc, SSB_CHIPCO_PMU_MAXRES_MSK, max_msk);
}
/* http://bcm-v4.sipsolutions.net/802.11/SSB/PmuInit */
void ssb_pmu_init(struct ssb_chipcommon *cc)
{
u32 pmucap;
if (!(cc->capabilities & SSB_CHIPCO_CAP_PMU))
return;
pmucap = chipco_read32(cc, SSB_CHIPCO_PMU_CAP);
cc->pmu.rev = (pmucap & SSB_CHIPCO_PMU_CAP_REVISION);
ssb_dbg("Found rev %u PMU (capabilities 0x%08X)\n",
cc->pmu.rev, pmucap);
if (cc->pmu.rev == 1)
chipco_mask32(cc, SSB_CHIPCO_PMU_CTL,
~SSB_CHIPCO_PMU_CTL_NOILPONW);
else
chipco_set32(cc, SSB_CHIPCO_PMU_CTL,
SSB_CHIPCO_PMU_CTL_NOILPONW);
ssb_pmu_pll_init(cc);
ssb_pmu_resources_init(cc);
}
void ssb_pmu_set_ldo_voltage(struct ssb_chipcommon *cc,
enum ssb_pmu_ldo_volt_id id, u32 voltage)
{
struct ssb_bus *bus = cc->dev->bus;
u32 addr, shift, mask;
switch (bus->chip_id) {
case 0x4328:
case 0x5354:
switch (id) {
case LDO_VOLT1:
addr = 2;
shift = 25;
mask = 0xF;
break;
case LDO_VOLT2:
addr = 3;
shift = 1;
mask = 0xF;
break;
case LDO_VOLT3:
addr = 3;
shift = 9;
mask = 0xF;
break;
case LDO_PAREF:
addr = 3;
shift = 17;
mask = 0x3F;
break;
default:
SSB_WARN_ON(1);
return;
}
break;
case 0x4312:
if (SSB_WARN_ON(id != LDO_PAREF))
return;
addr = 0;
shift = 21;
mask = 0x3F;
break;
default:
return;
}
ssb_chipco_regctl_maskset(cc, addr, ~(mask << shift),
(voltage & mask) << shift);
}
void ssb_pmu_set_ldo_paref(struct ssb_chipcommon *cc, bool on)
{
struct ssb_bus *bus = cc->dev->bus;
int ldo;
switch (bus->chip_id) {
case 0x4312:
ldo = SSB_PMURES_4312_PA_REF_LDO;
break;
case 0x4328:
ldo = SSB_PMURES_4328_PA_REF_LDO;
break;
case 0x5354:
ldo = SSB_PMURES_5354_PA_REF_LDO;
break;
default:
return;
}
if (on)
chipco_set32(cc, SSB_CHIPCO_PMU_MINRES_MSK, 1 << ldo);
else
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK, ~(1 << ldo));
chipco_read32(cc, SSB_CHIPCO_PMU_MINRES_MSK); //SPEC FIXME found via mmiotrace - dummy read?
}
EXPORT_SYMBOL(ssb_pmu_set_ldo_voltage);
EXPORT_SYMBOL(ssb_pmu_set_ldo_paref);
static u32 ssb_pmu_get_alp_clock_clk0(struct ssb_chipcommon *cc)
{
u32 crystalfreq;
const struct pmu0_plltab_entry *e = NULL;
crystalfreq = (chipco_read32(cc, SSB_CHIPCO_PMU_CTL) &
SSB_CHIPCO_PMU_CTL_XTALFREQ) >> SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT;
e = pmu0_plltab_find_entry(crystalfreq);
BUG_ON(!e);
return e->freq * 1000;
}
u32 ssb_pmu_get_alp_clock(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
switch (bus->chip_id) {
case 0x5354:
return ssb_pmu_get_alp_clock_clk0(cc);
default:
ssb_err("ERROR: PMU alp clock unknown for device %04X\n",
bus->chip_id);
return 0;
}
}
u32 ssb_pmu_get_cpu_clock(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
switch (bus->chip_id) {
case 0x5354:
/* 5354 chip uses a non programmable PLL of frequency 240MHz */
return 240000000;
default:
ssb_err("ERROR: PMU cpu clock unknown for device %04X\n",
bus->chip_id);
return 0;
}
}
u32 ssb_pmu_get_controlclock(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
switch (bus->chip_id) {
case 0x5354:
return 120000000;
default:
ssb_err("ERROR: PMU controlclock unknown for device %04X\n",
bus->chip_id);
return 0;
}
}
void ssb_pmu_spuravoid_pllupdate(struct ssb_chipcommon *cc, int spuravoid)
{
u32 pmu_ctl = 0;
switch (cc->dev->bus->chip_id) {
case 0x4322:
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL0, 0x11100070);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL1, 0x1014140a);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL5, 0x88888854);
if (spuravoid == 1)
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL2, 0x05201828);
else
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL2, 0x05001828);
pmu_ctl = SSB_CHIPCO_PMU_CTL_PLL_UPD;
break;
case 43222:
if (spuravoid == 1) {
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL0, 0x11500008);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL1, 0x0C000C06);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL2, 0x0F600a08);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL3, 0x00000000);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL4, 0x2001E920);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL5, 0x88888815);
} else {
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL0, 0x11100008);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL1, 0x0c000c06);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL2, 0x03000a08);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL3, 0x00000000);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL4, 0x200005c0);
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL5, 0x88888855);
}
pmu_ctl = SSB_CHIPCO_PMU_CTL_PLL_UPD;
break;
default:
ssb_printk(KERN_ERR PFX
"Unknown spuravoidance settings for chip 0x%04X, not changing PLL\n",
cc->dev->bus->chip_id);
return;
}
chipco_set32(cc, SSB_CHIPCO_PMU_CTL, pmu_ctl);
}
EXPORT_SYMBOL_GPL(ssb_pmu_spuravoid_pllupdate);
| gpl-2.0 |
yajnab/android_kernel_htc_golfu | arch/arm/mach-s3c2440/mach-anubis.c | 2984 | 11313 | /* linux/arch/arm/mach-s3c2440/mach-anubis.c
*
* Copyright 2003-2009 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* 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/init.h>
#include <linux/gpio.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/ata_platform.h>
#include <linux/i2c.h>
#include <linux/io.h>
#include <linux/sm501.h>
#include <linux/sm501-regs.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/anubis-map.h>
#include <mach/anubis-irq.h>
#include <mach/anubis-cpld.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <mach/regs-gpio.h>
#include <mach/regs-mem.h>
#include <mach/regs-lcd.h>
#include <plat/nand.h>
#include <plat/iic.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <net/ax88796.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/audio-simtec.h>
#define COPYRIGHT ", Copyright 2005-2009 Simtec Electronics"
static struct map_desc anubis_iodesc[] __initdata = {
/* ISA IO areas */
{
.virtual = (u32)S3C24XX_VA_ISA_BYTE,
.pfn = __phys_to_pfn(0x0),
.length = SZ_4M,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_WORD,
.pfn = __phys_to_pfn(0x0),
.length = SZ_4M,
.type = MT_DEVICE,
},
/* we could possibly compress the next set down into a set of smaller tables
* pagetables, but that would mean using an L2 section, and it still means
* we cannot actually feed the same register to an LDR due to 16K spacing
*/
/* CPLD control registers */
{
.virtual = (u32)ANUBIS_VA_CTRL1,
.pfn = __phys_to_pfn(ANUBIS_PA_CTRL1),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (u32)ANUBIS_VA_IDREG,
.pfn = __phys_to_pfn(ANUBIS_PA_IDREG),
.length = SZ_4K,
.type = MT_DEVICE,
},
};
#define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c24xx_uart_clksrc anubis_serial_clocks[] = {
[0] = {
.name = "uclk",
.divisor = 1,
.min_baud = 0,
.max_baud = 0,
},
[1] = {
.name = "pclk",
.divisor = 1,
.min_baud = 0,
.max_baud = 0,
}
};
static struct s3c2410_uartcfg anubis_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
.clocks = anubis_serial_clocks,
.clocks_size = ARRAY_SIZE(anubis_serial_clocks),
},
[1] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
.clocks = anubis_serial_clocks,
.clocks_size = ARRAY_SIZE(anubis_serial_clocks),
},
};
/* NAND Flash on Anubis board */
static int external_map[] = { 2 };
static int chip0_map[] = { 0 };
static int chip1_map[] = { 1 };
static struct mtd_partition __initdata anubis_default_nand_part[] = {
[0] = {
.name = "Boot Agent",
.size = SZ_16K,
.offset = 0,
},
[1] = {
.name = "/boot",
.size = SZ_4M - SZ_16K,
.offset = SZ_16K,
},
[2] = {
.name = "user1",
.offset = SZ_4M,
.size = SZ_32M - SZ_4M,
},
[3] = {
.name = "user2",
.offset = SZ_32M,
.size = MTDPART_SIZ_FULL,
}
};
static struct mtd_partition __initdata anubis_default_nand_part_large[] = {
[0] = {
.name = "Boot Agent",
.size = SZ_128K,
.offset = 0,
},
[1] = {
.name = "/boot",
.size = SZ_4M - SZ_128K,
.offset = SZ_128K,
},
[2] = {
.name = "user1",
.offset = SZ_4M,
.size = SZ_32M - SZ_4M,
},
[3] = {
.name = "user2",
.offset = SZ_32M,
.size = MTDPART_SIZ_FULL,
}
};
/* the Anubis has 3 selectable slots for nand-flash, the two
* on-board chip areas, as well as the external slot.
*
* Note, there is no current hot-plug support for the External
* socket.
*/
static struct s3c2410_nand_set __initdata anubis_nand_sets[] = {
[1] = {
.name = "External",
.nr_chips = 1,
.nr_map = external_map,
.nr_partitions = ARRAY_SIZE(anubis_default_nand_part),
.partitions = anubis_default_nand_part,
},
[0] = {
.name = "chip0",
.nr_chips = 1,
.nr_map = chip0_map,
.nr_partitions = ARRAY_SIZE(anubis_default_nand_part),
.partitions = anubis_default_nand_part,
},
[2] = {
.name = "chip1",
.nr_chips = 1,
.nr_map = chip1_map,
.nr_partitions = ARRAY_SIZE(anubis_default_nand_part),
.partitions = anubis_default_nand_part,
},
};
static void anubis_nand_select(struct s3c2410_nand_set *set, int slot)
{
unsigned int tmp;
slot = set->nr_map[slot] & 3;
pr_debug("anubis_nand: selecting slot %d (set %p,%p)\n",
slot, set, set->nr_map);
tmp = __raw_readb(ANUBIS_VA_CTRL1);
tmp &= ~ANUBIS_CTRL1_NANDSEL;
tmp |= slot;
pr_debug("anubis_nand: ctrl1 now %02x\n", tmp);
__raw_writeb(tmp, ANUBIS_VA_CTRL1);
}
static struct s3c2410_platform_nand __initdata anubis_nand_info = {
.tacls = 25,
.twrph0 = 55,
.twrph1 = 40,
.nr_sets = ARRAY_SIZE(anubis_nand_sets),
.sets = anubis_nand_sets,
.select_chip = anubis_nand_select,
};
/* IDE channels */
static struct pata_platform_info anubis_ide_platdata = {
.ioport_shift = 5,
};
static struct resource anubis_ide0_resource[] = {
{
.start = S3C2410_CS3,
.end = S3C2410_CS3 + (8*32) - 1,
.flags = IORESOURCE_MEM,
}, {
.start = S3C2410_CS3 + (1<<26) + (6*32),
.end = S3C2410_CS3 + (1<<26) + (7*32) - 1,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_IDE0,
.end = IRQ_IDE0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device anubis_device_ide0 = {
.name = "pata_platform",
.id = 0,
.num_resources = ARRAY_SIZE(anubis_ide0_resource),
.resource = anubis_ide0_resource,
.dev = {
.platform_data = &anubis_ide_platdata,
.coherent_dma_mask = ~0,
},
};
static struct resource anubis_ide1_resource[] = {
{
.start = S3C2410_CS4,
.end = S3C2410_CS4 + (8*32) - 1,
.flags = IORESOURCE_MEM,
}, {
.start = S3C2410_CS4 + (1<<26) + (6*32),
.end = S3C2410_CS4 + (1<<26) + (7*32) - 1,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_IDE0,
.end = IRQ_IDE0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device anubis_device_ide1 = {
.name = "pata_platform",
.id = 1,
.num_resources = ARRAY_SIZE(anubis_ide1_resource),
.resource = anubis_ide1_resource,
.dev = {
.platform_data = &anubis_ide_platdata,
.coherent_dma_mask = ~0,
},
};
/* Asix AX88796 10/100 ethernet controller */
static struct ax_plat_data anubis_asix_platdata = {
.flags = AXFLG_MAC_FROMDEV,
.wordlength = 2,
.dcr_val = 0x48,
.rcr_val = 0x40,
};
static struct resource anubis_asix_resource[] = {
[0] = {
.start = S3C2410_CS5,
.end = S3C2410_CS5 + (0x20 * 0x20) -1,
.flags = IORESOURCE_MEM
},
[1] = {
.start = IRQ_ASIX,
.end = IRQ_ASIX,
.flags = IORESOURCE_IRQ
}
};
static struct platform_device anubis_device_asix = {
.name = "ax88796",
.id = 0,
.num_resources = ARRAY_SIZE(anubis_asix_resource),
.resource = anubis_asix_resource,
.dev = {
.platform_data = &anubis_asix_platdata,
}
};
/* SM501 */
static struct resource anubis_sm501_resource[] = {
[0] = {
.start = S3C2410_CS2,
.end = S3C2410_CS2 + SZ_8M,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = S3C2410_CS2 + SZ_64M - SZ_2M,
.end = S3C2410_CS2 + SZ_64M - 1,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = IRQ_EINT0,
.end = IRQ_EINT0,
.flags = IORESOURCE_IRQ,
},
};
static struct sm501_initdata anubis_sm501_initdata = {
.gpio_high = {
.set = 0x3F000000, /* 24bit panel */
.mask = 0x0,
},
.misc_timing = {
.set = 0x010100, /* SDRAM timing */
.mask = 0x1F1F00,
},
.misc_control = {
.set = SM501_MISC_PNL_24BIT,
.mask = 0,
},
.devices = SM501_USE_GPIO,
/* set the SDRAM and bus clocks */
.mclk = 72 * MHZ,
.m1xclk = 144 * MHZ,
};
static struct sm501_platdata_gpio_i2c anubis_sm501_gpio_i2c[] = {
[0] = {
.bus_num = 1,
.pin_scl = 44,
.pin_sda = 45,
},
[1] = {
.bus_num = 2,
.pin_scl = 40,
.pin_sda = 41,
},
};
static struct sm501_platdata anubis_sm501_platdata = {
.init = &anubis_sm501_initdata,
.gpio_base = -1,
.gpio_i2c = anubis_sm501_gpio_i2c,
.gpio_i2c_nr = ARRAY_SIZE(anubis_sm501_gpio_i2c),
};
static struct platform_device anubis_device_sm501 = {
.name = "sm501",
.id = 0,
.num_resources = ARRAY_SIZE(anubis_sm501_resource),
.resource = anubis_sm501_resource,
.dev = {
.platform_data = &anubis_sm501_platdata,
},
};
/* Standard Anubis devices */
static struct platform_device *anubis_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_wdt,
&s3c_device_adc,
&s3c_device_i2c0,
&s3c_device_rtc,
&s3c_device_nand,
&anubis_device_ide0,
&anubis_device_ide1,
&anubis_device_asix,
&anubis_device_sm501,
};
static struct clk *anubis_clocks[] __initdata = {
&s3c24xx_dclk0,
&s3c24xx_dclk1,
&s3c24xx_clkout0,
&s3c24xx_clkout1,
&s3c24xx_uclk,
};
/* I2C devices. */
static struct i2c_board_info anubis_i2c_devs[] __initdata = {
{
I2C_BOARD_INFO("tps65011", 0x48),
.irq = IRQ_EINT20,
}
};
/* Audio setup */
static struct s3c24xx_audio_simtec_pdata __initdata anubis_audio = {
.have_mic = 1,
.have_lout = 1,
.output_cdclk = 1,
.use_mpllin = 1,
.amp_gpio = S3C2410_GPB(2),
.amp_gain[0] = S3C2410_GPD(10),
.amp_gain[1] = S3C2410_GPD(11),
};
static void __init anubis_map_io(void)
{
/* initialise the clocks */
s3c24xx_dclk0.parent = &clk_upll;
s3c24xx_dclk0.rate = 12*1000*1000;
s3c24xx_dclk1.parent = &clk_upll;
s3c24xx_dclk1.rate = 24*1000*1000;
s3c24xx_clkout0.parent = &s3c24xx_dclk0;
s3c24xx_clkout1.parent = &s3c24xx_dclk1;
s3c24xx_uclk.parent = &s3c24xx_clkout1;
s3c24xx_register_clocks(anubis_clocks, ARRAY_SIZE(anubis_clocks));
s3c24xx_init_io(anubis_iodesc, ARRAY_SIZE(anubis_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(anubis_uartcfgs, ARRAY_SIZE(anubis_uartcfgs));
/* check for the newer revision boards with large page nand */
if ((__raw_readb(ANUBIS_VA_IDREG) & ANUBIS_IDREG_REVMASK) >= 4) {
printk(KERN_INFO "ANUBIS-B detected (revision %d)\n",
__raw_readb(ANUBIS_VA_IDREG) & ANUBIS_IDREG_REVMASK);
anubis_nand_sets[0].partitions = anubis_default_nand_part_large;
anubis_nand_sets[0].nr_partitions = ARRAY_SIZE(anubis_default_nand_part_large);
} else {
/* ensure that the GPIO is setup */
s3c2410_gpio_setpin(S3C2410_GPA(0), 1);
}
}
static void __init anubis_init(void)
{
s3c_i2c0_set_platdata(NULL);
s3c_nand_set_platdata(&anubis_nand_info);
simtec_audio_add(NULL, false, &anubis_audio);
platform_add_devices(anubis_devices, ARRAY_SIZE(anubis_devices));
i2c_register_board_info(0, anubis_i2c_devs,
ARRAY_SIZE(anubis_i2c_devs));
}
MACHINE_START(ANUBIS, "Simtec-Anubis")
/* Maintainer: Ben Dooks <ben@simtec.co.uk> */
.boot_params = S3C2410_SDRAM_PA + 0x100,
.map_io = anubis_map_io,
.init_machine = anubis_init,
.init_irq = s3c24xx_init_irq,
.timer = &s3c24xx_timer,
MACHINE_END
| gpl-2.0 |
rutvik95/speedx_kernel_i9082 | drivers/scsi/aha1542.c | 3240 | 49697 | /* $Id: aha1542.c,v 1.1 1992/07/24 06:27:38 root Exp root $
* linux/kernel/aha1542.c
*
* Copyright (C) 1992 Tommy Thorn
* Copyright (C) 1993, 1994, 1995 Eric Youngdale
*
* Modified by Eric Youngdale
* Use request_irq and request_dma to help prevent unexpected conflicts
* Set up on-board DMA controller, such that we do not have to
* have the bios enabled to use the aha1542.
* Modified by David Gentzel
* Don't call request_dma if dma mask is 0 (for BusLogic BT-445S VL-Bus
* controller).
* Modified by Matti Aarnio
* Accept parameters from LILO cmd-line. -- 1-Oct-94
* Modified by Mike McLagan <mike.mclagan@linux.org>
* Recognise extended mode on AHA1542CP, different bit than 1542CF
* 1-Jan-97
* Modified by Bjorn L. Thordarson and Einar Thor Einarsson
* Recognize that DMA0 is valid DMA channel -- 13-Jul-98
* Modified by Chris Faulhaber <jedgar@fxp.org>
* Added module command-line options
* 19-Jul-99
* Modified by Adam Fritzler
* Added proper detection of the AHA-1640 (MCA version of AHA-1540)
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/isapnp.h>
#include <linux/blkdev.h>
#include <linux/mca.h>
#include <linux/mca-legacy.h>
#include <linux/slab.h>
#include <asm/dma.h>
#include <asm/system.h>
#include <asm/io.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "aha1542.h"
#define SCSI_BUF_PA(address) isa_virt_to_bus(address)
#define SCSI_SG_PA(sgent) (isa_page_to_bus(sg_page((sgent))) + (sgent)->offset)
#include<linux/stat.h>
#ifdef DEBUG
#define DEB(x) x
#else
#define DEB(x)
#endif
/*
static const char RCSid[] = "$Header: /usr/src/linux/kernel/blk_drv/scsi/RCS/aha1542.c,v 1.1 1992/07/24 06:27:38 root Exp root $";
*/
/* The adaptec can be configured for quite a number of addresses, but
I generally do not want the card poking around at random. We allow
two addresses - this allows people to use the Adaptec with a Midi
card, which also used 0x330 -- can be overridden with LILO! */
#define MAXBOARDS 4 /* Increase this and the sizes of the
arrays below, if you need more.. */
/* Boards 3,4 slots are reserved for ISAPnP/MCA scans */
static unsigned int bases[MAXBOARDS] __initdata = {0x330, 0x334, 0, 0};
/* set by aha1542_setup according to the command line; they also may
be marked __initdata, but require zero initializers then */
static int setup_called[MAXBOARDS];
static int setup_buson[MAXBOARDS];
static int setup_busoff[MAXBOARDS];
static int setup_dmaspeed[MAXBOARDS] __initdata = { -1, -1, -1, -1 };
/*
* LILO/Module params: aha1542=<PORTBASE>[,<BUSON>,<BUSOFF>[,<DMASPEED>]]
*
* Where: <PORTBASE> is any of the valid AHA addresses:
* 0x130, 0x134, 0x230, 0x234, 0x330, 0x334
* <BUSON> is the time (in microsecs) that AHA spends on the AT-bus
* when transferring data. 1542A power-on default is 11us,
* valid values are in range: 2..15 (decimal)
* <BUSOFF> is the time that AHA spends OFF THE BUS after while
* it is transferring data (not to monopolize the bus).
* Power-on default is 4us, valid range: 1..64 microseconds.
* <DMASPEED> Default is jumper selected (1542A: on the J1),
* but experimenter can alter it with this.
* Valid values: 5, 6, 7, 8, 10 (MB/s)
* Factory default is 5 MB/s.
*/
#if defined(MODULE)
static int isapnp = 0;
static int aha1542[] = {0x330, 11, 4, -1};
module_param_array(aha1542, int, NULL, 0);
module_param(isapnp, bool, 0);
static struct isapnp_device_id id_table[] __initdata = {
{
ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('A', 'D', 'P'), ISAPNP_FUNCTION(0x1542),
0
},
{0}
};
MODULE_DEVICE_TABLE(isapnp, id_table);
#else
static int isapnp = 1;
#endif
#define BIOS_TRANSLATION_1632 0 /* Used by some old 1542A boards */
#define BIOS_TRANSLATION_6432 1 /* Default case these days */
#define BIOS_TRANSLATION_25563 2 /* Big disk case */
struct aha1542_hostdata {
/* This will effectively start both of them at the first mailbox */
int bios_translation; /* Mapping bios uses - for compatibility */
int aha1542_last_mbi_used;
int aha1542_last_mbo_used;
Scsi_Cmnd *SCint[AHA1542_MAILBOXES];
struct mailbox mb[2 * AHA1542_MAILBOXES];
struct ccb ccb[AHA1542_MAILBOXES];
};
#define HOSTDATA(host) ((struct aha1542_hostdata *) &host->hostdata)
static DEFINE_SPINLOCK(aha1542_lock);
#define WAITnexttimeout 3000000
static void setup_mailboxes(int base_io, struct Scsi_Host *shpnt);
static int aha1542_restart(struct Scsi_Host *shost);
static void aha1542_intr_handle(struct Scsi_Host *shost);
#define aha1542_intr_reset(base) outb(IRST, CONTROL(base))
#define WAIT(port, mask, allof, noneof) \
{ register int WAITbits; \
register int WAITtimeout = WAITnexttimeout; \
while (1) { \
WAITbits = inb(port) & (mask); \
if ((WAITbits & (allof)) == (allof) && ((WAITbits & (noneof)) == 0)) \
break; \
if (--WAITtimeout == 0) goto fail; \
} \
}
/* Similar to WAIT, except we use the udelay call to regulate the
amount of time we wait. */
#define WAITd(port, mask, allof, noneof, timeout) \
{ register int WAITbits; \
register int WAITtimeout = timeout; \
while (1) { \
WAITbits = inb(port) & (mask); \
if ((WAITbits & (allof)) == (allof) && ((WAITbits & (noneof)) == 0)) \
break; \
mdelay(1); \
if (--WAITtimeout == 0) goto fail; \
} \
}
static void aha1542_stat(void)
{
/* int s = inb(STATUS), i = inb(INTRFLAGS);
printk("status=%x intrflags=%x\n", s, i, WAITnexttimeout-WAITtimeout); */
}
/* This is a bit complicated, but we need to make sure that an interrupt
routine does not send something out while we are in the middle of this.
Fortunately, it is only at boot time that multi-byte messages
are ever sent. */
static int aha1542_out(unsigned int base, unchar * cmdp, int len)
{
unsigned long flags = 0;
int got_lock;
if (len == 1) {
got_lock = 0;
while (1 == 1) {
WAIT(STATUS(base), CDF, 0, CDF);
spin_lock_irqsave(&aha1542_lock, flags);
if (inb(STATUS(base)) & CDF) {
spin_unlock_irqrestore(&aha1542_lock, flags);
continue;
}
outb(*cmdp, DATA(base));
spin_unlock_irqrestore(&aha1542_lock, flags);
return 0;
}
} else {
spin_lock_irqsave(&aha1542_lock, flags);
got_lock = 1;
while (len--) {
WAIT(STATUS(base), CDF, 0, CDF);
outb(*cmdp++, DATA(base));
}
spin_unlock_irqrestore(&aha1542_lock, flags);
}
return 0;
fail:
if (got_lock)
spin_unlock_irqrestore(&aha1542_lock, flags);
printk(KERN_ERR "aha1542_out failed(%d): ", len + 1);
aha1542_stat();
return 1;
}
/* Only used at boot time, so we do not need to worry about latency as much
here */
static int __init aha1542_in(unsigned int base, unchar * cmdp, int len)
{
unsigned long flags;
spin_lock_irqsave(&aha1542_lock, flags);
while (len--) {
WAIT(STATUS(base), DF, DF, 0);
*cmdp++ = inb(DATA(base));
}
spin_unlock_irqrestore(&aha1542_lock, flags);
return 0;
fail:
spin_unlock_irqrestore(&aha1542_lock, flags);
printk(KERN_ERR "aha1542_in failed(%d): ", len + 1);
aha1542_stat();
return 1;
}
/* Similar to aha1542_in, except that we wait a very short period of time.
We use this if we know the board is alive and awake, but we are not sure
if the board will respond to the command we are about to send or not */
static int __init aha1542_in1(unsigned int base, unchar * cmdp, int len)
{
unsigned long flags;
spin_lock_irqsave(&aha1542_lock, flags);
while (len--) {
WAITd(STATUS(base), DF, DF, 0, 100);
*cmdp++ = inb(DATA(base));
}
spin_unlock_irqrestore(&aha1542_lock, flags);
return 0;
fail:
spin_unlock_irqrestore(&aha1542_lock, flags);
return 1;
}
static int makecode(unsigned hosterr, unsigned scsierr)
{
switch (hosterr) {
case 0x0:
case 0xa: /* Linked command complete without error and linked normally */
case 0xb: /* Linked command complete without error, interrupt generated */
hosterr = 0;
break;
case 0x11: /* Selection time out-The initiator selection or target
reselection was not complete within the SCSI Time out period */
hosterr = DID_TIME_OUT;
break;
case 0x12: /* Data overrun/underrun-The target attempted to transfer more data
than was allocated by the Data Length field or the sum of the
Scatter / Gather Data Length fields. */
case 0x13: /* Unexpected bus free-The target dropped the SCSI BSY at an unexpected time. */
case 0x15: /* MBO command was not 00, 01 or 02-The first byte of the CB was
invalid. This usually indicates a software failure. */
case 0x16: /* Invalid CCB Operation Code-The first byte of the CCB was invalid.
This usually indicates a software failure. */
case 0x17: /* Linked CCB does not have the same LUN-A subsequent CCB of a set
of linked CCB's does not specify the same logical unit number as
the first. */
case 0x18: /* Invalid Target Direction received from Host-The direction of a
Target Mode CCB was invalid. */
case 0x19: /* Duplicate CCB Received in Target Mode-More than once CCB was
received to service data transfer between the same target LUN
and initiator SCSI ID in the same direction. */
case 0x1a: /* Invalid CCB or Segment List Parameter-A segment list with a zero
length segment or invalid segment list boundaries was received.
A CCB parameter was invalid. */
DEB(printk("Aha1542: %x %x\n", hosterr, scsierr));
hosterr = DID_ERROR; /* Couldn't find any better */
break;
case 0x14: /* Target bus phase sequence failure-An invalid bus phase or bus
phase sequence was requested by the target. The host adapter
will generate a SCSI Reset Condition, notifying the host with
a SCRD interrupt */
hosterr = DID_RESET;
break;
default:
printk(KERN_ERR "aha1542: makecode: unknown hoststatus %x\n", hosterr);
break;
}
return scsierr | (hosterr << 16);
}
static int __init aha1542_test_port(int bse, struct Scsi_Host *shpnt)
{
unchar inquiry_cmd[] = {CMD_INQUIRY};
unchar inquiry_result[4];
unchar *cmdp;
int len;
volatile int debug = 0;
/* Quick and dirty test for presence of the card. */
if (inb(STATUS(bse)) == 0xff)
return 0;
/* Reset the adapter. I ought to make a hard reset, but it's not really necessary */
/* DEB(printk("aha1542_test_port called \n")); */
/* In case some other card was probing here, reset interrupts */
aha1542_intr_reset(bse); /* reset interrupts, so they don't block */
outb(SRST | IRST /*|SCRST */ , CONTROL(bse));
mdelay(20); /* Wait a little bit for things to settle down. */
debug = 1;
/* Expect INIT and IDLE, any of the others are bad */
WAIT(STATUS(bse), STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
debug = 2;
/* Shouldn't have generated any interrupts during reset */
if (inb(INTRFLAGS(bse)) & INTRMASK)
goto fail;
/* Perform a host adapter inquiry instead so we do not need to set
up the mailboxes ahead of time */
aha1542_out(bse, inquiry_cmd, 1);
debug = 3;
len = 4;
cmdp = &inquiry_result[0];
while (len--) {
WAIT(STATUS(bse), DF, DF, 0);
*cmdp++ = inb(DATA(bse));
}
debug = 8;
/* Reading port should reset DF */
if (inb(STATUS(bse)) & DF)
goto fail;
debug = 9;
/* When HACC, command is completed, and we're though testing */
WAIT(INTRFLAGS(bse), HACC, HACC, 0);
/* now initialize adapter */
debug = 10;
/* Clear interrupts */
outb(IRST, CONTROL(bse));
debug = 11;
return debug; /* 1 = ok */
fail:
return 0; /* 0 = not ok */
}
/* A quick wrapper for do_aha1542_intr_handle to grab the spin lock */
static irqreturn_t do_aha1542_intr_handle(int dummy, void *dev_id)
{
unsigned long flags;
struct Scsi_Host *shost = dev_id;
spin_lock_irqsave(shost->host_lock, flags);
aha1542_intr_handle(shost);
spin_unlock_irqrestore(shost->host_lock, flags);
return IRQ_HANDLED;
}
/* A "high" level interrupt handler */
static void aha1542_intr_handle(struct Scsi_Host *shost)
{
void (*my_done) (Scsi_Cmnd *) = NULL;
int errstatus, mbi, mbo, mbistatus;
int number_serviced;
unsigned long flags;
Scsi_Cmnd *SCtmp;
int flag;
int needs_restart;
struct mailbox *mb;
struct ccb *ccb;
mb = HOSTDATA(shost)->mb;
ccb = HOSTDATA(shost)->ccb;
#ifdef DEBUG
{
flag = inb(INTRFLAGS(shost->io_port));
printk(KERN_DEBUG "aha1542_intr_handle: ");
if (!(flag & ANYINTR))
printk("no interrupt?");
if (flag & MBIF)
printk("MBIF ");
if (flag & MBOA)
printk("MBOF ");
if (flag & HACC)
printk("HACC ");
if (flag & SCRD)
printk("SCRD ");
printk("status %02x\n", inb(STATUS(shost->io_port)));
};
#endif
number_serviced = 0;
needs_restart = 0;
while (1 == 1) {
flag = inb(INTRFLAGS(shost->io_port));
/* Check for unusual interrupts. If any of these happen, we should
probably do something special, but for now just printing a message
is sufficient. A SCSI reset detected is something that we really
need to deal with in some way. */
if (flag & ~MBIF) {
if (flag & MBOA)
printk("MBOF ");
if (flag & HACC)
printk("HACC ");
if (flag & SCRD) {
needs_restart = 1;
printk("SCRD ");
}
}
aha1542_intr_reset(shost->io_port);
spin_lock_irqsave(&aha1542_lock, flags);
mbi = HOSTDATA(shost)->aha1542_last_mbi_used + 1;
if (mbi >= 2 * AHA1542_MAILBOXES)
mbi = AHA1542_MAILBOXES;
do {
if (mb[mbi].status != 0)
break;
mbi++;
if (mbi >= 2 * AHA1542_MAILBOXES)
mbi = AHA1542_MAILBOXES;
} while (mbi != HOSTDATA(shost)->aha1542_last_mbi_used);
if (mb[mbi].status == 0) {
spin_unlock_irqrestore(&aha1542_lock, flags);
/* Hmm, no mail. Must have read it the last time around */
if (!number_serviced && !needs_restart)
printk(KERN_WARNING "aha1542.c: interrupt received, but no mail.\n");
/* We detected a reset. Restart all pending commands for
devices that use the hard reset option */
if (needs_restart)
aha1542_restart(shost);
return;
};
mbo = (scsi2int(mb[mbi].ccbptr) - (SCSI_BUF_PA(&ccb[0]))) / sizeof(struct ccb);
mbistatus = mb[mbi].status;
mb[mbi].status = 0;
HOSTDATA(shost)->aha1542_last_mbi_used = mbi;
spin_unlock_irqrestore(&aha1542_lock, flags);
#ifdef DEBUG
{
if (ccb[mbo].tarstat | ccb[mbo].hastat)
printk(KERN_DEBUG "aha1542_command: returning %x (status %d)\n",
ccb[mbo].tarstat + ((int) ccb[mbo].hastat << 16), mb[mbi].status);
};
#endif
if (mbistatus == 3)
continue; /* Aborted command not found */
#ifdef DEBUG
printk(KERN_DEBUG "...done %d %d\n", mbo, mbi);
#endif
SCtmp = HOSTDATA(shost)->SCint[mbo];
if (!SCtmp || !SCtmp->scsi_done) {
printk(KERN_WARNING "aha1542_intr_handle: Unexpected interrupt\n");
printk(KERN_WARNING "tarstat=%x, hastat=%x idlun=%x ccb#=%d \n", ccb[mbo].tarstat,
ccb[mbo].hastat, ccb[mbo].idlun, mbo);
return;
}
my_done = SCtmp->scsi_done;
kfree(SCtmp->host_scribble);
SCtmp->host_scribble = NULL;
/* Fetch the sense data, and tuck it away, in the required slot. The
Adaptec automatically fetches it, and there is no guarantee that
we will still have it in the cdb when we come back */
if (ccb[mbo].tarstat == 2)
memcpy(SCtmp->sense_buffer, &ccb[mbo].cdb[ccb[mbo].cdblen],
SCSI_SENSE_BUFFERSIZE);
/* is there mail :-) */
/* more error checking left out here */
if (mbistatus != 1)
/* This is surely wrong, but I don't know what's right */
errstatus = makecode(ccb[mbo].hastat, ccb[mbo].tarstat);
else
errstatus = 0;
#ifdef DEBUG
if (errstatus)
printk(KERN_DEBUG "(aha1542 error:%x %x %x) ", errstatus,
ccb[mbo].hastat, ccb[mbo].tarstat);
#endif
if (ccb[mbo].tarstat == 2) {
#ifdef DEBUG
int i;
#endif
DEB(printk("aha1542_intr_handle: sense:"));
#ifdef DEBUG
for (i = 0; i < 12; i++)
printk("%02x ", ccb[mbo].cdb[ccb[mbo].cdblen + i]);
printk("\n");
#endif
/*
DEB(printk("aha1542_intr_handle: buf:"));
for (i = 0; i < bufflen; i++)
printk("%02x ", ((unchar *)buff)[i]);
printk("\n");
*/
}
DEB(if (errstatus) printk("aha1542_intr_handle: returning %6x\n", errstatus));
SCtmp->result = errstatus;
HOSTDATA(shost)->SCint[mbo] = NULL; /* This effectively frees up the mailbox slot, as
far as queuecommand is concerned */
my_done(SCtmp);
number_serviced++;
};
}
static int aha1542_queuecommand_lck(Scsi_Cmnd * SCpnt, void (*done) (Scsi_Cmnd *))
{
unchar ahacmd = CMD_START_SCSI;
unchar direction;
unchar *cmd = (unchar *) SCpnt->cmnd;
unchar target = SCpnt->device->id;
unchar lun = SCpnt->device->lun;
unsigned long flags;
int bufflen = scsi_bufflen(SCpnt);
int mbo;
struct mailbox *mb;
struct ccb *ccb;
DEB(int i);
mb = HOSTDATA(SCpnt->device->host)->mb;
ccb = HOSTDATA(SCpnt->device->host)->ccb;
DEB(if (target > 1) {
SCpnt->result = DID_TIME_OUT << 16;
done(SCpnt); return 0;
}
);
if (*cmd == REQUEST_SENSE) {
/* Don't do the command - we have the sense data already */
#if 0
/* scsi_request_sense() provides a buffer of size 256,
so there is no reason to expect equality */
if (bufflen != SCSI_SENSE_BUFFERSIZE)
printk(KERN_CRIT "aha1542: Wrong buffer length supplied "
"for request sense (%d)\n", bufflen);
#endif
SCpnt->result = 0;
done(SCpnt);
return 0;
}
#ifdef DEBUG
if (*cmd == READ_10 || *cmd == WRITE_10)
i = xscsi2int(cmd + 2);
else if (*cmd == READ_6 || *cmd == WRITE_6)
i = scsi2int(cmd + 2);
else
i = -1;
if (done)
printk(KERN_DEBUG "aha1542_queuecommand: dev %d cmd %02x pos %d len %d ", target, *cmd, i, bufflen);
else
printk(KERN_DEBUG "aha1542_command: dev %d cmd %02x pos %d len %d ", target, *cmd, i, bufflen);
aha1542_stat();
printk(KERN_DEBUG "aha1542_queuecommand: dumping scsi cmd:");
for (i = 0; i < SCpnt->cmd_len; i++)
printk("%02x ", cmd[i]);
printk("\n");
if (*cmd == WRITE_10 || *cmd == WRITE_6)
return 0; /* we are still testing, so *don't* write */
#endif
/* Use the outgoing mailboxes in a round-robin fashion, because this
is how the host adapter will scan for them */
spin_lock_irqsave(&aha1542_lock, flags);
mbo = HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used + 1;
if (mbo >= AHA1542_MAILBOXES)
mbo = 0;
do {
if (mb[mbo].status == 0 && HOSTDATA(SCpnt->device->host)->SCint[mbo] == NULL)
break;
mbo++;
if (mbo >= AHA1542_MAILBOXES)
mbo = 0;
} while (mbo != HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used);
if (mb[mbo].status || HOSTDATA(SCpnt->device->host)->SCint[mbo])
panic("Unable to find empty mailbox for aha1542.\n");
HOSTDATA(SCpnt->device->host)->SCint[mbo] = SCpnt; /* This will effectively prevent someone else from
screwing with this cdb. */
HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used = mbo;
spin_unlock_irqrestore(&aha1542_lock, flags);
#ifdef DEBUG
printk(KERN_DEBUG "Sending command (%d %x)...", mbo, done);
#endif
any2scsi(mb[mbo].ccbptr, SCSI_BUF_PA(&ccb[mbo])); /* This gets trashed for some reason */
memset(&ccb[mbo], 0, sizeof(struct ccb));
ccb[mbo].cdblen = SCpnt->cmd_len;
direction = 0;
if (*cmd == READ_10 || *cmd == READ_6)
direction = 8;
else if (*cmd == WRITE_10 || *cmd == WRITE_6)
direction = 16;
memcpy(ccb[mbo].cdb, cmd, ccb[mbo].cdblen);
if (bufflen) {
struct scatterlist *sg;
struct chain *cptr;
#ifdef DEBUG
unsigned char *ptr;
#endif
int i, sg_count = scsi_sg_count(SCpnt);
ccb[mbo].op = 2; /* SCSI Initiator Command w/scatter-gather */
SCpnt->host_scribble = kmalloc(sizeof(*cptr)*sg_count,
GFP_KERNEL | GFP_DMA);
cptr = (struct chain *) SCpnt->host_scribble;
if (cptr == NULL) {
/* free the claimed mailbox slot */
HOSTDATA(SCpnt->device->host)->SCint[mbo] = NULL;
return SCSI_MLQUEUE_HOST_BUSY;
}
scsi_for_each_sg(SCpnt, sg, sg_count, i) {
any2scsi(cptr[i].dataptr, SCSI_SG_PA(sg));
any2scsi(cptr[i].datalen, sg->length);
};
any2scsi(ccb[mbo].datalen, sg_count * sizeof(struct chain));
any2scsi(ccb[mbo].dataptr, SCSI_BUF_PA(cptr));
#ifdef DEBUG
printk("cptr %x: ", cptr);
ptr = (unsigned char *) cptr;
for (i = 0; i < 18; i++)
printk("%02x ", ptr[i]);
#endif
} else {
ccb[mbo].op = 0; /* SCSI Initiator Command */
SCpnt->host_scribble = NULL;
any2scsi(ccb[mbo].datalen, 0);
any2scsi(ccb[mbo].dataptr, 0);
};
ccb[mbo].idlun = (target & 7) << 5 | direction | (lun & 7); /*SCSI Target Id */
ccb[mbo].rsalen = 16;
ccb[mbo].linkptr[0] = ccb[mbo].linkptr[1] = ccb[mbo].linkptr[2] = 0;
ccb[mbo].commlinkid = 0;
#ifdef DEBUG
{
int i;
printk(KERN_DEBUG "aha1542_command: sending.. ");
for (i = 0; i < sizeof(ccb[mbo]) - 10; i++)
printk("%02x ", ((unchar *) & ccb[mbo])[i]);
};
#endif
if (done) {
DEB(printk("aha1542_queuecommand: now waiting for interrupt ");
aha1542_stat());
SCpnt->scsi_done = done;
mb[mbo].status = 1;
aha1542_out(SCpnt->device->host->io_port, &ahacmd, 1); /* start scsi command */
DEB(aha1542_stat());
} else
printk("aha1542_queuecommand: done can't be NULL\n");
return 0;
}
static DEF_SCSI_QCMD(aha1542_queuecommand)
/* Initialize mailboxes */
static void setup_mailboxes(int bse, struct Scsi_Host *shpnt)
{
int i;
struct mailbox *mb;
struct ccb *ccb;
unchar cmd[5] = { CMD_MBINIT, AHA1542_MAILBOXES, 0, 0, 0};
mb = HOSTDATA(shpnt)->mb;
ccb = HOSTDATA(shpnt)->ccb;
for (i = 0; i < AHA1542_MAILBOXES; i++) {
mb[i].status = mb[AHA1542_MAILBOXES + i].status = 0;
any2scsi(mb[i].ccbptr, SCSI_BUF_PA(&ccb[i]));
};
aha1542_intr_reset(bse); /* reset interrupts, so they don't block */
any2scsi((cmd + 2), SCSI_BUF_PA(mb));
aha1542_out(bse, cmd, 5);
WAIT(INTRFLAGS(bse), INTRMASK, HACC, 0);
while (0) {
fail:
printk(KERN_ERR "aha1542_detect: failed setting up mailboxes\n");
}
aha1542_intr_reset(bse);
}
static int __init aha1542_getconfig(int base_io, unsigned char *irq_level, unsigned char *dma_chan, unsigned char *scsi_id)
{
unchar inquiry_cmd[] = {CMD_RETCONF};
unchar inquiry_result[3];
int i;
i = inb(STATUS(base_io));
if (i & DF) {
i = inb(DATA(base_io));
};
aha1542_out(base_io, inquiry_cmd, 1);
aha1542_in(base_io, inquiry_result, 3);
WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
while (0) {
fail:
printk(KERN_ERR "aha1542_detect: query board settings\n");
}
aha1542_intr_reset(base_io);
switch (inquiry_result[0]) {
case 0x80:
*dma_chan = 7;
break;
case 0x40:
*dma_chan = 6;
break;
case 0x20:
*dma_chan = 5;
break;
case 0x01:
*dma_chan = 0;
break;
case 0:
/* This means that the adapter, although Adaptec 1542 compatible, doesn't use a DMA channel.
Currently only aware of the BusLogic BT-445S VL-Bus adapter which needs this. */
*dma_chan = 0xFF;
break;
default:
printk(KERN_ERR "Unable to determine Adaptec DMA priority. Disabling board\n");
return -1;
};
switch (inquiry_result[1]) {
case 0x40:
*irq_level = 15;
break;
case 0x20:
*irq_level = 14;
break;
case 0x8:
*irq_level = 12;
break;
case 0x4:
*irq_level = 11;
break;
case 0x2:
*irq_level = 10;
break;
case 0x1:
*irq_level = 9;
break;
default:
printk(KERN_ERR "Unable to determine Adaptec IRQ level. Disabling board\n");
return -1;
};
*scsi_id = inquiry_result[2] & 7;
return 0;
}
/* This function should only be called for 1542C boards - we can detect
the special firmware settings and unlock the board */
static int __init aha1542_mbenable(int base)
{
static unchar mbenable_cmd[3];
static unchar mbenable_result[2];
int retval;
retval = BIOS_TRANSLATION_6432;
mbenable_cmd[0] = CMD_EXTBIOS;
aha1542_out(base, mbenable_cmd, 1);
if (aha1542_in1(base, mbenable_result, 2))
return retval;
WAITd(INTRFLAGS(base), INTRMASK, HACC, 0, 100);
aha1542_intr_reset(base);
if ((mbenable_result[0] & 0x08) || mbenable_result[1]) {
mbenable_cmd[0] = CMD_MBENABLE;
mbenable_cmd[1] = 0;
mbenable_cmd[2] = mbenable_result[1];
if ((mbenable_result[0] & 0x08) && (mbenable_result[1] & 0x03))
retval = BIOS_TRANSLATION_25563;
aha1542_out(base, mbenable_cmd, 3);
WAIT(INTRFLAGS(base), INTRMASK, HACC, 0);
};
while (0) {
fail:
printk(KERN_ERR "aha1542_mbenable: Mailbox init failed\n");
}
aha1542_intr_reset(base);
return retval;
}
/* Query the board to find out if it is a 1542 or a 1740, or whatever. */
static int __init aha1542_query(int base_io, int *transl)
{
unchar inquiry_cmd[] = {CMD_INQUIRY};
unchar inquiry_result[4];
int i;
i = inb(STATUS(base_io));
if (i & DF) {
i = inb(DATA(base_io));
};
aha1542_out(base_io, inquiry_cmd, 1);
aha1542_in(base_io, inquiry_result, 4);
WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
while (0) {
fail:
printk(KERN_ERR "aha1542_detect: query card type\n");
}
aha1542_intr_reset(base_io);
*transl = BIOS_TRANSLATION_6432; /* Default case */
/* For an AHA1740 series board, we ignore the board since there is a
hardware bug which can lead to wrong blocks being returned if the board
is operating in the 1542 emulation mode. Since there is an extended mode
driver, we simply ignore the board and let the 1740 driver pick it up.
*/
if (inquiry_result[0] == 0x43) {
printk(KERN_INFO "aha1542.c: Emulation mode not supported for AHA 174N hardware.\n");
return 1;
};
/* Always call this - boards that do not support extended bios translation
will ignore the command, and we will set the proper default */
*transl = aha1542_mbenable(base_io);
return 0;
}
#ifndef MODULE
static char *setup_str[MAXBOARDS] __initdata;
static int setup_idx = 0;
static void __init aha1542_setup(char *str, int *ints)
{
const char *ahausage = "aha1542: usage: aha1542=<PORTBASE>[,<BUSON>,<BUSOFF>[,<DMASPEED>]]\n";
int setup_portbase;
if (setup_idx >= MAXBOARDS) {
printk(KERN_ERR "aha1542: aha1542_setup called too many times! Bad LILO params ?\n");
printk(KERN_ERR " Entryline 1: %s\n", setup_str[0]);
printk(KERN_ERR " Entryline 2: %s\n", setup_str[1]);
printk(KERN_ERR " This line: %s\n", str);
return;
}
if (ints[0] < 1 || ints[0] > 4) {
printk(KERN_ERR "aha1542: %s\n", str);
printk(ahausage);
printk(KERN_ERR "aha1542: Wrong parameters may cause system malfunction.. We try anyway..\n");
}
setup_called[setup_idx] = ints[0];
setup_str[setup_idx] = str;
setup_portbase = ints[0] >= 1 ? ints[1] : 0; /* Preserve the default value.. */
setup_buson[setup_idx] = ints[0] >= 2 ? ints[2] : 7;
setup_busoff[setup_idx] = ints[0] >= 3 ? ints[3] : 5;
if (ints[0] >= 4)
{
int atbt = -1;
switch (ints[4]) {
case 5:
atbt = 0x00;
break;
case 6:
atbt = 0x04;
break;
case 7:
atbt = 0x01;
break;
case 8:
atbt = 0x02;
break;
case 10:
atbt = 0x03;
break;
default:
printk(KERN_ERR "aha1542: %s\n", str);
printk(ahausage);
printk(KERN_ERR "aha1542: Valid values for DMASPEED are 5-8, 10 MB/s. Using jumper defaults.\n");
break;
}
setup_dmaspeed[setup_idx] = atbt;
}
if (setup_portbase != 0)
bases[setup_idx] = setup_portbase;
++setup_idx;
}
static int __init do_setup(char *str)
{
int ints[5];
int count=setup_idx;
get_options(str, ARRAY_SIZE(ints), ints);
aha1542_setup(str,ints);
return count<setup_idx;
}
__setup("aha1542=",do_setup);
#endif
/* return non-zero on detection */
static int __init aha1542_detect(struct scsi_host_template * tpnt)
{
unsigned char dma_chan;
unsigned char irq_level;
unsigned char scsi_id;
unsigned long flags;
unsigned int base_io;
int trans;
struct Scsi_Host *shpnt = NULL;
int count = 0;
int indx;
DEB(printk("aha1542_detect: \n"));
tpnt->proc_name = "aha1542";
#ifdef MODULE
bases[0] = aha1542[0];
setup_buson[0] = aha1542[1];
setup_busoff[0] = aha1542[2];
{
int atbt = -1;
switch (aha1542[3]) {
case 5:
atbt = 0x00;
break;
case 6:
atbt = 0x04;
break;
case 7:
atbt = 0x01;
break;
case 8:
atbt = 0x02;
break;
case 10:
atbt = 0x03;
break;
};
setup_dmaspeed[0] = atbt;
}
#endif
/*
* Find MicroChannel cards (AHA1640)
*/
#ifdef CONFIG_MCA_LEGACY
if(MCA_bus) {
int slot = 0;
int pos = 0;
for (indx = 0; (slot != MCA_NOTFOUND) && (indx < ARRAY_SIZE(bases)); indx++) {
if (bases[indx])
continue;
/* Detect only AHA-1640 cards -- MCA ID 0F1F */
slot = mca_find_unused_adapter(0x0f1f, slot);
if (slot == MCA_NOTFOUND)
break;
/* Found one */
pos = mca_read_stored_pos(slot, 3);
/* Decode address */
if (pos & 0x80) {
if (pos & 0x02) {
if (pos & 0x01)
bases[indx] = 0x334;
else
bases[indx] = 0x234;
} else {
if (pos & 0x01)
bases[indx] = 0x134;
}
} else {
if (pos & 0x02) {
if (pos & 0x01)
bases[indx] = 0x330;
else
bases[indx] = 0x230;
} else {
if (pos & 0x01)
bases[indx] = 0x130;
}
}
/* No need to decode IRQ and Arb level -- those are
* read off the card later.
*/
printk(KERN_INFO "Found an AHA-1640 in MCA slot %d, I/O 0x%04x\n", slot, bases[indx]);
mca_set_adapter_name(slot, "Adapter AHA-1640");
mca_set_adapter_procfn(slot, NULL, NULL);
mca_mark_as_used(slot);
/* Go on */
slot++;
}
}
#endif
/*
* Hunt for ISA Plug'n'Pray Adaptecs (AHA1535)
*/
if(isapnp)
{
struct pnp_dev *pdev = NULL;
for(indx = 0; indx < ARRAY_SIZE(bases); indx++) {
if(bases[indx])
continue;
pdev = pnp_find_dev(NULL, ISAPNP_VENDOR('A', 'D', 'P'),
ISAPNP_FUNCTION(0x1542), pdev);
if(pdev==NULL)
break;
/*
* Activate the PnP card
*/
if(pnp_device_attach(pdev)<0)
continue;
if(pnp_activate_dev(pdev)<0) {
pnp_device_detach(pdev);
continue;
}
if(!pnp_port_valid(pdev, 0)) {
pnp_device_detach(pdev);
continue;
}
bases[indx] = pnp_port_start(pdev, 0);
/* The card can be queried for its DMA, we have
the DMA set up that is enough */
printk(KERN_INFO "ISAPnP found an AHA1535 at I/O 0x%03X\n", bases[indx]);
}
}
for (indx = 0; indx < ARRAY_SIZE(bases); indx++)
if (bases[indx] != 0 && request_region(bases[indx], 4, "aha1542")) {
shpnt = scsi_register(tpnt,
sizeof(struct aha1542_hostdata));
if(shpnt==NULL) {
release_region(bases[indx], 4);
continue;
}
if (!aha1542_test_port(bases[indx], shpnt))
goto unregister;
base_io = bases[indx];
/* Set the Bus on/off-times as not to ruin floppy performance */
{
unchar oncmd[] = {CMD_BUSON_TIME, 7};
unchar offcmd[] = {CMD_BUSOFF_TIME, 5};
if (setup_called[indx]) {
oncmd[1] = setup_buson[indx];
offcmd[1] = setup_busoff[indx];
}
aha1542_intr_reset(base_io);
aha1542_out(base_io, oncmd, 2);
WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
aha1542_intr_reset(base_io);
aha1542_out(base_io, offcmd, 2);
WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
if (setup_dmaspeed[indx] >= 0) {
unchar dmacmd[] = {CMD_DMASPEED, 0};
dmacmd[1] = setup_dmaspeed[indx];
aha1542_intr_reset(base_io);
aha1542_out(base_io, dmacmd, 2);
WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
}
while (0) {
fail:
printk(KERN_ERR "aha1542_detect: setting bus on/off-time failed\n");
}
aha1542_intr_reset(base_io);
}
if (aha1542_query(base_io, &trans))
goto unregister;
if (aha1542_getconfig(base_io, &irq_level, &dma_chan, &scsi_id) == -1)
goto unregister;
printk(KERN_INFO "Configuring Adaptec (SCSI-ID %d) at IO:%x, IRQ %d", scsi_id, base_io, irq_level);
if (dma_chan != 0xFF)
printk(", DMA priority %d", dma_chan);
printk("\n");
DEB(aha1542_stat());
setup_mailboxes(base_io, shpnt);
DEB(aha1542_stat());
DEB(printk("aha1542_detect: enable interrupt channel %d\n", irq_level));
spin_lock_irqsave(&aha1542_lock, flags);
if (request_irq(irq_level, do_aha1542_intr_handle, 0,
"aha1542", shpnt)) {
printk(KERN_ERR "Unable to allocate IRQ for adaptec controller.\n");
spin_unlock_irqrestore(&aha1542_lock, flags);
goto unregister;
}
if (dma_chan != 0xFF) {
if (request_dma(dma_chan, "aha1542")) {
printk(KERN_ERR "Unable to allocate DMA channel for Adaptec.\n");
free_irq(irq_level, shpnt);
spin_unlock_irqrestore(&aha1542_lock, flags);
goto unregister;
}
if (dma_chan == 0 || dma_chan >= 5) {
set_dma_mode(dma_chan, DMA_MODE_CASCADE);
enable_dma(dma_chan);
}
}
shpnt->this_id = scsi_id;
shpnt->unique_id = base_io;
shpnt->io_port = base_io;
shpnt->n_io_port = 4; /* Number of bytes of I/O space used */
shpnt->dma_channel = dma_chan;
shpnt->irq = irq_level;
HOSTDATA(shpnt)->bios_translation = trans;
if (trans == BIOS_TRANSLATION_25563)
printk(KERN_INFO "aha1542.c: Using extended bios translation\n");
HOSTDATA(shpnt)->aha1542_last_mbi_used = (2 * AHA1542_MAILBOXES - 1);
HOSTDATA(shpnt)->aha1542_last_mbo_used = (AHA1542_MAILBOXES - 1);
memset(HOSTDATA(shpnt)->SCint, 0, sizeof(HOSTDATA(shpnt)->SCint));
spin_unlock_irqrestore(&aha1542_lock, flags);
#if 0
DEB(printk(" *** READ CAPACITY ***\n"));
{
unchar buf[8];
static unchar cmd[] = { READ_CAPACITY, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i;
for (i = 0; i < sizeof(buf); ++i)
buf[i] = 0x87;
for (i = 0; i < 2; ++i)
if (!aha1542_command(i, cmd, buf, sizeof(buf))) {
printk(KERN_DEBUG "aha_detect: LU %d sector_size %d device_size %d\n",
i, xscsi2int(buf + 4), xscsi2int(buf));
}
}
DEB(printk(" *** NOW RUNNING MY OWN TEST *** \n"));
for (i = 0; i < 4; ++i) {
unsigned char cmd[10];
static buffer[512];
cmd[0] = READ_10;
cmd[1] = 0;
xany2scsi(cmd + 2, i);
cmd[6] = 0;
cmd[7] = 0;
cmd[8] = 1;
cmd[9] = 0;
aha1542_command(0, cmd, buffer, 512);
}
#endif
count++;
continue;
unregister:
release_region(bases[indx], 4);
scsi_unregister(shpnt);
continue;
};
return count;
}
static int aha1542_release(struct Scsi_Host *shost)
{
if (shost->irq)
free_irq(shost->irq, shost);
if (shost->dma_channel != 0xff)
free_dma(shost->dma_channel);
if (shost->io_port && shost->n_io_port)
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
return 0;
}
static int aha1542_restart(struct Scsi_Host *shost)
{
int i;
int count = 0;
#if 0
unchar ahacmd = CMD_START_SCSI;
#endif
for (i = 0; i < AHA1542_MAILBOXES; i++)
if (HOSTDATA(shost)->SCint[i] &&
!(HOSTDATA(shost)->SCint[i]->device->soft_reset)) {
#if 0
HOSTDATA(shost)->mb[i].status = 1; /* Indicate ready to restart... */
#endif
count++;
}
printk(KERN_DEBUG "Potential to restart %d stalled commands...\n", count);
#if 0
/* start scsi command */
if (count)
aha1542_out(shost->io_port, &ahacmd, 1);
#endif
return 0;
}
/*
* This is a device reset. This is handled by sending a special command
* to the device.
*/
static int aha1542_dev_reset(Scsi_Cmnd * SCpnt)
{
unsigned long flags;
struct mailbox *mb;
unchar target = SCpnt->device->id;
unchar lun = SCpnt->device->lun;
int mbo;
struct ccb *ccb;
unchar ahacmd = CMD_START_SCSI;
ccb = HOSTDATA(SCpnt->device->host)->ccb;
mb = HOSTDATA(SCpnt->device->host)->mb;
spin_lock_irqsave(&aha1542_lock, flags);
mbo = HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used + 1;
if (mbo >= AHA1542_MAILBOXES)
mbo = 0;
do {
if (mb[mbo].status == 0 && HOSTDATA(SCpnt->device->host)->SCint[mbo] == NULL)
break;
mbo++;
if (mbo >= AHA1542_MAILBOXES)
mbo = 0;
} while (mbo != HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used);
if (mb[mbo].status || HOSTDATA(SCpnt->device->host)->SCint[mbo])
panic("Unable to find empty mailbox for aha1542.\n");
HOSTDATA(SCpnt->device->host)->SCint[mbo] = SCpnt; /* This will effectively
prevent someone else from
screwing with this cdb. */
HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used = mbo;
spin_unlock_irqrestore(&aha1542_lock, flags);
any2scsi(mb[mbo].ccbptr, SCSI_BUF_PA(&ccb[mbo])); /* This gets trashed for some reason */
memset(&ccb[mbo], 0, sizeof(struct ccb));
ccb[mbo].op = 0x81; /* BUS DEVICE RESET */
ccb[mbo].idlun = (target & 7) << 5 | (lun & 7); /*SCSI Target Id */
ccb[mbo].linkptr[0] = ccb[mbo].linkptr[1] = ccb[mbo].linkptr[2] = 0;
ccb[mbo].commlinkid = 0;
/*
* Now tell the 1542 to flush all pending commands for this
* target
*/
aha1542_out(SCpnt->device->host->io_port, &ahacmd, 1);
scmd_printk(KERN_WARNING, SCpnt,
"Trying device reset for target\n");
return SUCCESS;
#ifdef ERIC_neverdef
/*
* With the 1542 we apparently never get an interrupt to
* acknowledge a device reset being sent. Then again, Leonard
* says we are doing this wrong in the first place...
*
* Take a wait and see attitude. If we get spurious interrupts,
* then the device reset is doing something sane and useful, and
* we will wait for the interrupt to post completion.
*/
printk(KERN_WARNING "Sent BUS DEVICE RESET to target %d\n", SCpnt->target);
/*
* Free the command block for all commands running on this
* target...
*/
for (i = 0; i < AHA1542_MAILBOXES; i++) {
if (HOSTDATA(SCpnt->host)->SCint[i] &&
HOSTDATA(SCpnt->host)->SCint[i]->target == SCpnt->target) {
Scsi_Cmnd *SCtmp;
SCtmp = HOSTDATA(SCpnt->host)->SCint[i];
kfree(SCtmp->host_scribble);
SCtmp->host_scribble = NULL;
HOSTDATA(SCpnt->host)->SCint[i] = NULL;
HOSTDATA(SCpnt->host)->mb[i].status = 0;
}
}
return SUCCESS;
return FAILED;
#endif /* ERIC_neverdef */
}
static int aha1542_bus_reset(Scsi_Cmnd * SCpnt)
{
int i;
/*
* This does a scsi reset for all devices on the bus.
* In principle, we could also reset the 1542 - should
* we do this? Try this first, and we can add that later
* if it turns out to be useful.
*/
outb(SCRST, CONTROL(SCpnt->device->host->io_port));
/*
* Wait for the thing to settle down a bit. Unfortunately
* this is going to basically lock up the machine while we
* wait for this to complete. To be 100% correct, we need to
* check for timeout, and if we are doing something like this
* we are pretty desperate anyways.
*/
ssleep(4);
spin_lock_irq(SCpnt->device->host->host_lock);
WAIT(STATUS(SCpnt->device->host->io_port),
STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
/*
* Now try to pick up the pieces. For all pending commands,
* free any internal data structures, and basically clear things
* out. We do not try and restart any commands or anything -
* the strategy handler takes care of that crap.
*/
printk(KERN_WARNING "Sent BUS RESET to scsi host %d\n", SCpnt->device->host->host_no);
for (i = 0; i < AHA1542_MAILBOXES; i++) {
if (HOSTDATA(SCpnt->device->host)->SCint[i] != NULL) {
Scsi_Cmnd *SCtmp;
SCtmp = HOSTDATA(SCpnt->device->host)->SCint[i];
if (SCtmp->device->soft_reset) {
/*
* If this device implements the soft reset option,
* then it is still holding onto the command, and
* may yet complete it. In this case, we don't
* flush the data.
*/
continue;
}
kfree(SCtmp->host_scribble);
SCtmp->host_scribble = NULL;
HOSTDATA(SCpnt->device->host)->SCint[i] = NULL;
HOSTDATA(SCpnt->device->host)->mb[i].status = 0;
}
}
spin_unlock_irq(SCpnt->device->host->host_lock);
return SUCCESS;
fail:
spin_unlock_irq(SCpnt->device->host->host_lock);
return FAILED;
}
static int aha1542_host_reset(Scsi_Cmnd * SCpnt)
{
int i;
/*
* This does a scsi reset for all devices on the bus.
* In principle, we could also reset the 1542 - should
* we do this? Try this first, and we can add that later
* if it turns out to be useful.
*/
outb(HRST | SCRST, CONTROL(SCpnt->device->host->io_port));
/*
* Wait for the thing to settle down a bit. Unfortunately
* this is going to basically lock up the machine while we
* wait for this to complete. To be 100% correct, we need to
* check for timeout, and if we are doing something like this
* we are pretty desperate anyways.
*/
ssleep(4);
spin_lock_irq(SCpnt->device->host->host_lock);
WAIT(STATUS(SCpnt->device->host->io_port),
STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
/*
* We need to do this too before the 1542 can interact with
* us again.
*/
setup_mailboxes(SCpnt->device->host->io_port, SCpnt->device->host);
/*
* Now try to pick up the pieces. For all pending commands,
* free any internal data structures, and basically clear things
* out. We do not try and restart any commands or anything -
* the strategy handler takes care of that crap.
*/
printk(KERN_WARNING "Sent BUS RESET to scsi host %d\n", SCpnt->device->host->host_no);
for (i = 0; i < AHA1542_MAILBOXES; i++) {
if (HOSTDATA(SCpnt->device->host)->SCint[i] != NULL) {
Scsi_Cmnd *SCtmp;
SCtmp = HOSTDATA(SCpnt->device->host)->SCint[i];
if (SCtmp->device->soft_reset) {
/*
* If this device implements the soft reset option,
* then it is still holding onto the command, and
* may yet complete it. In this case, we don't
* flush the data.
*/
continue;
}
kfree(SCtmp->host_scribble);
SCtmp->host_scribble = NULL;
HOSTDATA(SCpnt->device->host)->SCint[i] = NULL;
HOSTDATA(SCpnt->device->host)->mb[i].status = 0;
}
}
spin_unlock_irq(SCpnt->device->host->host_lock);
return SUCCESS;
fail:
spin_unlock_irq(SCpnt->device->host->host_lock);
return FAILED;
}
#if 0
/*
* These are the old error handling routines. They are only temporarily
* here while we play with the new error handling code.
*/
static int aha1542_old_abort(Scsi_Cmnd * SCpnt)
{
#if 0
unchar ahacmd = CMD_START_SCSI;
unsigned long flags;
struct mailbox *mb;
int mbi, mbo, i;
printk(KERN_DEBUG "In aha1542_abort: %x %x\n",
inb(STATUS(SCpnt->host->io_port)),
inb(INTRFLAGS(SCpnt->host->io_port)));
spin_lock_irqsave(&aha1542_lock, flags);
mb = HOSTDATA(SCpnt->host)->mb;
mbi = HOSTDATA(SCpnt->host)->aha1542_last_mbi_used + 1;
if (mbi >= 2 * AHA1542_MAILBOXES)
mbi = AHA1542_MAILBOXES;
do {
if (mb[mbi].status != 0)
break;
mbi++;
if (mbi >= 2 * AHA1542_MAILBOXES)
mbi = AHA1542_MAILBOXES;
} while (mbi != HOSTDATA(SCpnt->host)->aha1542_last_mbi_used);
spin_unlock_irqrestore(&aha1542_lock, flags);
if (mb[mbi].status) {
printk(KERN_ERR "Lost interrupt discovered on irq %d - attempting to recover\n",
SCpnt->host->irq);
aha1542_intr_handle(SCpnt->host, NULL);
return 0;
}
/* OK, no lost interrupt. Try looking to see how many pending commands
we think we have. */
for (i = 0; i < AHA1542_MAILBOXES; i++)
if (HOSTDATA(SCpnt->host)->SCint[i]) {
if (HOSTDATA(SCpnt->host)->SCint[i] == SCpnt) {
printk(KERN_ERR "Timed out command pending for %s\n",
SCpnt->request->rq_disk ?
SCpnt->request->rq_disk->disk_name : "?"
);
if (HOSTDATA(SCpnt->host)->mb[i].status) {
printk(KERN_ERR "OGMB still full - restarting\n");
aha1542_out(SCpnt->host->io_port, &ahacmd, 1);
};
} else
printk(KERN_ERR "Other pending command %s\n",
SCpnt->request->rq_disk ?
SCpnt->request->rq_disk->disk_name : "?"
);
}
#endif
DEB(printk("aha1542_abort\n"));
#if 0
spin_lock_irqsave(&aha1542_lock, flags);
for (mbo = 0; mbo < AHA1542_MAILBOXES; mbo++) {
if (SCpnt == HOSTDATA(SCpnt->host)->SCint[mbo]) {
mb[mbo].status = 2; /* Abort command */
aha1542_out(SCpnt->host->io_port, &ahacmd, 1); /* start scsi command */
spin_unlock_irqrestore(&aha1542_lock, flags);
break;
}
}
if (AHA1542_MAILBOXES == mbo)
spin_unlock_irqrestore(&aha1542_lock, flags);
#endif
return SCSI_ABORT_SNOOZE;
}
/* We do not implement a reset function here, but the upper level code
assumes that it will get some kind of response for the command in
SCpnt. We must oblige, or the command will hang the scsi system.
For a first go, we assume that the 1542 notifies us with all of the
pending commands (it does implement soft reset, after all). */
static int aha1542_old_reset(Scsi_Cmnd * SCpnt, unsigned int reset_flags)
{
unchar ahacmd = CMD_START_SCSI;
int i;
/*
* See if a bus reset was suggested.
*/
if (reset_flags & SCSI_RESET_SUGGEST_BUS_RESET) {
/*
* This does a scsi reset for all devices on the bus.
* In principle, we could also reset the 1542 - should
* we do this? Try this first, and we can add that later
* if it turns out to be useful.
*/
outb(HRST | SCRST, CONTROL(SCpnt->host->io_port));
/*
* Wait for the thing to settle down a bit. Unfortunately
* this is going to basically lock up the machine while we
* wait for this to complete. To be 100% correct, we need to
* check for timeout, and if we are doing something like this
* we are pretty desperate anyways.
*/
WAIT(STATUS(SCpnt->host->io_port),
STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
/*
* We need to do this too before the 1542 can interact with
* us again.
*/
setup_mailboxes(SCpnt->host->io_port, SCpnt->host);
/*
* Now try to pick up the pieces. Restart all commands
* that are currently active on the bus, and reset all of
* the datastructures. We have some time to kill while
* things settle down, so print a nice message.
*/
printk(KERN_WARNING "Sent BUS RESET to scsi host %d\n", SCpnt->host->host_no);
for (i = 0; i < AHA1542_MAILBOXES; i++)
if (HOSTDATA(SCpnt->host)->SCint[i] != NULL) {
Scsi_Cmnd *SCtmp;
SCtmp = HOSTDATA(SCpnt->host)->SCint[i];
SCtmp->result = DID_RESET << 16;
kfree(SCtmp->host_scribble);
SCtmp->host_scribble = NULL;
printk(KERN_WARNING "Sending DID_RESET for target %d\n", SCpnt->target);
SCtmp->scsi_done(SCpnt);
HOSTDATA(SCpnt->host)->SCint[i] = NULL;
HOSTDATA(SCpnt->host)->mb[i].status = 0;
}
/*
* Now tell the mid-level code what we did here. Since
* we have restarted all of the outstanding commands,
* then report SUCCESS.
*/
return (SCSI_RESET_SUCCESS | SCSI_RESET_BUS_RESET);
fail:
printk(KERN_CRIT "aha1542.c: Unable to perform hard reset.\n");
printk(KERN_CRIT "Power cycle machine to reset\n");
return (SCSI_RESET_ERROR | SCSI_RESET_BUS_RESET);
} else {
/* This does a selective reset of just the one device */
/* First locate the ccb for this command */
for (i = 0; i < AHA1542_MAILBOXES; i++)
if (HOSTDATA(SCpnt->host)->SCint[i] == SCpnt) {
HOSTDATA(SCpnt->host)->ccb[i].op = 0x81; /* BUS DEVICE RESET */
/* Now tell the 1542 to flush all pending commands for this target */
aha1542_out(SCpnt->host->io_port, &ahacmd, 1);
/* Here is the tricky part. What to do next. Do we get an interrupt
for the commands that we aborted with the specified target, or
do we generate this on our own? Try it without first and see
what happens */
printk(KERN_WARNING "Sent BUS DEVICE RESET to target %d\n", SCpnt->target);
/* If the first does not work, then try the second. I think the
first option is more likely to be correct. Free the command
block for all commands running on this target... */
for (i = 0; i < AHA1542_MAILBOXES; i++)
if (HOSTDATA(SCpnt->host)->SCint[i] &&
HOSTDATA(SCpnt->host)->SCint[i]->target == SCpnt->target) {
Scsi_Cmnd *SCtmp;
SCtmp = HOSTDATA(SCpnt->host)->SCint[i];
SCtmp->result = DID_RESET << 16;
kfree(SCtmp->host_scribble);
SCtmp->host_scribble = NULL;
printk(KERN_WARNING "Sending DID_RESET for target %d\n", SCpnt->target);
SCtmp->scsi_done(SCpnt);
HOSTDATA(SCpnt->host)->SCint[i] = NULL;
HOSTDATA(SCpnt->host)->mb[i].status = 0;
}
return SCSI_RESET_SUCCESS;
}
}
/* No active command at this time, so this means that each time we got
some kind of response the last time through. Tell the mid-level code
to request sense information in order to decide what to do next. */
return SCSI_RESET_PUNT;
}
#endif /* end of big comment block around old_abort + old_reset */
static int aha1542_biosparam(struct scsi_device *sdev,
struct block_device *bdev, sector_t capacity, int *ip)
{
int translation_algorithm;
int size = capacity;
translation_algorithm = HOSTDATA(sdev->host)->bios_translation;
if ((size >> 11) > 1024 && translation_algorithm == BIOS_TRANSLATION_25563) {
/* Please verify that this is the same as what DOS returns */
ip[0] = 255;
ip[1] = 63;
ip[2] = size / 255 / 63;
} else {
ip[0] = 64;
ip[1] = 32;
ip[2] = size >> 11;
}
return 0;
}
MODULE_LICENSE("GPL");
static struct scsi_host_template driver_template = {
.proc_name = "aha1542",
.name = "Adaptec 1542",
.detect = aha1542_detect,
.release = aha1542_release,
.queuecommand = aha1542_queuecommand,
.eh_device_reset_handler= aha1542_dev_reset,
.eh_bus_reset_handler = aha1542_bus_reset,
.eh_host_reset_handler = aha1542_host_reset,
.bios_param = aha1542_biosparam,
.can_queue = AHA1542_MAILBOXES,
.this_id = 7,
.sg_tablesize = AHA1542_SCATTER,
.cmd_per_lun = AHA1542_CMDLUN,
.unchecked_isa_dma = 1,
.use_clustering = ENABLE_CLUSTERING,
};
#include "scsi_module.c"
| gpl-2.0 |
moscowdesire/Sony | drivers/net/wireless/ath/ath5k/debug.c | 4776 | 31602 | /*
* Copyright (c) 2007-2008 Bruno Randolf <bruno@thinktube.com>
*
* This file is free software: you may copy, redistribute 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 file 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/>.
*
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
* Copyright (c) 2004-2005 Atheros Communications, Inc.
* Copyright (c) 2006 Devicescape Software, Inc.
* Copyright (c) 2007 Jiri Slaby <jirislaby@gmail.com>
* Copyright (c) 2007 Luis R. Rodriguez <mcgrof@winlab.rutgers.edu>
*
* 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. Redistributions in binary form must reproduce at minimum a disclaimer
* similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
* redistribution must be conditioned upon including a substantially
* similar Disclaimer requirement for further binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 NONINFRINGEMENT, MERCHANTIBILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#include <linux/export.h>
#include <linux/moduleparam.h>
#include <linux/seq_file.h>
#include <linux/list.h>
#include "debug.h"
#include "ath5k.h"
#include "reg.h"
#include "base.h"
static unsigned int ath5k_debug;
module_param_named(debug, ath5k_debug, uint, 0);
/* debugfs: registers */
struct reg {
const char *name;
int addr;
};
#define REG_STRUCT_INIT(r) { #r, r }
/* just a few random registers, might want to add more */
static const struct reg regs[] = {
REG_STRUCT_INIT(AR5K_CR),
REG_STRUCT_INIT(AR5K_RXDP),
REG_STRUCT_INIT(AR5K_CFG),
REG_STRUCT_INIT(AR5K_IER),
REG_STRUCT_INIT(AR5K_BCR),
REG_STRUCT_INIT(AR5K_RTSD0),
REG_STRUCT_INIT(AR5K_RTSD1),
REG_STRUCT_INIT(AR5K_TXCFG),
REG_STRUCT_INIT(AR5K_RXCFG),
REG_STRUCT_INIT(AR5K_RXJLA),
REG_STRUCT_INIT(AR5K_MIBC),
REG_STRUCT_INIT(AR5K_TOPS),
REG_STRUCT_INIT(AR5K_RXNOFRM),
REG_STRUCT_INIT(AR5K_TXNOFRM),
REG_STRUCT_INIT(AR5K_RPGTO),
REG_STRUCT_INIT(AR5K_RFCNT),
REG_STRUCT_INIT(AR5K_MISC),
REG_STRUCT_INIT(AR5K_QCUDCU_CLKGT),
REG_STRUCT_INIT(AR5K_ISR),
REG_STRUCT_INIT(AR5K_PISR),
REG_STRUCT_INIT(AR5K_SISR0),
REG_STRUCT_INIT(AR5K_SISR1),
REG_STRUCT_INIT(AR5K_SISR2),
REG_STRUCT_INIT(AR5K_SISR3),
REG_STRUCT_INIT(AR5K_SISR4),
REG_STRUCT_INIT(AR5K_IMR),
REG_STRUCT_INIT(AR5K_PIMR),
REG_STRUCT_INIT(AR5K_SIMR0),
REG_STRUCT_INIT(AR5K_SIMR1),
REG_STRUCT_INIT(AR5K_SIMR2),
REG_STRUCT_INIT(AR5K_SIMR3),
REG_STRUCT_INIT(AR5K_SIMR4),
REG_STRUCT_INIT(AR5K_DCM_ADDR),
REG_STRUCT_INIT(AR5K_DCCFG),
REG_STRUCT_INIT(AR5K_CCFG),
REG_STRUCT_INIT(AR5K_CPC0),
REG_STRUCT_INIT(AR5K_CPC1),
REG_STRUCT_INIT(AR5K_CPC2),
REG_STRUCT_INIT(AR5K_CPC3),
REG_STRUCT_INIT(AR5K_CPCOVF),
REG_STRUCT_INIT(AR5K_RESET_CTL),
REG_STRUCT_INIT(AR5K_SLEEP_CTL),
REG_STRUCT_INIT(AR5K_INTPEND),
REG_STRUCT_INIT(AR5K_SFR),
REG_STRUCT_INIT(AR5K_PCICFG),
REG_STRUCT_INIT(AR5K_GPIOCR),
REG_STRUCT_INIT(AR5K_GPIODO),
REG_STRUCT_INIT(AR5K_SREV),
};
static void *reg_start(struct seq_file *seq, loff_t *pos)
{
return *pos < ARRAY_SIZE(regs) ? (void *)®s[*pos] : NULL;
}
static void reg_stop(struct seq_file *seq, void *p)
{
/* nothing to do */
}
static void *reg_next(struct seq_file *seq, void *p, loff_t *pos)
{
++*pos;
return *pos < ARRAY_SIZE(regs) ? (void *)®s[*pos] : NULL;
}
static int reg_show(struct seq_file *seq, void *p)
{
struct ath5k_hw *ah = seq->private;
struct reg *r = p;
seq_printf(seq, "%-25s0x%08x\n", r->name,
ath5k_hw_reg_read(ah, r->addr));
return 0;
}
static const struct seq_operations register_seq_ops = {
.start = reg_start,
.next = reg_next,
.stop = reg_stop,
.show = reg_show
};
static int open_file_registers(struct inode *inode, struct file *file)
{
struct seq_file *s;
int res;
res = seq_open(file, ®ister_seq_ops);
if (res == 0) {
s = file->private_data;
s->private = inode->i_private;
}
return res;
}
static const struct file_operations fops_registers = {
.open = open_file_registers,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
.owner = THIS_MODULE,
};
/* debugfs: beacons */
static ssize_t read_file_beacon(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[500];
unsigned int len = 0;
unsigned int v;
u64 tsf;
v = ath5k_hw_reg_read(ah, AR5K_BEACON);
len += snprintf(buf + len, sizeof(buf) - len,
"%-24s0x%08x\tintval: %d\tTIM: 0x%x\n",
"AR5K_BEACON", v, v & AR5K_BEACON_PERIOD,
(v & AR5K_BEACON_TIM) >> AR5K_BEACON_TIM_S);
len += snprintf(buf + len, sizeof(buf) - len, "%-24s0x%08x\n",
"AR5K_LAST_TSTP", ath5k_hw_reg_read(ah, AR5K_LAST_TSTP));
len += snprintf(buf + len, sizeof(buf) - len, "%-24s0x%08x\n\n",
"AR5K_BEACON_CNT", ath5k_hw_reg_read(ah, AR5K_BEACON_CNT));
v = ath5k_hw_reg_read(ah, AR5K_TIMER0);
len += snprintf(buf + len, sizeof(buf) - len, "%-24s0x%08x\tTU: %08x\n",
"AR5K_TIMER0 (TBTT)", v, v);
v = ath5k_hw_reg_read(ah, AR5K_TIMER1);
len += snprintf(buf + len, sizeof(buf) - len, "%-24s0x%08x\tTU: %08x\n",
"AR5K_TIMER1 (DMA)", v, v >> 3);
v = ath5k_hw_reg_read(ah, AR5K_TIMER2);
len += snprintf(buf + len, sizeof(buf) - len, "%-24s0x%08x\tTU: %08x\n",
"AR5K_TIMER2 (SWBA)", v, v >> 3);
v = ath5k_hw_reg_read(ah, AR5K_TIMER3);
len += snprintf(buf + len, sizeof(buf) - len, "%-24s0x%08x\tTU: %08x\n",
"AR5K_TIMER3 (ATIM)", v, v);
tsf = ath5k_hw_get_tsf64(ah);
len += snprintf(buf + len, sizeof(buf) - len,
"TSF\t\t0x%016llx\tTU: %08x\n",
(unsigned long long)tsf, TSF_TO_TU(tsf));
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_beacon(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[20];
if (copy_from_user(buf, userbuf, min(count, sizeof(buf))))
return -EFAULT;
if (strncmp(buf, "disable", 7) == 0) {
AR5K_REG_DISABLE_BITS(ah, AR5K_BEACON, AR5K_BEACON_ENABLE);
printk(KERN_INFO "debugfs disable beacons\n");
} else if (strncmp(buf, "enable", 6) == 0) {
AR5K_REG_ENABLE_BITS(ah, AR5K_BEACON, AR5K_BEACON_ENABLE);
printk(KERN_INFO "debugfs enable beacons\n");
}
return count;
}
static const struct file_operations fops_beacon = {
.read = read_file_beacon,
.write = write_file_beacon,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
/* debugfs: reset */
static ssize_t write_file_reset(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
ATH5K_DBG(ah, ATH5K_DEBUG_RESET, "debug file triggered reset\n");
ieee80211_queue_work(ah->hw, &ah->reset_work);
return count;
}
static const struct file_operations fops_reset = {
.write = write_file_reset,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = noop_llseek,
};
/* debugfs: debug level */
static const struct {
enum ath5k_debug_level level;
const char *name;
const char *desc;
} dbg_info[] = {
{ ATH5K_DEBUG_RESET, "reset", "reset and initialization" },
{ ATH5K_DEBUG_INTR, "intr", "interrupt handling" },
{ ATH5K_DEBUG_MODE, "mode", "mode init/setup" },
{ ATH5K_DEBUG_XMIT, "xmit", "basic xmit operation" },
{ ATH5K_DEBUG_BEACON, "beacon", "beacon handling" },
{ ATH5K_DEBUG_CALIBRATE, "calib", "periodic calibration" },
{ ATH5K_DEBUG_TXPOWER, "txpower", "transmit power setting" },
{ ATH5K_DEBUG_LED, "led", "LED management" },
{ ATH5K_DEBUG_DUMPBANDS, "dumpbands", "dump bands" },
{ ATH5K_DEBUG_DMA, "dma", "dma start/stop" },
{ ATH5K_DEBUG_ANI, "ani", "adaptive noise immunity" },
{ ATH5K_DEBUG_DESC, "desc", "descriptor chains" },
{ ATH5K_DEBUG_ANY, "all", "show all debug levels" },
};
static ssize_t read_file_debug(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[700];
unsigned int len = 0;
unsigned int i;
len += snprintf(buf + len, sizeof(buf) - len,
"DEBUG LEVEL: 0x%08x\n\n", ah->debug.level);
for (i = 0; i < ARRAY_SIZE(dbg_info) - 1; i++) {
len += snprintf(buf + len, sizeof(buf) - len,
"%10s %c 0x%08x - %s\n", dbg_info[i].name,
ah->debug.level & dbg_info[i].level ? '+' : ' ',
dbg_info[i].level, dbg_info[i].desc);
}
len += snprintf(buf + len, sizeof(buf) - len,
"%10s %c 0x%08x - %s\n", dbg_info[i].name,
ah->debug.level == dbg_info[i].level ? '+' : ' ',
dbg_info[i].level, dbg_info[i].desc);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_debug(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
unsigned int i;
char buf[20];
if (copy_from_user(buf, userbuf, min(count, sizeof(buf))))
return -EFAULT;
for (i = 0; i < ARRAY_SIZE(dbg_info); i++) {
if (strncmp(buf, dbg_info[i].name,
strlen(dbg_info[i].name)) == 0) {
ah->debug.level ^= dbg_info[i].level; /* toggle bit */
break;
}
}
return count;
}
static const struct file_operations fops_debug = {
.read = read_file_debug,
.write = write_file_debug,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
/* debugfs: antenna */
static ssize_t read_file_antenna(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[700];
unsigned int len = 0;
unsigned int i;
unsigned int v;
len += snprintf(buf + len, sizeof(buf) - len, "antenna mode\t%d\n",
ah->ah_ant_mode);
len += snprintf(buf + len, sizeof(buf) - len, "default antenna\t%d\n",
ah->ah_def_ant);
len += snprintf(buf + len, sizeof(buf) - len, "tx antenna\t%d\n",
ah->ah_tx_ant);
len += snprintf(buf + len, sizeof(buf) - len, "\nANTENNA\t\tRX\tTX\n");
for (i = 1; i < ARRAY_SIZE(ah->stats.antenna_rx); i++) {
len += snprintf(buf + len, sizeof(buf) - len,
"[antenna %d]\t%d\t%d\n",
i, ah->stats.antenna_rx[i], ah->stats.antenna_tx[i]);
}
len += snprintf(buf + len, sizeof(buf) - len, "[invalid]\t%d\t%d\n",
ah->stats.antenna_rx[0], ah->stats.antenna_tx[0]);
v = ath5k_hw_reg_read(ah, AR5K_DEFAULT_ANTENNA);
len += snprintf(buf + len, sizeof(buf) - len,
"\nAR5K_DEFAULT_ANTENNA\t0x%08x\n", v);
v = ath5k_hw_reg_read(ah, AR5K_STA_ID1);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_STA_ID1_DEFAULT_ANTENNA\t%d\n",
(v & AR5K_STA_ID1_DEFAULT_ANTENNA) != 0);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_STA_ID1_DESC_ANTENNA\t%d\n",
(v & AR5K_STA_ID1_DESC_ANTENNA) != 0);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_STA_ID1_RTS_DEF_ANTENNA\t%d\n",
(v & AR5K_STA_ID1_RTS_DEF_ANTENNA) != 0);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_STA_ID1_SELFGEN_DEF_ANT\t%d\n",
(v & AR5K_STA_ID1_SELFGEN_DEF_ANT) != 0);
v = ath5k_hw_reg_read(ah, AR5K_PHY_AGCCTL);
len += snprintf(buf + len, sizeof(buf) - len,
"\nAR5K_PHY_AGCCTL_OFDM_DIV_DIS\t%d\n",
(v & AR5K_PHY_AGCCTL_OFDM_DIV_DIS) != 0);
v = ath5k_hw_reg_read(ah, AR5K_PHY_RESTART);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_PHY_RESTART_DIV_GC\t\t%x\n",
(v & AR5K_PHY_RESTART_DIV_GC) >> AR5K_PHY_RESTART_DIV_GC_S);
v = ath5k_hw_reg_read(ah, AR5K_PHY_FAST_ANT_DIV);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_PHY_FAST_ANT_DIV_EN\t%d\n",
(v & AR5K_PHY_FAST_ANT_DIV_EN) != 0);
v = ath5k_hw_reg_read(ah, AR5K_PHY_ANT_SWITCH_TABLE_0);
len += snprintf(buf + len, sizeof(buf) - len,
"\nAR5K_PHY_ANT_SWITCH_TABLE_0\t0x%08x\n", v);
v = ath5k_hw_reg_read(ah, AR5K_PHY_ANT_SWITCH_TABLE_1);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_PHY_ANT_SWITCH_TABLE_1\t0x%08x\n", v);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_antenna(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
unsigned int i;
char buf[20];
if (copy_from_user(buf, userbuf, min(count, sizeof(buf))))
return -EFAULT;
if (strncmp(buf, "diversity", 9) == 0) {
ath5k_hw_set_antenna_mode(ah, AR5K_ANTMODE_DEFAULT);
printk(KERN_INFO "ath5k debug: enable diversity\n");
} else if (strncmp(buf, "fixed-a", 7) == 0) {
ath5k_hw_set_antenna_mode(ah, AR5K_ANTMODE_FIXED_A);
printk(KERN_INFO "ath5k debugfs: fixed antenna A\n");
} else if (strncmp(buf, "fixed-b", 7) == 0) {
ath5k_hw_set_antenna_mode(ah, AR5K_ANTMODE_FIXED_B);
printk(KERN_INFO "ath5k debug: fixed antenna B\n");
} else if (strncmp(buf, "clear", 5) == 0) {
for (i = 0; i < ARRAY_SIZE(ah->stats.antenna_rx); i++) {
ah->stats.antenna_rx[i] = 0;
ah->stats.antenna_tx[i] = 0;
}
printk(KERN_INFO "ath5k debug: cleared antenna stats\n");
}
return count;
}
static const struct file_operations fops_antenna = {
.read = read_file_antenna,
.write = write_file_antenna,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
/* debugfs: misc */
static ssize_t read_file_misc(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[700];
unsigned int len = 0;
u32 filt = ath5k_hw_get_rx_filter(ah);
len += snprintf(buf + len, sizeof(buf) - len, "bssid-mask: %pM\n",
ah->bssidmask);
len += snprintf(buf + len, sizeof(buf) - len, "filter-flags: 0x%x ",
filt);
if (filt & AR5K_RX_FILTER_UCAST)
len += snprintf(buf + len, sizeof(buf) - len, " UCAST");
if (filt & AR5K_RX_FILTER_MCAST)
len += snprintf(buf + len, sizeof(buf) - len, " MCAST");
if (filt & AR5K_RX_FILTER_BCAST)
len += snprintf(buf + len, sizeof(buf) - len, " BCAST");
if (filt & AR5K_RX_FILTER_CONTROL)
len += snprintf(buf + len, sizeof(buf) - len, " CONTROL");
if (filt & AR5K_RX_FILTER_BEACON)
len += snprintf(buf + len, sizeof(buf) - len, " BEACON");
if (filt & AR5K_RX_FILTER_PROM)
len += snprintf(buf + len, sizeof(buf) - len, " PROM");
if (filt & AR5K_RX_FILTER_XRPOLL)
len += snprintf(buf + len, sizeof(buf) - len, " XRPOLL");
if (filt & AR5K_RX_FILTER_PROBEREQ)
len += snprintf(buf + len, sizeof(buf) - len, " PROBEREQ");
if (filt & AR5K_RX_FILTER_PHYERR_5212)
len += snprintf(buf + len, sizeof(buf) - len, " PHYERR-5212");
if (filt & AR5K_RX_FILTER_RADARERR_5212)
len += snprintf(buf + len, sizeof(buf) - len, " RADARERR-5212");
if (filt & AR5K_RX_FILTER_PHYERR_5211)
snprintf(buf + len, sizeof(buf) - len, " PHYERR-5211");
if (filt & AR5K_RX_FILTER_RADARERR_5211)
len += snprintf(buf + len, sizeof(buf) - len, " RADARERR-5211");
len += snprintf(buf + len, sizeof(buf) - len, "\nopmode: %s (%d)\n",
ath_opmode_to_string(ah->opmode), ah->opmode);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_misc = {
.read = read_file_misc,
.open = simple_open,
.owner = THIS_MODULE,
};
/* debugfs: frameerrors */
static ssize_t read_file_frameerrors(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
struct ath5k_statistics *st = &ah->stats;
char buf[700];
unsigned int len = 0;
int i;
len += snprintf(buf + len, sizeof(buf) - len,
"RX\n---------------------\n");
len += snprintf(buf + len, sizeof(buf) - len, "CRC\t%u\t(%u%%)\n",
st->rxerr_crc,
st->rx_all_count > 0 ?
st->rxerr_crc * 100 / st->rx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "PHY\t%u\t(%u%%)\n",
st->rxerr_phy,
st->rx_all_count > 0 ?
st->rxerr_phy * 100 / st->rx_all_count : 0);
for (i = 0; i < 32; i++) {
if (st->rxerr_phy_code[i])
len += snprintf(buf + len, sizeof(buf) - len,
" phy_err[%u]\t%u\n",
i, st->rxerr_phy_code[i]);
}
len += snprintf(buf + len, sizeof(buf) - len, "FIFO\t%u\t(%u%%)\n",
st->rxerr_fifo,
st->rx_all_count > 0 ?
st->rxerr_fifo * 100 / st->rx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "decrypt\t%u\t(%u%%)\n",
st->rxerr_decrypt,
st->rx_all_count > 0 ?
st->rxerr_decrypt * 100 / st->rx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "MIC\t%u\t(%u%%)\n",
st->rxerr_mic,
st->rx_all_count > 0 ?
st->rxerr_mic * 100 / st->rx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "process\t%u\t(%u%%)\n",
st->rxerr_proc,
st->rx_all_count > 0 ?
st->rxerr_proc * 100 / st->rx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "jumbo\t%u\t(%u%%)\n",
st->rxerr_jumbo,
st->rx_all_count > 0 ?
st->rxerr_jumbo * 100 / st->rx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "[RX all\t%u]\n",
st->rx_all_count);
len += snprintf(buf + len, sizeof(buf) - len, "RX-all-bytes\t%u\n",
st->rx_bytes_count);
len += snprintf(buf + len, sizeof(buf) - len,
"\nTX\n---------------------\n");
len += snprintf(buf + len, sizeof(buf) - len, "retry\t%u\t(%u%%)\n",
st->txerr_retry,
st->tx_all_count > 0 ?
st->txerr_retry * 100 / st->tx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "FIFO\t%u\t(%u%%)\n",
st->txerr_fifo,
st->tx_all_count > 0 ?
st->txerr_fifo * 100 / st->tx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "filter\t%u\t(%u%%)\n",
st->txerr_filt,
st->tx_all_count > 0 ?
st->txerr_filt * 100 / st->tx_all_count : 0);
len += snprintf(buf + len, sizeof(buf) - len, "[TX all\t%u]\n",
st->tx_all_count);
len += snprintf(buf + len, sizeof(buf) - len, "TX-all-bytes\t%u\n",
st->tx_bytes_count);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_frameerrors(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
struct ath5k_statistics *st = &ah->stats;
char buf[20];
if (copy_from_user(buf, userbuf, min(count, sizeof(buf))))
return -EFAULT;
if (strncmp(buf, "clear", 5) == 0) {
st->rxerr_crc = 0;
st->rxerr_phy = 0;
st->rxerr_fifo = 0;
st->rxerr_decrypt = 0;
st->rxerr_mic = 0;
st->rxerr_proc = 0;
st->rxerr_jumbo = 0;
st->rx_all_count = 0;
st->txerr_retry = 0;
st->txerr_fifo = 0;
st->txerr_filt = 0;
st->tx_all_count = 0;
printk(KERN_INFO "ath5k debug: cleared frameerrors stats\n");
}
return count;
}
static const struct file_operations fops_frameerrors = {
.read = read_file_frameerrors,
.write = write_file_frameerrors,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
/* debugfs: ani */
static ssize_t read_file_ani(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
struct ath5k_statistics *st = &ah->stats;
struct ath5k_ani_state *as = &ah->ani_state;
char buf[700];
unsigned int len = 0;
len += snprintf(buf + len, sizeof(buf) - len,
"HW has PHY error counters:\t%s\n",
ah->ah_capabilities.cap_has_phyerr_counters ?
"yes" : "no");
len += snprintf(buf + len, sizeof(buf) - len,
"HW max spur immunity level:\t%d\n",
as->max_spur_level);
len += snprintf(buf + len, sizeof(buf) - len,
"\nANI state\n--------------------------------------------\n");
len += snprintf(buf + len, sizeof(buf) - len, "operating mode:\t\t\t");
switch (as->ani_mode) {
case ATH5K_ANI_MODE_OFF:
len += snprintf(buf + len, sizeof(buf) - len, "OFF\n");
break;
case ATH5K_ANI_MODE_MANUAL_LOW:
len += snprintf(buf + len, sizeof(buf) - len,
"MANUAL LOW\n");
break;
case ATH5K_ANI_MODE_MANUAL_HIGH:
len += snprintf(buf + len, sizeof(buf) - len,
"MANUAL HIGH\n");
break;
case ATH5K_ANI_MODE_AUTO:
len += snprintf(buf + len, sizeof(buf) - len, "AUTO\n");
break;
default:
len += snprintf(buf + len, sizeof(buf) - len,
"??? (not good)\n");
break;
}
len += snprintf(buf + len, sizeof(buf) - len,
"noise immunity level:\t\t%d\n",
as->noise_imm_level);
len += snprintf(buf + len, sizeof(buf) - len,
"spur immunity level:\t\t%d\n",
as->spur_level);
len += snprintf(buf + len, sizeof(buf) - len,
"firstep level:\t\t\t%d\n",
as->firstep_level);
len += snprintf(buf + len, sizeof(buf) - len,
"OFDM weak signal detection:\t%s\n",
as->ofdm_weak_sig ? "on" : "off");
len += snprintf(buf + len, sizeof(buf) - len,
"CCK weak signal detection:\t%s\n",
as->cck_weak_sig ? "on" : "off");
len += snprintf(buf + len, sizeof(buf) - len,
"\nMIB INTERRUPTS:\t\t%u\n",
st->mib_intr);
len += snprintf(buf + len, sizeof(buf) - len,
"beacon RSSI average:\t%d\n",
(int)ewma_read(&ah->ah_beacon_rssi_avg));
#define CC_PRINT(_struct, _field) \
_struct._field, \
_struct.cycles > 0 ? \
_struct._field * 100 / _struct.cycles : 0
len += snprintf(buf + len, sizeof(buf) - len,
"profcnt tx\t\t%u\t(%d%%)\n",
CC_PRINT(as->last_cc, tx_frame));
len += snprintf(buf + len, sizeof(buf) - len,
"profcnt rx\t\t%u\t(%d%%)\n",
CC_PRINT(as->last_cc, rx_frame));
len += snprintf(buf + len, sizeof(buf) - len,
"profcnt busy\t\t%u\t(%d%%)\n",
CC_PRINT(as->last_cc, rx_busy));
#undef CC_PRINT
len += snprintf(buf + len, sizeof(buf) - len, "profcnt cycles\t\t%u\n",
as->last_cc.cycles);
len += snprintf(buf + len, sizeof(buf) - len,
"listen time\t\t%d\tlast: %d\n",
as->listen_time, as->last_listen);
len += snprintf(buf + len, sizeof(buf) - len,
"OFDM errors\t\t%u\tlast: %u\tsum: %u\n",
as->ofdm_errors, as->last_ofdm_errors,
as->sum_ofdm_errors);
len += snprintf(buf + len, sizeof(buf) - len,
"CCK errors\t\t%u\tlast: %u\tsum: %u\n",
as->cck_errors, as->last_cck_errors,
as->sum_cck_errors);
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_PHYERR_CNT1\t%x\t(=%d)\n",
ath5k_hw_reg_read(ah, AR5K_PHYERR_CNT1),
ATH5K_ANI_OFDM_TRIG_HIGH - (ATH5K_PHYERR_CNT_MAX -
ath5k_hw_reg_read(ah, AR5K_PHYERR_CNT1)));
len += snprintf(buf + len, sizeof(buf) - len,
"AR5K_PHYERR_CNT2\t%x\t(=%d)\n",
ath5k_hw_reg_read(ah, AR5K_PHYERR_CNT2),
ATH5K_ANI_CCK_TRIG_HIGH - (ATH5K_PHYERR_CNT_MAX -
ath5k_hw_reg_read(ah, AR5K_PHYERR_CNT2)));
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_ani(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[20];
if (copy_from_user(buf, userbuf, min(count, sizeof(buf))))
return -EFAULT;
if (strncmp(buf, "sens-low", 8) == 0) {
ath5k_ani_init(ah, ATH5K_ANI_MODE_MANUAL_HIGH);
} else if (strncmp(buf, "sens-high", 9) == 0) {
ath5k_ani_init(ah, ATH5K_ANI_MODE_MANUAL_LOW);
} else if (strncmp(buf, "ani-off", 7) == 0) {
ath5k_ani_init(ah, ATH5K_ANI_MODE_OFF);
} else if (strncmp(buf, "ani-on", 6) == 0) {
ath5k_ani_init(ah, ATH5K_ANI_MODE_AUTO);
} else if (strncmp(buf, "noise-low", 9) == 0) {
ath5k_ani_set_noise_immunity_level(ah, 0);
} else if (strncmp(buf, "noise-high", 10) == 0) {
ath5k_ani_set_noise_immunity_level(ah,
ATH5K_ANI_MAX_NOISE_IMM_LVL);
} else if (strncmp(buf, "spur-low", 8) == 0) {
ath5k_ani_set_spur_immunity_level(ah, 0);
} else if (strncmp(buf, "spur-high", 9) == 0) {
ath5k_ani_set_spur_immunity_level(ah,
ah->ani_state.max_spur_level);
} else if (strncmp(buf, "fir-low", 7) == 0) {
ath5k_ani_set_firstep_level(ah, 0);
} else if (strncmp(buf, "fir-high", 8) == 0) {
ath5k_ani_set_firstep_level(ah, ATH5K_ANI_MAX_FIRSTEP_LVL);
} else if (strncmp(buf, "ofdm-off", 8) == 0) {
ath5k_ani_set_ofdm_weak_signal_detection(ah, false);
} else if (strncmp(buf, "ofdm-on", 7) == 0) {
ath5k_ani_set_ofdm_weak_signal_detection(ah, true);
} else if (strncmp(buf, "cck-off", 7) == 0) {
ath5k_ani_set_cck_weak_signal_detection(ah, false);
} else if (strncmp(buf, "cck-on", 6) == 0) {
ath5k_ani_set_cck_weak_signal_detection(ah, true);
}
return count;
}
static const struct file_operations fops_ani = {
.read = read_file_ani,
.write = write_file_ani,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
/* debugfs: queues etc */
static ssize_t read_file_queue(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[700];
unsigned int len = 0;
struct ath5k_txq *txq;
struct ath5k_buf *bf, *bf0;
int i, n;
len += snprintf(buf + len, sizeof(buf) - len,
"available txbuffers: %d\n", ah->txbuf_len);
for (i = 0; i < ARRAY_SIZE(ah->txqs); i++) {
txq = &ah->txqs[i];
len += snprintf(buf + len, sizeof(buf) - len,
"%02d: %ssetup\n", i, txq->setup ? "" : "not ");
if (!txq->setup)
continue;
n = 0;
spin_lock_bh(&txq->lock);
list_for_each_entry_safe(bf, bf0, &txq->q, list)
n++;
spin_unlock_bh(&txq->lock);
len += snprintf(buf + len, sizeof(buf) - len,
" len: %d bufs: %d\n", txq->txq_len, n);
len += snprintf(buf + len, sizeof(buf) - len,
" stuck: %d\n", txq->txq_stuck);
}
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_queue(struct file *file,
const char __user *userbuf,
size_t count, loff_t *ppos)
{
struct ath5k_hw *ah = file->private_data;
char buf[20];
if (copy_from_user(buf, userbuf, min(count, sizeof(buf))))
return -EFAULT;
if (strncmp(buf, "start", 5) == 0)
ieee80211_wake_queues(ah->hw);
else if (strncmp(buf, "stop", 4) == 0)
ieee80211_stop_queues(ah->hw);
return count;
}
static const struct file_operations fops_queue = {
.read = read_file_queue,
.write = write_file_queue,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
void
ath5k_debug_init_device(struct ath5k_hw *ah)
{
struct dentry *phydir;
ah->debug.level = ath5k_debug;
phydir = debugfs_create_dir("ath5k", ah->hw->wiphy->debugfsdir);
if (!phydir)
return;
debugfs_create_file("debug", S_IWUSR | S_IRUSR, phydir, ah,
&fops_debug);
debugfs_create_file("registers", S_IRUSR, phydir, ah, &fops_registers);
debugfs_create_file("beacon", S_IWUSR | S_IRUSR, phydir, ah,
&fops_beacon);
debugfs_create_file("reset", S_IWUSR, phydir, ah, &fops_reset);
debugfs_create_file("antenna", S_IWUSR | S_IRUSR, phydir, ah,
&fops_antenna);
debugfs_create_file("misc", S_IRUSR, phydir, ah, &fops_misc);
debugfs_create_file("frameerrors", S_IWUSR | S_IRUSR, phydir, ah,
&fops_frameerrors);
debugfs_create_file("ani", S_IWUSR | S_IRUSR, phydir, ah, &fops_ani);
debugfs_create_file("queue", S_IWUSR | S_IRUSR, phydir, ah,
&fops_queue);
debugfs_create_bool("32khz_clock", S_IWUSR | S_IRUSR, phydir,
&ah->ah_use_32khz_clock);
}
/* functions used in other places */
void
ath5k_debug_dump_bands(struct ath5k_hw *ah)
{
unsigned int b, i;
if (likely(!(ah->debug.level & ATH5K_DEBUG_DUMPBANDS)))
return;
BUG_ON(!ah->sbands);
for (b = 0; b < IEEE80211_NUM_BANDS; b++) {
struct ieee80211_supported_band *band = &ah->sbands[b];
char bname[6];
switch (band->band) {
case IEEE80211_BAND_2GHZ:
strcpy(bname, "2 GHz");
break;
case IEEE80211_BAND_5GHZ:
strcpy(bname, "5 GHz");
break;
default:
printk(KERN_DEBUG "Band not supported: %d\n",
band->band);
return;
}
printk(KERN_DEBUG "Band %s: channels %d, rates %d\n", bname,
band->n_channels, band->n_bitrates);
printk(KERN_DEBUG " channels:\n");
for (i = 0; i < band->n_channels; i++)
printk(KERN_DEBUG " %3d %d %.4x %.4x\n",
ieee80211_frequency_to_channel(
band->channels[i].center_freq),
band->channels[i].center_freq,
band->channels[i].hw_value,
band->channels[i].flags);
printk(KERN_DEBUG " rates:\n");
for (i = 0; i < band->n_bitrates; i++)
printk(KERN_DEBUG " %4d %.4x %.4x %.4x\n",
band->bitrates[i].bitrate,
band->bitrates[i].hw_value,
band->bitrates[i].flags,
band->bitrates[i].hw_value_short);
}
}
static inline void
ath5k_debug_printrxbuf(struct ath5k_buf *bf, int done,
struct ath5k_rx_status *rs)
{
struct ath5k_desc *ds = bf->desc;
struct ath5k_hw_all_rx_desc *rd = &ds->ud.ds_rx;
printk(KERN_DEBUG "R (%p %llx) %08x %08x %08x %08x %08x %08x %c\n",
ds, (unsigned long long)bf->daddr,
ds->ds_link, ds->ds_data,
rd->rx_ctl.rx_control_0, rd->rx_ctl.rx_control_1,
rd->rx_stat.rx_status_0, rd->rx_stat.rx_status_1,
!done ? ' ' : (rs->rs_status == 0) ? '*' : '!');
}
void
ath5k_debug_printrxbuffs(struct ath5k_hw *ah)
{
struct ath5k_desc *ds;
struct ath5k_buf *bf;
struct ath5k_rx_status rs = {};
int status;
if (likely(!(ah->debug.level & ATH5K_DEBUG_DESC)))
return;
printk(KERN_DEBUG "rxdp %x, rxlink %p\n",
ath5k_hw_get_rxdp(ah), ah->rxlink);
spin_lock_bh(&ah->rxbuflock);
list_for_each_entry(bf, &ah->rxbuf, list) {
ds = bf->desc;
status = ah->ah_proc_rx_desc(ah, ds, &rs);
if (!status)
ath5k_debug_printrxbuf(bf, status == 0, &rs);
}
spin_unlock_bh(&ah->rxbuflock);
}
void
ath5k_debug_printtxbuf(struct ath5k_hw *ah, struct ath5k_buf *bf)
{
struct ath5k_desc *ds = bf->desc;
struct ath5k_hw_5212_tx_desc *td = &ds->ud.ds_tx5212;
struct ath5k_tx_status ts = {};
int done;
if (likely(!(ah->debug.level & ATH5K_DEBUG_DESC)))
return;
done = ah->ah_proc_tx_desc(ah, bf->desc, &ts);
printk(KERN_DEBUG "T (%p %llx) %08x %08x %08x %08x %08x %08x %08x "
"%08x %c\n", ds, (unsigned long long)bf->daddr, ds->ds_link,
ds->ds_data, td->tx_ctl.tx_control_0, td->tx_ctl.tx_control_1,
td->tx_ctl.tx_control_2, td->tx_ctl.tx_control_3,
td->tx_stat.tx_status_0, td->tx_stat.tx_status_1,
done ? ' ' : (ts.ts_status == 0) ? '*' : '!');
}
| gpl-2.0 |
perillamint/Kite2 | sound/soc/samsung/smdk_wm8994.c | 4776 | 4736 | /*
* smdk_wm8994.c
*
* 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 "../codecs/wm8994.h"
#include <sound/pcm_params.h>
#include <linux/module.h>
/*
* Default CFG switch settings to use this driver:
* SMDKV310: CFG5-1000, CFG7-111111
*/
/*
* Configure audio route as :-
* $ amixer sset 'DAC1' on,on
* $ amixer sset 'Right Headphone Mux' 'DAC'
* $ amixer sset 'Left Headphone Mux' 'DAC'
* $ amixer sset 'DAC1R Mixer AIF1.1' on
* $ amixer sset 'DAC1L Mixer AIF1.1' on
* $ amixer sset 'IN2L' on
* $ amixer sset 'IN2L PGA IN2LN' on
* $ amixer sset 'MIXINL IN2L' on
* $ amixer sset 'AIF1ADC1L Mixer ADC/DMIC' on
* $ amixer sset 'IN2R' on
* $ amixer sset 'IN2R PGA IN2RN' on
* $ amixer sset 'MIXINR IN2R' on
* $ amixer sset 'AIF1ADC1R Mixer ADC/DMIC' on
*/
/* SMDK has a 16.934MHZ crystal attached to WM8994 */
#define SMDK_WM8994_FREQ 16934000
static int smdk_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
unsigned int pll_out;
int ret;
/* AIF1CLK should be >=3MHz for optimal performance */
if (params_format(params) == SNDRV_PCM_FORMAT_S24_LE)
pll_out = params_rate(params) * 384;
else if (params_rate(params) == 8000 || params_rate(params) == 11025)
pll_out = params_rate(params) * 512;
else
pll_out = params_rate(params) * 256;
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S
| SND_SOC_DAIFMT_NB_NF
| SND_SOC_DAIFMT_CBM_CFM);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S
| SND_SOC_DAIFMT_NB_NF
| SND_SOC_DAIFMT_CBM_CFM);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_pll(codec_dai, WM8994_FLL1, WM8994_FLL_SRC_MCLK1,
SMDK_WM8994_FREQ, pll_out);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_sysclk(codec_dai, WM8994_SYSCLK_FLL1,
pll_out, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
return 0;
}
/*
* SMDK WM8994 DAI operations.
*/
static struct snd_soc_ops smdk_ops = {
.hw_params = smdk_hw_params,
};
static int smdk_wm8994_init_paiftx(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
/* HeadPhone */
snd_soc_dapm_enable_pin(dapm, "HPOUT1R");
snd_soc_dapm_enable_pin(dapm, "HPOUT1L");
/* MicIn */
snd_soc_dapm_enable_pin(dapm, "IN1LN");
snd_soc_dapm_enable_pin(dapm, "IN1RN");
/* LineIn */
snd_soc_dapm_enable_pin(dapm, "IN2LN");
snd_soc_dapm_enable_pin(dapm, "IN2RN");
/* Other pins NC */
snd_soc_dapm_nc_pin(dapm, "HPOUT2P");
snd_soc_dapm_nc_pin(dapm, "HPOUT2N");
snd_soc_dapm_nc_pin(dapm, "SPKOUTLN");
snd_soc_dapm_nc_pin(dapm, "SPKOUTLP");
snd_soc_dapm_nc_pin(dapm, "SPKOUTRP");
snd_soc_dapm_nc_pin(dapm, "SPKOUTRN");
snd_soc_dapm_nc_pin(dapm, "LINEOUT1N");
snd_soc_dapm_nc_pin(dapm, "LINEOUT1P");
snd_soc_dapm_nc_pin(dapm, "LINEOUT2N");
snd_soc_dapm_nc_pin(dapm, "LINEOUT2P");
snd_soc_dapm_nc_pin(dapm, "IN1LP");
snd_soc_dapm_nc_pin(dapm, "IN2LP:VXRN");
snd_soc_dapm_nc_pin(dapm, "IN1RP");
snd_soc_dapm_nc_pin(dapm, "IN2RP:VXRP");
return 0;
}
static struct snd_soc_dai_link smdk_dai[] = {
{ /* Primary DAI i/f */
.name = "WM8994 AIF1",
.stream_name = "Pri_Dai",
.cpu_dai_name = "samsung-i2s.0",
.codec_dai_name = "wm8994-aif1",
.platform_name = "samsung-audio",
.codec_name = "wm8994-codec",
.init = smdk_wm8994_init_paiftx,
.ops = &smdk_ops,
}, { /* Sec_Fifo Playback i/f */
.name = "Sec_FIFO TX",
.stream_name = "Sec_Dai",
.cpu_dai_name = "samsung-i2s.4",
.codec_dai_name = "wm8994-aif1",
.platform_name = "samsung-audio",
.codec_name = "wm8994-codec",
.ops = &smdk_ops,
},
};
static struct snd_soc_card smdk = {
.name = "SMDK-I2S",
.owner = THIS_MODULE,
.dai_link = smdk_dai,
.num_links = ARRAY_SIZE(smdk_dai),
};
static struct platform_device *smdk_snd_device;
static int __init smdk_audio_init(void)
{
int ret;
smdk_snd_device = platform_device_alloc("soc-audio", -1);
if (!smdk_snd_device)
return -ENOMEM;
platform_set_drvdata(smdk_snd_device, &smdk);
ret = platform_device_add(smdk_snd_device);
if (ret)
platform_device_put(smdk_snd_device);
return ret;
}
module_init(smdk_audio_init);
static void __exit smdk_audio_exit(void)
{
platform_device_unregister(smdk_snd_device);
}
module_exit(smdk_audio_exit);
MODULE_DESCRIPTION("ALSA SoC SMDK WM8994");
MODULE_LICENSE("GPL");
| gpl-2.0 |
HealthyMarshmallow/android_kernel_lge_g2 | sound/soc/blackfin/bfin-eval-adav80x.c | 5032 | 4078 | /*
* Machine driver for EVAL-ADAV801 and EVAL-ADAV803 on Analog Devices bfin
* evaluation boards.
*
* Copyright 2011 Analog Devices Inc.
* Author: Lars-Peter Clausen <lars@metafoo.de>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include "../codecs/adav80x.h"
static const struct snd_soc_dapm_widget bfin_eval_adav80x_dapm_widgets[] = {
SND_SOC_DAPM_LINE("Line Out", NULL),
SND_SOC_DAPM_LINE("Line In", NULL),
};
static const struct snd_soc_dapm_route bfin_eval_adav80x_dapm_routes[] = {
{ "Line Out", NULL, "VOUTL" },
{ "Line Out", NULL, "VOUTR" },
{ "VINL", NULL, "Line In" },
{ "VINR", NULL, "Line In" },
};
static int bfin_eval_adav80x_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
int ret;
ret = snd_soc_dai_set_pll(codec_dai, ADAV80X_PLL1, ADAV80X_PLL_SRC_XTAL,
27000000, params_rate(params) * 256);
if (ret)
return ret;
ret = snd_soc_dai_set_sysclk(codec_dai, ADAV80X_CLK_PLL1,
params_rate(params) * 256, SND_SOC_CLOCK_IN);
return ret;
}
static int bfin_eval_adav80x_codec_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_dai *codec_dai = rtd->codec_dai;
snd_soc_dai_set_sysclk(codec_dai, ADAV80X_CLK_SYSCLK1, 0,
SND_SOC_CLOCK_OUT);
snd_soc_dai_set_sysclk(codec_dai, ADAV80X_CLK_SYSCLK2, 0,
SND_SOC_CLOCK_OUT);
snd_soc_dai_set_sysclk(codec_dai, ADAV80X_CLK_SYSCLK3, 0,
SND_SOC_CLOCK_OUT);
snd_soc_dai_set_sysclk(codec_dai, ADAV80X_CLK_XTAL, 2700000, 0);
return 0;
}
static struct snd_soc_ops bfin_eval_adav80x_ops = {
.hw_params = bfin_eval_adav80x_hw_params,
};
static struct snd_soc_dai_link bfin_eval_adav80x_dais[] = {
{
.name = "adav80x",
.stream_name = "ADAV80x HiFi",
.cpu_dai_name = "bfin-i2s.0",
.codec_dai_name = "adav80x-hifi",
.platform_name = "bfin-i2s-pcm-audio",
.init = bfin_eval_adav80x_codec_init,
.ops = &bfin_eval_adav80x_ops,
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM,
},
};
static struct snd_soc_card bfin_eval_adav80x = {
.name = "bfin-eval-adav80x",
.owner = THIS_MODULE,
.dai_link = bfin_eval_adav80x_dais,
.num_links = ARRAY_SIZE(bfin_eval_adav80x_dais),
.dapm_widgets = bfin_eval_adav80x_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(bfin_eval_adav80x_dapm_widgets),
.dapm_routes = bfin_eval_adav80x_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(bfin_eval_adav80x_dapm_routes),
};
enum bfin_eval_adav80x_type {
BFIN_EVAL_ADAV801,
BFIN_EVAL_ADAV803,
};
static int bfin_eval_adav80x_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &bfin_eval_adav80x;
const char *codec_name;
switch (platform_get_device_id(pdev)->driver_data) {
case BFIN_EVAL_ADAV801:
codec_name = "spi0.1";
break;
case BFIN_EVAL_ADAV803:
codec_name = "adav803.0-0034";
break;
default:
return -EINVAL;
}
bfin_eval_adav80x_dais[0].codec_name = codec_name;
card->dev = &pdev->dev;
return snd_soc_register_card(&bfin_eval_adav80x);
}
static int __devexit bfin_eval_adav80x_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
snd_soc_unregister_card(card);
return 0;
}
static const struct platform_device_id bfin_eval_adav80x_ids[] = {
{ "bfin-eval-adav801", BFIN_EVAL_ADAV801 },
{ "bfin-eval-adav803", BFIN_EVAL_ADAV803 },
{ },
};
MODULE_DEVICE_TABLE(platform, bfin_eval_adav80x_ids);
static struct platform_driver bfin_eval_adav80x_driver = {
.driver = {
.name = "bfin-eval-adav80x",
.owner = THIS_MODULE,
.pm = &snd_soc_pm_ops,
},
.probe = bfin_eval_adav80x_probe,
.remove = __devexit_p(bfin_eval_adav80x_remove),
.id_table = bfin_eval_adav80x_ids,
};
module_platform_driver(bfin_eval_adav80x_driver);
MODULE_AUTHOR("Lars-Peter Clausen <lars@metafoo.de>");
MODULE_DESCRIPTION("ALSA SoC bfin adav80x driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
spegelius/android_kernel_samsung_jf | arch/arm/plat-s3c24xx/cpu-freq-debugfs.c | 5288 | 4669 | /* linux/arch/arm/plat-s3c24xx/cpu-freq-debugfs.c
*
* Copyright (c) 2009 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C24XX CPU Frequency scaling - debugfs status support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/cpufreq.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/err.h>
#include <plat/cpu-freq-core.h>
static struct dentry *dbgfs_root;
static struct dentry *dbgfs_file_io;
static struct dentry *dbgfs_file_info;
static struct dentry *dbgfs_file_board;
#define print_ns(x) ((x) / 10), ((x) % 10)
static void show_max(struct seq_file *seq, struct s3c_freq *f)
{
seq_printf(seq, "MAX: F=%lu, H=%lu, P=%lu, A=%lu\n",
f->fclk, f->hclk, f->pclk, f->armclk);
}
static int board_show(struct seq_file *seq, void *p)
{
struct s3c_cpufreq_config *cfg;
struct s3c_cpufreq_board *brd;
cfg = s3c_cpufreq_getconfig();
if (!cfg) {
seq_printf(seq, "no configuration registered\n");
return 0;
}
brd = cfg->board;
if (!brd) {
seq_printf(seq, "no board definition set?\n");
return 0;
}
seq_printf(seq, "SDRAM refresh %u ns\n", brd->refresh);
seq_printf(seq, "auto_io=%u\n", brd->auto_io);
seq_printf(seq, "need_io=%u\n", brd->need_io);
show_max(seq, &brd->max);
return 0;
}
static int fops_board_open(struct inode *inode, struct file *file)
{
return single_open(file, board_show, NULL);
}
static const struct file_operations fops_board = {
.open = fops_board_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int info_show(struct seq_file *seq, void *p)
{
struct s3c_cpufreq_config *cfg;
cfg = s3c_cpufreq_getconfig();
if (!cfg) {
seq_printf(seq, "no configuration registered\n");
return 0;
}
seq_printf(seq, " FCLK %ld Hz\n", cfg->freq.fclk);
seq_printf(seq, " HCLK %ld Hz (%lu.%lu ns)\n",
cfg->freq.hclk, print_ns(cfg->freq.hclk_tns));
seq_printf(seq, " PCLK %ld Hz\n", cfg->freq.hclk);
seq_printf(seq, "ARMCLK %ld Hz\n", cfg->freq.armclk);
seq_printf(seq, "\n");
show_max(seq, &cfg->max);
seq_printf(seq, "Divisors: P=%d, H=%d, A=%d, dvs=%s\n",
cfg->divs.h_divisor, cfg->divs.p_divisor,
cfg->divs.arm_divisor, cfg->divs.dvs ? "on" : "off");
seq_printf(seq, "\n");
seq_printf(seq, "lock_pll=%u\n", cfg->lock_pll);
return 0;
}
static int fops_info_open(struct inode *inode, struct file *file)
{
return single_open(file, info_show, NULL);
}
static const struct file_operations fops_info = {
.open = fops_info_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int io_show(struct seq_file *seq, void *p)
{
void (*show_bank)(struct seq_file *, struct s3c_cpufreq_config *, union s3c_iobank *);
struct s3c_cpufreq_config *cfg;
struct s3c_iotimings *iot;
union s3c_iobank *iob;
int bank;
cfg = s3c_cpufreq_getconfig();
if (!cfg) {
seq_printf(seq, "no configuration registered\n");
return 0;
}
show_bank = cfg->info->debug_io_show;
if (!show_bank) {
seq_printf(seq, "no code to show bank timing\n");
return 0;
}
iot = s3c_cpufreq_getiotimings();
if (!iot) {
seq_printf(seq, "no io timings registered\n");
return 0;
}
seq_printf(seq, "hclk period is %lu.%lu ns\n", print_ns(cfg->freq.hclk_tns));
for (bank = 0; bank < MAX_BANKS; bank++) {
iob = &iot->bank[bank];
seq_printf(seq, "bank %d: ", bank);
if (!iob->io_2410) {
seq_printf(seq, "nothing set\n");
continue;
}
show_bank(seq, cfg, iob);
}
return 0;
}
static int fops_io_open(struct inode *inode, struct file *file)
{
return single_open(file, io_show, NULL);
}
static const struct file_operations fops_io = {
.open = fops_io_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int __init s3c_freq_debugfs_init(void)
{
dbgfs_root = debugfs_create_dir("s3c-cpufreq", NULL);
if (IS_ERR(dbgfs_root)) {
printk(KERN_ERR "%s: error creating debugfs root\n", __func__);
return PTR_ERR(dbgfs_root);
}
dbgfs_file_io = debugfs_create_file("io-timing", S_IRUGO, dbgfs_root,
NULL, &fops_io);
dbgfs_file_info = debugfs_create_file("info", S_IRUGO, dbgfs_root,
NULL, &fops_info);
dbgfs_file_board = debugfs_create_file("board", S_IRUGO, dbgfs_root,
NULL, &fops_board);
return 0;
}
late_initcall(s3c_freq_debugfs_init);
| gpl-2.0 |
boa19861105/android_443_KitKat_kernel_htc_dlxpul | drivers/media/dvb/dvb-usb/dvb-usb-remote.c | 10920 | 10929 | /* dvb-usb-remote.c is part of the DVB USB library.
*
* Copyright (C) 2004-6 Patrick Boettcher (patrick.boettcher@desy.de)
* see dvb-usb-init.c for copyright information.
*
* This file contains functions for initializing the input-device and for handling remote-control-queries.
*/
#include "dvb-usb-common.h"
#include <linux/usb/input.h>
static unsigned int
legacy_dvb_usb_get_keymap_index(const struct input_keymap_entry *ke,
struct rc_map_table *keymap,
unsigned int keymap_size)
{
unsigned int index;
unsigned int scancode;
if (ke->flags & INPUT_KEYMAP_BY_INDEX) {
index = ke->index;
} else {
if (input_scancode_to_scalar(ke, &scancode))
return keymap_size;
/* See if we can match the raw key code. */
for (index = 0; index < keymap_size; index++)
if (keymap[index].scancode == scancode)
break;
/* See if there is an unused hole in the map */
if (index >= keymap_size) {
for (index = 0; index < keymap_size; index++) {
if (keymap[index].keycode == KEY_RESERVED ||
keymap[index].keycode == KEY_UNKNOWN) {
break;
}
}
}
}
return index;
}
static int legacy_dvb_usb_getkeycode(struct input_dev *dev,
struct input_keymap_entry *ke)
{
struct dvb_usb_device *d = input_get_drvdata(dev);
struct rc_map_table *keymap = d->props.rc.legacy.rc_map_table;
unsigned int keymap_size = d->props.rc.legacy.rc_map_size;
unsigned int index;
index = legacy_dvb_usb_get_keymap_index(ke, keymap, keymap_size);
if (index >= keymap_size)
return -EINVAL;
ke->keycode = keymap[index].keycode;
if (ke->keycode == KEY_UNKNOWN)
ke->keycode = KEY_RESERVED;
ke->len = sizeof(keymap[index].scancode);
memcpy(&ke->scancode, &keymap[index].scancode, ke->len);
ke->index = index;
return 0;
}
static int legacy_dvb_usb_setkeycode(struct input_dev *dev,
const struct input_keymap_entry *ke,
unsigned int *old_keycode)
{
struct dvb_usb_device *d = input_get_drvdata(dev);
struct rc_map_table *keymap = d->props.rc.legacy.rc_map_table;
unsigned int keymap_size = d->props.rc.legacy.rc_map_size;
unsigned int index;
index = legacy_dvb_usb_get_keymap_index(ke, keymap, keymap_size);
/*
* FIXME: Currently, it is not possible to increase the size of
* scancode table. For it to happen, one possibility
* would be to allocate a table with key_map_size + 1,
* copying data, appending the new key on it, and freeing
* the old one - or maybe just allocating some spare space
*/
if (index >= keymap_size)
return -EINVAL;
*old_keycode = keymap[index].keycode;
keymap->keycode = ke->keycode;
__set_bit(ke->keycode, dev->keybit);
if (*old_keycode != KEY_RESERVED) {
__clear_bit(*old_keycode, dev->keybit);
for (index = 0; index < keymap_size; index++) {
if (keymap[index].keycode == *old_keycode) {
__set_bit(*old_keycode, dev->keybit);
break;
}
}
}
return 0;
}
/* Remote-control poll function - called every dib->rc_query_interval ms to see
* whether the remote control has received anything.
*
* TODO: Fix the repeat rate of the input device.
*/
static void legacy_dvb_usb_read_remote_control(struct work_struct *work)
{
struct dvb_usb_device *d =
container_of(work, struct dvb_usb_device, rc_query_work.work);
u32 event;
int state;
/* TODO: need a lock here. We can simply skip checking for the remote control
if we're busy. */
/* when the parameter has been set to 1 via sysfs while the driver was running */
if (dvb_usb_disable_rc_polling)
return;
if (d->props.rc.legacy.rc_query(d,&event,&state)) {
err("error while querying for an remote control event.");
goto schedule;
}
switch (state) {
case REMOTE_NO_KEY_PRESSED:
break;
case REMOTE_KEY_PRESSED:
deb_rc("key pressed\n");
d->last_event = event;
case REMOTE_KEY_REPEAT:
deb_rc("key repeated\n");
input_event(d->input_dev, EV_KEY, event, 1);
input_sync(d->input_dev);
input_event(d->input_dev, EV_KEY, d->last_event, 0);
input_sync(d->input_dev);
break;
default:
break;
}
/* improved repeat handling ???
switch (state) {
case REMOTE_NO_KEY_PRESSED:
deb_rc("NO KEY PRESSED\n");
if (d->last_state != REMOTE_NO_KEY_PRESSED) {
deb_rc("releasing event %d\n",d->last_event);
input_event(d->rc_input_dev, EV_KEY, d->last_event, 0);
input_sync(d->rc_input_dev);
}
d->last_state = REMOTE_NO_KEY_PRESSED;
d->last_event = 0;
break;
case REMOTE_KEY_PRESSED:
deb_rc("KEY PRESSED\n");
deb_rc("pressing event %d\n",event);
input_event(d->rc_input_dev, EV_KEY, event, 1);
input_sync(d->rc_input_dev);
d->last_event = event;
d->last_state = REMOTE_KEY_PRESSED;
break;
case REMOTE_KEY_REPEAT:
deb_rc("KEY_REPEAT\n");
if (d->last_state != REMOTE_NO_KEY_PRESSED) {
deb_rc("repeating event %d\n",d->last_event);
input_event(d->rc_input_dev, EV_KEY, d->last_event, 2);
input_sync(d->rc_input_dev);
d->last_state = REMOTE_KEY_REPEAT;
}
default:
break;
}
*/
schedule:
schedule_delayed_work(&d->rc_query_work,msecs_to_jiffies(d->props.rc.legacy.rc_interval));
}
static int legacy_dvb_usb_remote_init(struct dvb_usb_device *d)
{
int i, err, rc_interval;
struct input_dev *input_dev;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->evbit[0] = BIT_MASK(EV_KEY);
input_dev->name = "IR-receiver inside an USB DVB receiver";
input_dev->phys = d->rc_phys;
usb_to_input_id(d->udev, &input_dev->id);
input_dev->dev.parent = &d->udev->dev;
d->input_dev = input_dev;
d->rc_dev = NULL;
input_dev->getkeycode = legacy_dvb_usb_getkeycode;
input_dev->setkeycode = legacy_dvb_usb_setkeycode;
/* set the bits for the keys */
deb_rc("key map size: %d\n", d->props.rc.legacy.rc_map_size);
for (i = 0; i < d->props.rc.legacy.rc_map_size; i++) {
deb_rc("setting bit for event %d item %d\n",
d->props.rc.legacy.rc_map_table[i].keycode, i);
set_bit(d->props.rc.legacy.rc_map_table[i].keycode, input_dev->keybit);
}
/* setting these two values to non-zero, we have to manage key repeats */
input_dev->rep[REP_PERIOD] = d->props.rc.legacy.rc_interval;
input_dev->rep[REP_DELAY] = d->props.rc.legacy.rc_interval + 150;
input_set_drvdata(input_dev, d);
err = input_register_device(input_dev);
if (err)
input_free_device(input_dev);
rc_interval = d->props.rc.legacy.rc_interval;
INIT_DELAYED_WORK(&d->rc_query_work, legacy_dvb_usb_read_remote_control);
info("schedule remote query interval to %d msecs.", rc_interval);
schedule_delayed_work(&d->rc_query_work,
msecs_to_jiffies(rc_interval));
d->state |= DVB_USB_STATE_REMOTE;
return err;
}
/* Remote-control poll function - called every dib->rc_query_interval ms to see
* whether the remote control has received anything.
*
* TODO: Fix the repeat rate of the input device.
*/
static void dvb_usb_read_remote_control(struct work_struct *work)
{
struct dvb_usb_device *d =
container_of(work, struct dvb_usb_device, rc_query_work.work);
int err;
/* TODO: need a lock here. We can simply skip checking for the remote control
if we're busy. */
/* when the parameter has been set to 1 via sysfs while the
* driver was running, or when bulk mode is enabled after IR init
*/
if (dvb_usb_disable_rc_polling || d->props.rc.core.bulk_mode)
return;
err = d->props.rc.core.rc_query(d);
if (err)
err("error %d while querying for an remote control event.", err);
schedule_delayed_work(&d->rc_query_work,
msecs_to_jiffies(d->props.rc.core.rc_interval));
}
static int rc_core_dvb_usb_remote_init(struct dvb_usb_device *d)
{
int err, rc_interval;
struct rc_dev *dev;
dev = rc_allocate_device();
if (!dev)
return -ENOMEM;
dev->driver_name = d->props.rc.core.module_name;
dev->map_name = d->props.rc.core.rc_codes;
dev->change_protocol = d->props.rc.core.change_protocol;
dev->allowed_protos = d->props.rc.core.allowed_protos;
dev->driver_type = d->props.rc.core.driver_type;
usb_to_input_id(d->udev, &dev->input_id);
dev->input_name = "IR-receiver inside an USB DVB receiver";
dev->input_phys = d->rc_phys;
dev->dev.parent = &d->udev->dev;
dev->priv = d;
err = rc_register_device(dev);
if (err < 0) {
rc_free_device(dev);
return err;
}
d->input_dev = NULL;
d->rc_dev = dev;
if (!d->props.rc.core.rc_query || d->props.rc.core.bulk_mode)
return 0;
/* Polling mode - initialize a work queue for handling it */
INIT_DELAYED_WORK(&d->rc_query_work, dvb_usb_read_remote_control);
rc_interval = d->props.rc.core.rc_interval;
info("schedule remote query interval to %d msecs.", rc_interval);
schedule_delayed_work(&d->rc_query_work,
msecs_to_jiffies(rc_interval));
return 0;
}
int dvb_usb_remote_init(struct dvb_usb_device *d)
{
int err;
if (dvb_usb_disable_rc_polling)
return 0;
if (d->props.rc.legacy.rc_map_table && d->props.rc.legacy.rc_query)
d->props.rc.mode = DVB_RC_LEGACY;
else if (d->props.rc.core.rc_codes)
d->props.rc.mode = DVB_RC_CORE;
else
return 0;
usb_make_path(d->udev, d->rc_phys, sizeof(d->rc_phys));
strlcat(d->rc_phys, "/ir0", sizeof(d->rc_phys));
/* Start the remote-control polling. */
if (d->props.rc.legacy.rc_interval < 40)
d->props.rc.legacy.rc_interval = 100; /* default */
if (d->props.rc.mode == DVB_RC_LEGACY)
err = legacy_dvb_usb_remote_init(d);
else
err = rc_core_dvb_usb_remote_init(d);
if (err)
return err;
d->state |= DVB_USB_STATE_REMOTE;
return 0;
}
int dvb_usb_remote_exit(struct dvb_usb_device *d)
{
if (d->state & DVB_USB_STATE_REMOTE) {
cancel_delayed_work_sync(&d->rc_query_work);
if (d->props.rc.mode == DVB_RC_LEGACY)
input_unregister_device(d->input_dev);
else
rc_unregister_device(d->rc_dev);
}
d->state &= ~DVB_USB_STATE_REMOTE;
return 0;
}
#define DVB_USB_RC_NEC_EMPTY 0x00
#define DVB_USB_RC_NEC_KEY_PRESSED 0x01
#define DVB_USB_RC_NEC_KEY_REPEATED 0x02
int dvb_usb_nec_rc_key_to_event(struct dvb_usb_device *d,
u8 keybuf[5], u32 *event, int *state)
{
int i;
struct rc_map_table *keymap = d->props.rc.legacy.rc_map_table;
*event = 0;
*state = REMOTE_NO_KEY_PRESSED;
switch (keybuf[0]) {
case DVB_USB_RC_NEC_EMPTY:
break;
case DVB_USB_RC_NEC_KEY_PRESSED:
if ((u8) ~keybuf[1] != keybuf[2] ||
(u8) ~keybuf[3] != keybuf[4]) {
deb_err("remote control checksum failed.\n");
break;
}
/* See if we can match the raw key code. */
for (i = 0; i < d->props.rc.legacy.rc_map_size; i++)
if (rc5_custom(&keymap[i]) == keybuf[1] &&
rc5_data(&keymap[i]) == keybuf[3]) {
*event = keymap[i].keycode;
*state = REMOTE_KEY_PRESSED;
return 0;
}
deb_err("key mapping failed - no appropriate key found in keymapping\n");
break;
case DVB_USB_RC_NEC_KEY_REPEATED:
*state = REMOTE_KEY_REPEAT;
break;
default:
deb_err("unknown type of remote status: %d\n",keybuf[0]);
break;
}
return 0;
}
EXPORT_SYMBOL(dvb_usb_nec_rc_key_to_event);
| gpl-2.0 |
Team-Blackout/mecha-3.0.xx | arch/powerpc/math-emu/fmadds.c | 13736 | 1131 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
#include <math-emu/single.h>
int
fmadds(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_DS(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
poondog/M8 | arch/powerpc/math-emu/fnmadds.c | 13736 | 1169 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
#include <math-emu/single.h>
int
fnmadds(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
if (R_c != FP_CLS_NAN)
R_s ^= 1;
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_DS(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
goodhanrry/n9200_goodhanrry_kernel | drivers/media/platform/exynos/fimg2d/fimg2d_cache.c | 169 | 5349 | /* linux/drivers/media/video/exynos/fimg2d/fimg2d_cache.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Samsung Graphics 2D 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/sched.h>
#include <linux/dma-mapping.h>
#include <asm/pgtable.h>
#include <asm/cacheflush.h>
#include "fimg2d.h"
#include "fimg2d_cache.h"
#define LV1_SHIFT 20
#define LV1_PT_SIZE SZ_1M
#define LV2_PT_SIZE SZ_1K
#define LV2_BASE_MASK 0x3ff
#define LV2_PT_MASK 0xff000
#define LV2_SHIFT 12
#define LV1_DESC_MASK 0x3
#define LV2_DESC_MASK 0x2
int fimg2d_fixup_user_fault(unsigned long address)
{
int ret;
pr_info("%s: fault @ %#lx while cache flush\n", __func__, address);
ret = fixup_user_fault(current, current->mm, address, 0);
if (ret)
pr_info("%s: failed to fixup fault @ %#lx\n", __func__, address);
else
pr_info("%s: successed fixup fault @ %#lx\n", __func__, address);
return ret;
}
static inline unsigned long virt2phys(struct mm_struct *mm, unsigned long vaddr)
{
unsigned long *pgd;
unsigned long *lv1d, *lv2d;
pgd = (unsigned long *)mm->pgd;
lv1d = pgd + (vaddr >> LV1_SHIFT);
if ((*lv1d & LV1_DESC_MASK) != 0x1) {
fimg2d_debug("invalid LV1 descriptor, "
"pgd %p lv1d 0x%lx vaddr 0x%lx\n",
pgd, *lv1d, vaddr);
return 0;
}
lv2d = (unsigned long *)phys_to_virt(*lv1d & ~LV2_BASE_MASK) +
((vaddr & LV2_PT_MASK) >> LV2_SHIFT);
if ((*lv2d & LV2_DESC_MASK) != 0x2) {
fimg2d_debug("invalid LV2 descriptor, "
"pgd %p lv2d 0x%lx vaddr 0x%lx\n",
pgd, *lv2d, vaddr);
return 0;
}
return (*lv2d & PAGE_MASK) | (vaddr & (PAGE_SIZE-1));
}
#ifdef CONFIG_OUTER_CACHE
void fimg2d_dma_sync_outer(struct mm_struct *mm, unsigned long vaddr,
size_t size, enum cache_opr opr)
{
int len;
unsigned long cur, end, next, paddr;
cur = vaddr;
end = vaddr + size;
if (opr == CACHE_CLEAN) {
while (cur < end) {
next = (cur + PAGE_SIZE) & PAGE_MASK;
if (next > end)
next = end;
len = next - cur;
paddr = virt2phys(mm, cur);
if (paddr)
outer_clean_range(paddr, paddr + len);
cur += len;
}
} else if (opr == CACHE_FLUSH) {
while (cur < end) {
next = (cur + PAGE_SIZE) & PAGE_MASK;
if (next > end)
next = end;
len = next - cur;
paddr = virt2phys(mm, cur);
if (paddr)
outer_flush_range(paddr, paddr + len);
cur += len;
}
}
}
void fimg2d_clean_outer_pagetable(struct mm_struct *mm, unsigned long vaddr,
size_t size)
{
unsigned long *pgd;
unsigned long *lv1, *lv1end;
unsigned long lv2pa;
pgd = (unsigned long *)mm->pgd;
lv1 = pgd + (vaddr >> LV1_SHIFT);
lv1end = pgd + ((vaddr + size + LV1_PT_SIZE-1) >> LV1_SHIFT);
/* clean level1 page table */
outer_clean_range(virt_to_phys(lv1), virt_to_phys(lv1end));
do {
lv2pa = *lv1 & ~LV2_BASE_MASK; /* lv2 pt base */
/* clean level2 page table */
outer_clean_range(lv2pa, lv2pa + LV2_PT_SIZE);
lv1++;
} while (lv1 != lv1end);
}
#endif /* CONFIG_OUTER_CACHE */
enum pt_status fimg2d_check_pagetable(struct mm_struct *mm,
unsigned long vaddr, size_t size, int write)
{
#ifndef FIMG2D_IOVMM_PAGETABLE
unsigned long *pgd;
unsigned long *lv1d, *lv2d;
pgd = (unsigned long *)mm->pgd;
size += offset_in_page(vaddr);
size = PAGE_ALIGN(size);
while ((long)size > 0) {
unsigned long *lv2d_first;
unsigned long lv2d_base, lv2d_end;
lv1d = pgd + (vaddr >> LV1_SHIFT);
/*
* check level 1 descriptor
* lv1 desc[1:0] = 00 --> fault
* lv1 desc[1:0] = 01 --> page table
* lv1 desc[1:0] = 10 --> section or supersection
* lv1 desc[1:0] = 11 --> reserved
*/
if ((*lv1d & LV1_DESC_MASK) != 0x1) {
fimg2d_debug("invalid LV1 descriptor, "
"pgd %p lv1d 0x%lx vaddr 0x%lx\n",
pgd, *lv1d, vaddr);
return PT_FAULT;
}
dma_sync_single_for_device(NULL, virt_to_phys((void *) lv1d),
sizeof(lv1d), DMA_TO_DEVICE);
lv2d_base = (unsigned long)phys_to_virt(*lv1d & ~LV2_BASE_MASK);
lv2d_end = lv2d_base + LV2_PT_SIZE;
lv2d = (unsigned long *)lv2d_base +
(((vaddr & LV2_PT_MASK) >> LV2_SHIFT));
lv2d_first = lv2d;
do {
if (write && (!pte_present(*lv2d) ||
!pte_write(*lv2d))) {
struct vm_area_struct *vma;
vma = find_vma(mm, vaddr);
if (!vma) {
pr_err("%s: vma is null\n", __func__);
return PT_FAULT;
}
if (vma->vm_end < (vaddr + size)) {
pr_err("%s: vma overflow: %#lx--%#lx, "
"vaddr: %#lx, size: %zd\n",
__func__, vma->vm_start,
vma->vm_end, vaddr, size);
return PT_FAULT;
}
handle_mm_fault(mm, vma, vaddr,
FAULT_FLAG_WRITE);
}
/*
* check level 2 descriptor
* lv2 desc[1:0] = 00 --> fault
* lv2 desc[1:0] = 01 --> 64k pgae
* lv2 desc[1:0] = 1x --> 4k page
*/
if ((*lv2d & LV2_DESC_MASK) != 0x2) {
fimg2d_debug("invalid LV2 descriptor, "
"pgd %p lv2d 0x%lx "
"vaddr 0x%lx\n",
pgd, *lv2d, vaddr);
return PT_FAULT;
}
vaddr += PAGE_SIZE;
size -= PAGE_SIZE;
} while (lv2d++, ((unsigned long)lv2d < lv2d_end) && (size > 0));
dma_sync_single_for_device(NULL,
virt_to_phys((void *) lv2d_first),
(size_t)(lv2d - lv2d_first), DMA_TO_DEVICE);
}
#endif
return PT_NORMAL;
}
| gpl-2.0 |
forumber/2.6.35.7-u8800pro-cm7 | drivers/misc/tsif.c | 169 | 43458 | /*
* TSIF Driver
*
* Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
#include <linux/err.h> /* IS_ERR etc. */
#include <linux/platform_device.h>
#include <linux/ioport.h> /* XXX_mem_region */
#include <linux/debugfs.h>
#include <linux/dma-mapping.h> /* dma_XXX */
#include <linux/delay.h> /* msleep */
#include <linux/io.h> /* ioXXX */
#include <linux/uaccess.h> /* copy_from_user */
#include <linux/clk.h>
#include <linux/wakelock.h>
#include <linux/tsif_api.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h> /* kfree, kzalloc */
#include <mach/gpio.h>
#include <mach/dma.h>
#include <mach/msm_tsif.h>
/*
* TSIF register offsets
*/
#define TSIF_STS_CTL_OFF (0x0)
#define TSIF_TIME_LIMIT_OFF (0x4)
#define TSIF_CLK_REF_OFF (0x8)
#define TSIF_LPBK_FLAGS_OFF (0xc)
#define TSIF_LPBK_DATA_OFF (0x10)
#define TSIF_TEST_CTL_OFF (0x14)
#define TSIF_TEST_MODE_OFF (0x18)
#define TSIF_TEST_RESET_OFF (0x1c)
#define TSIF_TEST_EXPORT_OFF (0x20)
#define TSIF_TEST_CURRENT_OFF (0x24)
#define TSIF_DATA_PORT_OFF (0x100)
/* bits for TSIF_STS_CTL register */
#define TSIF_STS_CTL_EN_IRQ (1 << 28)
#define TSIF_STS_CTL_PACK_AVAIL (1 << 27)
#define TSIF_STS_CTL_1ST_PACKET (1 << 26)
#define TSIF_STS_CTL_OVERFLOW (1 << 25)
#define TSIF_STS_CTL_LOST_SYNC (1 << 24)
#define TSIF_STS_CTL_TIMEOUT (1 << 23)
#define TSIF_STS_CTL_INV_SYNC (1 << 21)
#define TSIF_STS_CTL_INV_NULL (1 << 20)
#define TSIF_STS_CTL_INV_ERROR (1 << 19)
#define TSIF_STS_CTL_INV_ENABLE (1 << 18)
#define TSIF_STS_CTL_INV_DATA (1 << 17)
#define TSIF_STS_CTL_INV_CLOCK (1 << 16)
#define TSIF_STS_CTL_SPARE (1 << 15)
#define TSIF_STS_CTL_EN_NULL (1 << 11)
#define TSIF_STS_CTL_EN_ERROR (1 << 10)
#define TSIF_STS_CTL_LAST_BIT (1 << 9)
#define TSIF_STS_CTL_EN_TIME_LIM (1 << 8)
#define TSIF_STS_CTL_EN_TCR (1 << 7)
#define TSIF_STS_CTL_TEST_MODE (3 << 5)
#define TSIF_STS_CTL_EN_DM (1 << 4)
#define TSIF_STS_CTL_STOP (1 << 3)
#define TSIF_STS_CTL_START (1 << 0)
/*
* Data buffering parameters
*
* Data stored in cyclic buffer;
*
* Data organized in chunks of packets.
* One chunk processed at a time by the data mover
*
*/
#define TSIF_PKTS_IN_CHUNK_DEFAULT (16) /**< packets in one DM chunk */
#define TSIF_CHUNKS_IN_BUF_DEFAULT (8)
#define TSIF_PKTS_IN_CHUNK (tsif_device->pkts_per_chunk)
#define TSIF_CHUNKS_IN_BUF (tsif_device->chunks_per_buf)
#define TSIF_PKTS_IN_BUF (TSIF_PKTS_IN_CHUNK * TSIF_CHUNKS_IN_BUF)
#define TSIF_BUF_SIZE (TSIF_PKTS_IN_BUF * TSIF_PKT_SIZE)
#define ROW_RESET (MSM_CLK_CTL_BASE + 0x214)
#define GLBL_CLK_ENA (MSM_CLK_CTL_BASE + 0x000)
#define CLK_HALT_STATEB (MSM_CLK_CTL_BASE + 0x104)
#define TSIF_NS_REG (MSM_CLK_CTL_BASE + 0x0b4)
#define TV_NS_REG (MSM_CLK_CTL_BASE + 0x0bc)
/* used to create debugfs entries */
static const struct {
const char *name;
mode_t mode;
int offset;
} debugfs_tsif_regs[] = {
{"sts_ctl", S_IRUGO | S_IWUSR, TSIF_STS_CTL_OFF},
{"time_limit", S_IRUGO | S_IWUSR, TSIF_TIME_LIMIT_OFF},
{"clk_ref", S_IRUGO | S_IWUSR, TSIF_CLK_REF_OFF},
{"lpbk_flags", S_IRUGO | S_IWUSR, TSIF_LPBK_FLAGS_OFF},
{"lpbk_data", S_IRUGO | S_IWUSR, TSIF_LPBK_DATA_OFF},
{"test_ctl", S_IRUGO | S_IWUSR, TSIF_TEST_CTL_OFF},
{"test_mode", S_IRUGO | S_IWUSR, TSIF_TEST_MODE_OFF},
{"test_reset", S_IWUSR, TSIF_TEST_RESET_OFF},
{"test_export", S_IRUGO | S_IWUSR, TSIF_TEST_EXPORT_OFF},
{"test_current", S_IRUGO, TSIF_TEST_CURRENT_OFF},
{"data_port", S_IRUSR, TSIF_DATA_PORT_OFF},
};
/* structures for Data Mover */
struct tsif_dmov_cmd {
dmov_box box;
dma_addr_t box_ptr;
};
struct msm_tsif_device;
struct tsif_xfer {
struct msm_dmov_cmd hdr;
struct msm_tsif_device *tsif_device;
int busy;
int wi; /**< set devices's write index after xfer */
};
struct msm_tsif_device {
struct list_head devlist;
struct platform_device *pdev;
struct resource *memres;
void __iomem *base;
unsigned int irq;
int mode;
u32 time_limit;
enum tsif_state state;
struct wake_lock wake_lock;
/* clocks */
struct clk *tsif_clk;
struct clk *tsif_pclk;
struct clk *tsif_ref_clk;
/* debugfs */
struct dentry *dent_tsif;
struct dentry *debugfs_tsif_regs[ARRAY_SIZE(debugfs_tsif_regs)];
struct dentry *debugfs_gpio;
struct dentry *debugfs_action;
struct dentry *debugfs_dma;
struct dentry *debugfs_databuf;
struct debugfs_blob_wrapper blob_wrapper_databuf;
/* DMA related */
int dma;
int crci;
void *data_buffer;
dma_addr_t data_buffer_dma;
u32 pkts_per_chunk;
u32 chunks_per_buf;
int ri;
int wi;
int dmwi; /**< DataMover write index */
struct tsif_dmov_cmd *dmov_cmd[2];
dma_addr_t dmov_cmd_dma[2];
struct tsif_xfer xfer[2];
struct tasklet_struct dma_refill;
/* statistics */
u32 stat_rx;
u32 stat_overflow;
u32 stat_lost_sync;
u32 stat_timeout;
u32 stat_dmov_err;
u32 stat_soft_drop;
int stat_ifi; /* inter frame interval */
u32 stat0, stat1;
/* client */
void *client_data;
void (*client_notify)(void *client_data);
};
/* ===clocks begin=== */
static void tsif_put_clocks(struct msm_tsif_device *tsif_device)
{
if (tsif_device->tsif_clk) {
clk_put(tsif_device->tsif_clk);
tsif_device->tsif_clk = NULL;
}
if (tsif_device->tsif_pclk) {
clk_put(tsif_device->tsif_pclk);
tsif_device->tsif_pclk = NULL;
}
if (tsif_device->tsif_ref_clk) {
clk_put(tsif_device->tsif_ref_clk);
tsif_device->tsif_ref_clk = NULL;
}
}
static int tsif_get_clocks(struct msm_tsif_device *tsif_device)
{
struct msm_tsif_platform_data *pdata =
tsif_device->pdev->dev.platform_data;
int rc = 0;
if (pdata->tsif_clk) {
tsif_device->tsif_clk = clk_get(NULL, pdata->tsif_clk);
if (IS_ERR(tsif_device->tsif_clk)) {
dev_err(&tsif_device->pdev->dev, "failed to get %s\n",
pdata->tsif_clk);
rc = PTR_ERR(tsif_device->tsif_clk);
tsif_device->tsif_clk = NULL;
goto ret;
}
}
if (pdata->tsif_pclk) {
tsif_device->tsif_pclk = clk_get(NULL, pdata->tsif_pclk);
if (IS_ERR(tsif_device->tsif_pclk)) {
dev_err(&tsif_device->pdev->dev, "failed to get %s\n",
pdata->tsif_pclk);
rc = PTR_ERR(tsif_device->tsif_pclk);
tsif_device->tsif_pclk = NULL;
goto ret;
}
}
if (pdata->tsif_ref_clk) {
tsif_device->tsif_ref_clk = clk_get(NULL, pdata->tsif_ref_clk);
if (IS_ERR(tsif_device->tsif_ref_clk)) {
dev_err(&tsif_device->pdev->dev, "failed to get %s\n",
pdata->tsif_ref_clk);
rc = PTR_ERR(tsif_device->tsif_ref_clk);
tsif_device->tsif_ref_clk = NULL;
goto ret;
}
}
return 0;
ret:
tsif_put_clocks(tsif_device);
return rc;
}
static void tsif_clock(struct msm_tsif_device *tsif_device, int on)
{
if (on) {
if (tsif_device->tsif_clk)
clk_enable(tsif_device->tsif_clk);
if (tsif_device->tsif_pclk)
clk_enable(tsif_device->tsif_pclk);
clk_enable(tsif_device->tsif_ref_clk);
} else {
if (tsif_device->tsif_clk)
clk_disable(tsif_device->tsif_clk);
if (tsif_device->tsif_pclk)
clk_disable(tsif_device->tsif_pclk);
clk_disable(tsif_device->tsif_ref_clk);
}
}
/* ===clocks end=== */
/* ===gpio begin=== */
static void tsif_gpios_free(const struct msm_gpio *table, int size)
{
int i;
const struct msm_gpio *g;
for (i = size-1; i >= 0; i--) {
g = table + i;
gpio_free(GPIO_PIN(g->gpio_cfg));
}
}
static int tsif_gpios_request(const struct msm_gpio *table, int size)
{
int rc;
int i;
const struct msm_gpio *g;
for (i = 0; i < size; i++) {
g = table + i;
rc = gpio_request(GPIO_PIN(g->gpio_cfg), g->label);
if (rc) {
pr_err("gpio_request(%d) <%s> failed: %d\n",
GPIO_PIN(g->gpio_cfg), g->label ?: "?", rc);
goto err;
}
}
return 0;
err:
tsif_gpios_free(table, i);
return rc;
}
static int tsif_gpios_disable(const struct msm_gpio *table, int size)
{
int rc = 0;
int i;
const struct msm_gpio *g;
for (i = size-1; i >= 0; i--) {
int tmp;
g = table + i;
tmp = gpio_tlmm_config(g->gpio_cfg, GPIO_CFG_DISABLE);
if (tmp) {
pr_err("gpio_tlmm_config(0x%08x, GPIO_CFG_DISABLE)"
" <%s> failed: %d\n",
g->gpio_cfg, g->label ?: "?", rc);
pr_err("pin %d func %d dir %d pull %d drvstr %d\n",
GPIO_PIN(g->gpio_cfg), GPIO_FUNC(g->gpio_cfg),
GPIO_DIR(g->gpio_cfg), GPIO_PULL(g->gpio_cfg),
GPIO_DRVSTR(g->gpio_cfg));
if (!rc)
rc = tmp;
}
}
return rc;
}
static int tsif_gpios_enable(const struct msm_gpio *table, int size)
{
int rc;
int i;
const struct msm_gpio *g;
for (i = 0; i < size; i++) {
g = table + i;
rc = gpio_tlmm_config(g->gpio_cfg, GPIO_CFG_ENABLE);
if (rc) {
pr_err("gpio_tlmm_config(0x%08x, GPIO_CFG_ENABLE)"
" <%s> failed: %d\n",
g->gpio_cfg, g->label ?: "?", rc);
pr_err("pin %d func %d dir %d pull %d drvstr %d\n",
GPIO_PIN(g->gpio_cfg), GPIO_FUNC(g->gpio_cfg),
GPIO_DIR(g->gpio_cfg), GPIO_PULL(g->gpio_cfg),
GPIO_DRVSTR(g->gpio_cfg));
goto err;
}
}
return 0;
err:
tsif_gpios_disable(table, i);
return rc;
}
static int tsif_gpios_request_enable(const struct msm_gpio *table, int size)
{
int rc = tsif_gpios_request(table, size);
if (rc)
return rc;
rc = tsif_gpios_enable(table, size);
if (rc)
tsif_gpios_free(table, size);
return rc;
}
static void tsif_gpios_disable_free(const struct msm_gpio *table, int size)
{
tsif_gpios_disable(table, size);
tsif_gpios_free(table, size);
}
static int tsif_start_gpios(struct msm_tsif_device *tsif_device)
{
struct msm_tsif_platform_data *pdata =
tsif_device->pdev->dev.platform_data;
return tsif_gpios_request_enable(pdata->gpios, pdata->num_gpios);
}
static void tsif_stop_gpios(struct msm_tsif_device *tsif_device)
{
struct msm_tsif_platform_data *pdata =
tsif_device->pdev->dev.platform_data;
tsif_gpios_disable_free(pdata->gpios, pdata->num_gpios);
}
/* ===gpio end=== */
static int tsif_start_hw(struct msm_tsif_device *tsif_device)
{
u32 ctl = TSIF_STS_CTL_EN_IRQ |
TSIF_STS_CTL_EN_TIME_LIM |
TSIF_STS_CTL_EN_TCR |
TSIF_STS_CTL_EN_DM;
dev_info(&tsif_device->pdev->dev, "%s\n", __func__);
switch (tsif_device->mode) {
case 1: /* mode 1 */
ctl |= (0 << 5);
break;
case 2: /* mode 2 */
ctl |= (1 << 5);
break;
case 3: /* manual - control from debugfs */
return 0;
break;
default:
return -EINVAL;
}
iowrite32(ctl, tsif_device->base + TSIF_STS_CTL_OFF);
iowrite32(tsif_device->time_limit,
tsif_device->base + TSIF_TIME_LIMIT_OFF);
wmb();
iowrite32(ctl | TSIF_STS_CTL_START,
tsif_device->base + TSIF_STS_CTL_OFF);
wmb();
ctl = ioread32(tsif_device->base + TSIF_STS_CTL_OFF);
return (ctl & TSIF_STS_CTL_START) ? 0 : -EFAULT;
}
static void tsif_stop_hw(struct msm_tsif_device *tsif_device)
{
iowrite32(TSIF_STS_CTL_STOP, tsif_device->base + TSIF_STS_CTL_OFF);
wmb();
}
/* ===DMA begin=== */
/**
* TSIF DMA theory of operation
*
* Circular memory buffer \a tsif_mem_buffer allocated;
* 4 pointers points to and moved forward on:
* - \a ri index of first ready to read packet.
* Updated by client's call to tsif_reclaim_packets()
* - \a wi points to the next packet to be written by DM.
* Data below is valid and will not be overriden by DMA.
* Moved on DM callback
* - \a dmwi points to the next packet not scheduled yet for DM
* moved when packet scheduled for DM
*
* In addition, DM xfer keep internal \a wi - copy of \a tsif_device->dmwi
* at time immediately after scheduling.
*
* Initially, 2 packets get scheduled for the DM.
*
* Upon packet receive, DM writes packet to the pre-programmed
* location and invoke its callback.
*
* DM callback moves sets wi pointer to \a xfer->wi;
* then it schedules next packet for DM and moves \a dmwi pointer.
*
* Buffer overflow handling
*
* If \a dmwi == \a ri-1, buffer is full and \a dmwi can't be advanced.
* DMA re-scheduled to the same index.
* Callback check and not move \a wi to become equal to \a ri
*
* On \a read request, data between \a ri and \a wi pointers may be read;
* \ri pointer moved accordingly.
*
* It is always granted, on modulo sizeof(tsif_mem_buffer), that
* \a wi is between [\a ri, \a dmwi]
*
* Amount of data available is (wi-ri)*TSIF_PKT_SIZE
*
* Number of scheduled packets for DM: (dmwi-wi)
*/
/**
* tsif_dma_schedule - schedule DMA transfers
*
* @tsif_device: device
*
* Executed from process context on init, or from tasklet when
* re-scheduling upon DMA completion.
* This prevent concurrent execution from several CPU's
*/
static void tsif_dma_schedule(struct msm_tsif_device *tsif_device)
{
int i, dmwi0, dmwi1, found = 0;
/* find free entry */
for (i = 0; i < 2; i++) {
struct tsif_xfer *xfer = &tsif_device->xfer[i];
if (xfer->busy)
continue;
found++;
xfer->busy = 1;
dmwi0 = tsif_device->dmwi;
tsif_device->dmov_cmd[i]->box.dst_row_addr =
tsif_device->data_buffer_dma + TSIF_PKT_SIZE * dmwi0;
/* proposed value for dmwi */
dmwi1 = (dmwi0 + TSIF_PKTS_IN_CHUNK) % TSIF_PKTS_IN_BUF;
/**
* If dmwi going to overlap with ri,
* overflow occurs because data was not read.
* Still get this packet, to not interrupt TSIF
* hardware, but do not advance dmwi.
*
* Upon receive, packet will be dropped.
*/
if (dmwi1 != tsif_device->ri) {
tsif_device->dmwi = dmwi1;
} else {
dev_info(&tsif_device->pdev->dev,
"Overflow detected\n");
}
xfer->wi = tsif_device->dmwi;
#ifdef CONFIG_TSIF_DEBUG
dev_info(&tsif_device->pdev->dev,
"schedule xfer[%d] -> [%2d]{%2d}\n",
i, dmwi0, xfer->wi);
#endif
/* complete all the writes to box */
dma_coherent_pre_ops();
msm_dmov_enqueue_cmd(tsif_device->dma, &xfer->hdr);
}
if (!found)
dev_info(&tsif_device->pdev->dev,
"All xfer entries are busy\n");
}
/**
* tsif_dmov_complete_func - DataMover completion callback
*
* @cmd: original DM command
* @result: DM result
* @err: optional error buffer
*
* Executed in IRQ context (Data Mover's IRQ)
* DataMover's spinlock @msm_dmov_lock held.
*/
static void tsif_dmov_complete_func(struct msm_dmov_cmd *cmd,
unsigned int result,
struct msm_dmov_errdata *err)
{
int i;
u32 data_offset;
struct tsif_xfer *xfer;
struct msm_tsif_device *tsif_device;
int reschedule = 0;
if (!(result & DMOV_RSLT_VALID)) { /* can I trust to @cmd? */
pr_err("Invalid DMOV result: rc=0x%08x, cmd = %p", result, cmd);
return;
}
/* restore original context */
xfer = container_of(cmd, struct tsif_xfer, hdr);
tsif_device = xfer->tsif_device;
i = xfer - tsif_device->xfer;
data_offset = tsif_device->dmov_cmd[i]->box.dst_row_addr -
tsif_device->data_buffer_dma;
/* order reads from the xferred buffer */
dma_coherent_post_ops();
if (result & DMOV_RSLT_DONE) {
int w = data_offset / TSIF_PKT_SIZE;
tsif_device->stat_rx++;
/*
* sowtware overflow when I was scheduled?
*
* @w is where this xfer was actually written to;
* @xfer->wi is where device's @wi will be set;
*
* if these 2 are equal, we are short in space and
* going to overwrite this xfer - this is "soft drop"
*/
if (w == xfer->wi)
tsif_device->stat_soft_drop++;
reschedule = (tsif_device->state == tsif_state_running);
#ifdef CONFIG_TSIF_DEBUG
/* IFI calculation */
/*
* update stat_ifi (inter frame interval)
*
* Calculate time difference between last and 1-st
* packets in chunk
*
* To be removed after tuning
*/
if (TSIF_PKTS_IN_CHUNK > 1) {
void *ptr = tsif_device->data_buffer + data_offset;
u32 *p0 = ptr;
u32 *p1 = ptr + (TSIF_PKTS_IN_CHUNK - 1) *
TSIF_PKT_SIZE;
u32 tts0 = TSIF_STATUS_TTS(tsif_device->stat0 =
tsif_pkt_status(p0));
u32 tts1 = TSIF_STATUS_TTS(tsif_device->stat1 =
tsif_pkt_status(p1));
tsif_device->stat_ifi = (tts1 - tts0) /
(TSIF_PKTS_IN_CHUNK - 1);
}
#endif
} else {
/**
* Error or flush
*
* To recover - re-open TSIF device.
*/
/* mark status "not valid" in data buffer */
int n;
void *ptr = tsif_device->data_buffer + data_offset;
for (n = 0; n < TSIF_PKTS_IN_CHUNK; n++) {
u32 *p = ptr + (n * TSIF_PKT_SIZE);
/* last dword is status + TTS */
p[TSIF_PKT_SIZE / sizeof(*p) - 1] = 0;
}
if (result & DMOV_RSLT_ERROR) {
dev_err(&tsif_device->pdev->dev,
"DMA error (0x%08x)\n", result);
tsif_device->stat_dmov_err++;
/* force device close */
if (tsif_device->state == tsif_state_running) {
tsif_stop_hw(tsif_device);
/*
* Clocks _may_ be stopped right from IRQ
* context. This is far from optimal w.r.t
* latency.
*
* But, this branch taken only in case of
* severe hardware problem (I don't even know
* what should happens for DMOV_RSLT_ERROR);
* thus I prefer code simplicity over
* performance.
*/
tsif_clock(tsif_device, 0);
tsif_device->state = tsif_state_flushing;
}
}
if (result & DMOV_RSLT_FLUSH) {
/*
* Flushing normally happens in process of
* @tsif_stop(), when we are waiting for outstanding
* DMA commands to be flushed.
*/
dev_info(&tsif_device->pdev->dev,
"DMA channel flushed (0x%08x)\n", result);
if (tsif_device->state == tsif_state_flushing) {
if ((!tsif_device->xfer[0].busy) &&
(!tsif_device->xfer[1].busy)) {
tsif_device->state = tsif_state_stopped;
}
}
}
if (err)
dev_err(&tsif_device->pdev->dev,
"Flush data: %08x %08x %08x %08x %08x %08x\n",
err->flush[0], err->flush[1], err->flush[2],
err->flush[3], err->flush[4], err->flush[5]);
}
tsif_device->wi = xfer->wi;
xfer->busy = 0;
if (tsif_device->client_notify)
tsif_device->client_notify(tsif_device->client_data);
/*
* Can't schedule next DMA -
* DataMover driver still hold its semaphore,
* deadlock will occur.
*/
if (reschedule)
tasklet_schedule(&tsif_device->dma_refill);
}
/**
* tsif_dma_refill - tasklet function for tsif_device->dma_refill
*
* @data: tsif_device
*
* Reschedule DMA requests
*
* Executed in tasklet
*/
static void tsif_dma_refill(unsigned long data)
{
struct msm_tsif_device *tsif_device = (struct msm_tsif_device *) data;
if (tsif_device->state == tsif_state_running)
tsif_dma_schedule(tsif_device);
}
/**
* tsif_dma_flush - flush DMA channel
*
* @tsif_device:
*
* busy wait till DMA flushed
*/
static void tsif_dma_flush(struct msm_tsif_device *tsif_device)
{
if (tsif_device->xfer[0].busy || tsif_device->xfer[1].busy) {
tsif_device->state = tsif_state_flushing;
while (tsif_device->xfer[0].busy ||
tsif_device->xfer[1].busy) {
msm_dmov_flush(tsif_device->dma);
msleep(10);
}
}
tsif_device->state = tsif_state_stopped;
if (tsif_device->client_notify)
tsif_device->client_notify(tsif_device->client_data);
}
static void tsif_dma_exit(struct msm_tsif_device *tsif_device)
{
int i;
tsif_device->state = tsif_state_flushing;
tasklet_kill(&tsif_device->dma_refill);
tsif_dma_flush(tsif_device);
for (i = 0; i < 2; i++) {
if (tsif_device->dmov_cmd[i]) {
dma_free_coherent(NULL, sizeof(struct tsif_dmov_cmd),
tsif_device->dmov_cmd[i],
tsif_device->dmov_cmd_dma[i]);
tsif_device->dmov_cmd[i] = NULL;
}
}
if (tsif_device->data_buffer) {
tsif_device->blob_wrapper_databuf.data = NULL;
tsif_device->blob_wrapper_databuf.size = 0;
dma_free_coherent(NULL, TSIF_BUF_SIZE,
tsif_device->data_buffer,
tsif_device->data_buffer_dma);
tsif_device->data_buffer = NULL;
}
}
static int tsif_dma_init(struct msm_tsif_device *tsif_device)
{
int i;
/* TODO: allocate all DMA memory in one buffer */
/* Note: don't pass device,
it require coherent_dma_mask id device definition */
tsif_device->data_buffer = dma_alloc_coherent(NULL, TSIF_BUF_SIZE,
&tsif_device->data_buffer_dma, GFP_KERNEL);
if (!tsif_device->data_buffer)
goto err;
dev_info(&tsif_device->pdev->dev, "data_buffer: %p phys 0x%08x\n",
tsif_device->data_buffer, tsif_device->data_buffer_dma);
tsif_device->blob_wrapper_databuf.data = tsif_device->data_buffer;
tsif_device->blob_wrapper_databuf.size = TSIF_BUF_SIZE;
tsif_device->ri = 0;
tsif_device->wi = 0;
tsif_device->dmwi = 0;
for (i = 0; i < 2; i++) {
dmov_box *box;
struct msm_dmov_cmd *hdr;
tsif_device->dmov_cmd[i] = dma_alloc_coherent(NULL,
sizeof(struct tsif_dmov_cmd),
&tsif_device->dmov_cmd_dma[i], GFP_KERNEL);
if (!tsif_device->dmov_cmd[i])
goto err;
dev_info(&tsif_device->pdev->dev, "dma[%i]: %p phys 0x%08x\n",
i, tsif_device->dmov_cmd[i],
tsif_device->dmov_cmd_dma[i]);
/* dst in 16 LSB, src in 16 MSB */
box = &(tsif_device->dmov_cmd[i]->box);
box->cmd = CMD_MODE_BOX | CMD_LC |
CMD_SRC_CRCI(tsif_device->crci);
box->src_row_addr =
tsif_device->memres->start + TSIF_DATA_PORT_OFF;
box->src_dst_len = (TSIF_PKT_SIZE << 16) | TSIF_PKT_SIZE;
box->num_rows = (TSIF_PKTS_IN_CHUNK << 16) | TSIF_PKTS_IN_CHUNK;
box->row_offset = (0 << 16) | TSIF_PKT_SIZE;
tsif_device->dmov_cmd[i]->box_ptr = CMD_PTR_LP |
DMOV_CMD_ADDR(tsif_device->dmov_cmd_dma[i] +
offsetof(struct tsif_dmov_cmd, box));
tsif_device->xfer[i].tsif_device = tsif_device;
hdr = &tsif_device->xfer[i].hdr;
hdr->cmdptr = DMOV_CMD_ADDR(tsif_device->dmov_cmd_dma[i] +
offsetof(struct tsif_dmov_cmd, box_ptr));
hdr->complete_func = tsif_dmov_complete_func;
}
msm_dmov_flush(tsif_device->dma);
return 0;
err:
dev_err(&tsif_device->pdev->dev, "Failed to allocate DMA buffers\n");
tsif_dma_exit(tsif_device);
return -ENOMEM;
}
/* ===DMA end=== */
/* ===IRQ begin=== */
static irqreturn_t tsif_irq(int irq, void *dev_id)
{
struct msm_tsif_device *tsif_device = dev_id;
u32 sts_ctl = ioread32(tsif_device->base + TSIF_STS_CTL_OFF);
if (!(sts_ctl & (TSIF_STS_CTL_PACK_AVAIL |
TSIF_STS_CTL_OVERFLOW |
TSIF_STS_CTL_LOST_SYNC |
TSIF_STS_CTL_TIMEOUT))) {
dev_warn(&tsif_device->pdev->dev, "Spurious interrupt\n");
return IRQ_NONE;
}
if (sts_ctl & TSIF_STS_CTL_PACK_AVAIL) {
dev_info(&tsif_device->pdev->dev, "TSIF IRQ: PACK_AVAIL\n");
tsif_device->stat_rx++;
}
if (sts_ctl & TSIF_STS_CTL_OVERFLOW) {
dev_info(&tsif_device->pdev->dev, "TSIF IRQ: OVERFLOW\n");
tsif_device->stat_overflow++;
}
if (sts_ctl & TSIF_STS_CTL_LOST_SYNC) {
dev_info(&tsif_device->pdev->dev, "TSIF IRQ: LOST SYNC\n");
tsif_device->stat_lost_sync++;
}
if (sts_ctl & TSIF_STS_CTL_TIMEOUT) {
dev_info(&tsif_device->pdev->dev, "TSIF IRQ: TIMEOUT\n");
tsif_device->stat_timeout++;
}
iowrite32(sts_ctl, tsif_device->base + TSIF_STS_CTL_OFF);
wmb();
return IRQ_HANDLED;
}
/* ===IRQ end=== */
/* ===Device attributes begin=== */
static ssize_t show_stats(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
char *state_string;
switch (tsif_device->state) {
case tsif_state_stopped:
state_string = "stopped";
break;
case tsif_state_running:
state_string = "running";
break;
case tsif_state_flushing:
state_string = "flushing";
break;
default:
state_string = "???";
}
return snprintf(buf, PAGE_SIZE,
"Device %s\n"
"Mode = %d\n"
"Time limit = %d\n"
"State %s\n"
"Client = %p\n"
"Pkt/Buf = %d\n"
"Pkt/chunk = %d\n"
"--statistics--\n"
"Rx chunks = %d\n"
"Overflow = %d\n"
"Lost sync = %d\n"
"Timeout = %d\n"
"DMA error = %d\n"
"Soft drop = %d\n"
"IFI = %d\n"
"(0x%08x - 0x%08x) / %d\n"
"--debug--\n"
"GLBL_CLK_ENA = 0x%08x\n"
"ROW_RESET = 0x%08x\n"
"CLK_HALT_STATEB = 0x%08x\n"
"TV_NS_REG = 0x%08x\n"
"TSIF_NS_REG = 0x%08x\n",
dev_name(dev),
tsif_device->mode,
tsif_device->time_limit,
state_string,
tsif_device->client_data,
TSIF_PKTS_IN_BUF,
TSIF_PKTS_IN_CHUNK,
tsif_device->stat_rx,
tsif_device->stat_overflow,
tsif_device->stat_lost_sync,
tsif_device->stat_timeout,
tsif_device->stat_dmov_err,
tsif_device->stat_soft_drop,
tsif_device->stat_ifi,
tsif_device->stat1,
tsif_device->stat0,
TSIF_PKTS_IN_CHUNK - 1,
ioread32(GLBL_CLK_ENA),
ioread32(ROW_RESET),
ioread32(CLK_HALT_STATEB),
ioread32(TV_NS_REG),
ioread32(TSIF_NS_REG)
);
}
/**
* set_stats - reset statistics on write
*
* @dev:
* @attr:
* @buf:
* @count:
*/
static ssize_t set_stats(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
tsif_device->stat_rx = 0;
tsif_device->stat_overflow = 0;
tsif_device->stat_lost_sync = 0;
tsif_device->stat_timeout = 0;
tsif_device->stat_dmov_err = 0;
tsif_device->stat_soft_drop = 0;
tsif_device->stat_ifi = 0;
return count;
}
static DEVICE_ATTR(stats, S_IRUGO | S_IWUSR, show_stats, set_stats);
static ssize_t show_mode(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%d\n", tsif_device->mode);
}
static ssize_t set_mode(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
int value;
int rc;
if (1 != sscanf(buf, "%d", &value)) {
dev_err(&tsif_device->pdev->dev,
"Failed to parse integer: <%s>\n", buf);
return -EINVAL;
}
rc = tsif_set_mode(tsif_device, value);
if (!rc)
rc = count;
return rc;
}
static DEVICE_ATTR(mode, S_IRUGO | S_IWUSR, show_mode, set_mode);
static ssize_t show_time_limit(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%d\n", tsif_device->time_limit);
}
static ssize_t set_time_limit(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
int value;
int rc;
if (1 != sscanf(buf, "%d", &value)) {
dev_err(&tsif_device->pdev->dev,
"Failed to parse integer: <%s>\n", buf);
return -EINVAL;
}
rc = tsif_set_time_limit(tsif_device, value);
if (!rc)
rc = count;
return rc;
}
static DEVICE_ATTR(time_limit, S_IRUGO | S_IWUSR,
show_time_limit, set_time_limit);
static ssize_t show_buf_config(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%d * %d\n",
tsif_device->pkts_per_chunk,
tsif_device->chunks_per_buf);
}
static ssize_t set_buf_config(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct msm_tsif_device *tsif_device = dev_get_drvdata(dev);
u32 p, c;
int rc;
if (2 != sscanf(buf, "%d * %d", &p, &c)) {
dev_err(&tsif_device->pdev->dev,
"Failed to parse integer: <%s>\n", buf);
return -EINVAL;
}
rc = tsif_set_buf_config(tsif_device, p, c);
if (!rc)
rc = count;
return rc;
}
static DEVICE_ATTR(buf_config, S_IRUGO | S_IWUSR,
show_buf_config, set_buf_config);
static struct attribute *dev_attrs[] = {
&dev_attr_stats.attr,
&dev_attr_mode.attr,
&dev_attr_time_limit.attr,
&dev_attr_buf_config.attr,
NULL,
};
static struct attribute_group dev_attr_grp = {
.attrs = dev_attrs,
};
/* ===Device attributes end=== */
/* ===debugfs begin=== */
static int debugfs_iomem_x32_set(void *data, u64 val)
{
iowrite32(val, data);
wmb();
return 0;
}
static int debugfs_iomem_x32_get(void *data, u64 *val)
{
*val = ioread32(data);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_iomem_x32, debugfs_iomem_x32_get,
debugfs_iomem_x32_set, "0x%08llx\n");
struct dentry *debugfs_create_iomem_x32(const char *name, mode_t mode,
struct dentry *parent, u32 *value)
{
return debugfs_create_file(name, mode, parent, value, &fops_iomem_x32);
}
static int action_open(struct msm_tsif_device *tsif_device)
{
int rc = -EINVAL;
int result;
dev_info(&tsif_device->pdev->dev, "%s\n", __func__);
if (tsif_device->state != tsif_state_stopped)
return -EAGAIN;
rc = tsif_dma_init(tsif_device);
if (rc) {
dev_err(&tsif_device->pdev->dev, "failed to init DMA\n");
return rc;
}
tsif_device->state = tsif_state_running;
/*
* DMA should be scheduled prior to TSIF hardware initialization,
* otherwise "bus error" will be reported by Data Mover
*/
enable_irq(tsif_device->irq);
tsif_clock(tsif_device, 1);
tsif_dma_schedule(tsif_device);
rc = tsif_start_hw(tsif_device);
if (rc) {
dev_err(&tsif_device->pdev->dev, "Unable to start HW\n");
tsif_dma_exit(tsif_device);
tsif_clock(tsif_device, 0);
return rc;
}
result = pm_runtime_get(&tsif_device->pdev->dev);
if (result < 0) {
dev_err(&tsif_device->pdev->dev,
"Runtime PM: Unable to wake up the device, rc = %d\n",
result);
return result;
}
wake_lock(&tsif_device->wake_lock);
return rc;
}
static int action_close(struct msm_tsif_device *tsif_device)
{
dev_info(&tsif_device->pdev->dev, "%s, state %d\n", __func__,
(int)tsif_device->state);
/*
* DMA should be flushed/stopped prior to TSIF hardware stop,
* otherwise "bus error" will be reported by Data Mover
*/
tsif_stop_hw(tsif_device);
tsif_dma_exit(tsif_device);
tsif_clock(tsif_device, 0);
disable_irq(tsif_device->irq);
pm_runtime_put(&tsif_device->pdev->dev);
wake_unlock(&tsif_device->wake_lock);
return 0;
}
static struct {
int (*func)(struct msm_tsif_device *);
const char *name;
} actions[] = {
{ action_open, "open"},
{ action_close, "close"},
};
static ssize_t tsif_debugfs_action_write(struct file *filp,
const char __user *userbuf,
size_t count, loff_t *f_pos)
{
int i;
struct msm_tsif_device *tsif_device = filp->private_data;
char s[40];
int len = min(sizeof(s) - 1, count);
if (copy_from_user(s, userbuf, len))
return -EFAULT;
s[len] = '\0';
dev_info(&tsif_device->pdev->dev, "%s:%s\n", __func__, s);
for (i = 0; i < ARRAY_SIZE(actions); i++) {
if (!strncmp(s, actions[i].name,
min(count, strlen(actions[i].name)))) {
int rc = actions[i].func(tsif_device);
if (!rc)
rc = count;
return rc;
}
}
return -EINVAL;
}
static int tsif_debugfs_generic_open(struct inode *inode, struct file *filp)
{
filp->private_data = inode->i_private;
return 0;
}
static const struct file_operations fops_debugfs_action = {
.open = tsif_debugfs_generic_open,
.write = tsif_debugfs_action_write,
};
static ssize_t tsif_debugfs_dma_read(struct file *filp, char __user *userbuf,
size_t count, loff_t *f_pos)
{
static char bufa[200];
static char *buf = bufa;
int sz = sizeof(bufa);
struct msm_tsif_device *tsif_device = filp->private_data;
int len = 0;
if (tsif_device) {
int i;
len += snprintf(buf + len, sz - len,
"ri %3d | wi %3d | dmwi %3d |",
tsif_device->ri, tsif_device->wi,
tsif_device->dmwi);
for (i = 0; i < 2; i++) {
struct tsif_xfer *xfer = &tsif_device->xfer[i];
if (xfer->busy) {
u32 dst =
tsif_device->dmov_cmd[i]->box.dst_row_addr;
u32 base = tsif_device->data_buffer_dma;
int w = (dst - base) / TSIF_PKT_SIZE;
len += snprintf(buf + len, sz - len,
" [%3d]{%3d}",
w, xfer->wi);
} else {
len += snprintf(buf + len, sz - len,
" ---idle---");
}
}
len += snprintf(buf + len, sz - len, "\n");
} else {
len += snprintf(buf + len, sz - len, "No TSIF device???\n");
}
return simple_read_from_buffer(userbuf, count, f_pos, buf, len);
}
static const struct file_operations fops_debugfs_dma = {
.open = tsif_debugfs_generic_open,
.read = tsif_debugfs_dma_read,
};
static ssize_t tsif_debugfs_gpios_read(struct file *filp, char __user *userbuf,
size_t count, loff_t *f_pos)
{
static char bufa[300];
static char *buf = bufa;
int sz = sizeof(bufa);
struct msm_tsif_device *tsif_device = filp->private_data;
int len = 0;
if (tsif_device) {
struct msm_tsif_platform_data *pdata =
tsif_device->pdev->dev.platform_data;
int i;
for (i = 0; i < pdata->num_gpios; i++) {
if (pdata->gpios[i].gpio_cfg) {
int x = !!gpio_get_value(GPIO_PIN(
pdata->gpios[i].gpio_cfg));
len += snprintf(buf + len, sz - len,
"%15s: %d\n",
pdata->gpios[i].label, x);
}
}
} else {
len += snprintf(buf + len, sz - len, "No TSIF device???\n");
}
return simple_read_from_buffer(userbuf, count, f_pos, buf, len);
}
static const struct file_operations fops_debugfs_gpios = {
.open = tsif_debugfs_generic_open,
.read = tsif_debugfs_gpios_read,
};
static void tsif_debugfs_init(struct msm_tsif_device *tsif_device)
{
tsif_device->dent_tsif = debugfs_create_dir(
dev_name(&tsif_device->pdev->dev), NULL);
if (tsif_device->dent_tsif) {
int i;
void __iomem *base = tsif_device->base;
for (i = 0; i < ARRAY_SIZE(debugfs_tsif_regs); i++) {
tsif_device->debugfs_tsif_regs[i] =
debugfs_create_iomem_x32(
debugfs_tsif_regs[i].name,
debugfs_tsif_regs[i].mode,
tsif_device->dent_tsif,
base + debugfs_tsif_regs[i].offset);
}
tsif_device->debugfs_gpio = debugfs_create_file("gpios",
S_IRUGO,
tsif_device->dent_tsif, tsif_device, &fops_debugfs_gpios);
tsif_device->debugfs_action = debugfs_create_file("action",
S_IWUSR,
tsif_device->dent_tsif, tsif_device, &fops_debugfs_action);
tsif_device->debugfs_dma = debugfs_create_file("dma",
S_IRUGO,
tsif_device->dent_tsif, tsif_device, &fops_debugfs_dma);
tsif_device->debugfs_databuf = debugfs_create_blob("data_buf",
S_IRUGO,
tsif_device->dent_tsif, &tsif_device->blob_wrapper_databuf);
}
}
static void tsif_debugfs_exit(struct msm_tsif_device *tsif_device)
{
if (tsif_device->dent_tsif) {
int i;
debugfs_remove_recursive(tsif_device->dent_tsif);
tsif_device->dent_tsif = NULL;
for (i = 0; i < ARRAY_SIZE(debugfs_tsif_regs); i++)
tsif_device->debugfs_tsif_regs[i] = NULL;
tsif_device->debugfs_gpio = NULL;
tsif_device->debugfs_action = NULL;
tsif_device->debugfs_dma = NULL;
tsif_device->debugfs_databuf = NULL;
}
}
/* ===debugfs end=== */
/* ===module begin=== */
static LIST_HEAD(tsif_devices);
static struct msm_tsif_device *tsif_find_by_id(int id)
{
struct msm_tsif_device *tsif_device;
list_for_each_entry(tsif_device, &tsif_devices, devlist) {
if (tsif_device->pdev->id == id)
return tsif_device;
}
return NULL;
}
static int __devinit msm_tsif_probe(struct platform_device *pdev)
{
int rc = -ENODEV;
struct msm_tsif_platform_data *plat = pdev->dev.platform_data;
struct msm_tsif_device *tsif_device;
struct resource *res;
/* check device validity */
/* must have platform data */
if (!plat) {
dev_err(&pdev->dev, "Platform data not available\n");
rc = -EINVAL;
goto out;
}
/*TODO macro for max. id*/
if ((pdev->id < 0) || (pdev->id > 0)) {
dev_err(&pdev->dev, "Invalid device ID %d\n", pdev->id);
rc = -EINVAL;
goto out;
}
/* OK, we will use this device */
tsif_device = kzalloc(sizeof(struct msm_tsif_device), GFP_KERNEL);
if (!tsif_device) {
dev_err(&pdev->dev, "Failed to allocate memory for device\n");
rc = -ENOMEM;
goto out;
}
/* cross links */
tsif_device->pdev = pdev;
platform_set_drvdata(pdev, tsif_device);
tsif_device->mode = 1;
tsif_device->pkts_per_chunk = TSIF_PKTS_IN_CHUNK_DEFAULT;
tsif_device->chunks_per_buf = TSIF_CHUNKS_IN_BUF_DEFAULT;
tasklet_init(&tsif_device->dma_refill, tsif_dma_refill,
(unsigned long)tsif_device);
if (tsif_get_clocks(tsif_device))
goto err_clocks;
/* map I/O memory */
tsif_device->memres = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!tsif_device->memres) {
dev_err(&pdev->dev, "Missing MEM resource\n");
rc = -ENXIO;
goto err_rgn;
}
res = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!res) {
dev_err(&pdev->dev, "Missing DMA resource\n");
rc = -ENXIO;
goto err_rgn;
}
tsif_device->dma = res->start;
tsif_device->crci = res->end;
tsif_device->base = ioremap(tsif_device->memres->start,
resource_size(tsif_device->memres));
if (!tsif_device->base) {
dev_err(&pdev->dev, "ioremap failed\n");
goto err_ioremap;
}
dev_info(&pdev->dev, "remapped phys 0x%08x => virt %p\n",
tsif_device->memres->start, tsif_device->base);
rc = tsif_start_gpios(tsif_device);
if (rc)
goto err_gpio;
pm_runtime_set_active(&pdev->dev);
pm_runtime_enable(&pdev->dev);
tsif_debugfs_init(tsif_device);
rc = platform_get_irq(pdev, 0);
if (rc > 0) {
tsif_device->irq = rc;
rc = request_irq(tsif_device->irq, tsif_irq, IRQF_SHARED,
dev_name(&pdev->dev), tsif_device);
disable_irq(tsif_device->irq);
}
if (rc) {
dev_err(&pdev->dev, "failed to request IRQ %d : %d\n",
tsif_device->irq, rc);
goto err_irq;
}
rc = sysfs_create_group(&pdev->dev.kobj, &dev_attr_grp);
if (rc) {
dev_err(&pdev->dev, "failed to create dev. attrs : %d\n", rc);
goto err_attrs;
}
wake_lock_init(&tsif_device->wake_lock, WAKE_LOCK_SUSPEND,
dev_name(&pdev->dev));
dev_info(&pdev->dev, "Configured irq %d memory 0x%08x DMA %d CRCI %d\n",
tsif_device->irq, tsif_device->memres->start,
tsif_device->dma, tsif_device->crci);
list_add(&tsif_device->devlist, &tsif_devices);
return 0;
/* error path */
sysfs_remove_group(&pdev->dev.kobj, &dev_attr_grp);
err_attrs:
free_irq(tsif_device->irq, tsif_device);
err_irq:
tsif_debugfs_exit(tsif_device);
tsif_stop_gpios(tsif_device);
err_gpio:
iounmap(tsif_device->base);
err_ioremap:
err_rgn:
tsif_put_clocks(tsif_device);
err_clocks:
kfree(tsif_device);
out:
return rc;
}
static int __devexit msm_tsif_remove(struct platform_device *pdev)
{
struct msm_tsif_device *tsif_device = platform_get_drvdata(pdev);
dev_info(&pdev->dev, "Unload\n");
list_del(&tsif_device->devlist);
wake_lock_destroy(&tsif_device->wake_lock);
sysfs_remove_group(&pdev->dev.kobj, &dev_attr_grp);
free_irq(tsif_device->irq, tsif_device);
tsif_debugfs_exit(tsif_device);
tsif_dma_exit(tsif_device);
tsif_stop_gpios(tsif_device);
iounmap(tsif_device->base);
tsif_put_clocks(tsif_device);
pm_runtime_put(&pdev->dev);
pm_runtime_disable(&pdev->dev);
kfree(tsif_device);
return 0;
}
static int tsif_runtime_suspend(struct device *dev)
{
dev_dbg(dev, "pm_runtime: suspending...\n");
return 0;
}
static int tsif_runtime_resume(struct device *dev)
{
dev_dbg(dev, "pm_runtime: resuming...\n");
return 0;
}
static const struct dev_pm_ops tsif_dev_pm_ops = {
.runtime_suspend = tsif_runtime_suspend,
.runtime_resume = tsif_runtime_resume,
};
static struct platform_driver msm_tsif_driver = {
.probe = msm_tsif_probe,
.remove = __exit_p(msm_tsif_remove),
.driver = {
.name = "msm_tsif",
.pm = &tsif_dev_pm_ops,
},
};
static int __init mod_init(void)
{
int rc = platform_driver_register(&msm_tsif_driver);
if (rc)
pr_err("TSIF: platform_driver_register failed: %d\n", rc);
return rc;
}
static void __exit mod_exit(void)
{
platform_driver_unregister(&msm_tsif_driver);
}
/* ===module end=== */
/* public API */
void *tsif_attach(int id, void (*notify)(void *client_data), void *data)
{
struct msm_tsif_device *tsif_device = tsif_find_by_id(id);
if (tsif_device->client_notify || tsif_device->client_data)
return ERR_PTR(-EBUSY);
tsif_device->client_notify = notify;
tsif_device->client_data = data;
/* prevent from unloading */
get_device(&tsif_device->pdev->dev);
return tsif_device;
}
EXPORT_SYMBOL(tsif_attach);
void tsif_detach(void *cookie)
{
struct msm_tsif_device *tsif_device = cookie;
tsif_device->client_notify = NULL;
tsif_device->client_data = NULL;
put_device(&tsif_device->pdev->dev);
}
EXPORT_SYMBOL(tsif_detach);
void tsif_get_info(void *cookie, void **pdata, int *psize)
{
struct msm_tsif_device *tsif_device = cookie;
if (pdata)
*pdata = tsif_device->data_buffer;
if (psize)
*psize = TSIF_PKTS_IN_BUF;
}
EXPORT_SYMBOL(tsif_get_info);
int tsif_set_mode(void *cookie, int mode)
{
struct msm_tsif_device *tsif_device = cookie;
if (tsif_device->state != tsif_state_stopped) {
dev_err(&tsif_device->pdev->dev,
"Can't change mode while device is active\n");
return -EBUSY;
}
switch (mode) {
case 1:
case 2:
case 3:
tsif_device->mode = mode;
break;
default:
dev_err(&tsif_device->pdev->dev, "Invalid mode: %d\n", mode);
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(tsif_set_mode);
int tsif_set_time_limit(void *cookie, u32 value)
{
struct msm_tsif_device *tsif_device = cookie;
if (tsif_device->state != tsif_state_stopped) {
dev_err(&tsif_device->pdev->dev,
"Can't change time limit while device is active\n");
return -EBUSY;
}
if (value != (value & 0xFFFFFF)) {
dev_err(&tsif_device->pdev->dev,
"Invalid time limit (should be 24 bit): %#x\n", value);
return -EINVAL;
}
tsif_device->time_limit = value;
return 0;
}
EXPORT_SYMBOL(tsif_set_time_limit);
int tsif_set_buf_config(void *cookie, u32 pkts_in_chunk, u32 chunks_in_buf)
{
struct msm_tsif_device *tsif_device = cookie;
if (tsif_device->data_buffer) {
dev_err(&tsif_device->pdev->dev,
"Data buffer already allocated: %p\n",
tsif_device->data_buffer);
return -EBUSY;
}
/* check for crazy user */
if (pkts_in_chunk * chunks_in_buf > 10240) {
dev_err(&tsif_device->pdev->dev,
"Buffer requested is too large: %d * %d\n",
pkts_in_chunk,
chunks_in_buf);
return -EINVAL;
}
/* parameters are OK, execute */
tsif_device->pkts_per_chunk = pkts_in_chunk;
tsif_device->chunks_per_buf = chunks_in_buf;
return 0;
}
EXPORT_SYMBOL(tsif_set_buf_config);
void tsif_get_state(void *cookie, int *ri, int *wi, enum tsif_state *state)
{
struct msm_tsif_device *tsif_device = cookie;
if (ri)
*ri = tsif_device->ri;
if (wi)
*wi = tsif_device->wi;
if (state)
*state = tsif_device->state;
}
EXPORT_SYMBOL(tsif_get_state);
int tsif_start(void *cookie)
{
struct msm_tsif_device *tsif_device = cookie;
return action_open(tsif_device);
}
EXPORT_SYMBOL(tsif_start);
void tsif_stop(void *cookie)
{
struct msm_tsif_device *tsif_device = cookie;
action_close(tsif_device);
}
EXPORT_SYMBOL(tsif_stop);
void tsif_reclaim_packets(void *cookie, int read_index)
{
struct msm_tsif_device *tsif_device = cookie;
tsif_device->ri = read_index;
}
EXPORT_SYMBOL(tsif_reclaim_packets);
module_init(mod_init);
module_exit(mod_exit);
MODULE_DESCRIPTION("TSIF (Transport Stream Interface)"
" Driver for the MSM chipset");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
0xD34D/-0xD34D--Kindle-Fire-Kernel | crypto/des_generic.c | 937 | 36209 | /*
* Cryptographic API.
*
* DES & Triple DES EDE Cipher Algorithms.
*
* Copyright (c) 2005 Dag Arne Osvik <da@osvik.no>
*
* 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 <asm/byteorder.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/crypto.h>
#include <linux/types.h>
#include <crypto/des.h>
#define ROL(x, r) ((x) = rol32((x), (r)))
#define ROR(x, r) ((x) = ror32((x), (r)))
struct des_ctx {
u32 expkey[DES_EXPKEY_WORDS];
};
struct des3_ede_ctx {
u32 expkey[DES3_EDE_EXPKEY_WORDS];
};
/* Lookup tables for key expansion */
static const u8 pc1[256] = {
0x00, 0x00, 0x40, 0x04, 0x10, 0x10, 0x50, 0x14,
0x04, 0x40, 0x44, 0x44, 0x14, 0x50, 0x54, 0x54,
0x02, 0x02, 0x42, 0x06, 0x12, 0x12, 0x52, 0x16,
0x06, 0x42, 0x46, 0x46, 0x16, 0x52, 0x56, 0x56,
0x80, 0x08, 0xc0, 0x0c, 0x90, 0x18, 0xd0, 0x1c,
0x84, 0x48, 0xc4, 0x4c, 0x94, 0x58, 0xd4, 0x5c,
0x82, 0x0a, 0xc2, 0x0e, 0x92, 0x1a, 0xd2, 0x1e,
0x86, 0x4a, 0xc6, 0x4e, 0x96, 0x5a, 0xd6, 0x5e,
0x20, 0x20, 0x60, 0x24, 0x30, 0x30, 0x70, 0x34,
0x24, 0x60, 0x64, 0x64, 0x34, 0x70, 0x74, 0x74,
0x22, 0x22, 0x62, 0x26, 0x32, 0x32, 0x72, 0x36,
0x26, 0x62, 0x66, 0x66, 0x36, 0x72, 0x76, 0x76,
0xa0, 0x28, 0xe0, 0x2c, 0xb0, 0x38, 0xf0, 0x3c,
0xa4, 0x68, 0xe4, 0x6c, 0xb4, 0x78, 0xf4, 0x7c,
0xa2, 0x2a, 0xe2, 0x2e, 0xb2, 0x3a, 0xf2, 0x3e,
0xa6, 0x6a, 0xe6, 0x6e, 0xb6, 0x7a, 0xf6, 0x7e,
0x08, 0x80, 0x48, 0x84, 0x18, 0x90, 0x58, 0x94,
0x0c, 0xc0, 0x4c, 0xc4, 0x1c, 0xd0, 0x5c, 0xd4,
0x0a, 0x82, 0x4a, 0x86, 0x1a, 0x92, 0x5a, 0x96,
0x0e, 0xc2, 0x4e, 0xc6, 0x1e, 0xd2, 0x5e, 0xd6,
0x88, 0x88, 0xc8, 0x8c, 0x98, 0x98, 0xd8, 0x9c,
0x8c, 0xc8, 0xcc, 0xcc, 0x9c, 0xd8, 0xdc, 0xdc,
0x8a, 0x8a, 0xca, 0x8e, 0x9a, 0x9a, 0xda, 0x9e,
0x8e, 0xca, 0xce, 0xce, 0x9e, 0xda, 0xde, 0xde,
0x28, 0xa0, 0x68, 0xa4, 0x38, 0xb0, 0x78, 0xb4,
0x2c, 0xe0, 0x6c, 0xe4, 0x3c, 0xf0, 0x7c, 0xf4,
0x2a, 0xa2, 0x6a, 0xa6, 0x3a, 0xb2, 0x7a, 0xb6,
0x2e, 0xe2, 0x6e, 0xe6, 0x3e, 0xf2, 0x7e, 0xf6,
0xa8, 0xa8, 0xe8, 0xac, 0xb8, 0xb8, 0xf8, 0xbc,
0xac, 0xe8, 0xec, 0xec, 0xbc, 0xf8, 0xfc, 0xfc,
0xaa, 0xaa, 0xea, 0xae, 0xba, 0xba, 0xfa, 0xbe,
0xae, 0xea, 0xee, 0xee, 0xbe, 0xfa, 0xfe, 0xfe
};
static const u8 rs[256] = {
0x00, 0x00, 0x80, 0x80, 0x02, 0x02, 0x82, 0x82,
0x04, 0x04, 0x84, 0x84, 0x06, 0x06, 0x86, 0x86,
0x08, 0x08, 0x88, 0x88, 0x0a, 0x0a, 0x8a, 0x8a,
0x0c, 0x0c, 0x8c, 0x8c, 0x0e, 0x0e, 0x8e, 0x8e,
0x10, 0x10, 0x90, 0x90, 0x12, 0x12, 0x92, 0x92,
0x14, 0x14, 0x94, 0x94, 0x16, 0x16, 0x96, 0x96,
0x18, 0x18, 0x98, 0x98, 0x1a, 0x1a, 0x9a, 0x9a,
0x1c, 0x1c, 0x9c, 0x9c, 0x1e, 0x1e, 0x9e, 0x9e,
0x20, 0x20, 0xa0, 0xa0, 0x22, 0x22, 0xa2, 0xa2,
0x24, 0x24, 0xa4, 0xa4, 0x26, 0x26, 0xa6, 0xa6,
0x28, 0x28, 0xa8, 0xa8, 0x2a, 0x2a, 0xaa, 0xaa,
0x2c, 0x2c, 0xac, 0xac, 0x2e, 0x2e, 0xae, 0xae,
0x30, 0x30, 0xb0, 0xb0, 0x32, 0x32, 0xb2, 0xb2,
0x34, 0x34, 0xb4, 0xb4, 0x36, 0x36, 0xb6, 0xb6,
0x38, 0x38, 0xb8, 0xb8, 0x3a, 0x3a, 0xba, 0xba,
0x3c, 0x3c, 0xbc, 0xbc, 0x3e, 0x3e, 0xbe, 0xbe,
0x40, 0x40, 0xc0, 0xc0, 0x42, 0x42, 0xc2, 0xc2,
0x44, 0x44, 0xc4, 0xc4, 0x46, 0x46, 0xc6, 0xc6,
0x48, 0x48, 0xc8, 0xc8, 0x4a, 0x4a, 0xca, 0xca,
0x4c, 0x4c, 0xcc, 0xcc, 0x4e, 0x4e, 0xce, 0xce,
0x50, 0x50, 0xd0, 0xd0, 0x52, 0x52, 0xd2, 0xd2,
0x54, 0x54, 0xd4, 0xd4, 0x56, 0x56, 0xd6, 0xd6,
0x58, 0x58, 0xd8, 0xd8, 0x5a, 0x5a, 0xda, 0xda,
0x5c, 0x5c, 0xdc, 0xdc, 0x5e, 0x5e, 0xde, 0xde,
0x60, 0x60, 0xe0, 0xe0, 0x62, 0x62, 0xe2, 0xe2,
0x64, 0x64, 0xe4, 0xe4, 0x66, 0x66, 0xe6, 0xe6,
0x68, 0x68, 0xe8, 0xe8, 0x6a, 0x6a, 0xea, 0xea,
0x6c, 0x6c, 0xec, 0xec, 0x6e, 0x6e, 0xee, 0xee,
0x70, 0x70, 0xf0, 0xf0, 0x72, 0x72, 0xf2, 0xf2,
0x74, 0x74, 0xf4, 0xf4, 0x76, 0x76, 0xf6, 0xf6,
0x78, 0x78, 0xf8, 0xf8, 0x7a, 0x7a, 0xfa, 0xfa,
0x7c, 0x7c, 0xfc, 0xfc, 0x7e, 0x7e, 0xfe, 0xfe
};
static const u32 pc2[1024] = {
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00040000, 0x00000000, 0x04000000, 0x00100000,
0x00400000, 0x00000008, 0x00000800, 0x40000000,
0x00440000, 0x00000008, 0x04000800, 0x40100000,
0x00000400, 0x00000020, 0x08000000, 0x00000100,
0x00040400, 0x00000020, 0x0c000000, 0x00100100,
0x00400400, 0x00000028, 0x08000800, 0x40000100,
0x00440400, 0x00000028, 0x0c000800, 0x40100100,
0x80000000, 0x00000010, 0x00000000, 0x00800000,
0x80040000, 0x00000010, 0x04000000, 0x00900000,
0x80400000, 0x00000018, 0x00000800, 0x40800000,
0x80440000, 0x00000018, 0x04000800, 0x40900000,
0x80000400, 0x00000030, 0x08000000, 0x00800100,
0x80040400, 0x00000030, 0x0c000000, 0x00900100,
0x80400400, 0x00000038, 0x08000800, 0x40800100,
0x80440400, 0x00000038, 0x0c000800, 0x40900100,
0x10000000, 0x00000000, 0x00200000, 0x00001000,
0x10040000, 0x00000000, 0x04200000, 0x00101000,
0x10400000, 0x00000008, 0x00200800, 0x40001000,
0x10440000, 0x00000008, 0x04200800, 0x40101000,
0x10000400, 0x00000020, 0x08200000, 0x00001100,
0x10040400, 0x00000020, 0x0c200000, 0x00101100,
0x10400400, 0x00000028, 0x08200800, 0x40001100,
0x10440400, 0x00000028, 0x0c200800, 0x40101100,
0x90000000, 0x00000010, 0x00200000, 0x00801000,
0x90040000, 0x00000010, 0x04200000, 0x00901000,
0x90400000, 0x00000018, 0x00200800, 0x40801000,
0x90440000, 0x00000018, 0x04200800, 0x40901000,
0x90000400, 0x00000030, 0x08200000, 0x00801100,
0x90040400, 0x00000030, 0x0c200000, 0x00901100,
0x90400400, 0x00000038, 0x08200800, 0x40801100,
0x90440400, 0x00000038, 0x0c200800, 0x40901100,
0x00000200, 0x00080000, 0x00000000, 0x00000004,
0x00040200, 0x00080000, 0x04000000, 0x00100004,
0x00400200, 0x00080008, 0x00000800, 0x40000004,
0x00440200, 0x00080008, 0x04000800, 0x40100004,
0x00000600, 0x00080020, 0x08000000, 0x00000104,
0x00040600, 0x00080020, 0x0c000000, 0x00100104,
0x00400600, 0x00080028, 0x08000800, 0x40000104,
0x00440600, 0x00080028, 0x0c000800, 0x40100104,
0x80000200, 0x00080010, 0x00000000, 0x00800004,
0x80040200, 0x00080010, 0x04000000, 0x00900004,
0x80400200, 0x00080018, 0x00000800, 0x40800004,
0x80440200, 0x00080018, 0x04000800, 0x40900004,
0x80000600, 0x00080030, 0x08000000, 0x00800104,
0x80040600, 0x00080030, 0x0c000000, 0x00900104,
0x80400600, 0x00080038, 0x08000800, 0x40800104,
0x80440600, 0x00080038, 0x0c000800, 0x40900104,
0x10000200, 0x00080000, 0x00200000, 0x00001004,
0x10040200, 0x00080000, 0x04200000, 0x00101004,
0x10400200, 0x00080008, 0x00200800, 0x40001004,
0x10440200, 0x00080008, 0x04200800, 0x40101004,
0x10000600, 0x00080020, 0x08200000, 0x00001104,
0x10040600, 0x00080020, 0x0c200000, 0x00101104,
0x10400600, 0x00080028, 0x08200800, 0x40001104,
0x10440600, 0x00080028, 0x0c200800, 0x40101104,
0x90000200, 0x00080010, 0x00200000, 0x00801004,
0x90040200, 0x00080010, 0x04200000, 0x00901004,
0x90400200, 0x00080018, 0x00200800, 0x40801004,
0x90440200, 0x00080018, 0x04200800, 0x40901004,
0x90000600, 0x00080030, 0x08200000, 0x00801104,
0x90040600, 0x00080030, 0x0c200000, 0x00901104,
0x90400600, 0x00080038, 0x08200800, 0x40801104,
0x90440600, 0x00080038, 0x0c200800, 0x40901104,
0x00000002, 0x00002000, 0x20000000, 0x00000001,
0x00040002, 0x00002000, 0x24000000, 0x00100001,
0x00400002, 0x00002008, 0x20000800, 0x40000001,
0x00440002, 0x00002008, 0x24000800, 0x40100001,
0x00000402, 0x00002020, 0x28000000, 0x00000101,
0x00040402, 0x00002020, 0x2c000000, 0x00100101,
0x00400402, 0x00002028, 0x28000800, 0x40000101,
0x00440402, 0x00002028, 0x2c000800, 0x40100101,
0x80000002, 0x00002010, 0x20000000, 0x00800001,
0x80040002, 0x00002010, 0x24000000, 0x00900001,
0x80400002, 0x00002018, 0x20000800, 0x40800001,
0x80440002, 0x00002018, 0x24000800, 0x40900001,
0x80000402, 0x00002030, 0x28000000, 0x00800101,
0x80040402, 0x00002030, 0x2c000000, 0x00900101,
0x80400402, 0x00002038, 0x28000800, 0x40800101,
0x80440402, 0x00002038, 0x2c000800, 0x40900101,
0x10000002, 0x00002000, 0x20200000, 0x00001001,
0x10040002, 0x00002000, 0x24200000, 0x00101001,
0x10400002, 0x00002008, 0x20200800, 0x40001001,
0x10440002, 0x00002008, 0x24200800, 0x40101001,
0x10000402, 0x00002020, 0x28200000, 0x00001101,
0x10040402, 0x00002020, 0x2c200000, 0x00101101,
0x10400402, 0x00002028, 0x28200800, 0x40001101,
0x10440402, 0x00002028, 0x2c200800, 0x40101101,
0x90000002, 0x00002010, 0x20200000, 0x00801001,
0x90040002, 0x00002010, 0x24200000, 0x00901001,
0x90400002, 0x00002018, 0x20200800, 0x40801001,
0x90440002, 0x00002018, 0x24200800, 0x40901001,
0x90000402, 0x00002030, 0x28200000, 0x00801101,
0x90040402, 0x00002030, 0x2c200000, 0x00901101,
0x90400402, 0x00002038, 0x28200800, 0x40801101,
0x90440402, 0x00002038, 0x2c200800, 0x40901101,
0x00000202, 0x00082000, 0x20000000, 0x00000005,
0x00040202, 0x00082000, 0x24000000, 0x00100005,
0x00400202, 0x00082008, 0x20000800, 0x40000005,
0x00440202, 0x00082008, 0x24000800, 0x40100005,
0x00000602, 0x00082020, 0x28000000, 0x00000105,
0x00040602, 0x00082020, 0x2c000000, 0x00100105,
0x00400602, 0x00082028, 0x28000800, 0x40000105,
0x00440602, 0x00082028, 0x2c000800, 0x40100105,
0x80000202, 0x00082010, 0x20000000, 0x00800005,
0x80040202, 0x00082010, 0x24000000, 0x00900005,
0x80400202, 0x00082018, 0x20000800, 0x40800005,
0x80440202, 0x00082018, 0x24000800, 0x40900005,
0x80000602, 0x00082030, 0x28000000, 0x00800105,
0x80040602, 0x00082030, 0x2c000000, 0x00900105,
0x80400602, 0x00082038, 0x28000800, 0x40800105,
0x80440602, 0x00082038, 0x2c000800, 0x40900105,
0x10000202, 0x00082000, 0x20200000, 0x00001005,
0x10040202, 0x00082000, 0x24200000, 0x00101005,
0x10400202, 0x00082008, 0x20200800, 0x40001005,
0x10440202, 0x00082008, 0x24200800, 0x40101005,
0x10000602, 0x00082020, 0x28200000, 0x00001105,
0x10040602, 0x00082020, 0x2c200000, 0x00101105,
0x10400602, 0x00082028, 0x28200800, 0x40001105,
0x10440602, 0x00082028, 0x2c200800, 0x40101105,
0x90000202, 0x00082010, 0x20200000, 0x00801005,
0x90040202, 0x00082010, 0x24200000, 0x00901005,
0x90400202, 0x00082018, 0x20200800, 0x40801005,
0x90440202, 0x00082018, 0x24200800, 0x40901005,
0x90000602, 0x00082030, 0x28200000, 0x00801105,
0x90040602, 0x00082030, 0x2c200000, 0x00901105,
0x90400602, 0x00082038, 0x28200800, 0x40801105,
0x90440602, 0x00082038, 0x2c200800, 0x40901105,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000008, 0x00080000, 0x10000000,
0x02000000, 0x00000000, 0x00000080, 0x00001000,
0x02000000, 0x00000008, 0x00080080, 0x10001000,
0x00004000, 0x00000000, 0x00000040, 0x00040000,
0x00004000, 0x00000008, 0x00080040, 0x10040000,
0x02004000, 0x00000000, 0x000000c0, 0x00041000,
0x02004000, 0x00000008, 0x000800c0, 0x10041000,
0x00020000, 0x00008000, 0x08000000, 0x00200000,
0x00020000, 0x00008008, 0x08080000, 0x10200000,
0x02020000, 0x00008000, 0x08000080, 0x00201000,
0x02020000, 0x00008008, 0x08080080, 0x10201000,
0x00024000, 0x00008000, 0x08000040, 0x00240000,
0x00024000, 0x00008008, 0x08080040, 0x10240000,
0x02024000, 0x00008000, 0x080000c0, 0x00241000,
0x02024000, 0x00008008, 0x080800c0, 0x10241000,
0x00000000, 0x01000000, 0x00002000, 0x00000020,
0x00000000, 0x01000008, 0x00082000, 0x10000020,
0x02000000, 0x01000000, 0x00002080, 0x00001020,
0x02000000, 0x01000008, 0x00082080, 0x10001020,
0x00004000, 0x01000000, 0x00002040, 0x00040020,
0x00004000, 0x01000008, 0x00082040, 0x10040020,
0x02004000, 0x01000000, 0x000020c0, 0x00041020,
0x02004000, 0x01000008, 0x000820c0, 0x10041020,
0x00020000, 0x01008000, 0x08002000, 0x00200020,
0x00020000, 0x01008008, 0x08082000, 0x10200020,
0x02020000, 0x01008000, 0x08002080, 0x00201020,
0x02020000, 0x01008008, 0x08082080, 0x10201020,
0x00024000, 0x01008000, 0x08002040, 0x00240020,
0x00024000, 0x01008008, 0x08082040, 0x10240020,
0x02024000, 0x01008000, 0x080020c0, 0x00241020,
0x02024000, 0x01008008, 0x080820c0, 0x10241020,
0x00000400, 0x04000000, 0x00100000, 0x00000004,
0x00000400, 0x04000008, 0x00180000, 0x10000004,
0x02000400, 0x04000000, 0x00100080, 0x00001004,
0x02000400, 0x04000008, 0x00180080, 0x10001004,
0x00004400, 0x04000000, 0x00100040, 0x00040004,
0x00004400, 0x04000008, 0x00180040, 0x10040004,
0x02004400, 0x04000000, 0x001000c0, 0x00041004,
0x02004400, 0x04000008, 0x001800c0, 0x10041004,
0x00020400, 0x04008000, 0x08100000, 0x00200004,
0x00020400, 0x04008008, 0x08180000, 0x10200004,
0x02020400, 0x04008000, 0x08100080, 0x00201004,
0x02020400, 0x04008008, 0x08180080, 0x10201004,
0x00024400, 0x04008000, 0x08100040, 0x00240004,
0x00024400, 0x04008008, 0x08180040, 0x10240004,
0x02024400, 0x04008000, 0x081000c0, 0x00241004,
0x02024400, 0x04008008, 0x081800c0, 0x10241004,
0x00000400, 0x05000000, 0x00102000, 0x00000024,
0x00000400, 0x05000008, 0x00182000, 0x10000024,
0x02000400, 0x05000000, 0x00102080, 0x00001024,
0x02000400, 0x05000008, 0x00182080, 0x10001024,
0x00004400, 0x05000000, 0x00102040, 0x00040024,
0x00004400, 0x05000008, 0x00182040, 0x10040024,
0x02004400, 0x05000000, 0x001020c0, 0x00041024,
0x02004400, 0x05000008, 0x001820c0, 0x10041024,
0x00020400, 0x05008000, 0x08102000, 0x00200024,
0x00020400, 0x05008008, 0x08182000, 0x10200024,
0x02020400, 0x05008000, 0x08102080, 0x00201024,
0x02020400, 0x05008008, 0x08182080, 0x10201024,
0x00024400, 0x05008000, 0x08102040, 0x00240024,
0x00024400, 0x05008008, 0x08182040, 0x10240024,
0x02024400, 0x05008000, 0x081020c0, 0x00241024,
0x02024400, 0x05008008, 0x081820c0, 0x10241024,
0x00000800, 0x00010000, 0x20000000, 0x00000010,
0x00000800, 0x00010008, 0x20080000, 0x10000010,
0x02000800, 0x00010000, 0x20000080, 0x00001010,
0x02000800, 0x00010008, 0x20080080, 0x10001010,
0x00004800, 0x00010000, 0x20000040, 0x00040010,
0x00004800, 0x00010008, 0x20080040, 0x10040010,
0x02004800, 0x00010000, 0x200000c0, 0x00041010,
0x02004800, 0x00010008, 0x200800c0, 0x10041010,
0x00020800, 0x00018000, 0x28000000, 0x00200010,
0x00020800, 0x00018008, 0x28080000, 0x10200010,
0x02020800, 0x00018000, 0x28000080, 0x00201010,
0x02020800, 0x00018008, 0x28080080, 0x10201010,
0x00024800, 0x00018000, 0x28000040, 0x00240010,
0x00024800, 0x00018008, 0x28080040, 0x10240010,
0x02024800, 0x00018000, 0x280000c0, 0x00241010,
0x02024800, 0x00018008, 0x280800c0, 0x10241010,
0x00000800, 0x01010000, 0x20002000, 0x00000030,
0x00000800, 0x01010008, 0x20082000, 0x10000030,
0x02000800, 0x01010000, 0x20002080, 0x00001030,
0x02000800, 0x01010008, 0x20082080, 0x10001030,
0x00004800, 0x01010000, 0x20002040, 0x00040030,
0x00004800, 0x01010008, 0x20082040, 0x10040030,
0x02004800, 0x01010000, 0x200020c0, 0x00041030,
0x02004800, 0x01010008, 0x200820c0, 0x10041030,
0x00020800, 0x01018000, 0x28002000, 0x00200030,
0x00020800, 0x01018008, 0x28082000, 0x10200030,
0x02020800, 0x01018000, 0x28002080, 0x00201030,
0x02020800, 0x01018008, 0x28082080, 0x10201030,
0x00024800, 0x01018000, 0x28002040, 0x00240030,
0x00024800, 0x01018008, 0x28082040, 0x10240030,
0x02024800, 0x01018000, 0x280020c0, 0x00241030,
0x02024800, 0x01018008, 0x280820c0, 0x10241030,
0x00000c00, 0x04010000, 0x20100000, 0x00000014,
0x00000c00, 0x04010008, 0x20180000, 0x10000014,
0x02000c00, 0x04010000, 0x20100080, 0x00001014,
0x02000c00, 0x04010008, 0x20180080, 0x10001014,
0x00004c00, 0x04010000, 0x20100040, 0x00040014,
0x00004c00, 0x04010008, 0x20180040, 0x10040014,
0x02004c00, 0x04010000, 0x201000c0, 0x00041014,
0x02004c00, 0x04010008, 0x201800c0, 0x10041014,
0x00020c00, 0x04018000, 0x28100000, 0x00200014,
0x00020c00, 0x04018008, 0x28180000, 0x10200014,
0x02020c00, 0x04018000, 0x28100080, 0x00201014,
0x02020c00, 0x04018008, 0x28180080, 0x10201014,
0x00024c00, 0x04018000, 0x28100040, 0x00240014,
0x00024c00, 0x04018008, 0x28180040, 0x10240014,
0x02024c00, 0x04018000, 0x281000c0, 0x00241014,
0x02024c00, 0x04018008, 0x281800c0, 0x10241014,
0x00000c00, 0x05010000, 0x20102000, 0x00000034,
0x00000c00, 0x05010008, 0x20182000, 0x10000034,
0x02000c00, 0x05010000, 0x20102080, 0x00001034,
0x02000c00, 0x05010008, 0x20182080, 0x10001034,
0x00004c00, 0x05010000, 0x20102040, 0x00040034,
0x00004c00, 0x05010008, 0x20182040, 0x10040034,
0x02004c00, 0x05010000, 0x201020c0, 0x00041034,
0x02004c00, 0x05010008, 0x201820c0, 0x10041034,
0x00020c00, 0x05018000, 0x28102000, 0x00200034,
0x00020c00, 0x05018008, 0x28182000, 0x10200034,
0x02020c00, 0x05018000, 0x28102080, 0x00201034,
0x02020c00, 0x05018008, 0x28182080, 0x10201034,
0x00024c00, 0x05018000, 0x28102040, 0x00240034,
0x00024c00, 0x05018008, 0x28182040, 0x10240034,
0x02024c00, 0x05018000, 0x281020c0, 0x00241034,
0x02024c00, 0x05018008, 0x281820c0, 0x10241034
};
/* S-box lookup tables */
static const u32 S1[64] = {
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
static const u32 S2[64] = {
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
static const u32 S3[64] = {
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
static const u32 S4[64] = {
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
static const u32 S5[64] = {
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
static const u32 S6[64] = {
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
static const u32 S7[64] = {
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
static const u32 S8[64] = {
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/* Encryption components: IP, FP, and round function */
#define IP(L, R, T) \
ROL(R, 4); \
T = L; \
L ^= R; \
L &= 0xf0f0f0f0; \
R ^= L; \
L ^= T; \
ROL(R, 12); \
T = L; \
L ^= R; \
L &= 0xffff0000; \
R ^= L; \
L ^= T; \
ROR(R, 14); \
T = L; \
L ^= R; \
L &= 0xcccccccc; \
R ^= L; \
L ^= T; \
ROL(R, 6); \
T = L; \
L ^= R; \
L &= 0xff00ff00; \
R ^= L; \
L ^= T; \
ROR(R, 7); \
T = L; \
L ^= R; \
L &= 0xaaaaaaaa; \
R ^= L; \
L ^= T; \
ROL(L, 1);
#define FP(L, R, T) \
ROR(L, 1); \
T = L; \
L ^= R; \
L &= 0xaaaaaaaa; \
R ^= L; \
L ^= T; \
ROL(R, 7); \
T = L; \
L ^= R; \
L &= 0xff00ff00; \
R ^= L; \
L ^= T; \
ROR(R, 6); \
T = L; \
L ^= R; \
L &= 0xcccccccc; \
R ^= L; \
L ^= T; \
ROL(R, 14); \
T = L; \
L ^= R; \
L &= 0xffff0000; \
R ^= L; \
L ^= T; \
ROR(R, 12); \
T = L; \
L ^= R; \
L &= 0xf0f0f0f0; \
R ^= L; \
L ^= T; \
ROR(R, 4);
#define ROUND(L, R, A, B, K, d) \
B = K[0]; A = K[1]; K += d; \
B ^= R; A ^= R; \
B &= 0x3f3f3f3f; ROR(A, 4); \
L ^= S8[0xff & B]; A &= 0x3f3f3f3f; \
L ^= S6[0xff & (B >> 8)]; B >>= 16; \
L ^= S7[0xff & A]; \
L ^= S5[0xff & (A >> 8)]; A >>= 16; \
L ^= S4[0xff & B]; \
L ^= S2[0xff & (B >> 8)]; \
L ^= S3[0xff & A]; \
L ^= S1[0xff & (A >> 8)];
/*
* PC2 lookup tables are organized as 2 consecutive sets of 4 interleaved
* tables of 128 elements. One set is for C_i and the other for D_i, while
* the 4 interleaved tables correspond to four 7-bit subsets of C_i or D_i.
*
* After PC1 each of the variables a,b,c,d contains a 7 bit subset of C_i
* or D_i in bits 7-1 (bit 0 being the least significant).
*/
#define T1(x) pt[2 * (x) + 0]
#define T2(x) pt[2 * (x) + 1]
#define T3(x) pt[2 * (x) + 2]
#define T4(x) pt[2 * (x) + 3]
#define PC2(a, b, c, d) (T4(d) | T3(c) | T2(b) | T1(a))
/*
* Encryption key expansion
*
* RFC2451: Weak key checks SHOULD be performed.
*
* FIPS 74:
*
* Keys having duals are keys which produce all zeros, all ones, or
* alternating zero-one patterns in the C and D registers after Permuted
* Choice 1 has operated on the key.
*
*/
unsigned long des_ekey(u32 *pe, const u8 *k)
{
/* K&R: long is at least 32 bits */
unsigned long a, b, c, d, w;
const u32 *pt = pc2;
d = k[4]; d &= 0x0e; d <<= 4; d |= k[0] & 0x1e; d = pc1[d];
c = k[5]; c &= 0x0e; c <<= 4; c |= k[1] & 0x1e; c = pc1[c];
b = k[6]; b &= 0x0e; b <<= 4; b |= k[2] & 0x1e; b = pc1[b];
a = k[7]; a &= 0x0e; a <<= 4; a |= k[3] & 0x1e; a = pc1[a];
pe[15 * 2 + 0] = PC2(a, b, c, d); d = rs[d];
pe[14 * 2 + 0] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[13 * 2 + 0] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[12 * 2 + 0] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[11 * 2 + 0] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[10 * 2 + 0] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 9 * 2 + 0] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 8 * 2 + 0] = PC2(d, a, b, c); c = rs[c];
pe[ 7 * 2 + 0] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 6 * 2 + 0] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[ 5 * 2 + 0] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 4 * 2 + 0] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[ 3 * 2 + 0] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 2 * 2 + 0] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[ 1 * 2 + 0] = PC2(c, d, a, b); b = rs[b];
pe[ 0 * 2 + 0] = PC2(b, c, d, a);
/* Check if first half is weak */
w = (a ^ c) | (b ^ d) | (rs[a] ^ c) | (b ^ rs[d]);
/* Skip to next table set */
pt += 512;
d = k[0]; d &= 0xe0; d >>= 4; d |= k[4] & 0xf0; d = pc1[d + 1];
c = k[1]; c &= 0xe0; c >>= 4; c |= k[5] & 0xf0; c = pc1[c + 1];
b = k[2]; b &= 0xe0; b >>= 4; b |= k[6] & 0xf0; b = pc1[b + 1];
a = k[3]; a &= 0xe0; a >>= 4; a |= k[7] & 0xf0; a = pc1[a + 1];
/* Check if second half is weak */
w |= (a ^ c) | (b ^ d) | (rs[a] ^ c) | (b ^ rs[d]);
pe[15 * 2 + 1] = PC2(a, b, c, d); d = rs[d];
pe[14 * 2 + 1] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[13 * 2 + 1] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[12 * 2 + 1] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[11 * 2 + 1] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[10 * 2 + 1] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 9 * 2 + 1] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 8 * 2 + 1] = PC2(d, a, b, c); c = rs[c];
pe[ 7 * 2 + 1] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 6 * 2 + 1] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[ 5 * 2 + 1] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 4 * 2 + 1] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[ 3 * 2 + 1] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 2 * 2 + 1] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[ 1 * 2 + 1] = PC2(c, d, a, b); b = rs[b];
pe[ 0 * 2 + 1] = PC2(b, c, d, a);
/* Fixup: 2413 5768 -> 1357 2468 */
for (d = 0; d < 16; ++d) {
a = pe[2 * d];
b = pe[2 * d + 1];
c = a ^ b;
c &= 0xffff0000;
a ^= c;
b ^= c;
ROL(b, 18);
pe[2 * d] = a;
pe[2 * d + 1] = b;
}
/* Zero if weak key */
return w;
}
EXPORT_SYMBOL_GPL(des_ekey);
/*
* Decryption key expansion
*
* No weak key checking is performed, as this is only used by triple DES
*
*/
static void dkey(u32 *pe, const u8 *k)
{
/* K&R: long is at least 32 bits */
unsigned long a, b, c, d;
const u32 *pt = pc2;
d = k[4]; d &= 0x0e; d <<= 4; d |= k[0] & 0x1e; d = pc1[d];
c = k[5]; c &= 0x0e; c <<= 4; c |= k[1] & 0x1e; c = pc1[c];
b = k[6]; b &= 0x0e; b <<= 4; b |= k[2] & 0x1e; b = pc1[b];
a = k[7]; a &= 0x0e; a <<= 4; a |= k[3] & 0x1e; a = pc1[a];
pe[ 0 * 2] = PC2(a, b, c, d); d = rs[d];
pe[ 1 * 2] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 2 * 2] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 3 * 2] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 4 * 2] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 5 * 2] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 6 * 2] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 7 * 2] = PC2(d, a, b, c); c = rs[c];
pe[ 8 * 2] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 9 * 2] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[10 * 2] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[11 * 2] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[12 * 2] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[13 * 2] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[14 * 2] = PC2(c, d, a, b); b = rs[b];
pe[15 * 2] = PC2(b, c, d, a);
/* Skip to next table set */
pt += 512;
d = k[0]; d &= 0xe0; d >>= 4; d |= k[4] & 0xf0; d = pc1[d + 1];
c = k[1]; c &= 0xe0; c >>= 4; c |= k[5] & 0xf0; c = pc1[c + 1];
b = k[2]; b &= 0xe0; b >>= 4; b |= k[6] & 0xf0; b = pc1[b + 1];
a = k[3]; a &= 0xe0; a >>= 4; a |= k[7] & 0xf0; a = pc1[a + 1];
pe[ 0 * 2 + 1] = PC2(a, b, c, d); d = rs[d];
pe[ 1 * 2 + 1] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 2 * 2 + 1] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 3 * 2 + 1] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 4 * 2 + 1] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 5 * 2 + 1] = PC2(d, a, b, c); c = rs[c]; b = rs[b];
pe[ 6 * 2 + 1] = PC2(b, c, d, a); a = rs[a]; d = rs[d];
pe[ 7 * 2 + 1] = PC2(d, a, b, c); c = rs[c];
pe[ 8 * 2 + 1] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[ 9 * 2 + 1] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[10 * 2 + 1] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[11 * 2 + 1] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[12 * 2 + 1] = PC2(c, d, a, b); b = rs[b]; a = rs[a];
pe[13 * 2 + 1] = PC2(a, b, c, d); d = rs[d]; c = rs[c];
pe[14 * 2 + 1] = PC2(c, d, a, b); b = rs[b];
pe[15 * 2 + 1] = PC2(b, c, d, a);
/* Fixup: 2413 5768 -> 1357 2468 */
for (d = 0; d < 16; ++d) {
a = pe[2 * d];
b = pe[2 * d + 1];
c = a ^ b;
c &= 0xffff0000;
a ^= c;
b ^= c;
ROL(b, 18);
pe[2 * d] = a;
pe[2 * d + 1] = b;
}
}
static int des_setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keylen)
{
struct des_ctx *dctx = crypto_tfm_ctx(tfm);
u32 *flags = &tfm->crt_flags;
u32 tmp[DES_EXPKEY_WORDS];
int ret;
/* Expand to tmp */
ret = des_ekey(tmp, key);
if (unlikely(ret == 0) && (*flags & CRYPTO_TFM_REQ_WEAK_KEY)) {
*flags |= CRYPTO_TFM_RES_WEAK_KEY;
return -EINVAL;
}
/* Copy to output */
memcpy(dctx->expkey, tmp, sizeof(dctx->expkey));
return 0;
}
static void des_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct des_ctx *ctx = crypto_tfm_ctx(tfm);
const u32 *K = ctx->expkey;
const __le32 *s = (const __le32 *)src;
__le32 *d = (__le32 *)dst;
u32 L, R, A, B;
int i;
L = le32_to_cpu(s[0]);
R = le32_to_cpu(s[1]);
IP(L, R, A);
for (i = 0; i < 8; i++) {
ROUND(L, R, A, B, K, 2);
ROUND(R, L, A, B, K, 2);
}
FP(R, L, A);
d[0] = cpu_to_le32(R);
d[1] = cpu_to_le32(L);
}
static void des_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct des_ctx *ctx = crypto_tfm_ctx(tfm);
const u32 *K = ctx->expkey + DES_EXPKEY_WORDS - 2;
const __le32 *s = (const __le32 *)src;
__le32 *d = (__le32 *)dst;
u32 L, R, A, B;
int i;
L = le32_to_cpu(s[0]);
R = le32_to_cpu(s[1]);
IP(L, R, A);
for (i = 0; i < 8; i++) {
ROUND(L, R, A, B, K, -2);
ROUND(R, L, A, B, K, -2);
}
FP(R, L, A);
d[0] = cpu_to_le32(R);
d[1] = cpu_to_le32(L);
}
/*
* RFC2451:
*
* For DES-EDE3, there is no known need to reject weak or
* complementation keys. Any weakness is obviated by the use of
* multiple keys.
*
* However, if the first two or last two independent 64-bit keys are
* equal (k1 == k2 or k2 == k3), then the DES3 operation is simply the
* same as DES. Implementers MUST reject keys that exhibit this
* property.
*
*/
static int des3_ede_setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keylen)
{
const u32 *K = (const u32 *)key;
struct des3_ede_ctx *dctx = crypto_tfm_ctx(tfm);
u32 *expkey = dctx->expkey;
u32 *flags = &tfm->crt_flags;
if (unlikely(!((K[0] ^ K[2]) | (K[1] ^ K[3])) ||
!((K[2] ^ K[4]) | (K[3] ^ K[5]))) &&
(*flags & CRYPTO_TFM_REQ_WEAK_KEY)) {
*flags |= CRYPTO_TFM_RES_WEAK_KEY;
return -EINVAL;
}
des_ekey(expkey, key); expkey += DES_EXPKEY_WORDS; key += DES_KEY_SIZE;
dkey(expkey, key); expkey += DES_EXPKEY_WORDS; key += DES_KEY_SIZE;
des_ekey(expkey, key);
return 0;
}
static void des3_ede_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct des3_ede_ctx *dctx = crypto_tfm_ctx(tfm);
const u32 *K = dctx->expkey;
const __le32 *s = (const __le32 *)src;
__le32 *d = (__le32 *)dst;
u32 L, R, A, B;
int i;
L = le32_to_cpu(s[0]);
R = le32_to_cpu(s[1]);
IP(L, R, A);
for (i = 0; i < 8; i++) {
ROUND(L, R, A, B, K, 2);
ROUND(R, L, A, B, K, 2);
}
for (i = 0; i < 8; i++) {
ROUND(R, L, A, B, K, 2);
ROUND(L, R, A, B, K, 2);
}
for (i = 0; i < 8; i++) {
ROUND(L, R, A, B, K, 2);
ROUND(R, L, A, B, K, 2);
}
FP(R, L, A);
d[0] = cpu_to_le32(R);
d[1] = cpu_to_le32(L);
}
static void des3_ede_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct des3_ede_ctx *dctx = crypto_tfm_ctx(tfm);
const u32 *K = dctx->expkey + DES3_EDE_EXPKEY_WORDS - 2;
const __le32 *s = (const __le32 *)src;
__le32 *d = (__le32 *)dst;
u32 L, R, A, B;
int i;
L = le32_to_cpu(s[0]);
R = le32_to_cpu(s[1]);
IP(L, R, A);
for (i = 0; i < 8; i++) {
ROUND(L, R, A, B, K, -2);
ROUND(R, L, A, B, K, -2);
}
for (i = 0; i < 8; i++) {
ROUND(R, L, A, B, K, -2);
ROUND(L, R, A, B, K, -2);
}
for (i = 0; i < 8; i++) {
ROUND(L, R, A, B, K, -2);
ROUND(R, L, A, B, K, -2);
}
FP(R, L, A);
d[0] = cpu_to_le32(R);
d[1] = cpu_to_le32(L);
}
static struct crypto_alg des_alg = {
.cra_name = "des",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct des_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_list = LIST_HEAD_INIT(des_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = DES_KEY_SIZE,
.cia_max_keysize = DES_KEY_SIZE,
.cia_setkey = des_setkey,
.cia_encrypt = des_encrypt,
.cia_decrypt = des_decrypt } }
};
static struct crypto_alg des3_ede_alg = {
.cra_name = "des3_ede",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct des3_ede_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_list = LIST_HEAD_INIT(des3_ede_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = DES3_EDE_KEY_SIZE,
.cia_max_keysize = DES3_EDE_KEY_SIZE,
.cia_setkey = des3_ede_setkey,
.cia_encrypt = des3_ede_encrypt,
.cia_decrypt = des3_ede_decrypt } }
};
MODULE_ALIAS("des3_ede");
static int __init des_generic_mod_init(void)
{
int ret = 0;
ret = crypto_register_alg(&des_alg);
if (ret < 0)
goto out;
ret = crypto_register_alg(&des3_ede_alg);
if (ret < 0)
crypto_unregister_alg(&des_alg);
out:
return ret;
}
static void __exit des_generic_mod_fini(void)
{
crypto_unregister_alg(&des3_ede_alg);
crypto_unregister_alg(&des_alg);
}
module_init(des_generic_mod_init);
module_exit(des_generic_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("DES & Triple DES EDE Cipher Algorithms");
MODULE_AUTHOR("Dag Arne Osvik <da@osvik.no>");
MODULE_ALIAS("des");
| gpl-2.0 |
wow73611/smdk6410-linux-3.18.14 | fs/btrfs/tests/extent-buffer-tests.c | 937 | 5890 | /*
* Copyright (C) 2013 Fusion IO. 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/slab.h>
#include "btrfs-tests.h"
#include "../ctree.h"
#include "../extent_io.h"
#include "../disk-io.h"
static int test_btrfs_split_item(void)
{
struct btrfs_path *path;
struct btrfs_root *root;
struct extent_buffer *eb;
struct btrfs_item *item;
char *value = "mary had a little lamb";
char *split1 = "mary had a little";
char *split2 = " lamb";
char *split3 = "mary";
char *split4 = " had a little";
char buf[32];
struct btrfs_key key;
u32 value_len = strlen(value);
int ret = 0;
test_msg("Running btrfs_split_item tests\n");
root = btrfs_alloc_dummy_root();
if (IS_ERR(root)) {
test_msg("Could not allocate root\n");
return PTR_ERR(root);
}
path = btrfs_alloc_path();
if (!path) {
test_msg("Could not allocate path\n");
kfree(root);
return -ENOMEM;
}
path->nodes[0] = eb = alloc_dummy_extent_buffer(0, 4096);
if (!eb) {
test_msg("Could not allocate dummy buffer\n");
ret = -ENOMEM;
goto out;
}
path->slots[0] = 0;
key.objectid = 0;
key.type = BTRFS_EXTENT_CSUM_KEY;
key.offset = 0;
setup_items_for_insert(root, path, &key, &value_len, value_len,
value_len + sizeof(struct btrfs_item), 1);
item = btrfs_item_nr(0);
write_extent_buffer(eb, value, btrfs_item_ptr_offset(eb, 0),
value_len);
key.offset = 3;
/*
* Passing NULL trans here should be safe because we have plenty of
* space in this leaf to split the item without having to split the
* leaf.
*/
ret = btrfs_split_item(NULL, root, path, &key, 17);
if (ret) {
test_msg("Split item failed %d\n", ret);
goto out;
}
/*
* Read the first slot, it should have the original key and contain only
* 'mary had a little'
*/
btrfs_item_key_to_cpu(eb, &key, 0);
if (key.objectid != 0 || key.type != BTRFS_EXTENT_CSUM_KEY ||
key.offset != 0) {
test_msg("Invalid key at slot 0\n");
ret = -EINVAL;
goto out;
}
item = btrfs_item_nr(0);
if (btrfs_item_size(eb, item) != strlen(split1)) {
test_msg("Invalid len in the first split\n");
ret = -EINVAL;
goto out;
}
read_extent_buffer(eb, buf, btrfs_item_ptr_offset(eb, 0),
strlen(split1));
if (memcmp(buf, split1, strlen(split1))) {
test_msg("Data in the buffer doesn't match what it should "
"in the first split have='%.*s' want '%s'\n",
(int)strlen(split1), buf, split1);
ret = -EINVAL;
goto out;
}
btrfs_item_key_to_cpu(eb, &key, 1);
if (key.objectid != 0 || key.type != BTRFS_EXTENT_CSUM_KEY ||
key.offset != 3) {
test_msg("Invalid key at slot 1\n");
ret = -EINVAL;
goto out;
}
item = btrfs_item_nr(1);
if (btrfs_item_size(eb, item) != strlen(split2)) {
test_msg("Invalid len in the second split\n");
ret = -EINVAL;
goto out;
}
read_extent_buffer(eb, buf, btrfs_item_ptr_offset(eb, 1),
strlen(split2));
if (memcmp(buf, split2, strlen(split2))) {
test_msg("Data in the buffer doesn't match what it should "
"in the second split\n");
ret = -EINVAL;
goto out;
}
key.offset = 1;
/* Do it again so we test memmoving the other items in the leaf */
ret = btrfs_split_item(NULL, root, path, &key, 4);
if (ret) {
test_msg("Second split item failed %d\n", ret);
goto out;
}
btrfs_item_key_to_cpu(eb, &key, 0);
if (key.objectid != 0 || key.type != BTRFS_EXTENT_CSUM_KEY ||
key.offset != 0) {
test_msg("Invalid key at slot 0\n");
ret = -EINVAL;
goto out;
}
item = btrfs_item_nr(0);
if (btrfs_item_size(eb, item) != strlen(split3)) {
test_msg("Invalid len in the first split\n");
ret = -EINVAL;
goto out;
}
read_extent_buffer(eb, buf, btrfs_item_ptr_offset(eb, 0),
strlen(split3));
if (memcmp(buf, split3, strlen(split3))) {
test_msg("Data in the buffer doesn't match what it should "
"in the third split");
ret = -EINVAL;
goto out;
}
btrfs_item_key_to_cpu(eb, &key, 1);
if (key.objectid != 0 || key.type != BTRFS_EXTENT_CSUM_KEY ||
key.offset != 1) {
test_msg("Invalid key at slot 1\n");
ret = -EINVAL;
goto out;
}
item = btrfs_item_nr(1);
if (btrfs_item_size(eb, item) != strlen(split4)) {
test_msg("Invalid len in the second split\n");
ret = -EINVAL;
goto out;
}
read_extent_buffer(eb, buf, btrfs_item_ptr_offset(eb, 1),
strlen(split4));
if (memcmp(buf, split4, strlen(split4))) {
test_msg("Data in the buffer doesn't match what it should "
"in the fourth split\n");
ret = -EINVAL;
goto out;
}
btrfs_item_key_to_cpu(eb, &key, 2);
if (key.objectid != 0 || key.type != BTRFS_EXTENT_CSUM_KEY ||
key.offset != 3) {
test_msg("Invalid key at slot 2\n");
ret = -EINVAL;
goto out;
}
item = btrfs_item_nr(2);
if (btrfs_item_size(eb, item) != strlen(split2)) {
test_msg("Invalid len in the second split\n");
ret = -EINVAL;
goto out;
}
read_extent_buffer(eb, buf, btrfs_item_ptr_offset(eb, 2),
strlen(split2));
if (memcmp(buf, split2, strlen(split2))) {
test_msg("Data in the buffer doesn't match what it should "
"in the last chunk\n");
ret = -EINVAL;
goto out;
}
out:
btrfs_free_path(path);
kfree(root);
return ret;
}
int btrfs_test_extent_buffer_operations(void)
{
test_msg("Running extent buffer operation tests");
return test_btrfs_split_item();
}
| gpl-2.0 |
frankiek3/android_kernel_samsung_intercept | drivers/block/umem.c | 2473 | 30577 | /*
* mm.c - Micro Memory(tm) PCI memory board block device driver - v2.3
*
* (C) 2001 San Mehat <nettwerk@valinux.com>
* (C) 2001 Johannes Erdfelt <jerdfelt@valinux.com>
* (C) 2001 NeilBrown <neilb@cse.unsw.edu.au>
*
* This driver for the Micro Memory PCI Memory Module with Battery Backup
* is Copyright Micro Memory Inc 2001-2002. All rights reserved.
*
* This driver is released to the public under the terms of the
* GNU GENERAL PUBLIC LICENSE version 2
* See the file COPYING for details.
*
* This driver provides a standard block device interface for Micro Memory(tm)
* PCI based RAM boards.
* 10/05/01: Phap Nguyen - Rebuilt the driver
* 10/22/01: Phap Nguyen - v2.1 Added disk partitioning
* 29oct2001:NeilBrown - Use make_request_fn instead of request_fn
* - use stand disk partitioning (so fdisk works).
* 08nov2001:NeilBrown - change driver name from "mm" to "umem"
* - incorporate into main kernel
* 08apr2002:NeilBrown - Move some of interrupt handle to tasklet
* - use spin_lock_bh instead of _irq
* - Never block on make_request. queue
* bh's instead.
* - unregister umem from devfs at mod unload
* - Change version to 2.3
* 07Nov2001:Phap Nguyen - Select pci read command: 06, 12, 15 (Decimal)
* 07Jan2002: P. Nguyen - Used PCI Memory Write & Invalidate for DMA
* 15May2002:NeilBrown - convert to bio for 2.5
* 17May2002:NeilBrown - remove init_mem initialisation. Instead detect
* - a sequence of writes that cover the card, and
* - set initialised bit then.
*/
#undef DEBUG /* #define DEBUG if you want debugging info (pr_debug) */
#include <linux/fs.h>
#include <linux/bio.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/gfp.h>
#include <linux/ioctl.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/timer.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/fcntl.h> /* O_ACCMODE */
#include <linux/hdreg.h> /* HDIO_GETGEO */
#include "umem.h"
#include <asm/uaccess.h>
#include <asm/io.h>
#define MM_MAXCARDS 4
#define MM_RAHEAD 2 /* two sectors */
#define MM_BLKSIZE 1024 /* 1k blocks */
#define MM_HARDSECT 512 /* 512-byte hardware sectors */
#define MM_SHIFT 6 /* max 64 partitions on 4 cards */
/*
* Version Information
*/
#define DRIVER_NAME "umem"
#define DRIVER_VERSION "v2.3"
#define DRIVER_AUTHOR "San Mehat, Johannes Erdfelt, NeilBrown"
#define DRIVER_DESC "Micro Memory(tm) PCI memory board block driver"
static int debug;
/* #define HW_TRACE(x) writeb(x,cards[0].csr_remap + MEMCTRLSTATUS_MAGIC) */
#define HW_TRACE(x)
#define DEBUG_LED_ON_TRANSFER 0x01
#define DEBUG_BATTERY_POLLING 0x02
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug bitmask");
static int pci_read_cmd = 0x0C; /* Read Multiple */
module_param(pci_read_cmd, int, 0);
MODULE_PARM_DESC(pci_read_cmd, "PCI read command");
static int pci_write_cmd = 0x0F; /* Write and Invalidate */
module_param(pci_write_cmd, int, 0);
MODULE_PARM_DESC(pci_write_cmd, "PCI write command");
static int pci_cmds;
static int major_nr;
#include <linux/blkdev.h>
#include <linux/blkpg.h>
struct cardinfo {
struct pci_dev *dev;
unsigned char __iomem *csr_remap;
unsigned int mm_size; /* size in kbytes */
unsigned int init_size; /* initial segment, in sectors,
* that we know to
* have been written
*/
struct bio *bio, *currentbio, **biotail;
int current_idx;
sector_t current_sector;
struct request_queue *queue;
struct mm_page {
dma_addr_t page_dma;
struct mm_dma_desc *desc;
int cnt, headcnt;
struct bio *bio, **biotail;
int idx;
} mm_pages[2];
#define DESC_PER_PAGE ((PAGE_SIZE*2)/sizeof(struct mm_dma_desc))
int Active, Ready;
struct tasklet_struct tasklet;
unsigned int dma_status;
struct {
int good;
int warned;
unsigned long last_change;
} battery[2];
spinlock_t lock;
int check_batteries;
int flags;
};
static struct cardinfo cards[MM_MAXCARDS];
static struct timer_list battery_timer;
static int num_cards;
static struct gendisk *mm_gendisk[MM_MAXCARDS];
static void check_batteries(struct cardinfo *card);
static int get_userbit(struct cardinfo *card, int bit)
{
unsigned char led;
led = readb(card->csr_remap + MEMCTRLCMD_LEDCTRL);
return led & bit;
}
static int set_userbit(struct cardinfo *card, int bit, unsigned char state)
{
unsigned char led;
led = readb(card->csr_remap + MEMCTRLCMD_LEDCTRL);
if (state)
led |= bit;
else
led &= ~bit;
writeb(led, card->csr_remap + MEMCTRLCMD_LEDCTRL);
return 0;
}
/*
* NOTE: For the power LED, use the LED_POWER_* macros since they differ
*/
static void set_led(struct cardinfo *card, int shift, unsigned char state)
{
unsigned char led;
led = readb(card->csr_remap + MEMCTRLCMD_LEDCTRL);
if (state == LED_FLIP)
led ^= (1<<shift);
else {
led &= ~(0x03 << shift);
led |= (state << shift);
}
writeb(led, card->csr_remap + MEMCTRLCMD_LEDCTRL);
}
#ifdef MM_DIAG
static void dump_regs(struct cardinfo *card)
{
unsigned char *p;
int i, i1;
p = card->csr_remap;
for (i = 0; i < 8; i++) {
printk(KERN_DEBUG "%p ", p);
for (i1 = 0; i1 < 16; i1++)
printk("%02x ", *p++);
printk("\n");
}
}
#endif
static void dump_dmastat(struct cardinfo *card, unsigned int dmastat)
{
dev_printk(KERN_DEBUG, &card->dev->dev, "DMAstat - ");
if (dmastat & DMASCR_ANY_ERR)
printk(KERN_CONT "ANY_ERR ");
if (dmastat & DMASCR_MBE_ERR)
printk(KERN_CONT "MBE_ERR ");
if (dmastat & DMASCR_PARITY_ERR_REP)
printk(KERN_CONT "PARITY_ERR_REP ");
if (dmastat & DMASCR_PARITY_ERR_DET)
printk(KERN_CONT "PARITY_ERR_DET ");
if (dmastat & DMASCR_SYSTEM_ERR_SIG)
printk(KERN_CONT "SYSTEM_ERR_SIG ");
if (dmastat & DMASCR_TARGET_ABT)
printk(KERN_CONT "TARGET_ABT ");
if (dmastat & DMASCR_MASTER_ABT)
printk(KERN_CONT "MASTER_ABT ");
if (dmastat & DMASCR_CHAIN_COMPLETE)
printk(KERN_CONT "CHAIN_COMPLETE ");
if (dmastat & DMASCR_DMA_COMPLETE)
printk(KERN_CONT "DMA_COMPLETE ");
printk("\n");
}
/*
* Theory of request handling
*
* Each bio is assigned to one mm_dma_desc - which may not be enough FIXME
* We have two pages of mm_dma_desc, holding about 64 descriptors
* each. These are allocated at init time.
* One page is "Ready" and is either full, or can have request added.
* The other page might be "Active", which DMA is happening on it.
*
* Whenever IO on the active page completes, the Ready page is activated
* and the ex-Active page is clean out and made Ready.
* Otherwise the Ready page is only activated when it becomes full.
*
* If a request arrives while both pages a full, it is queued, and b_rdev is
* overloaded to record whether it was a read or a write.
*
* The interrupt handler only polls the device to clear the interrupt.
* The processing of the result is done in a tasklet.
*/
static void mm_start_io(struct cardinfo *card)
{
/* we have the lock, we know there is
* no IO active, and we know that card->Active
* is set
*/
struct mm_dma_desc *desc;
struct mm_page *page;
int offset;
/* make the last descriptor end the chain */
page = &card->mm_pages[card->Active];
pr_debug("start_io: %d %d->%d\n",
card->Active, page->headcnt, page->cnt - 1);
desc = &page->desc[page->cnt-1];
desc->control_bits |= cpu_to_le32(DMASCR_CHAIN_COMP_EN);
desc->control_bits &= ~cpu_to_le32(DMASCR_CHAIN_EN);
desc->sem_control_bits = desc->control_bits;
if (debug & DEBUG_LED_ON_TRANSFER)
set_led(card, LED_REMOVE, LED_ON);
desc = &page->desc[page->headcnt];
writel(0, card->csr_remap + DMA_PCI_ADDR);
writel(0, card->csr_remap + DMA_PCI_ADDR + 4);
writel(0, card->csr_remap + DMA_LOCAL_ADDR);
writel(0, card->csr_remap + DMA_LOCAL_ADDR + 4);
writel(0, card->csr_remap + DMA_TRANSFER_SIZE);
writel(0, card->csr_remap + DMA_TRANSFER_SIZE + 4);
writel(0, card->csr_remap + DMA_SEMAPHORE_ADDR);
writel(0, card->csr_remap + DMA_SEMAPHORE_ADDR + 4);
offset = ((char *)desc) - ((char *)page->desc);
writel(cpu_to_le32((page->page_dma+offset) & 0xffffffff),
card->csr_remap + DMA_DESCRIPTOR_ADDR);
/* Force the value to u64 before shifting otherwise >> 32 is undefined C
* and on some ports will do nothing ! */
writel(cpu_to_le32(((u64)page->page_dma)>>32),
card->csr_remap + DMA_DESCRIPTOR_ADDR + 4);
/* Go, go, go */
writel(cpu_to_le32(DMASCR_GO | DMASCR_CHAIN_EN | pci_cmds),
card->csr_remap + DMA_STATUS_CTRL);
}
static int add_bio(struct cardinfo *card);
static void activate(struct cardinfo *card)
{
/* if No page is Active, and Ready is
* not empty, then switch Ready page
* to active and start IO.
* Then add any bh's that are available to Ready
*/
do {
while (add_bio(card))
;
if (card->Active == -1 &&
card->mm_pages[card->Ready].cnt > 0) {
card->Active = card->Ready;
card->Ready = 1-card->Ready;
mm_start_io(card);
}
} while (card->Active == -1 && add_bio(card));
}
static inline void reset_page(struct mm_page *page)
{
page->cnt = 0;
page->headcnt = 0;
page->bio = NULL;
page->biotail = &page->bio;
}
/*
* If there is room on Ready page, take
* one bh off list and add it.
* return 1 if there was room, else 0.
*/
static int add_bio(struct cardinfo *card)
{
struct mm_page *p;
struct mm_dma_desc *desc;
dma_addr_t dma_handle;
int offset;
struct bio *bio;
struct bio_vec *vec;
int idx;
int rw;
int len;
bio = card->currentbio;
if (!bio && card->bio) {
card->currentbio = card->bio;
card->current_idx = card->bio->bi_idx;
card->current_sector = card->bio->bi_sector;
card->bio = card->bio->bi_next;
if (card->bio == NULL)
card->biotail = &card->bio;
card->currentbio->bi_next = NULL;
return 1;
}
if (!bio)
return 0;
idx = card->current_idx;
rw = bio_rw(bio);
if (card->mm_pages[card->Ready].cnt >= DESC_PER_PAGE)
return 0;
vec = bio_iovec_idx(bio, idx);
len = vec->bv_len;
dma_handle = pci_map_page(card->dev,
vec->bv_page,
vec->bv_offset,
len,
(rw == READ) ?
PCI_DMA_FROMDEVICE : PCI_DMA_TODEVICE);
p = &card->mm_pages[card->Ready];
desc = &p->desc[p->cnt];
p->cnt++;
if (p->bio == NULL)
p->idx = idx;
if ((p->biotail) != &bio->bi_next) {
*(p->biotail) = bio;
p->biotail = &(bio->bi_next);
bio->bi_next = NULL;
}
desc->data_dma_handle = dma_handle;
desc->pci_addr = cpu_to_le64((u64)desc->data_dma_handle);
desc->local_addr = cpu_to_le64(card->current_sector << 9);
desc->transfer_size = cpu_to_le32(len);
offset = (((char *)&desc->sem_control_bits) - ((char *)p->desc));
desc->sem_addr = cpu_to_le64((u64)(p->page_dma+offset));
desc->zero1 = desc->zero2 = 0;
offset = (((char *)(desc+1)) - ((char *)p->desc));
desc->next_desc_addr = cpu_to_le64(p->page_dma+offset);
desc->control_bits = cpu_to_le32(DMASCR_GO|DMASCR_ERR_INT_EN|
DMASCR_PARITY_INT_EN|
DMASCR_CHAIN_EN |
DMASCR_SEM_EN |
pci_cmds);
if (rw == WRITE)
desc->control_bits |= cpu_to_le32(DMASCR_TRANSFER_READ);
desc->sem_control_bits = desc->control_bits;
card->current_sector += (len >> 9);
idx++;
card->current_idx = idx;
if (idx >= bio->bi_vcnt)
card->currentbio = NULL;
return 1;
}
static void process_page(unsigned long data)
{
/* check if any of the requests in the page are DMA_COMPLETE,
* and deal with them appropriately.
* If we find a descriptor without DMA_COMPLETE in the semaphore, then
* dma must have hit an error on that descriptor, so use dma_status
* instead and assume that all following descriptors must be re-tried.
*/
struct mm_page *page;
struct bio *return_bio = NULL;
struct cardinfo *card = (struct cardinfo *)data;
unsigned int dma_status = card->dma_status;
spin_lock_bh(&card->lock);
if (card->Active < 0)
goto out_unlock;
page = &card->mm_pages[card->Active];
while (page->headcnt < page->cnt) {
struct bio *bio = page->bio;
struct mm_dma_desc *desc = &page->desc[page->headcnt];
int control = le32_to_cpu(desc->sem_control_bits);
int last = 0;
int idx;
if (!(control & DMASCR_DMA_COMPLETE)) {
control = dma_status;
last = 1;
}
page->headcnt++;
idx = page->idx;
page->idx++;
if (page->idx >= bio->bi_vcnt) {
page->bio = bio->bi_next;
if (page->bio)
page->idx = page->bio->bi_idx;
}
pci_unmap_page(card->dev, desc->data_dma_handle,
bio_iovec_idx(bio, idx)->bv_len,
(control & DMASCR_TRANSFER_READ) ?
PCI_DMA_TODEVICE : PCI_DMA_FROMDEVICE);
if (control & DMASCR_HARD_ERROR) {
/* error */
clear_bit(BIO_UPTODATE, &bio->bi_flags);
dev_printk(KERN_WARNING, &card->dev->dev,
"I/O error on sector %d/%d\n",
le32_to_cpu(desc->local_addr)>>9,
le32_to_cpu(desc->transfer_size));
dump_dmastat(card, control);
} else if ((bio->bi_rw & REQ_WRITE) &&
le32_to_cpu(desc->local_addr) >> 9 ==
card->init_size) {
card->init_size += le32_to_cpu(desc->transfer_size) >> 9;
if (card->init_size >> 1 >= card->mm_size) {
dev_printk(KERN_INFO, &card->dev->dev,
"memory now initialised\n");
set_userbit(card, MEMORY_INITIALIZED, 1);
}
}
if (bio != page->bio) {
bio->bi_next = return_bio;
return_bio = bio;
}
if (last)
break;
}
if (debug & DEBUG_LED_ON_TRANSFER)
set_led(card, LED_REMOVE, LED_OFF);
if (card->check_batteries) {
card->check_batteries = 0;
check_batteries(card);
}
if (page->headcnt >= page->cnt) {
reset_page(page);
card->Active = -1;
activate(card);
} else {
/* haven't finished with this one yet */
pr_debug("do some more\n");
mm_start_io(card);
}
out_unlock:
spin_unlock_bh(&card->lock);
while (return_bio) {
struct bio *bio = return_bio;
return_bio = bio->bi_next;
bio->bi_next = NULL;
bio_endio(bio, 0);
}
}
static void mm_unplug(struct blk_plug_cb *cb, bool from_schedule)
{
struct cardinfo *card = cb->data;
spin_lock_irq(&card->lock);
activate(card);
spin_unlock_irq(&card->lock);
kfree(cb);
}
static int mm_check_plugged(struct cardinfo *card)
{
return !!blk_check_plugged(mm_unplug, card, sizeof(struct blk_plug_cb));
}
static void mm_make_request(struct request_queue *q, struct bio *bio)
{
struct cardinfo *card = q->queuedata;
pr_debug("mm_make_request %llu %u\n",
(unsigned long long)bio->bi_sector, bio->bi_size);
spin_lock_irq(&card->lock);
*card->biotail = bio;
bio->bi_next = NULL;
card->biotail = &bio->bi_next;
if (bio->bi_rw & REQ_SYNC || !mm_check_plugged(card))
activate(card);
spin_unlock_irq(&card->lock);
return;
}
static irqreturn_t mm_interrupt(int irq, void *__card)
{
struct cardinfo *card = (struct cardinfo *) __card;
unsigned int dma_status;
unsigned short cfg_status;
HW_TRACE(0x30);
dma_status = le32_to_cpu(readl(card->csr_remap + DMA_STATUS_CTRL));
if (!(dma_status & (DMASCR_ERROR_MASK | DMASCR_CHAIN_COMPLETE))) {
/* interrupt wasn't for me ... */
return IRQ_NONE;
}
/* clear COMPLETION interrupts */
if (card->flags & UM_FLAG_NO_BYTE_STATUS)
writel(cpu_to_le32(DMASCR_DMA_COMPLETE|DMASCR_CHAIN_COMPLETE),
card->csr_remap + DMA_STATUS_CTRL);
else
writeb((DMASCR_DMA_COMPLETE|DMASCR_CHAIN_COMPLETE) >> 16,
card->csr_remap + DMA_STATUS_CTRL + 2);
/* log errors and clear interrupt status */
if (dma_status & DMASCR_ANY_ERR) {
unsigned int data_log1, data_log2;
unsigned int addr_log1, addr_log2;
unsigned char stat, count, syndrome, check;
stat = readb(card->csr_remap + MEMCTRLCMD_ERRSTATUS);
data_log1 = le32_to_cpu(readl(card->csr_remap +
ERROR_DATA_LOG));
data_log2 = le32_to_cpu(readl(card->csr_remap +
ERROR_DATA_LOG + 4));
addr_log1 = le32_to_cpu(readl(card->csr_remap +
ERROR_ADDR_LOG));
addr_log2 = readb(card->csr_remap + ERROR_ADDR_LOG + 4);
count = readb(card->csr_remap + ERROR_COUNT);
syndrome = readb(card->csr_remap + ERROR_SYNDROME);
check = readb(card->csr_remap + ERROR_CHECK);
dump_dmastat(card, dma_status);
if (stat & 0x01)
dev_printk(KERN_ERR, &card->dev->dev,
"Memory access error detected (err count %d)\n",
count);
if (stat & 0x02)
dev_printk(KERN_ERR, &card->dev->dev,
"Multi-bit EDC error\n");
dev_printk(KERN_ERR, &card->dev->dev,
"Fault Address 0x%02x%08x, Fault Data 0x%08x%08x\n",
addr_log2, addr_log1, data_log2, data_log1);
dev_printk(KERN_ERR, &card->dev->dev,
"Fault Check 0x%02x, Fault Syndrome 0x%02x\n",
check, syndrome);
writeb(0, card->csr_remap + ERROR_COUNT);
}
if (dma_status & DMASCR_PARITY_ERR_REP) {
dev_printk(KERN_ERR, &card->dev->dev,
"PARITY ERROR REPORTED\n");
pci_read_config_word(card->dev, PCI_STATUS, &cfg_status);
pci_write_config_word(card->dev, PCI_STATUS, cfg_status);
}
if (dma_status & DMASCR_PARITY_ERR_DET) {
dev_printk(KERN_ERR, &card->dev->dev,
"PARITY ERROR DETECTED\n");
pci_read_config_word(card->dev, PCI_STATUS, &cfg_status);
pci_write_config_word(card->dev, PCI_STATUS, cfg_status);
}
if (dma_status & DMASCR_SYSTEM_ERR_SIG) {
dev_printk(KERN_ERR, &card->dev->dev, "SYSTEM ERROR\n");
pci_read_config_word(card->dev, PCI_STATUS, &cfg_status);
pci_write_config_word(card->dev, PCI_STATUS, cfg_status);
}
if (dma_status & DMASCR_TARGET_ABT) {
dev_printk(KERN_ERR, &card->dev->dev, "TARGET ABORT\n");
pci_read_config_word(card->dev, PCI_STATUS, &cfg_status);
pci_write_config_word(card->dev, PCI_STATUS, cfg_status);
}
if (dma_status & DMASCR_MASTER_ABT) {
dev_printk(KERN_ERR, &card->dev->dev, "MASTER ABORT\n");
pci_read_config_word(card->dev, PCI_STATUS, &cfg_status);
pci_write_config_word(card->dev, PCI_STATUS, cfg_status);
}
/* and process the DMA descriptors */
card->dma_status = dma_status;
tasklet_schedule(&card->tasklet);
HW_TRACE(0x36);
return IRQ_HANDLED;
}
/*
* If both batteries are good, no LED
* If either battery has been warned, solid LED
* If both batteries are bad, flash the LED quickly
* If either battery is bad, flash the LED semi quickly
*/
static void set_fault_to_battery_status(struct cardinfo *card)
{
if (card->battery[0].good && card->battery[1].good)
set_led(card, LED_FAULT, LED_OFF);
else if (card->battery[0].warned || card->battery[1].warned)
set_led(card, LED_FAULT, LED_ON);
else if (!card->battery[0].good && !card->battery[1].good)
set_led(card, LED_FAULT, LED_FLASH_7_0);
else
set_led(card, LED_FAULT, LED_FLASH_3_5);
}
static void init_battery_timer(void);
static int check_battery(struct cardinfo *card, int battery, int status)
{
if (status != card->battery[battery].good) {
card->battery[battery].good = !card->battery[battery].good;
card->battery[battery].last_change = jiffies;
if (card->battery[battery].good) {
dev_printk(KERN_ERR, &card->dev->dev,
"Battery %d now good\n", battery + 1);
card->battery[battery].warned = 0;
} else
dev_printk(KERN_ERR, &card->dev->dev,
"Battery %d now FAILED\n", battery + 1);
return 1;
} else if (!card->battery[battery].good &&
!card->battery[battery].warned &&
time_after_eq(jiffies, card->battery[battery].last_change +
(HZ * 60 * 60 * 5))) {
dev_printk(KERN_ERR, &card->dev->dev,
"Battery %d still FAILED after 5 hours\n", battery + 1);
card->battery[battery].warned = 1;
return 1;
}
return 0;
}
static void check_batteries(struct cardinfo *card)
{
/* NOTE: this must *never* be called while the card
* is doing (bus-to-card) DMA, or you will need the
* reset switch
*/
unsigned char status;
int ret1, ret2;
status = readb(card->csr_remap + MEMCTRLSTATUS_BATTERY);
if (debug & DEBUG_BATTERY_POLLING)
dev_printk(KERN_DEBUG, &card->dev->dev,
"checking battery status, 1 = %s, 2 = %s\n",
(status & BATTERY_1_FAILURE) ? "FAILURE" : "OK",
(status & BATTERY_2_FAILURE) ? "FAILURE" : "OK");
ret1 = check_battery(card, 0, !(status & BATTERY_1_FAILURE));
ret2 = check_battery(card, 1, !(status & BATTERY_2_FAILURE));
if (ret1 || ret2)
set_fault_to_battery_status(card);
}
static void check_all_batteries(unsigned long ptr)
{
int i;
for (i = 0; i < num_cards; i++)
if (!(cards[i].flags & UM_FLAG_NO_BATT)) {
struct cardinfo *card = &cards[i];
spin_lock_bh(&card->lock);
if (card->Active >= 0)
card->check_batteries = 1;
else
check_batteries(card);
spin_unlock_bh(&card->lock);
}
init_battery_timer();
}
static void init_battery_timer(void)
{
init_timer(&battery_timer);
battery_timer.function = check_all_batteries;
battery_timer.expires = jiffies + (HZ * 60);
add_timer(&battery_timer);
}
static void del_battery_timer(void)
{
del_timer(&battery_timer);
}
/*
* Note no locks taken out here. In a worst case scenario, we could drop
* a chunk of system memory. But that should never happen, since validation
* happens at open or mount time, when locks are held.
*
* That's crap, since doing that while some partitions are opened
* or mounted will give you really nasty results.
*/
static int mm_revalidate(struct gendisk *disk)
{
struct cardinfo *card = disk->private_data;
set_capacity(disk, card->mm_size << 1);
return 0;
}
static int mm_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct cardinfo *card = bdev->bd_disk->private_data;
int size = card->mm_size * (1024 / MM_HARDSECT);
/*
* get geometry: we have to fake one... trim the size to a
* multiple of 2048 (1M): tell we have 32 sectors, 64 heads,
* whatever cylinders.
*/
geo->heads = 64;
geo->sectors = 32;
geo->cylinders = size / (geo->heads * geo->sectors);
return 0;
}
static const struct block_device_operations mm_fops = {
.owner = THIS_MODULE,
.getgeo = mm_getgeo,
.revalidate_disk = mm_revalidate,
};
static int mm_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
int ret = -ENODEV;
struct cardinfo *card = &cards[num_cards];
unsigned char mem_present;
unsigned char batt_status;
unsigned int saved_bar, data;
unsigned long csr_base;
unsigned long csr_len;
int magic_number;
static int printed_version;
if (!printed_version++)
printk(KERN_INFO DRIVER_VERSION " : " DRIVER_DESC "\n");
ret = pci_enable_device(dev);
if (ret)
return ret;
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0xF8);
pci_set_master(dev);
card->dev = dev;
csr_base = pci_resource_start(dev, 0);
csr_len = pci_resource_len(dev, 0);
if (!csr_base || !csr_len)
return -ENODEV;
dev_printk(KERN_INFO, &dev->dev,
"Micro Memory(tm) controller found (PCI Mem Module (Battery Backup))\n");
if (pci_set_dma_mask(dev, DMA_BIT_MASK(64)) &&
pci_set_dma_mask(dev, DMA_BIT_MASK(32))) {
dev_printk(KERN_WARNING, &dev->dev, "NO suitable DMA found\n");
return -ENOMEM;
}
ret = pci_request_regions(dev, DRIVER_NAME);
if (ret) {
dev_printk(KERN_ERR, &card->dev->dev,
"Unable to request memory region\n");
goto failed_req_csr;
}
card->csr_remap = ioremap_nocache(csr_base, csr_len);
if (!card->csr_remap) {
dev_printk(KERN_ERR, &card->dev->dev,
"Unable to remap memory region\n");
ret = -ENOMEM;
goto failed_remap_csr;
}
dev_printk(KERN_INFO, &card->dev->dev,
"CSR 0x%08lx -> 0x%p (0x%lx)\n",
csr_base, card->csr_remap, csr_len);
switch (card->dev->device) {
case 0x5415:
card->flags |= UM_FLAG_NO_BYTE_STATUS | UM_FLAG_NO_BATTREG;
magic_number = 0x59;
break;
case 0x5425:
card->flags |= UM_FLAG_NO_BYTE_STATUS;
magic_number = 0x5C;
break;
case 0x6155:
card->flags |= UM_FLAG_NO_BYTE_STATUS |
UM_FLAG_NO_BATTREG | UM_FLAG_NO_BATT;
magic_number = 0x99;
break;
default:
magic_number = 0x100;
break;
}
if (readb(card->csr_remap + MEMCTRLSTATUS_MAGIC) != magic_number) {
dev_printk(KERN_ERR, &card->dev->dev, "Magic number invalid\n");
ret = -ENOMEM;
goto failed_magic;
}
card->mm_pages[0].desc = pci_alloc_consistent(card->dev,
PAGE_SIZE * 2,
&card->mm_pages[0].page_dma);
card->mm_pages[1].desc = pci_alloc_consistent(card->dev,
PAGE_SIZE * 2,
&card->mm_pages[1].page_dma);
if (card->mm_pages[0].desc == NULL ||
card->mm_pages[1].desc == NULL) {
dev_printk(KERN_ERR, &card->dev->dev, "alloc failed\n");
goto failed_alloc;
}
reset_page(&card->mm_pages[0]);
reset_page(&card->mm_pages[1]);
card->Ready = 0; /* page 0 is ready */
card->Active = -1; /* no page is active */
card->bio = NULL;
card->biotail = &card->bio;
card->queue = blk_alloc_queue(GFP_KERNEL);
if (!card->queue)
goto failed_alloc;
blk_queue_make_request(card->queue, mm_make_request);
card->queue->queue_lock = &card->lock;
card->queue->queuedata = card;
tasklet_init(&card->tasklet, process_page, (unsigned long)card);
card->check_batteries = 0;
mem_present = readb(card->csr_remap + MEMCTRLSTATUS_MEMORY);
switch (mem_present) {
case MEM_128_MB:
card->mm_size = 1024 * 128;
break;
case MEM_256_MB:
card->mm_size = 1024 * 256;
break;
case MEM_512_MB:
card->mm_size = 1024 * 512;
break;
case MEM_1_GB:
card->mm_size = 1024 * 1024;
break;
case MEM_2_GB:
card->mm_size = 1024 * 2048;
break;
default:
card->mm_size = 0;
break;
}
/* Clear the LED's we control */
set_led(card, LED_REMOVE, LED_OFF);
set_led(card, LED_FAULT, LED_OFF);
batt_status = readb(card->csr_remap + MEMCTRLSTATUS_BATTERY);
card->battery[0].good = !(batt_status & BATTERY_1_FAILURE);
card->battery[1].good = !(batt_status & BATTERY_2_FAILURE);
card->battery[0].last_change = card->battery[1].last_change = jiffies;
if (card->flags & UM_FLAG_NO_BATT)
dev_printk(KERN_INFO, &card->dev->dev,
"Size %d KB\n", card->mm_size);
else {
dev_printk(KERN_INFO, &card->dev->dev,
"Size %d KB, Battery 1 %s (%s), Battery 2 %s (%s)\n",
card->mm_size,
batt_status & BATTERY_1_DISABLED ? "Disabled" : "Enabled",
card->battery[0].good ? "OK" : "FAILURE",
batt_status & BATTERY_2_DISABLED ? "Disabled" : "Enabled",
card->battery[1].good ? "OK" : "FAILURE");
set_fault_to_battery_status(card);
}
pci_read_config_dword(dev, PCI_BASE_ADDRESS_1, &saved_bar);
data = 0xffffffff;
pci_write_config_dword(dev, PCI_BASE_ADDRESS_1, data);
pci_read_config_dword(dev, PCI_BASE_ADDRESS_1, &data);
pci_write_config_dword(dev, PCI_BASE_ADDRESS_1, saved_bar);
data &= 0xfffffff0;
data = ~data;
data += 1;
if (request_irq(dev->irq, mm_interrupt, IRQF_SHARED, DRIVER_NAME,
card)) {
dev_printk(KERN_ERR, &card->dev->dev,
"Unable to allocate IRQ\n");
ret = -ENODEV;
goto failed_req_irq;
}
dev_printk(KERN_INFO, &card->dev->dev,
"Window size %d bytes, IRQ %d\n", data, dev->irq);
spin_lock_init(&card->lock);
pci_set_drvdata(dev, card);
if (pci_write_cmd != 0x0F) /* If not Memory Write & Invalidate */
pci_write_cmd = 0x07; /* then Memory Write command */
if (pci_write_cmd & 0x08) { /* use Memory Write and Invalidate */
unsigned short cfg_command;
pci_read_config_word(dev, PCI_COMMAND, &cfg_command);
cfg_command |= 0x10; /* Memory Write & Invalidate Enable */
pci_write_config_word(dev, PCI_COMMAND, cfg_command);
}
pci_cmds = (pci_read_cmd << 28) | (pci_write_cmd << 24);
num_cards++;
if (!get_userbit(card, MEMORY_INITIALIZED)) {
dev_printk(KERN_INFO, &card->dev->dev,
"memory NOT initialized. Consider over-writing whole device.\n");
card->init_size = 0;
} else {
dev_printk(KERN_INFO, &card->dev->dev,
"memory already initialized\n");
card->init_size = card->mm_size;
}
/* Enable ECC */
writeb(EDC_STORE_CORRECT, card->csr_remap + MEMCTRLCMD_ERRCTRL);
return 0;
failed_req_irq:
failed_alloc:
if (card->mm_pages[0].desc)
pci_free_consistent(card->dev, PAGE_SIZE*2,
card->mm_pages[0].desc,
card->mm_pages[0].page_dma);
if (card->mm_pages[1].desc)
pci_free_consistent(card->dev, PAGE_SIZE*2,
card->mm_pages[1].desc,
card->mm_pages[1].page_dma);
failed_magic:
iounmap(card->csr_remap);
failed_remap_csr:
pci_release_regions(dev);
failed_req_csr:
return ret;
}
static void mm_pci_remove(struct pci_dev *dev)
{
struct cardinfo *card = pci_get_drvdata(dev);
tasklet_kill(&card->tasklet);
free_irq(dev->irq, card);
iounmap(card->csr_remap);
if (card->mm_pages[0].desc)
pci_free_consistent(card->dev, PAGE_SIZE*2,
card->mm_pages[0].desc,
card->mm_pages[0].page_dma);
if (card->mm_pages[1].desc)
pci_free_consistent(card->dev, PAGE_SIZE*2,
card->mm_pages[1].desc,
card->mm_pages[1].page_dma);
blk_cleanup_queue(card->queue);
pci_release_regions(dev);
pci_disable_device(dev);
}
static const struct pci_device_id mm_pci_ids[] = {
{PCI_DEVICE(PCI_VENDOR_ID_MICRO_MEMORY, PCI_DEVICE_ID_MICRO_MEMORY_5415CN)},
{PCI_DEVICE(PCI_VENDOR_ID_MICRO_MEMORY, PCI_DEVICE_ID_MICRO_MEMORY_5425CN)},
{PCI_DEVICE(PCI_VENDOR_ID_MICRO_MEMORY, PCI_DEVICE_ID_MICRO_MEMORY_6155)},
{
.vendor = 0x8086,
.device = 0xB555,
.subvendor = 0x1332,
.subdevice = 0x5460,
.class = 0x050000,
.class_mask = 0,
}, { /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, mm_pci_ids);
static struct pci_driver mm_pci_driver = {
.name = DRIVER_NAME,
.id_table = mm_pci_ids,
.probe = mm_pci_probe,
.remove = mm_pci_remove,
};
static int __init mm_init(void)
{
int retval, i;
int err;
retval = pci_register_driver(&mm_pci_driver);
if (retval)
return -ENOMEM;
err = major_nr = register_blkdev(0, DRIVER_NAME);
if (err < 0) {
pci_unregister_driver(&mm_pci_driver);
return -EIO;
}
for (i = 0; i < num_cards; i++) {
mm_gendisk[i] = alloc_disk(1 << MM_SHIFT);
if (!mm_gendisk[i])
goto out;
}
for (i = 0; i < num_cards; i++) {
struct gendisk *disk = mm_gendisk[i];
sprintf(disk->disk_name, "umem%c", 'a'+i);
spin_lock_init(&cards[i].lock);
disk->major = major_nr;
disk->first_minor = i << MM_SHIFT;
disk->fops = &mm_fops;
disk->private_data = &cards[i];
disk->queue = cards[i].queue;
set_capacity(disk, cards[i].mm_size << 1);
add_disk(disk);
}
init_battery_timer();
printk(KERN_INFO "MM: desc_per_page = %ld\n", DESC_PER_PAGE);
/* printk("mm_init: Done. 10-19-01 9:00\n"); */
return 0;
out:
pci_unregister_driver(&mm_pci_driver);
unregister_blkdev(major_nr, DRIVER_NAME);
while (i--)
put_disk(mm_gendisk[i]);
return -ENOMEM;
}
static void __exit mm_cleanup(void)
{
int i;
del_battery_timer();
for (i = 0; i < num_cards ; i++) {
del_gendisk(mm_gendisk[i]);
put_disk(mm_gendisk[i]);
}
pci_unregister_driver(&mm_pci_driver);
unregister_blkdev(major_nr, DRIVER_NAME);
}
module_init(mm_init);
module_exit(mm_cleanup);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
PennPanda/litmus-rt | arch/arm/mach-omap2/clkt2xxx_osc.c | 2729 | 1884 | /*
* OMAP2xxx osc_clk-specific clock code
*
* Copyright (C) 2005-2008 Texas Instruments, Inc.
* Copyright (C) 2004-2010 Nokia Corporation
*
* Contacts:
* Richard Woodruff <r-woodruff2@ti.com>
* Paul Walmsley
*
* Based on earlier work by Tuukka Tikkanen, Tony Lindgren,
* Gordon McNutt and RidgeRun, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#undef DEBUG
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include "clock.h"
#include "clock2xxx.h"
#include "prm2xxx_3xxx.h"
#include "prm-regbits-24xx.h"
/*
* XXX This does not actually enable the osc_ck, since the osc_ck must
* be running for this function to be called. Instead, this function
* is used to disable an autoidle mode on the osc_ck. The existing
* clk_enable/clk_disable()-based usecounting for osc_ck should be
* replaced with autoidle-based usecounting.
*/
int omap2_enable_osc_ck(struct clk_hw *clk)
{
u32 pcc;
pcc = __raw_readl(prcm_clksrc_ctrl);
__raw_writel(pcc & ~OMAP_AUTOEXTCLKMODE_MASK, prcm_clksrc_ctrl);
return 0;
}
/*
* XXX This does not actually disable the osc_ck, since doing so would
* immediately halt the system. Instead, this function is used to
* enable an autoidle mode on the osc_ck. The existing
* clk_enable/clk_disable()-based usecounting for osc_ck should be
* replaced with autoidle-based usecounting.
*/
void omap2_disable_osc_ck(struct clk_hw *clk)
{
u32 pcc;
pcc = __raw_readl(prcm_clksrc_ctrl);
__raw_writel(pcc | OMAP_AUTOEXTCLKMODE_MASK, prcm_clksrc_ctrl);
}
unsigned long omap2_osc_clk_recalc(struct clk_hw *clk,
unsigned long parent_rate)
{
return omap2xxx_get_apll_clkin() * omap2xxx_get_sysclkdiv();
}
| gpl-2.0 |
Split-Screen/android_kernel_motorola_msm8960-common | drivers/media/video/gspca/m5602/m5602_s5k83a.c | 3241 | 14773 | /*
* Driver for the s5k83a sensor
*
* Copyright (C) 2008 Erik Andrén
* Copyright (C) 2007 Ilyes Gouta. Based on the m5603x Linux Driver Project.
* Copyright (C) 2005 m5603x Linux Driver Project <m5602@x3ng.com.br>
*
* Portions of code to USB interface and ALi driver software,
* Copyright (c) 2006 Willem Duinker
* v4l2 interface modeled after the V4L2 driver
* for SN9C10x PC Camera Controllers
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/kthread.h>
#include "m5602_s5k83a.h"
static int s5k83a_set_gain(struct gspca_dev *gspca_dev, __s32 val);
static int s5k83a_get_gain(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k83a_set_brightness(struct gspca_dev *gspca_dev, __s32 val);
static int s5k83a_get_brightness(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k83a_set_exposure(struct gspca_dev *gspca_dev, __s32 val);
static int s5k83a_get_exposure(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k83a_get_vflip(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k83a_set_vflip(struct gspca_dev *gspca_dev, __s32 val);
static int s5k83a_get_hflip(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k83a_set_hflip(struct gspca_dev *gspca_dev, __s32 val);
static struct v4l2_pix_format s5k83a_modes[] = {
{
640,
480,
V4L2_PIX_FMT_SBGGR8,
V4L2_FIELD_NONE,
.sizeimage =
640 * 480,
.bytesperline = 640,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0
}
};
static const struct ctrl s5k83a_ctrls[] = {
#define GAIN_IDX 0
{
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "gain",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x01,
.default_value = S5K83A_DEFAULT_GAIN,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = s5k83a_set_gain,
.get = s5k83a_get_gain
},
#define BRIGHTNESS_IDX 1
{
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "brightness",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x01,
.default_value = S5K83A_DEFAULT_BRIGHTNESS,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = s5k83a_set_brightness,
.get = s5k83a_get_brightness,
},
#define EXPOSURE_IDX 2
{
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x00,
.maximum = S5K83A_MAXIMUM_EXPOSURE,
.step = 0x01,
.default_value = S5K83A_DEFAULT_EXPOSURE,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = s5k83a_set_exposure,
.get = s5k83a_get_exposure
},
#define HFLIP_IDX 3
{
{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "horizontal flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0
},
.set = s5k83a_set_hflip,
.get = s5k83a_get_hflip
},
#define VFLIP_IDX 4
{
{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "vertical flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0
},
.set = s5k83a_set_vflip,
.get = s5k83a_get_vflip
}
};
static void s5k83a_dump_registers(struct sd *sd);
static int s5k83a_get_rotation(struct sd *sd, u8 *reg_data);
static int s5k83a_set_led_indication(struct sd *sd, u8 val);
static int s5k83a_set_flip_real(struct gspca_dev *gspca_dev,
__s32 vflip, __s32 hflip);
int s5k83a_probe(struct sd *sd)
{
struct s5k83a_priv *sens_priv;
u8 prod_id = 0, ver_id = 0;
int i, err = 0;
if (force_sensor) {
if (force_sensor == S5K83A_SENSOR) {
info("Forcing a %s sensor", s5k83a.name);
goto sensor_found;
}
/* If we want to force another sensor, don't try to probe this
* one */
return -ENODEV;
}
PDEBUG(D_PROBE, "Probing for a s5k83a sensor");
/* Preinit the sensor */
for (i = 0; i < ARRAY_SIZE(preinit_s5k83a) && !err; i++) {
u8 data[2] = {preinit_s5k83a[i][2], preinit_s5k83a[i][3]};
if (preinit_s5k83a[i][0] == SENSOR)
err = m5602_write_sensor(sd, preinit_s5k83a[i][1],
data, 2);
else
err = m5602_write_bridge(sd, preinit_s5k83a[i][1],
data[0]);
}
/* We don't know what register (if any) that contain the product id
* Just pick the first addresses that seem to produce the same results
* on multiple machines */
if (m5602_read_sensor(sd, 0x00, &prod_id, 1))
return -ENODEV;
if (m5602_read_sensor(sd, 0x01, &ver_id, 1))
return -ENODEV;
if ((prod_id == 0xff) || (ver_id == 0xff))
return -ENODEV;
else
info("Detected a s5k83a sensor");
sensor_found:
sens_priv = kmalloc(
sizeof(struct s5k83a_priv), GFP_KERNEL);
if (!sens_priv)
return -ENOMEM;
sens_priv->settings =
kmalloc(sizeof(s32)*ARRAY_SIZE(s5k83a_ctrls), GFP_KERNEL);
if (!sens_priv->settings) {
kfree(sens_priv);
return -ENOMEM;
}
sd->gspca_dev.cam.cam_mode = s5k83a_modes;
sd->gspca_dev.cam.nmodes = ARRAY_SIZE(s5k83a_modes);
sd->desc->ctrls = s5k83a_ctrls;
sd->desc->nctrls = ARRAY_SIZE(s5k83a_ctrls);
/* null the pointer! thread is't running now */
sens_priv->rotation_thread = NULL;
for (i = 0; i < ARRAY_SIZE(s5k83a_ctrls); i++)
sens_priv->settings[i] = s5k83a_ctrls[i].qctrl.default_value;
sd->sensor_priv = sens_priv;
return 0;
}
int s5k83a_init(struct sd *sd)
{
int i, err = 0;
s32 *sensor_settings =
((struct s5k83a_priv *) sd->sensor_priv)->settings;
for (i = 0; i < ARRAY_SIZE(init_s5k83a) && !err; i++) {
u8 data[2] = {0x00, 0x00};
switch (init_s5k83a[i][0]) {
case BRIDGE:
err = m5602_write_bridge(sd,
init_s5k83a[i][1],
init_s5k83a[i][2]);
break;
case SENSOR:
data[0] = init_s5k83a[i][2];
err = m5602_write_sensor(sd,
init_s5k83a[i][1], data, 1);
break;
case SENSOR_LONG:
data[0] = init_s5k83a[i][2];
data[1] = init_s5k83a[i][3];
err = m5602_write_sensor(sd,
init_s5k83a[i][1], data, 2);
break;
default:
info("Invalid stream command, exiting init");
return -EINVAL;
}
}
if (dump_sensor)
s5k83a_dump_registers(sd);
err = s5k83a_set_gain(&sd->gspca_dev, sensor_settings[GAIN_IDX]);
if (err < 0)
return err;
err = s5k83a_set_brightness(&sd->gspca_dev,
sensor_settings[BRIGHTNESS_IDX]);
if (err < 0)
return err;
err = s5k83a_set_exposure(&sd->gspca_dev,
sensor_settings[EXPOSURE_IDX]);
if (err < 0)
return err;
err = s5k83a_set_hflip(&sd->gspca_dev, sensor_settings[HFLIP_IDX]);
if (err < 0)
return err;
err = s5k83a_set_vflip(&sd->gspca_dev, sensor_settings[VFLIP_IDX]);
return err;
}
static int rotation_thread_function(void *data)
{
struct sd *sd = (struct sd *) data;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
u8 reg, previous_rotation = 0;
__s32 vflip, hflip;
set_current_state(TASK_INTERRUPTIBLE);
while (!schedule_timeout(100)) {
if (mutex_lock_interruptible(&sd->gspca_dev.usb_lock))
break;
s5k83a_get_rotation(sd, ®);
if (previous_rotation != reg) {
previous_rotation = reg;
info("Camera was flipped");
s5k83a_get_vflip((struct gspca_dev *) sd, &vflip);
s5k83a_get_hflip((struct gspca_dev *) sd, &hflip);
if (reg) {
vflip = !vflip;
hflip = !hflip;
}
s5k83a_set_flip_real((struct gspca_dev *) sd,
vflip, hflip);
}
mutex_unlock(&sd->gspca_dev.usb_lock);
set_current_state(TASK_INTERRUPTIBLE);
}
/* return to "front" flip */
if (previous_rotation) {
s5k83a_get_vflip((struct gspca_dev *) sd, &vflip);
s5k83a_get_hflip((struct gspca_dev *) sd, &hflip);
s5k83a_set_flip_real((struct gspca_dev *) sd, vflip, hflip);
}
sens_priv->rotation_thread = NULL;
return 0;
}
int s5k83a_start(struct sd *sd)
{
int i, err = 0;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
/* Create another thread, polling the GPIO ports of the camera to check
if it got rotated. This is how the windows driver does it so we have
to assume that there is no better way of accomplishing this */
sens_priv->rotation_thread = kthread_create(rotation_thread_function,
sd, "rotation thread");
wake_up_process(sens_priv->rotation_thread);
/* Preinit the sensor */
for (i = 0; i < ARRAY_SIZE(start_s5k83a) && !err; i++) {
u8 data[2] = {start_s5k83a[i][2], start_s5k83a[i][3]};
if (start_s5k83a[i][0] == SENSOR)
err = m5602_write_sensor(sd, start_s5k83a[i][1],
data, 2);
else
err = m5602_write_bridge(sd, start_s5k83a[i][1],
data[0]);
}
if (err < 0)
return err;
return s5k83a_set_led_indication(sd, 1);
}
int s5k83a_stop(struct sd *sd)
{
struct s5k83a_priv *sens_priv = sd->sensor_priv;
if (sens_priv->rotation_thread)
kthread_stop(sens_priv->rotation_thread);
return s5k83a_set_led_indication(sd, 0);
}
void s5k83a_disconnect(struct sd *sd)
{
struct s5k83a_priv *sens_priv = sd->sensor_priv;
s5k83a_stop(sd);
sd->sensor = NULL;
kfree(sens_priv->settings);
kfree(sens_priv);
}
static int s5k83a_get_gain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
*val = sens_priv->settings[GAIN_IDX];
return 0;
}
static int s5k83a_set_gain(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 data[2];
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
sens_priv->settings[GAIN_IDX] = val;
data[0] = 0x00;
data[1] = 0x20;
err = m5602_write_sensor(sd, 0x14, data, 2);
if (err < 0)
return err;
data[0] = 0x01;
data[1] = 0x00;
err = m5602_write_sensor(sd, 0x0d, data, 2);
if (err < 0)
return err;
/* FIXME: This is not sane, we need to figure out the composition
of these registers */
data[0] = val >> 3; /* gain, high 5 bits */
data[1] = val >> 1; /* gain, high 7 bits */
err = m5602_write_sensor(sd, S5K83A_GAIN, data, 2);
return err;
}
static int s5k83a_get_brightness(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
*val = sens_priv->settings[BRIGHTNESS_IDX];
return 0;
}
static int s5k83a_set_brightness(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 data[1];
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
sens_priv->settings[BRIGHTNESS_IDX] = val;
data[0] = val;
err = m5602_write_sensor(sd, S5K83A_BRIGHTNESS, data, 1);
return err;
}
static int s5k83a_get_exposure(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
*val = sens_priv->settings[EXPOSURE_IDX];
return 0;
}
static int s5k83a_set_exposure(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 data[2];
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
sens_priv->settings[EXPOSURE_IDX] = val;
data[0] = 0;
data[1] = val;
err = m5602_write_sensor(sd, S5K83A_EXPOSURE, data, 2);
return err;
}
static int s5k83a_get_vflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
*val = sens_priv->settings[VFLIP_IDX];
return 0;
}
static int s5k83a_set_flip_real(struct gspca_dev *gspca_dev,
__s32 vflip, __s32 hflip)
{
int err;
u8 data[1];
struct sd *sd = (struct sd *) gspca_dev;
data[0] = 0x05;
err = m5602_write_sensor(sd, S5K83A_PAGE_MAP, data, 1);
if (err < 0)
return err;
/* six bit is vflip, seven is hflip */
data[0] = S5K83A_FLIP_MASK;
data[0] = (vflip) ? data[0] | 0x40 : data[0];
data[0] = (hflip) ? data[0] | 0x80 : data[0];
err = m5602_write_sensor(sd, S5K83A_FLIP, data, 1);
if (err < 0)
return err;
data[0] = (vflip) ? 0x0b : 0x0a;
err = m5602_write_sensor(sd, S5K83A_VFLIP_TUNE, data, 1);
if (err < 0)
return err;
data[0] = (hflip) ? 0x0a : 0x0b;
err = m5602_write_sensor(sd, S5K83A_HFLIP_TUNE, data, 1);
return err;
}
static int s5k83a_set_vflip(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 reg;
__s32 hflip;
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
sens_priv->settings[VFLIP_IDX] = val;
s5k83a_get_hflip(gspca_dev, &hflip);
err = s5k83a_get_rotation(sd, ®);
if (err < 0)
return err;
if (reg) {
val = !val;
hflip = !hflip;
}
err = s5k83a_set_flip_real(gspca_dev, val, hflip);
return err;
}
static int s5k83a_get_hflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
*val = sens_priv->settings[HFLIP_IDX];
return 0;
}
static int s5k83a_set_hflip(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 reg;
__s32 vflip;
struct sd *sd = (struct sd *) gspca_dev;
struct s5k83a_priv *sens_priv = sd->sensor_priv;
sens_priv->settings[HFLIP_IDX] = val;
s5k83a_get_vflip(gspca_dev, &vflip);
err = s5k83a_get_rotation(sd, ®);
if (err < 0)
return err;
if (reg) {
val = !val;
vflip = !vflip;
}
err = s5k83a_set_flip_real(gspca_dev, vflip, val);
return err;
}
static int s5k83a_set_led_indication(struct sd *sd, u8 val)
{
int err = 0;
u8 data[1];
err = m5602_read_bridge(sd, M5602_XB_GPIO_DAT, data);
if (err < 0)
return err;
if (val)
data[0] = data[0] | S5K83A_GPIO_LED_MASK;
else
data[0] = data[0] & ~S5K83A_GPIO_LED_MASK;
err = m5602_write_bridge(sd, M5602_XB_GPIO_DAT, data[0]);
return err;
}
/* Get camera rotation on Acer notebooks */
static int s5k83a_get_rotation(struct sd *sd, u8 *reg_data)
{
int err = m5602_read_bridge(sd, M5602_XB_GPIO_DAT, reg_data);
*reg_data = (*reg_data & S5K83A_GPIO_ROTATION_MASK) ? 0 : 1;
return err;
}
static void s5k83a_dump_registers(struct sd *sd)
{
int address;
u8 page, old_page;
m5602_read_sensor(sd, S5K83A_PAGE_MAP, &old_page, 1);
for (page = 0; page < 16; page++) {
m5602_write_sensor(sd, S5K83A_PAGE_MAP, &page, 1);
info("Dumping the s5k83a register state for page 0x%x", page);
for (address = 0; address <= 0xff; address++) {
u8 val = 0;
m5602_read_sensor(sd, address, &val, 1);
info("register 0x%x contains 0x%x",
address, val);
}
}
info("s5k83a register state dump complete");
for (page = 0; page < 16; page++) {
m5602_write_sensor(sd, S5K83A_PAGE_MAP, &page, 1);
info("Probing for which registers that are read/write "
"for page 0x%x", page);
for (address = 0; address <= 0xff; address++) {
u8 old_val, ctrl_val, test_val = 0xff;
m5602_read_sensor(sd, address, &old_val, 1);
m5602_write_sensor(sd, address, &test_val, 1);
m5602_read_sensor(sd, address, &ctrl_val, 1);
if (ctrl_val == test_val)
info("register 0x%x is writeable", address);
else
info("register 0x%x is read only", address);
/* Restore original val */
m5602_write_sensor(sd, address, &old_val, 1);
}
}
info("Read/write register probing complete");
m5602_write_sensor(sd, S5K83A_PAGE_MAP, &old_page, 1);
}
| gpl-2.0 |
shepherd44/kernel_3.14.4 | drivers/input/ff-memless.c | 3497 | 14537 | /*
* Force feedback support for memoryless devices
*
* Copyright (c) 2006 Anssi Hannula <anssi.hannula@gmail.com>
* Copyright (c) 2006 Dmitry Torokhov <dtor@mail.ru>
*/
/*
* 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
*/
/* #define DEBUG */
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/spinlock.h>
#include <linux/jiffies.h>
#include <linux/fixp-arith.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Anssi Hannula <anssi.hannula@gmail.com>");
MODULE_DESCRIPTION("Force feedback support for memoryless devices");
/* Number of effects handled with memoryless devices */
#define FF_MEMLESS_EFFECTS 16
/* Envelope update interval in ms */
#define FF_ENVELOPE_INTERVAL 50
#define FF_EFFECT_STARTED 0
#define FF_EFFECT_PLAYING 1
#define FF_EFFECT_ABORTING 2
struct ml_effect_state {
struct ff_effect *effect;
unsigned long flags; /* effect state (STARTED, PLAYING, etc) */
int count; /* loop count of the effect */
unsigned long play_at; /* start time */
unsigned long stop_at; /* stop time */
unsigned long adj_at; /* last time the effect was sent */
};
struct ml_device {
void *private;
struct ml_effect_state states[FF_MEMLESS_EFFECTS];
int gain;
struct timer_list timer;
struct input_dev *dev;
int (*play_effect)(struct input_dev *dev, void *data,
struct ff_effect *effect);
};
static const struct ff_envelope *get_envelope(const struct ff_effect *effect)
{
static const struct ff_envelope empty_envelope;
switch (effect->type) {
case FF_PERIODIC:
return &effect->u.periodic.envelope;
case FF_CONSTANT:
return &effect->u.constant.envelope;
default:
return &empty_envelope;
}
}
/*
* Check for the next time envelope requires an update on memoryless devices
*/
static unsigned long calculate_next_time(struct ml_effect_state *state)
{
const struct ff_envelope *envelope = get_envelope(state->effect);
unsigned long attack_stop, fade_start, next_fade;
if (envelope->attack_length) {
attack_stop = state->play_at +
msecs_to_jiffies(envelope->attack_length);
if (time_before(state->adj_at, attack_stop))
return state->adj_at +
msecs_to_jiffies(FF_ENVELOPE_INTERVAL);
}
if (state->effect->replay.length) {
if (envelope->fade_length) {
/* check when fading should start */
fade_start = state->stop_at -
msecs_to_jiffies(envelope->fade_length);
if (time_before(state->adj_at, fade_start))
return fade_start;
/* already fading, advance to next checkpoint */
next_fade = state->adj_at +
msecs_to_jiffies(FF_ENVELOPE_INTERVAL);
if (time_before(next_fade, state->stop_at))
return next_fade;
}
return state->stop_at;
}
return state->play_at;
}
static void ml_schedule_timer(struct ml_device *ml)
{
struct ml_effect_state *state;
unsigned long now = jiffies;
unsigned long earliest = 0;
unsigned long next_at;
int events = 0;
int i;
pr_debug("calculating next timer\n");
for (i = 0; i < FF_MEMLESS_EFFECTS; i++) {
state = &ml->states[i];
if (!test_bit(FF_EFFECT_STARTED, &state->flags))
continue;
if (test_bit(FF_EFFECT_PLAYING, &state->flags))
next_at = calculate_next_time(state);
else
next_at = state->play_at;
if (time_before_eq(now, next_at) &&
(++events == 1 || time_before(next_at, earliest)))
earliest = next_at;
}
if (!events) {
pr_debug("no actions\n");
del_timer(&ml->timer);
} else {
pr_debug("timer set\n");
mod_timer(&ml->timer, earliest);
}
}
/*
* Apply an envelope to a value
*/
static int apply_envelope(struct ml_effect_state *state, int value,
struct ff_envelope *envelope)
{
struct ff_effect *effect = state->effect;
unsigned long now = jiffies;
int time_from_level;
int time_of_envelope;
int envelope_level;
int difference;
if (envelope->attack_length &&
time_before(now,
state->play_at + msecs_to_jiffies(envelope->attack_length))) {
pr_debug("value = 0x%x, attack_level = 0x%x\n",
value, envelope->attack_level);
time_from_level = jiffies_to_msecs(now - state->play_at);
time_of_envelope = envelope->attack_length;
envelope_level = min_t(u16, envelope->attack_level, 0x7fff);
} else if (envelope->fade_length && effect->replay.length &&
time_after(now,
state->stop_at - msecs_to_jiffies(envelope->fade_length)) &&
time_before(now, state->stop_at)) {
time_from_level = jiffies_to_msecs(state->stop_at - now);
time_of_envelope = envelope->fade_length;
envelope_level = min_t(u16, envelope->fade_level, 0x7fff);
} else
return value;
difference = abs(value) - envelope_level;
pr_debug("difference = %d\n", difference);
pr_debug("time_from_level = 0x%x\n", time_from_level);
pr_debug("time_of_envelope = 0x%x\n", time_of_envelope);
difference = difference * time_from_level / time_of_envelope;
pr_debug("difference = %d\n", difference);
return value < 0 ?
-(difference + envelope_level) : (difference + envelope_level);
}
/*
* Return the type the effect has to be converted into (memless devices)
*/
static int get_compatible_type(struct ff_device *ff, int effect_type)
{
if (test_bit(effect_type, ff->ffbit))
return effect_type;
if (effect_type == FF_PERIODIC && test_bit(FF_RUMBLE, ff->ffbit))
return FF_RUMBLE;
pr_err("invalid type in get_compatible_type()\n");
return 0;
}
/*
* Only left/right direction should be used (under/over 0x8000) for
* forward/reverse motor direction (to keep calculation fast & simple).
*/
static u16 ml_calculate_direction(u16 direction, u16 force,
u16 new_direction, u16 new_force)
{
if (!force)
return new_direction;
if (!new_force)
return direction;
return (((u32)(direction >> 1) * force +
(new_direction >> 1) * new_force) /
(force + new_force)) << 1;
}
/*
* Combine two effects and apply gain.
*/
static void ml_combine_effects(struct ff_effect *effect,
struct ml_effect_state *state,
int gain)
{
struct ff_effect *new = state->effect;
unsigned int strong, weak, i;
int x, y;
fixp_t level;
switch (new->type) {
case FF_CONSTANT:
i = new->direction * 360 / 0xffff;
level = fixp_new16(apply_envelope(state,
new->u.constant.level,
&new->u.constant.envelope));
x = fixp_mult(fixp_sin(i), level) * gain / 0xffff;
y = fixp_mult(-fixp_cos(i), level) * gain / 0xffff;
/*
* here we abuse ff_ramp to hold x and y of constant force
* If in future any driver wants something else than x and y
* in s8, this should be changed to something more generic
*/
effect->u.ramp.start_level =
clamp_val(effect->u.ramp.start_level + x, -0x80, 0x7f);
effect->u.ramp.end_level =
clamp_val(effect->u.ramp.end_level + y, -0x80, 0x7f);
break;
case FF_RUMBLE:
strong = (u32)new->u.rumble.strong_magnitude * gain / 0xffff;
weak = (u32)new->u.rumble.weak_magnitude * gain / 0xffff;
if (effect->u.rumble.strong_magnitude + strong)
effect->direction = ml_calculate_direction(
effect->direction,
effect->u.rumble.strong_magnitude,
new->direction, strong);
else if (effect->u.rumble.weak_magnitude + weak)
effect->direction = ml_calculate_direction(
effect->direction,
effect->u.rumble.weak_magnitude,
new->direction, weak);
else
effect->direction = 0;
effect->u.rumble.strong_magnitude =
min(strong + effect->u.rumble.strong_magnitude,
0xffffU);
effect->u.rumble.weak_magnitude =
min(weak + effect->u.rumble.weak_magnitude, 0xffffU);
break;
case FF_PERIODIC:
i = apply_envelope(state, abs(new->u.periodic.magnitude),
&new->u.periodic.envelope);
/* here we also scale it 0x7fff => 0xffff */
i = i * gain / 0x7fff;
if (effect->u.rumble.strong_magnitude + i)
effect->direction = ml_calculate_direction(
effect->direction,
effect->u.rumble.strong_magnitude,
new->direction, i);
else
effect->direction = 0;
effect->u.rumble.strong_magnitude =
min(i + effect->u.rumble.strong_magnitude, 0xffffU);
effect->u.rumble.weak_magnitude =
min(i + effect->u.rumble.weak_magnitude, 0xffffU);
break;
default:
pr_err("invalid type in ml_combine_effects()\n");
break;
}
}
/*
* Because memoryless devices have only one effect per effect type active
* at one time we have to combine multiple effects into one
*/
static int ml_get_combo_effect(struct ml_device *ml,
unsigned long *effect_handled,
struct ff_effect *combo_effect)
{
struct ff_effect *effect;
struct ml_effect_state *state;
int effect_type;
int i;
memset(combo_effect, 0, sizeof(struct ff_effect));
for (i = 0; i < FF_MEMLESS_EFFECTS; i++) {
if (__test_and_set_bit(i, effect_handled))
continue;
state = &ml->states[i];
effect = state->effect;
if (!test_bit(FF_EFFECT_STARTED, &state->flags))
continue;
if (time_before(jiffies, state->play_at))
continue;
/*
* here we have started effects that are either
* currently playing (and may need be aborted)
* or need to start playing.
*/
effect_type = get_compatible_type(ml->dev->ff, effect->type);
if (combo_effect->type != effect_type) {
if (combo_effect->type != 0) {
__clear_bit(i, effect_handled);
continue;
}
combo_effect->type = effect_type;
}
if (__test_and_clear_bit(FF_EFFECT_ABORTING, &state->flags)) {
__clear_bit(FF_EFFECT_PLAYING, &state->flags);
__clear_bit(FF_EFFECT_STARTED, &state->flags);
} else if (effect->replay.length &&
time_after_eq(jiffies, state->stop_at)) {
__clear_bit(FF_EFFECT_PLAYING, &state->flags);
if (--state->count <= 0) {
__clear_bit(FF_EFFECT_STARTED, &state->flags);
} else {
state->play_at = jiffies +
msecs_to_jiffies(effect->replay.delay);
state->stop_at = state->play_at +
msecs_to_jiffies(effect->replay.length);
}
} else {
__set_bit(FF_EFFECT_PLAYING, &state->flags);
state->adj_at = jiffies;
ml_combine_effects(combo_effect, state, ml->gain);
}
}
return combo_effect->type != 0;
}
static void ml_play_effects(struct ml_device *ml)
{
struct ff_effect effect;
DECLARE_BITMAP(handled_bm, FF_MEMLESS_EFFECTS);
memset(handled_bm, 0, sizeof(handled_bm));
while (ml_get_combo_effect(ml, handled_bm, &effect))
ml->play_effect(ml->dev, ml->private, &effect);
ml_schedule_timer(ml);
}
static void ml_effect_timer(unsigned long timer_data)
{
struct input_dev *dev = (struct input_dev *)timer_data;
struct ml_device *ml = dev->ff->private;
unsigned long flags;
pr_debug("timer: updating effects\n");
spin_lock_irqsave(&dev->event_lock, flags);
ml_play_effects(ml);
spin_unlock_irqrestore(&dev->event_lock, flags);
}
/*
* Sets requested gain for FF effects. Called with dev->event_lock held.
*/
static void ml_ff_set_gain(struct input_dev *dev, u16 gain)
{
struct ml_device *ml = dev->ff->private;
int i;
ml->gain = gain;
for (i = 0; i < FF_MEMLESS_EFFECTS; i++)
__clear_bit(FF_EFFECT_PLAYING, &ml->states[i].flags);
ml_play_effects(ml);
}
/*
* Start/stop specified FF effect. Called with dev->event_lock held.
*/
static int ml_ff_playback(struct input_dev *dev, int effect_id, int value)
{
struct ml_device *ml = dev->ff->private;
struct ml_effect_state *state = &ml->states[effect_id];
if (value > 0) {
pr_debug("initiated play\n");
__set_bit(FF_EFFECT_STARTED, &state->flags);
state->count = value;
state->play_at = jiffies +
msecs_to_jiffies(state->effect->replay.delay);
state->stop_at = state->play_at +
msecs_to_jiffies(state->effect->replay.length);
state->adj_at = state->play_at;
} else {
pr_debug("initiated stop\n");
if (test_bit(FF_EFFECT_PLAYING, &state->flags))
__set_bit(FF_EFFECT_ABORTING, &state->flags);
else
__clear_bit(FF_EFFECT_STARTED, &state->flags);
}
ml_play_effects(ml);
return 0;
}
static int ml_ff_upload(struct input_dev *dev,
struct ff_effect *effect, struct ff_effect *old)
{
struct ml_device *ml = dev->ff->private;
struct ml_effect_state *state = &ml->states[effect->id];
spin_lock_irq(&dev->event_lock);
if (test_bit(FF_EFFECT_STARTED, &state->flags)) {
__clear_bit(FF_EFFECT_PLAYING, &state->flags);
state->play_at = jiffies +
msecs_to_jiffies(state->effect->replay.delay);
state->stop_at = state->play_at +
msecs_to_jiffies(state->effect->replay.length);
state->adj_at = state->play_at;
ml_schedule_timer(ml);
}
spin_unlock_irq(&dev->event_lock);
return 0;
}
static void ml_ff_destroy(struct ff_device *ff)
{
struct ml_device *ml = ff->private;
kfree(ml->private);
}
/**
* input_ff_create_memless() - create memoryless force-feedback device
* @dev: input device supporting force-feedback
* @data: driver-specific data to be passed into @play_effect
* @play_effect: driver-specific method for playing FF effect
*/
int input_ff_create_memless(struct input_dev *dev, void *data,
int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
{
struct ml_device *ml;
struct ff_device *ff;
int error;
int i;
ml = kzalloc(sizeof(struct ml_device), GFP_KERNEL);
if (!ml)
return -ENOMEM;
ml->dev = dev;
ml->private = data;
ml->play_effect = play_effect;
ml->gain = 0xffff;
setup_timer(&ml->timer, ml_effect_timer, (unsigned long)dev);
set_bit(FF_GAIN, dev->ffbit);
error = input_ff_create(dev, FF_MEMLESS_EFFECTS);
if (error) {
kfree(ml);
return error;
}
ff = dev->ff;
ff->private = ml;
ff->upload = ml_ff_upload;
ff->playback = ml_ff_playback;
ff->set_gain = ml_ff_set_gain;
ff->destroy = ml_ff_destroy;
/* we can emulate periodic effects with RUMBLE */
if (test_bit(FF_RUMBLE, ff->ffbit)) {
set_bit(FF_PERIODIC, dev->ffbit);
set_bit(FF_SINE, dev->ffbit);
set_bit(FF_TRIANGLE, dev->ffbit);
set_bit(FF_SQUARE, dev->ffbit);
}
for (i = 0; i < FF_MEMLESS_EFFECTS; i++)
ml->states[i].effect = &ff->effects[i];
return 0;
}
EXPORT_SYMBOL_GPL(input_ff_create_memless);
| gpl-2.0 |
skelitonlord/android_kernel_samsung_matissewifi | arch/sparc/kernel/process_64.c | 4521 | 20600 | /* arch/sparc64/kernel/process.c
*
* Copyright (C) 1995, 1996, 2008 David S. Miller (davem@davemloft.net)
* Copyright (C) 1996 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1997, 1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
/*
* This file handles the architecture-dependent parts of process handling..
*/
#include <stdarg.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/delay.h>
#include <linux/compat.h>
#include <linux/tick.h>
#include <linux/init.h>
#include <linux/cpu.h>
#include <linux/elfcore.h>
#include <linux/sysrq.h>
#include <linux/nmi.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/pstate.h>
#include <asm/elf.h>
#include <asm/fpumacro.h>
#include <asm/head.h>
#include <asm/cpudata.h>
#include <asm/mmu_context.h>
#include <asm/unistd.h>
#include <asm/hypervisor.h>
#include <asm/syscalls.h>
#include <asm/irq_regs.h>
#include <asm/smp.h>
#include "kstack.h"
static void sparc64_yield(int cpu)
{
if (tlb_type != hypervisor) {
touch_nmi_watchdog();
return;
}
clear_thread_flag(TIF_POLLING_NRFLAG);
smp_mb__after_clear_bit();
while (!need_resched() && !cpu_is_offline(cpu)) {
unsigned long pstate;
/* Disable interrupts. */
__asm__ __volatile__(
"rdpr %%pstate, %0\n\t"
"andn %0, %1, %0\n\t"
"wrpr %0, %%g0, %%pstate"
: "=&r" (pstate)
: "i" (PSTATE_IE));
if (!need_resched() && !cpu_is_offline(cpu))
sun4v_cpu_yield();
/* Re-enable interrupts. */
__asm__ __volatile__(
"rdpr %%pstate, %0\n\t"
"or %0, %1, %0\n\t"
"wrpr %0, %%g0, %%pstate"
: "=&r" (pstate)
: "i" (PSTATE_IE));
}
set_thread_flag(TIF_POLLING_NRFLAG);
}
/* The idle loop on sparc64. */
void cpu_idle(void)
{
int cpu = smp_processor_id();
set_thread_flag(TIF_POLLING_NRFLAG);
while(1) {
tick_nohz_idle_enter();
rcu_idle_enter();
while (!need_resched() && !cpu_is_offline(cpu))
sparc64_yield(cpu);
rcu_idle_exit();
tick_nohz_idle_exit();
#ifdef CONFIG_HOTPLUG_CPU
if (cpu_is_offline(cpu)) {
sched_preempt_enable_no_resched();
cpu_play_dead();
}
#endif
schedule_preempt_disabled();
}
}
#ifdef CONFIG_COMPAT
static void show_regwindow32(struct pt_regs *regs)
{
struct reg_window32 __user *rw;
struct reg_window32 r_w;
mm_segment_t old_fs;
__asm__ __volatile__ ("flushw");
rw = compat_ptr((unsigned)regs->u_regs[14]);
old_fs = get_fs();
set_fs (USER_DS);
if (copy_from_user (&r_w, rw, sizeof(r_w))) {
set_fs (old_fs);
return;
}
set_fs (old_fs);
printk("l0: %08x l1: %08x l2: %08x l3: %08x "
"l4: %08x l5: %08x l6: %08x l7: %08x\n",
r_w.locals[0], r_w.locals[1], r_w.locals[2], r_w.locals[3],
r_w.locals[4], r_w.locals[5], r_w.locals[6], r_w.locals[7]);
printk("i0: %08x i1: %08x i2: %08x i3: %08x "
"i4: %08x i5: %08x i6: %08x i7: %08x\n",
r_w.ins[0], r_w.ins[1], r_w.ins[2], r_w.ins[3],
r_w.ins[4], r_w.ins[5], r_w.ins[6], r_w.ins[7]);
}
#else
#define show_regwindow32(regs) do { } while (0)
#endif
static void show_regwindow(struct pt_regs *regs)
{
struct reg_window __user *rw;
struct reg_window *rwk;
struct reg_window r_w;
mm_segment_t old_fs;
if ((regs->tstate & TSTATE_PRIV) || !(test_thread_flag(TIF_32BIT))) {
__asm__ __volatile__ ("flushw");
rw = (struct reg_window __user *)
(regs->u_regs[14] + STACK_BIAS);
rwk = (struct reg_window *)
(regs->u_regs[14] + STACK_BIAS);
if (!(regs->tstate & TSTATE_PRIV)) {
old_fs = get_fs();
set_fs (USER_DS);
if (copy_from_user (&r_w, rw, sizeof(r_w))) {
set_fs (old_fs);
return;
}
rwk = &r_w;
set_fs (old_fs);
}
} else {
show_regwindow32(regs);
return;
}
printk("l0: %016lx l1: %016lx l2: %016lx l3: %016lx\n",
rwk->locals[0], rwk->locals[1], rwk->locals[2], rwk->locals[3]);
printk("l4: %016lx l5: %016lx l6: %016lx l7: %016lx\n",
rwk->locals[4], rwk->locals[5], rwk->locals[6], rwk->locals[7]);
printk("i0: %016lx i1: %016lx i2: %016lx i3: %016lx\n",
rwk->ins[0], rwk->ins[1], rwk->ins[2], rwk->ins[3]);
printk("i4: %016lx i5: %016lx i6: %016lx i7: %016lx\n",
rwk->ins[4], rwk->ins[5], rwk->ins[6], rwk->ins[7]);
if (regs->tstate & TSTATE_PRIV)
printk("I7: <%pS>\n", (void *) rwk->ins[7]);
}
void show_regs(struct pt_regs *regs)
{
printk("TSTATE: %016lx TPC: %016lx TNPC: %016lx Y: %08x %s\n", regs->tstate,
regs->tpc, regs->tnpc, regs->y, print_tainted());
printk("TPC: <%pS>\n", (void *) regs->tpc);
printk("g0: %016lx g1: %016lx g2: %016lx g3: %016lx\n",
regs->u_regs[0], regs->u_regs[1], regs->u_regs[2],
regs->u_regs[3]);
printk("g4: %016lx g5: %016lx g6: %016lx g7: %016lx\n",
regs->u_regs[4], regs->u_regs[5], regs->u_regs[6],
regs->u_regs[7]);
printk("o0: %016lx o1: %016lx o2: %016lx o3: %016lx\n",
regs->u_regs[8], regs->u_regs[9], regs->u_regs[10],
regs->u_regs[11]);
printk("o4: %016lx o5: %016lx sp: %016lx ret_pc: %016lx\n",
regs->u_regs[12], regs->u_regs[13], regs->u_regs[14],
regs->u_regs[15]);
printk("RPC: <%pS>\n", (void *) regs->u_regs[15]);
show_regwindow(regs);
show_stack(current, (unsigned long *) regs->u_regs[UREG_FP]);
}
struct global_reg_snapshot global_reg_snapshot[NR_CPUS];
static DEFINE_SPINLOCK(global_reg_snapshot_lock);
static void __global_reg_self(struct thread_info *tp, struct pt_regs *regs,
int this_cpu)
{
flushw_all();
global_reg_snapshot[this_cpu].tstate = regs->tstate;
global_reg_snapshot[this_cpu].tpc = regs->tpc;
global_reg_snapshot[this_cpu].tnpc = regs->tnpc;
global_reg_snapshot[this_cpu].o7 = regs->u_regs[UREG_I7];
if (regs->tstate & TSTATE_PRIV) {
struct reg_window *rw;
rw = (struct reg_window *)
(regs->u_regs[UREG_FP] + STACK_BIAS);
if (kstack_valid(tp, (unsigned long) rw)) {
global_reg_snapshot[this_cpu].i7 = rw->ins[7];
rw = (struct reg_window *)
(rw->ins[6] + STACK_BIAS);
if (kstack_valid(tp, (unsigned long) rw))
global_reg_snapshot[this_cpu].rpc = rw->ins[7];
}
} else {
global_reg_snapshot[this_cpu].i7 = 0;
global_reg_snapshot[this_cpu].rpc = 0;
}
global_reg_snapshot[this_cpu].thread = tp;
}
/* In order to avoid hangs we do not try to synchronize with the
* global register dump client cpus. The last store they make is to
* the thread pointer, so do a short poll waiting for that to become
* non-NULL.
*/
static void __global_reg_poll(struct global_reg_snapshot *gp)
{
int limit = 0;
while (!gp->thread && ++limit < 100) {
barrier();
udelay(1);
}
}
void arch_trigger_all_cpu_backtrace(void)
{
struct thread_info *tp = current_thread_info();
struct pt_regs *regs = get_irq_regs();
unsigned long flags;
int this_cpu, cpu;
if (!regs)
regs = tp->kregs;
spin_lock_irqsave(&global_reg_snapshot_lock, flags);
memset(global_reg_snapshot, 0, sizeof(global_reg_snapshot));
this_cpu = raw_smp_processor_id();
__global_reg_self(tp, regs, this_cpu);
smp_fetch_global_regs();
for_each_online_cpu(cpu) {
struct global_reg_snapshot *gp = &global_reg_snapshot[cpu];
__global_reg_poll(gp);
tp = gp->thread;
printk("%c CPU[%3d]: TSTATE[%016lx] TPC[%016lx] TNPC[%016lx] TASK[%s:%d]\n",
(cpu == this_cpu ? '*' : ' '), cpu,
gp->tstate, gp->tpc, gp->tnpc,
((tp && tp->task) ? tp->task->comm : "NULL"),
((tp && tp->task) ? tp->task->pid : -1));
if (gp->tstate & TSTATE_PRIV) {
printk(" TPC[%pS] O7[%pS] I7[%pS] RPC[%pS]\n",
(void *) gp->tpc,
(void *) gp->o7,
(void *) gp->i7,
(void *) gp->rpc);
} else {
printk(" TPC[%lx] O7[%lx] I7[%lx] RPC[%lx]\n",
gp->tpc, gp->o7, gp->i7, gp->rpc);
}
}
memset(global_reg_snapshot, 0, sizeof(global_reg_snapshot));
spin_unlock_irqrestore(&global_reg_snapshot_lock, flags);
}
#ifdef CONFIG_MAGIC_SYSRQ
static void sysrq_handle_globreg(int key)
{
arch_trigger_all_cpu_backtrace();
}
static struct sysrq_key_op sparc_globalreg_op = {
.handler = sysrq_handle_globreg,
.help_msg = "Globalregs",
.action_msg = "Show Global CPU Regs",
};
static int __init sparc_globreg_init(void)
{
return register_sysrq_key('y', &sparc_globalreg_op);
}
core_initcall(sparc_globreg_init);
#endif
unsigned long thread_saved_pc(struct task_struct *tsk)
{
struct thread_info *ti = task_thread_info(tsk);
unsigned long ret = 0xdeadbeefUL;
if (ti && ti->ksp) {
unsigned long *sp;
sp = (unsigned long *)(ti->ksp + STACK_BIAS);
if (((unsigned long)sp & (sizeof(long) - 1)) == 0UL &&
sp[14]) {
unsigned long *fp;
fp = (unsigned long *)(sp[14] + STACK_BIAS);
if (((unsigned long)fp & (sizeof(long) - 1)) == 0UL)
ret = fp[15];
}
}
return ret;
}
/* Free current thread data structures etc.. */
void exit_thread(void)
{
struct thread_info *t = current_thread_info();
if (t->utraps) {
if (t->utraps[0] < 2)
kfree (t->utraps);
else
t->utraps[0]--;
}
}
void flush_thread(void)
{
struct thread_info *t = current_thread_info();
struct mm_struct *mm;
mm = t->task->mm;
if (mm)
tsb_context_switch(mm);
set_thread_wsaved(0);
/* Clear FPU register state. */
t->fpsaved[0] = 0;
}
/* It's a bit more tricky when 64-bit tasks are involved... */
static unsigned long clone_stackframe(unsigned long csp, unsigned long psp)
{
unsigned long fp, distance, rval;
if (!(test_thread_flag(TIF_32BIT))) {
csp += STACK_BIAS;
psp += STACK_BIAS;
__get_user(fp, &(((struct reg_window __user *)psp)->ins[6]));
fp += STACK_BIAS;
} else
__get_user(fp, &(((struct reg_window32 __user *)psp)->ins[6]));
/* Now align the stack as this is mandatory in the Sparc ABI
* due to how register windows work. This hides the
* restriction from thread libraries etc.
*/
csp &= ~15UL;
distance = fp - psp;
rval = (csp - distance);
if (copy_in_user((void __user *) rval, (void __user *) psp, distance))
rval = 0;
else if (test_thread_flag(TIF_32BIT)) {
if (put_user(((u32)csp),
&(((struct reg_window32 __user *)rval)->ins[6])))
rval = 0;
} else {
if (put_user(((u64)csp - STACK_BIAS),
&(((struct reg_window __user *)rval)->ins[6])))
rval = 0;
else
rval = rval - STACK_BIAS;
}
return rval;
}
/* Standard stuff. */
static inline void shift_window_buffer(int first_win, int last_win,
struct thread_info *t)
{
int i;
for (i = first_win; i < last_win; i++) {
t->rwbuf_stkptrs[i] = t->rwbuf_stkptrs[i+1];
memcpy(&t->reg_window[i], &t->reg_window[i+1],
sizeof(struct reg_window));
}
}
void synchronize_user_stack(void)
{
struct thread_info *t = current_thread_info();
unsigned long window;
flush_user_windows();
if ((window = get_thread_wsaved()) != 0) {
int winsize = sizeof(struct reg_window);
int bias = 0;
if (test_thread_flag(TIF_32BIT))
winsize = sizeof(struct reg_window32);
else
bias = STACK_BIAS;
window -= 1;
do {
unsigned long sp = (t->rwbuf_stkptrs[window] + bias);
struct reg_window *rwin = &t->reg_window[window];
if (!copy_to_user((char __user *)sp, rwin, winsize)) {
shift_window_buffer(window, get_thread_wsaved() - 1, t);
set_thread_wsaved(get_thread_wsaved() - 1);
}
} while (window--);
}
}
static void stack_unaligned(unsigned long sp)
{
siginfo_t info;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *) sp;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void fault_in_user_windows(void)
{
struct thread_info *t = current_thread_info();
unsigned long window;
int winsize = sizeof(struct reg_window);
int bias = 0;
if (test_thread_flag(TIF_32BIT))
winsize = sizeof(struct reg_window32);
else
bias = STACK_BIAS;
flush_user_windows();
window = get_thread_wsaved();
if (likely(window != 0)) {
window -= 1;
do {
unsigned long sp = (t->rwbuf_stkptrs[window] + bias);
struct reg_window *rwin = &t->reg_window[window];
if (unlikely(sp & 0x7UL))
stack_unaligned(sp);
if (unlikely(copy_to_user((char __user *)sp,
rwin, winsize)))
goto barf;
} while (window--);
}
set_thread_wsaved(0);
return;
barf:
set_thread_wsaved(window + 1);
do_exit(SIGILL);
}
asmlinkage long sparc_do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size)
{
int __user *parent_tid_ptr, *child_tid_ptr;
unsigned long orig_i1 = regs->u_regs[UREG_I1];
long ret;
#ifdef CONFIG_COMPAT
if (test_thread_flag(TIF_32BIT)) {
parent_tid_ptr = compat_ptr(regs->u_regs[UREG_I2]);
child_tid_ptr = compat_ptr(regs->u_regs[UREG_I4]);
} else
#endif
{
parent_tid_ptr = (int __user *) regs->u_regs[UREG_I2];
child_tid_ptr = (int __user *) regs->u_regs[UREG_I4];
}
ret = do_fork(clone_flags, stack_start,
regs, stack_size,
parent_tid_ptr, child_tid_ptr);
/* If we get an error and potentially restart the system
* call, we're screwed because copy_thread() clobbered
* the parent's %o1. So detect that case and restore it
* here.
*/
if ((unsigned long)ret >= -ERESTART_RESTARTBLOCK)
regs->u_regs[UREG_I1] = orig_i1;
return ret;
}
/* Copy a Sparc thread. The fork() return value conventions
* under SunOS are nothing short of bletcherous:
* Parent --> %o0 == childs pid, %o1 == 0
* Child --> %o0 == parents pid, %o1 == 1
*/
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long unused,
struct task_struct *p, struct pt_regs *regs)
{
struct thread_info *t = task_thread_info(p);
struct sparc_stackf *parent_sf;
unsigned long child_stack_sz;
char *child_trap_frame;
int kernel_thread;
kernel_thread = (regs->tstate & TSTATE_PRIV) ? 1 : 0;
parent_sf = ((struct sparc_stackf *) regs) - 1;
/* Calculate offset to stack_frame & pt_regs */
child_stack_sz = ((STACKFRAME_SZ + TRACEREG_SZ) +
(kernel_thread ? STACKFRAME_SZ : 0));
child_trap_frame = (task_stack_page(p) +
(THREAD_SIZE - child_stack_sz));
memcpy(child_trap_frame, parent_sf, child_stack_sz);
t->flags = (t->flags & ~((0xffUL << TI_FLAG_CWP_SHIFT) |
(0xffUL << TI_FLAG_CURRENT_DS_SHIFT))) |
(((regs->tstate + 1) & TSTATE_CWP) << TI_FLAG_CWP_SHIFT);
t->new_child = 1;
t->ksp = ((unsigned long) child_trap_frame) - STACK_BIAS;
t->kregs = (struct pt_regs *) (child_trap_frame +
sizeof(struct sparc_stackf));
t->fpsaved[0] = 0;
if (kernel_thread) {
struct sparc_stackf *child_sf = (struct sparc_stackf *)
(child_trap_frame + (STACKFRAME_SZ + TRACEREG_SZ));
/* Zero terminate the stack backtrace. */
child_sf->fp = NULL;
t->kregs->u_regs[UREG_FP] =
((unsigned long) child_sf) - STACK_BIAS;
t->flags |= ((long)ASI_P << TI_FLAG_CURRENT_DS_SHIFT);
t->kregs->u_regs[UREG_G6] = (unsigned long) t;
t->kregs->u_regs[UREG_G4] = (unsigned long) t->task;
} else {
if (t->flags & _TIF_32BIT) {
sp &= 0x00000000ffffffffUL;
regs->u_regs[UREG_FP] &= 0x00000000ffffffffUL;
}
t->kregs->u_regs[UREG_FP] = sp;
t->flags |= ((long)ASI_AIUS << TI_FLAG_CURRENT_DS_SHIFT);
if (sp != regs->u_regs[UREG_FP]) {
unsigned long csp;
csp = clone_stackframe(sp, regs->u_regs[UREG_FP]);
if (!csp)
return -EFAULT;
t->kregs->u_regs[UREG_FP] = csp;
}
if (t->utraps)
t->utraps[0]++;
}
/* Set the return value for the child. */
t->kregs->u_regs[UREG_I0] = current->pid;
t->kregs->u_regs[UREG_I1] = 1;
/* Set the second return value for the parent. */
regs->u_regs[UREG_I1] = 0;
if (clone_flags & CLONE_SETTLS)
t->kregs->u_regs[UREG_G7] = regs->u_regs[UREG_I3];
return 0;
}
/*
* This is the mechanism for creating a new kernel thread.
*
* NOTE! Only a kernel-only process(ie the swapper or direct descendants
* who haven't done an "execve()") should use this: it will work within
* a system call from a "real" process, but the process memory space will
* not be freed until both the parent and the child have exited.
*/
pid_t kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
{
long retval;
/* If the parent runs before fn(arg) is called by the child,
* the input registers of this function can be clobbered.
* So we stash 'fn' and 'arg' into global registers which
* will not be modified by the parent.
*/
__asm__ __volatile__("mov %4, %%g2\n\t" /* Save FN into global */
"mov %5, %%g3\n\t" /* Save ARG into global */
"mov %1, %%g1\n\t" /* Clone syscall nr. */
"mov %2, %%o0\n\t" /* Clone flags. */
"mov 0, %%o1\n\t" /* usp arg == 0 */
"t 0x6d\n\t" /* Linux/Sparc clone(). */
"brz,a,pn %%o1, 1f\n\t" /* Parent, just return. */
" mov %%o0, %0\n\t"
"jmpl %%g2, %%o7\n\t" /* Call the function. */
" mov %%g3, %%o0\n\t" /* Set arg in delay. */
"mov %3, %%g1\n\t"
"t 0x6d\n\t" /* Linux/Sparc exit(). */
/* Notreached by child. */
"1:" :
"=r" (retval) :
"i" (__NR_clone), "r" (flags | CLONE_VM | CLONE_UNTRACED),
"i" (__NR_exit), "r" (fn), "r" (arg) :
"g1", "g2", "g3", "o0", "o1", "memory", "cc");
return retval;
}
EXPORT_SYMBOL(kernel_thread);
typedef struct {
union {
unsigned int pr_regs[32];
unsigned long pr_dregs[16];
} pr_fr;
unsigned int __unused;
unsigned int pr_fsr;
unsigned char pr_qcnt;
unsigned char pr_q_entrysize;
unsigned char pr_en;
unsigned int pr_q[64];
} elf_fpregset_t32;
/*
* fill in the fpu structure for a core dump.
*/
int dump_fpu (struct pt_regs * regs, elf_fpregset_t * fpregs)
{
unsigned long *kfpregs = current_thread_info()->fpregs;
unsigned long fprs = current_thread_info()->fpsaved[0];
if (test_thread_flag(TIF_32BIT)) {
elf_fpregset_t32 *fpregs32 = (elf_fpregset_t32 *)fpregs;
if (fprs & FPRS_DL)
memcpy(&fpregs32->pr_fr.pr_regs[0], kfpregs,
sizeof(unsigned int) * 32);
else
memset(&fpregs32->pr_fr.pr_regs[0], 0,
sizeof(unsigned int) * 32);
fpregs32->pr_qcnt = 0;
fpregs32->pr_q_entrysize = 8;
memset(&fpregs32->pr_q[0], 0,
(sizeof(unsigned int) * 64));
if (fprs & FPRS_FEF) {
fpregs32->pr_fsr = (unsigned int) current_thread_info()->xfsr[0];
fpregs32->pr_en = 1;
} else {
fpregs32->pr_fsr = 0;
fpregs32->pr_en = 0;
}
} else {
if(fprs & FPRS_DL)
memcpy(&fpregs->pr_regs[0], kfpregs,
sizeof(unsigned int) * 32);
else
memset(&fpregs->pr_regs[0], 0,
sizeof(unsigned int) * 32);
if(fprs & FPRS_DU)
memcpy(&fpregs->pr_regs[16], kfpregs+16,
sizeof(unsigned int) * 32);
else
memset(&fpregs->pr_regs[16], 0,
sizeof(unsigned int) * 32);
if(fprs & FPRS_FEF) {
fpregs->pr_fsr = current_thread_info()->xfsr[0];
fpregs->pr_gsr = current_thread_info()->gsr[0];
} else {
fpregs->pr_fsr = fpregs->pr_gsr = 0;
}
fpregs->pr_fprs = fprs;
}
return 1;
}
EXPORT_SYMBOL(dump_fpu);
/*
* sparc_execve() executes a new program after the asm stub has set
* things up for us. This should basically do what I want it to.
*/
asmlinkage int sparc_execve(struct pt_regs *regs)
{
int error, base = 0;
char *filename;
/* User register window flush is done by entry.S */
/* Check for indirect call. */
if (regs->u_regs[UREG_G1] == 0)
base = 1;
filename = getname((char __user *)regs->u_regs[base + UREG_I0]);
error = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
error = do_execve(filename,
(const char __user *const __user *)
regs->u_regs[base + UREG_I1],
(const char __user *const __user *)
regs->u_regs[base + UREG_I2], regs);
putname(filename);
if (!error) {
fprs_write(0);
current_thread_info()->xfsr[0] = 0;
current_thread_info()->fpsaved[0] = 0;
regs->tstate &= ~TSTATE_PEF;
}
out:
return error;
}
unsigned long get_wchan(struct task_struct *task)
{
unsigned long pc, fp, bias = 0;
struct thread_info *tp;
struct reg_window *rw;
unsigned long ret = 0;
int count = 0;
if (!task || task == current ||
task->state == TASK_RUNNING)
goto out;
tp = task_thread_info(task);
bias = STACK_BIAS;
fp = task_thread_info(task)->ksp + bias;
do {
if (!kstack_valid(tp, fp))
break;
rw = (struct reg_window *) fp;
pc = rw->ins[7];
if (!in_sched_functions(pc)) {
ret = pc;
goto out;
}
fp = rw->ins[6] + bias;
} while (++count < 16);
out:
return ret;
}
| gpl-2.0 |
NoelMacwan/Kernel-10.4.1.B.0.101 | arch/sparc/kernel/process_64.c | 4521 | 20600 | /* arch/sparc64/kernel/process.c
*
* Copyright (C) 1995, 1996, 2008 David S. Miller (davem@davemloft.net)
* Copyright (C) 1996 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1997, 1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
/*
* This file handles the architecture-dependent parts of process handling..
*/
#include <stdarg.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/delay.h>
#include <linux/compat.h>
#include <linux/tick.h>
#include <linux/init.h>
#include <linux/cpu.h>
#include <linux/elfcore.h>
#include <linux/sysrq.h>
#include <linux/nmi.h>
#include <asm/uaccess.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/pstate.h>
#include <asm/elf.h>
#include <asm/fpumacro.h>
#include <asm/head.h>
#include <asm/cpudata.h>
#include <asm/mmu_context.h>
#include <asm/unistd.h>
#include <asm/hypervisor.h>
#include <asm/syscalls.h>
#include <asm/irq_regs.h>
#include <asm/smp.h>
#include "kstack.h"
static void sparc64_yield(int cpu)
{
if (tlb_type != hypervisor) {
touch_nmi_watchdog();
return;
}
clear_thread_flag(TIF_POLLING_NRFLAG);
smp_mb__after_clear_bit();
while (!need_resched() && !cpu_is_offline(cpu)) {
unsigned long pstate;
/* Disable interrupts. */
__asm__ __volatile__(
"rdpr %%pstate, %0\n\t"
"andn %0, %1, %0\n\t"
"wrpr %0, %%g0, %%pstate"
: "=&r" (pstate)
: "i" (PSTATE_IE));
if (!need_resched() && !cpu_is_offline(cpu))
sun4v_cpu_yield();
/* Re-enable interrupts. */
__asm__ __volatile__(
"rdpr %%pstate, %0\n\t"
"or %0, %1, %0\n\t"
"wrpr %0, %%g0, %%pstate"
: "=&r" (pstate)
: "i" (PSTATE_IE));
}
set_thread_flag(TIF_POLLING_NRFLAG);
}
/* The idle loop on sparc64. */
void cpu_idle(void)
{
int cpu = smp_processor_id();
set_thread_flag(TIF_POLLING_NRFLAG);
while(1) {
tick_nohz_idle_enter();
rcu_idle_enter();
while (!need_resched() && !cpu_is_offline(cpu))
sparc64_yield(cpu);
rcu_idle_exit();
tick_nohz_idle_exit();
#ifdef CONFIG_HOTPLUG_CPU
if (cpu_is_offline(cpu)) {
sched_preempt_enable_no_resched();
cpu_play_dead();
}
#endif
schedule_preempt_disabled();
}
}
#ifdef CONFIG_COMPAT
static void show_regwindow32(struct pt_regs *regs)
{
struct reg_window32 __user *rw;
struct reg_window32 r_w;
mm_segment_t old_fs;
__asm__ __volatile__ ("flushw");
rw = compat_ptr((unsigned)regs->u_regs[14]);
old_fs = get_fs();
set_fs (USER_DS);
if (copy_from_user (&r_w, rw, sizeof(r_w))) {
set_fs (old_fs);
return;
}
set_fs (old_fs);
printk("l0: %08x l1: %08x l2: %08x l3: %08x "
"l4: %08x l5: %08x l6: %08x l7: %08x\n",
r_w.locals[0], r_w.locals[1], r_w.locals[2], r_w.locals[3],
r_w.locals[4], r_w.locals[5], r_w.locals[6], r_w.locals[7]);
printk("i0: %08x i1: %08x i2: %08x i3: %08x "
"i4: %08x i5: %08x i6: %08x i7: %08x\n",
r_w.ins[0], r_w.ins[1], r_w.ins[2], r_w.ins[3],
r_w.ins[4], r_w.ins[5], r_w.ins[6], r_w.ins[7]);
}
#else
#define show_regwindow32(regs) do { } while (0)
#endif
static void show_regwindow(struct pt_regs *regs)
{
struct reg_window __user *rw;
struct reg_window *rwk;
struct reg_window r_w;
mm_segment_t old_fs;
if ((regs->tstate & TSTATE_PRIV) || !(test_thread_flag(TIF_32BIT))) {
__asm__ __volatile__ ("flushw");
rw = (struct reg_window __user *)
(regs->u_regs[14] + STACK_BIAS);
rwk = (struct reg_window *)
(regs->u_regs[14] + STACK_BIAS);
if (!(regs->tstate & TSTATE_PRIV)) {
old_fs = get_fs();
set_fs (USER_DS);
if (copy_from_user (&r_w, rw, sizeof(r_w))) {
set_fs (old_fs);
return;
}
rwk = &r_w;
set_fs (old_fs);
}
} else {
show_regwindow32(regs);
return;
}
printk("l0: %016lx l1: %016lx l2: %016lx l3: %016lx\n",
rwk->locals[0], rwk->locals[1], rwk->locals[2], rwk->locals[3]);
printk("l4: %016lx l5: %016lx l6: %016lx l7: %016lx\n",
rwk->locals[4], rwk->locals[5], rwk->locals[6], rwk->locals[7]);
printk("i0: %016lx i1: %016lx i2: %016lx i3: %016lx\n",
rwk->ins[0], rwk->ins[1], rwk->ins[2], rwk->ins[3]);
printk("i4: %016lx i5: %016lx i6: %016lx i7: %016lx\n",
rwk->ins[4], rwk->ins[5], rwk->ins[6], rwk->ins[7]);
if (regs->tstate & TSTATE_PRIV)
printk("I7: <%pS>\n", (void *) rwk->ins[7]);
}
void show_regs(struct pt_regs *regs)
{
printk("TSTATE: %016lx TPC: %016lx TNPC: %016lx Y: %08x %s\n", regs->tstate,
regs->tpc, regs->tnpc, regs->y, print_tainted());
printk("TPC: <%pS>\n", (void *) regs->tpc);
printk("g0: %016lx g1: %016lx g2: %016lx g3: %016lx\n",
regs->u_regs[0], regs->u_regs[1], regs->u_regs[2],
regs->u_regs[3]);
printk("g4: %016lx g5: %016lx g6: %016lx g7: %016lx\n",
regs->u_regs[4], regs->u_regs[5], regs->u_regs[6],
regs->u_regs[7]);
printk("o0: %016lx o1: %016lx o2: %016lx o3: %016lx\n",
regs->u_regs[8], regs->u_regs[9], regs->u_regs[10],
regs->u_regs[11]);
printk("o4: %016lx o5: %016lx sp: %016lx ret_pc: %016lx\n",
regs->u_regs[12], regs->u_regs[13], regs->u_regs[14],
regs->u_regs[15]);
printk("RPC: <%pS>\n", (void *) regs->u_regs[15]);
show_regwindow(regs);
show_stack(current, (unsigned long *) regs->u_regs[UREG_FP]);
}
struct global_reg_snapshot global_reg_snapshot[NR_CPUS];
static DEFINE_SPINLOCK(global_reg_snapshot_lock);
static void __global_reg_self(struct thread_info *tp, struct pt_regs *regs,
int this_cpu)
{
flushw_all();
global_reg_snapshot[this_cpu].tstate = regs->tstate;
global_reg_snapshot[this_cpu].tpc = regs->tpc;
global_reg_snapshot[this_cpu].tnpc = regs->tnpc;
global_reg_snapshot[this_cpu].o7 = regs->u_regs[UREG_I7];
if (regs->tstate & TSTATE_PRIV) {
struct reg_window *rw;
rw = (struct reg_window *)
(regs->u_regs[UREG_FP] + STACK_BIAS);
if (kstack_valid(tp, (unsigned long) rw)) {
global_reg_snapshot[this_cpu].i7 = rw->ins[7];
rw = (struct reg_window *)
(rw->ins[6] + STACK_BIAS);
if (kstack_valid(tp, (unsigned long) rw))
global_reg_snapshot[this_cpu].rpc = rw->ins[7];
}
} else {
global_reg_snapshot[this_cpu].i7 = 0;
global_reg_snapshot[this_cpu].rpc = 0;
}
global_reg_snapshot[this_cpu].thread = tp;
}
/* In order to avoid hangs we do not try to synchronize with the
* global register dump client cpus. The last store they make is to
* the thread pointer, so do a short poll waiting for that to become
* non-NULL.
*/
static void __global_reg_poll(struct global_reg_snapshot *gp)
{
int limit = 0;
while (!gp->thread && ++limit < 100) {
barrier();
udelay(1);
}
}
void arch_trigger_all_cpu_backtrace(void)
{
struct thread_info *tp = current_thread_info();
struct pt_regs *regs = get_irq_regs();
unsigned long flags;
int this_cpu, cpu;
if (!regs)
regs = tp->kregs;
spin_lock_irqsave(&global_reg_snapshot_lock, flags);
memset(global_reg_snapshot, 0, sizeof(global_reg_snapshot));
this_cpu = raw_smp_processor_id();
__global_reg_self(tp, regs, this_cpu);
smp_fetch_global_regs();
for_each_online_cpu(cpu) {
struct global_reg_snapshot *gp = &global_reg_snapshot[cpu];
__global_reg_poll(gp);
tp = gp->thread;
printk("%c CPU[%3d]: TSTATE[%016lx] TPC[%016lx] TNPC[%016lx] TASK[%s:%d]\n",
(cpu == this_cpu ? '*' : ' '), cpu,
gp->tstate, gp->tpc, gp->tnpc,
((tp && tp->task) ? tp->task->comm : "NULL"),
((tp && tp->task) ? tp->task->pid : -1));
if (gp->tstate & TSTATE_PRIV) {
printk(" TPC[%pS] O7[%pS] I7[%pS] RPC[%pS]\n",
(void *) gp->tpc,
(void *) gp->o7,
(void *) gp->i7,
(void *) gp->rpc);
} else {
printk(" TPC[%lx] O7[%lx] I7[%lx] RPC[%lx]\n",
gp->tpc, gp->o7, gp->i7, gp->rpc);
}
}
memset(global_reg_snapshot, 0, sizeof(global_reg_snapshot));
spin_unlock_irqrestore(&global_reg_snapshot_lock, flags);
}
#ifdef CONFIG_MAGIC_SYSRQ
static void sysrq_handle_globreg(int key)
{
arch_trigger_all_cpu_backtrace();
}
static struct sysrq_key_op sparc_globalreg_op = {
.handler = sysrq_handle_globreg,
.help_msg = "Globalregs",
.action_msg = "Show Global CPU Regs",
};
static int __init sparc_globreg_init(void)
{
return register_sysrq_key('y', &sparc_globalreg_op);
}
core_initcall(sparc_globreg_init);
#endif
unsigned long thread_saved_pc(struct task_struct *tsk)
{
struct thread_info *ti = task_thread_info(tsk);
unsigned long ret = 0xdeadbeefUL;
if (ti && ti->ksp) {
unsigned long *sp;
sp = (unsigned long *)(ti->ksp + STACK_BIAS);
if (((unsigned long)sp & (sizeof(long) - 1)) == 0UL &&
sp[14]) {
unsigned long *fp;
fp = (unsigned long *)(sp[14] + STACK_BIAS);
if (((unsigned long)fp & (sizeof(long) - 1)) == 0UL)
ret = fp[15];
}
}
return ret;
}
/* Free current thread data structures etc.. */
void exit_thread(void)
{
struct thread_info *t = current_thread_info();
if (t->utraps) {
if (t->utraps[0] < 2)
kfree (t->utraps);
else
t->utraps[0]--;
}
}
void flush_thread(void)
{
struct thread_info *t = current_thread_info();
struct mm_struct *mm;
mm = t->task->mm;
if (mm)
tsb_context_switch(mm);
set_thread_wsaved(0);
/* Clear FPU register state. */
t->fpsaved[0] = 0;
}
/* It's a bit more tricky when 64-bit tasks are involved... */
static unsigned long clone_stackframe(unsigned long csp, unsigned long psp)
{
unsigned long fp, distance, rval;
if (!(test_thread_flag(TIF_32BIT))) {
csp += STACK_BIAS;
psp += STACK_BIAS;
__get_user(fp, &(((struct reg_window __user *)psp)->ins[6]));
fp += STACK_BIAS;
} else
__get_user(fp, &(((struct reg_window32 __user *)psp)->ins[6]));
/* Now align the stack as this is mandatory in the Sparc ABI
* due to how register windows work. This hides the
* restriction from thread libraries etc.
*/
csp &= ~15UL;
distance = fp - psp;
rval = (csp - distance);
if (copy_in_user((void __user *) rval, (void __user *) psp, distance))
rval = 0;
else if (test_thread_flag(TIF_32BIT)) {
if (put_user(((u32)csp),
&(((struct reg_window32 __user *)rval)->ins[6])))
rval = 0;
} else {
if (put_user(((u64)csp - STACK_BIAS),
&(((struct reg_window __user *)rval)->ins[6])))
rval = 0;
else
rval = rval - STACK_BIAS;
}
return rval;
}
/* Standard stuff. */
static inline void shift_window_buffer(int first_win, int last_win,
struct thread_info *t)
{
int i;
for (i = first_win; i < last_win; i++) {
t->rwbuf_stkptrs[i] = t->rwbuf_stkptrs[i+1];
memcpy(&t->reg_window[i], &t->reg_window[i+1],
sizeof(struct reg_window));
}
}
void synchronize_user_stack(void)
{
struct thread_info *t = current_thread_info();
unsigned long window;
flush_user_windows();
if ((window = get_thread_wsaved()) != 0) {
int winsize = sizeof(struct reg_window);
int bias = 0;
if (test_thread_flag(TIF_32BIT))
winsize = sizeof(struct reg_window32);
else
bias = STACK_BIAS;
window -= 1;
do {
unsigned long sp = (t->rwbuf_stkptrs[window] + bias);
struct reg_window *rwin = &t->reg_window[window];
if (!copy_to_user((char __user *)sp, rwin, winsize)) {
shift_window_buffer(window, get_thread_wsaved() - 1, t);
set_thread_wsaved(get_thread_wsaved() - 1);
}
} while (window--);
}
}
static void stack_unaligned(unsigned long sp)
{
siginfo_t info;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *) sp;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void fault_in_user_windows(void)
{
struct thread_info *t = current_thread_info();
unsigned long window;
int winsize = sizeof(struct reg_window);
int bias = 0;
if (test_thread_flag(TIF_32BIT))
winsize = sizeof(struct reg_window32);
else
bias = STACK_BIAS;
flush_user_windows();
window = get_thread_wsaved();
if (likely(window != 0)) {
window -= 1;
do {
unsigned long sp = (t->rwbuf_stkptrs[window] + bias);
struct reg_window *rwin = &t->reg_window[window];
if (unlikely(sp & 0x7UL))
stack_unaligned(sp);
if (unlikely(copy_to_user((char __user *)sp,
rwin, winsize)))
goto barf;
} while (window--);
}
set_thread_wsaved(0);
return;
barf:
set_thread_wsaved(window + 1);
do_exit(SIGILL);
}
asmlinkage long sparc_do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size)
{
int __user *parent_tid_ptr, *child_tid_ptr;
unsigned long orig_i1 = regs->u_regs[UREG_I1];
long ret;
#ifdef CONFIG_COMPAT
if (test_thread_flag(TIF_32BIT)) {
parent_tid_ptr = compat_ptr(regs->u_regs[UREG_I2]);
child_tid_ptr = compat_ptr(regs->u_regs[UREG_I4]);
} else
#endif
{
parent_tid_ptr = (int __user *) regs->u_regs[UREG_I2];
child_tid_ptr = (int __user *) regs->u_regs[UREG_I4];
}
ret = do_fork(clone_flags, stack_start,
regs, stack_size,
parent_tid_ptr, child_tid_ptr);
/* If we get an error and potentially restart the system
* call, we're screwed because copy_thread() clobbered
* the parent's %o1. So detect that case and restore it
* here.
*/
if ((unsigned long)ret >= -ERESTART_RESTARTBLOCK)
regs->u_regs[UREG_I1] = orig_i1;
return ret;
}
/* Copy a Sparc thread. The fork() return value conventions
* under SunOS are nothing short of bletcherous:
* Parent --> %o0 == childs pid, %o1 == 0
* Child --> %o0 == parents pid, %o1 == 1
*/
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long unused,
struct task_struct *p, struct pt_regs *regs)
{
struct thread_info *t = task_thread_info(p);
struct sparc_stackf *parent_sf;
unsigned long child_stack_sz;
char *child_trap_frame;
int kernel_thread;
kernel_thread = (regs->tstate & TSTATE_PRIV) ? 1 : 0;
parent_sf = ((struct sparc_stackf *) regs) - 1;
/* Calculate offset to stack_frame & pt_regs */
child_stack_sz = ((STACKFRAME_SZ + TRACEREG_SZ) +
(kernel_thread ? STACKFRAME_SZ : 0));
child_trap_frame = (task_stack_page(p) +
(THREAD_SIZE - child_stack_sz));
memcpy(child_trap_frame, parent_sf, child_stack_sz);
t->flags = (t->flags & ~((0xffUL << TI_FLAG_CWP_SHIFT) |
(0xffUL << TI_FLAG_CURRENT_DS_SHIFT))) |
(((regs->tstate + 1) & TSTATE_CWP) << TI_FLAG_CWP_SHIFT);
t->new_child = 1;
t->ksp = ((unsigned long) child_trap_frame) - STACK_BIAS;
t->kregs = (struct pt_regs *) (child_trap_frame +
sizeof(struct sparc_stackf));
t->fpsaved[0] = 0;
if (kernel_thread) {
struct sparc_stackf *child_sf = (struct sparc_stackf *)
(child_trap_frame + (STACKFRAME_SZ + TRACEREG_SZ));
/* Zero terminate the stack backtrace. */
child_sf->fp = NULL;
t->kregs->u_regs[UREG_FP] =
((unsigned long) child_sf) - STACK_BIAS;
t->flags |= ((long)ASI_P << TI_FLAG_CURRENT_DS_SHIFT);
t->kregs->u_regs[UREG_G6] = (unsigned long) t;
t->kregs->u_regs[UREG_G4] = (unsigned long) t->task;
} else {
if (t->flags & _TIF_32BIT) {
sp &= 0x00000000ffffffffUL;
regs->u_regs[UREG_FP] &= 0x00000000ffffffffUL;
}
t->kregs->u_regs[UREG_FP] = sp;
t->flags |= ((long)ASI_AIUS << TI_FLAG_CURRENT_DS_SHIFT);
if (sp != regs->u_regs[UREG_FP]) {
unsigned long csp;
csp = clone_stackframe(sp, regs->u_regs[UREG_FP]);
if (!csp)
return -EFAULT;
t->kregs->u_regs[UREG_FP] = csp;
}
if (t->utraps)
t->utraps[0]++;
}
/* Set the return value for the child. */
t->kregs->u_regs[UREG_I0] = current->pid;
t->kregs->u_regs[UREG_I1] = 1;
/* Set the second return value for the parent. */
regs->u_regs[UREG_I1] = 0;
if (clone_flags & CLONE_SETTLS)
t->kregs->u_regs[UREG_G7] = regs->u_regs[UREG_I3];
return 0;
}
/*
* This is the mechanism for creating a new kernel thread.
*
* NOTE! Only a kernel-only process(ie the swapper or direct descendants
* who haven't done an "execve()") should use this: it will work within
* a system call from a "real" process, but the process memory space will
* not be freed until both the parent and the child have exited.
*/
pid_t kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
{
long retval;
/* If the parent runs before fn(arg) is called by the child,
* the input registers of this function can be clobbered.
* So we stash 'fn' and 'arg' into global registers which
* will not be modified by the parent.
*/
__asm__ __volatile__("mov %4, %%g2\n\t" /* Save FN into global */
"mov %5, %%g3\n\t" /* Save ARG into global */
"mov %1, %%g1\n\t" /* Clone syscall nr. */
"mov %2, %%o0\n\t" /* Clone flags. */
"mov 0, %%o1\n\t" /* usp arg == 0 */
"t 0x6d\n\t" /* Linux/Sparc clone(). */
"brz,a,pn %%o1, 1f\n\t" /* Parent, just return. */
" mov %%o0, %0\n\t"
"jmpl %%g2, %%o7\n\t" /* Call the function. */
" mov %%g3, %%o0\n\t" /* Set arg in delay. */
"mov %3, %%g1\n\t"
"t 0x6d\n\t" /* Linux/Sparc exit(). */
/* Notreached by child. */
"1:" :
"=r" (retval) :
"i" (__NR_clone), "r" (flags | CLONE_VM | CLONE_UNTRACED),
"i" (__NR_exit), "r" (fn), "r" (arg) :
"g1", "g2", "g3", "o0", "o1", "memory", "cc");
return retval;
}
EXPORT_SYMBOL(kernel_thread);
typedef struct {
union {
unsigned int pr_regs[32];
unsigned long pr_dregs[16];
} pr_fr;
unsigned int __unused;
unsigned int pr_fsr;
unsigned char pr_qcnt;
unsigned char pr_q_entrysize;
unsigned char pr_en;
unsigned int pr_q[64];
} elf_fpregset_t32;
/*
* fill in the fpu structure for a core dump.
*/
int dump_fpu (struct pt_regs * regs, elf_fpregset_t * fpregs)
{
unsigned long *kfpregs = current_thread_info()->fpregs;
unsigned long fprs = current_thread_info()->fpsaved[0];
if (test_thread_flag(TIF_32BIT)) {
elf_fpregset_t32 *fpregs32 = (elf_fpregset_t32 *)fpregs;
if (fprs & FPRS_DL)
memcpy(&fpregs32->pr_fr.pr_regs[0], kfpregs,
sizeof(unsigned int) * 32);
else
memset(&fpregs32->pr_fr.pr_regs[0], 0,
sizeof(unsigned int) * 32);
fpregs32->pr_qcnt = 0;
fpregs32->pr_q_entrysize = 8;
memset(&fpregs32->pr_q[0], 0,
(sizeof(unsigned int) * 64));
if (fprs & FPRS_FEF) {
fpregs32->pr_fsr = (unsigned int) current_thread_info()->xfsr[0];
fpregs32->pr_en = 1;
} else {
fpregs32->pr_fsr = 0;
fpregs32->pr_en = 0;
}
} else {
if(fprs & FPRS_DL)
memcpy(&fpregs->pr_regs[0], kfpregs,
sizeof(unsigned int) * 32);
else
memset(&fpregs->pr_regs[0], 0,
sizeof(unsigned int) * 32);
if(fprs & FPRS_DU)
memcpy(&fpregs->pr_regs[16], kfpregs+16,
sizeof(unsigned int) * 32);
else
memset(&fpregs->pr_regs[16], 0,
sizeof(unsigned int) * 32);
if(fprs & FPRS_FEF) {
fpregs->pr_fsr = current_thread_info()->xfsr[0];
fpregs->pr_gsr = current_thread_info()->gsr[0];
} else {
fpregs->pr_fsr = fpregs->pr_gsr = 0;
}
fpregs->pr_fprs = fprs;
}
return 1;
}
EXPORT_SYMBOL(dump_fpu);
/*
* sparc_execve() executes a new program after the asm stub has set
* things up for us. This should basically do what I want it to.
*/
asmlinkage int sparc_execve(struct pt_regs *regs)
{
int error, base = 0;
char *filename;
/* User register window flush is done by entry.S */
/* Check for indirect call. */
if (regs->u_regs[UREG_G1] == 0)
base = 1;
filename = getname((char __user *)regs->u_regs[base + UREG_I0]);
error = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
error = do_execve(filename,
(const char __user *const __user *)
regs->u_regs[base + UREG_I1],
(const char __user *const __user *)
regs->u_regs[base + UREG_I2], regs);
putname(filename);
if (!error) {
fprs_write(0);
current_thread_info()->xfsr[0] = 0;
current_thread_info()->fpsaved[0] = 0;
regs->tstate &= ~TSTATE_PEF;
}
out:
return error;
}
unsigned long get_wchan(struct task_struct *task)
{
unsigned long pc, fp, bias = 0;
struct thread_info *tp;
struct reg_window *rw;
unsigned long ret = 0;
int count = 0;
if (!task || task == current ||
task->state == TASK_RUNNING)
goto out;
tp = task_thread_info(task);
bias = STACK_BIAS;
fp = task_thread_info(task)->ksp + bias;
do {
if (!kstack_valid(tp, fp))
break;
rw = (struct reg_window *) fp;
pc = rw->ins[7];
if (!in_sched_functions(pc)) {
ret = pc;
goto out;
}
fp = rw->ins[6] + bias;
} while (++count < 16);
out:
return ret;
}
| gpl-2.0 |
fnoji/android_kernel_htc_impj | drivers/input/tablet/wacom_sys.c | 4777 | 29880 | /*
* drivers/input/tablet/wacom_sys.c
*
* USB Wacom tablet support - system specific code
*/
/*
* 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 "wacom_wac.h"
#include "wacom.h"
/* defines to get HID report descriptor */
#define HID_DEVICET_HID (USB_TYPE_CLASS | 0x01)
#define HID_DEVICET_REPORT (USB_TYPE_CLASS | 0x02)
#define HID_USAGE_UNDEFINED 0x00
#define HID_USAGE_PAGE 0x05
#define HID_USAGE_PAGE_DIGITIZER 0x0d
#define HID_USAGE_PAGE_DESKTOP 0x01
#define HID_USAGE 0x09
#define HID_USAGE_X 0x30
#define HID_USAGE_Y 0x31
#define HID_USAGE_X_TILT 0x3d
#define HID_USAGE_Y_TILT 0x3e
#define HID_USAGE_FINGER 0x22
#define HID_USAGE_STYLUS 0x20
#define HID_COLLECTION 0xa1
#define HID_COLLECTION_LOGICAL 0x02
#define HID_COLLECTION_END 0xc0
enum {
WCM_UNDEFINED = 0,
WCM_DESKTOP,
WCM_DIGITIZER,
};
struct hid_descriptor {
struct usb_descriptor_header header;
__le16 bcdHID;
u8 bCountryCode;
u8 bNumDescriptors;
u8 bDescriptorType;
__le16 wDescriptorLength;
} __attribute__ ((packed));
/* defines to get/set USB message */
#define USB_REQ_GET_REPORT 0x01
#define USB_REQ_SET_REPORT 0x09
#define WAC_HID_FEATURE_REPORT 0x03
#define WAC_MSG_RETRIES 5
#define WAC_CMD_LED_CONTROL 0x20
#define WAC_CMD_ICON_START 0x21
#define WAC_CMD_ICON_XFER 0x23
#define WAC_CMD_RETRIES 10
static int wacom_get_report(struct usb_interface *intf, u8 type, u8 id,
void *buf, size_t size, unsigned int retries)
{
struct usb_device *dev = interface_to_usbdev(intf);
int retval;
do {
retval = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_REPORT,
USB_DIR_IN | USB_TYPE_CLASS |
USB_RECIP_INTERFACE,
(type << 8) + id,
intf->altsetting[0].desc.bInterfaceNumber,
buf, size, 100);
} while ((retval == -ETIMEDOUT || retval == -EPIPE) && --retries);
return retval;
}
static int wacom_set_report(struct usb_interface *intf, u8 type, u8 id,
void *buf, size_t size, unsigned int retries)
{
struct usb_device *dev = interface_to_usbdev(intf);
int retval;
do {
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_REPORT,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
(type << 8) + id,
intf->altsetting[0].desc.bInterfaceNumber,
buf, size, 1000);
} while ((retval == -ETIMEDOUT || retval == -EPIPE) && --retries);
return retval;
}
static void wacom_sys_irq(struct urb *urb)
{
struct wacom *wacom = urb->context;
int retval;
switch (urb->status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d", __func__, urb->status);
return;
default:
dbg("%s - nonzero urb status received: %d", __func__, urb->status);
goto exit;
}
wacom_wac_irq(&wacom->wacom_wac, urb->actual_length);
exit:
usb_mark_last_busy(wacom->usbdev);
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
err ("%s - usb_submit_urb failed with result %d",
__func__, retval);
}
static int wacom_open(struct input_dev *dev)
{
struct wacom *wacom = input_get_drvdata(dev);
int retval = 0;
if (usb_autopm_get_interface(wacom->intf) < 0)
return -EIO;
mutex_lock(&wacom->lock);
if (usb_submit_urb(wacom->irq, GFP_KERNEL)) {
retval = -EIO;
goto out;
}
wacom->open = true;
wacom->intf->needs_remote_wakeup = 1;
out:
mutex_unlock(&wacom->lock);
usb_autopm_put_interface(wacom->intf);
return retval;
}
static void wacom_close(struct input_dev *dev)
{
struct wacom *wacom = input_get_drvdata(dev);
int autopm_error;
autopm_error = usb_autopm_get_interface(wacom->intf);
mutex_lock(&wacom->lock);
usb_kill_urb(wacom->irq);
wacom->open = false;
wacom->intf->needs_remote_wakeup = 0;
mutex_unlock(&wacom->lock);
if (!autopm_error)
usb_autopm_put_interface(wacom->intf);
}
/*
* Static values for max X/Y and resolution of Pen interface is stored in
* features. This mean physical size of active area can be computed.
* This is useful to do when Pen and Touch have same active area of tablet.
* This means for Touch device, we only need to find max X/Y value and we
* have enough information to compute resolution of touch.
*/
static void wacom_set_phy_from_res(struct wacom_features *features)
{
features->x_phy = (features->x_max * 100) / features->x_resolution;
features->y_phy = (features->y_max * 100) / features->y_resolution;
}
static int wacom_parse_logical_collection(unsigned char *report,
struct wacom_features *features)
{
int length = 0;
if (features->type == BAMBOO_PT) {
/* Logical collection is only used by 3rd gen Bamboo Touch */
features->pktlen = WACOM_PKGLEN_BBTOUCH3;
features->device_type = BTN_TOOL_FINGER;
wacom_set_phy_from_res(features);
features->x_max = features->y_max =
get_unaligned_le16(&report[10]);
length = 11;
}
return length;
}
/*
* Interface Descriptor of wacom devices can be incomplete and
* inconsistent so wacom_features table is used to store stylus
* device's packet lengths, various maximum values, and tablet
* resolution based on product ID's.
*
* For devices that contain 2 interfaces, wacom_features table is
* inaccurate for the touch interface. Since the Interface Descriptor
* for touch interfaces has pretty complete data, this function exists
* to query tablet for this missing information instead of hard coding in
* an additional table.
*
* A typical Interface Descriptor for a stylus will contain a
* boot mouse application collection that is not of interest and this
* function will ignore it.
*
* It also contains a digitizer application collection that also is not
* of interest since any information it contains would be duplicate
* of what is in wacom_features. Usually it defines a report of an array
* of bytes that could be used as max length of the stylus packet returned.
* If it happens to define a Digitizer-Stylus Physical Collection then
* the X and Y logical values contain valid data but it is ignored.
*
* A typical Interface Descriptor for a touch interface will contain a
* Digitizer-Finger Physical Collection which will define both logical
* X/Y maximum as well as the physical size of tablet. Since touch
* interfaces haven't supported pressure or distance, this is enough
* information to override invalid values in the wacom_features table.
*
* 3rd gen Bamboo Touch no longer define a Digitizer-Finger Pysical
* Collection. Instead they define a Logical Collection with a single
* Logical Maximum for both X and Y.
*/
static int wacom_parse_hid(struct usb_interface *intf,
struct hid_descriptor *hid_desc,
struct wacom_features *features)
{
struct usb_device *dev = interface_to_usbdev(intf);
char limit = 0;
/* result has to be defined as int for some devices */
int result = 0;
int i = 0, usage = WCM_UNDEFINED, finger = 0, pen = 0;
unsigned char *report;
report = kzalloc(hid_desc->wDescriptorLength, GFP_KERNEL);
if (!report)
return -ENOMEM;
/* retrive report descriptors */
do {
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
HID_DEVICET_REPORT << 8,
intf->altsetting[0].desc.bInterfaceNumber, /* interface */
report,
hid_desc->wDescriptorLength,
5000); /* 5 secs */
} while (result < 0 && limit++ < WAC_MSG_RETRIES);
/* No need to parse the Descriptor. It isn't an error though */
if (result < 0)
goto out;
for (i = 0; i < hid_desc->wDescriptorLength; i++) {
switch (report[i]) {
case HID_USAGE_PAGE:
switch (report[i + 1]) {
case HID_USAGE_PAGE_DIGITIZER:
usage = WCM_DIGITIZER;
i++;
break;
case HID_USAGE_PAGE_DESKTOP:
usage = WCM_DESKTOP;
i++;
break;
}
break;
case HID_USAGE:
switch (report[i + 1]) {
case HID_USAGE_X:
if (usage == WCM_DESKTOP) {
if (finger) {
features->device_type = BTN_TOOL_FINGER;
if (features->type == TABLETPC2FG) {
/* need to reset back */
features->pktlen = WACOM_PKGLEN_TPC2FG;
}
if (features->type == BAMBOO_PT) {
/* need to reset back */
features->pktlen = WACOM_PKGLEN_BBTOUCH;
features->x_phy =
get_unaligned_le16(&report[i + 5]);
features->x_max =
get_unaligned_le16(&report[i + 8]);
i += 15;
} else {
features->x_max =
get_unaligned_le16(&report[i + 3]);
features->x_phy =
get_unaligned_le16(&report[i + 6]);
features->unit = report[i + 9];
features->unitExpo = report[i + 11];
i += 12;
}
} else if (pen) {
/* penabled only accepts exact bytes of data */
if (features->type == TABLETPC2FG)
features->pktlen = WACOM_PKGLEN_GRAPHIRE;
features->device_type = BTN_TOOL_PEN;
features->x_max =
get_unaligned_le16(&report[i + 3]);
i += 4;
}
}
break;
case HID_USAGE_Y:
if (usage == WCM_DESKTOP) {
if (finger) {
features->device_type = BTN_TOOL_FINGER;
if (features->type == TABLETPC2FG) {
/* need to reset back */
features->pktlen = WACOM_PKGLEN_TPC2FG;
features->y_max =
get_unaligned_le16(&report[i + 3]);
features->y_phy =
get_unaligned_le16(&report[i + 6]);
i += 7;
} else if (features->type == BAMBOO_PT) {
/* need to reset back */
features->pktlen = WACOM_PKGLEN_BBTOUCH;
features->y_phy =
get_unaligned_le16(&report[i + 3]);
features->y_max =
get_unaligned_le16(&report[i + 6]);
i += 12;
} else {
features->y_max =
features->x_max;
features->y_phy =
get_unaligned_le16(&report[i + 3]);
i += 4;
}
} else if (pen) {
/* penabled only accepts exact bytes of data */
if (features->type == TABLETPC2FG)
features->pktlen = WACOM_PKGLEN_GRAPHIRE;
features->device_type = BTN_TOOL_PEN;
features->y_max =
get_unaligned_le16(&report[i + 3]);
i += 4;
}
}
break;
case HID_USAGE_FINGER:
finger = 1;
i++;
break;
/*
* Requiring Stylus Usage will ignore boot mouse
* X/Y values and some cases of invalid Digitizer X/Y
* values commonly reported.
*/
case HID_USAGE_STYLUS:
pen = 1;
i++;
break;
}
break;
case HID_COLLECTION_END:
/* reset UsagePage and Finger */
finger = usage = 0;
break;
case HID_COLLECTION:
i++;
switch (report[i]) {
case HID_COLLECTION_LOGICAL:
i += wacom_parse_logical_collection(&report[i],
features);
break;
}
break;
}
}
out:
result = 0;
kfree(report);
return result;
}
static int wacom_query_tablet_data(struct usb_interface *intf, struct wacom_features *features)
{
unsigned char *rep_data;
int limit = 0, report_id = 2;
int error = -ENOMEM;
rep_data = kmalloc(4, GFP_KERNEL);
if (!rep_data)
return error;
/* ask to report tablet data if it is MT Tablet PC or
* not a Tablet PC */
if (features->type == TABLETPC2FG) {
do {
rep_data[0] = 3;
rep_data[1] = 4;
rep_data[2] = 0;
rep_data[3] = 0;
report_id = 3;
error = wacom_set_report(intf, WAC_HID_FEATURE_REPORT,
report_id, rep_data, 4, 1);
if (error >= 0)
error = wacom_get_report(intf,
WAC_HID_FEATURE_REPORT,
report_id, rep_data, 4, 1);
} while ((error < 0 || rep_data[1] != 4) && limit++ < WAC_MSG_RETRIES);
} else if (features->type != TABLETPC &&
features->type != WIRELESS &&
features->device_type == BTN_TOOL_PEN) {
do {
rep_data[0] = 2;
rep_data[1] = 2;
error = wacom_set_report(intf, WAC_HID_FEATURE_REPORT,
report_id, rep_data, 2, 1);
if (error >= 0)
error = wacom_get_report(intf,
WAC_HID_FEATURE_REPORT,
report_id, rep_data, 2, 1);
} while ((error < 0 || rep_data[1] != 2) && limit++ < WAC_MSG_RETRIES);
}
kfree(rep_data);
return error < 0 ? error : 0;
}
static int wacom_retrieve_hid_descriptor(struct usb_interface *intf,
struct wacom_features *features)
{
int error = 0;
struct usb_host_interface *interface = intf->cur_altsetting;
struct hid_descriptor *hid_desc;
/* default features */
features->device_type = BTN_TOOL_PEN;
features->x_fuzz = 4;
features->y_fuzz = 4;
features->pressure_fuzz = 0;
features->distance_fuzz = 0;
/*
* The wireless device HID is basic and layout conflicts with
* other tablets (monitor and touch interface can look like pen).
* Skip the query for this type and modify defaults based on
* interface number.
*/
if (features->type == WIRELESS) {
if (intf->cur_altsetting->desc.bInterfaceNumber == 0) {
features->device_type = 0;
} else if (intf->cur_altsetting->desc.bInterfaceNumber == 2) {
features->device_type = BTN_TOOL_DOUBLETAP;
features->pktlen = WACOM_PKGLEN_BBTOUCH3;
}
}
/* only Tablet PCs and Bamboo P&T need to retrieve the info */
if ((features->type != TABLETPC) && (features->type != TABLETPC2FG) &&
(features->type != BAMBOO_PT))
goto out;
if (usb_get_extra_descriptor(interface, HID_DEVICET_HID, &hid_desc)) {
if (usb_get_extra_descriptor(&interface->endpoint[0],
HID_DEVICET_REPORT, &hid_desc)) {
printk("wacom: can not retrieve extra class descriptor\n");
error = 1;
goto out;
}
}
error = wacom_parse_hid(intf, hid_desc, features);
if (error)
goto out;
out:
return error;
}
struct wacom_usbdev_data {
struct list_head list;
struct kref kref;
struct usb_device *dev;
struct wacom_shared shared;
};
static LIST_HEAD(wacom_udev_list);
static DEFINE_MUTEX(wacom_udev_list_lock);
static struct wacom_usbdev_data *wacom_get_usbdev_data(struct usb_device *dev)
{
struct wacom_usbdev_data *data;
list_for_each_entry(data, &wacom_udev_list, list) {
if (data->dev == dev) {
kref_get(&data->kref);
return data;
}
}
return NULL;
}
static int wacom_add_shared_data(struct wacom_wac *wacom,
struct usb_device *dev)
{
struct wacom_usbdev_data *data;
int retval = 0;
mutex_lock(&wacom_udev_list_lock);
data = wacom_get_usbdev_data(dev);
if (!data) {
data = kzalloc(sizeof(struct wacom_usbdev_data), GFP_KERNEL);
if (!data) {
retval = -ENOMEM;
goto out;
}
kref_init(&data->kref);
data->dev = dev;
list_add_tail(&data->list, &wacom_udev_list);
}
wacom->shared = &data->shared;
out:
mutex_unlock(&wacom_udev_list_lock);
return retval;
}
static void wacom_release_shared_data(struct kref *kref)
{
struct wacom_usbdev_data *data =
container_of(kref, struct wacom_usbdev_data, kref);
mutex_lock(&wacom_udev_list_lock);
list_del(&data->list);
mutex_unlock(&wacom_udev_list_lock);
kfree(data);
}
static void wacom_remove_shared_data(struct wacom_wac *wacom)
{
struct wacom_usbdev_data *data;
if (wacom->shared) {
data = container_of(wacom->shared, struct wacom_usbdev_data, shared);
kref_put(&data->kref, wacom_release_shared_data);
wacom->shared = NULL;
}
}
static int wacom_led_control(struct wacom *wacom)
{
unsigned char *buf;
int retval, led = 0;
buf = kzalloc(9, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (wacom->wacom_wac.features.type == WACOM_21UX2 ||
wacom->wacom_wac.features.type == WACOM_24HD)
led = (wacom->led.select[1] << 4) | 0x40;
led |= wacom->led.select[0] | 0x4;
buf[0] = WAC_CMD_LED_CONTROL;
buf[1] = led;
buf[2] = wacom->led.llv;
buf[3] = wacom->led.hlv;
buf[4] = wacom->led.img_lum;
retval = wacom_set_report(wacom->intf, 0x03, WAC_CMD_LED_CONTROL,
buf, 9, WAC_CMD_RETRIES);
kfree(buf);
return retval;
}
static int wacom_led_putimage(struct wacom *wacom, int button_id, const void *img)
{
unsigned char *buf;
int i, retval;
buf = kzalloc(259, GFP_KERNEL);
if (!buf)
return -ENOMEM;
/* Send 'start' command */
buf[0] = WAC_CMD_ICON_START;
buf[1] = 1;
retval = wacom_set_report(wacom->intf, 0x03, WAC_CMD_ICON_START,
buf, 2, WAC_CMD_RETRIES);
if (retval < 0)
goto out;
buf[0] = WAC_CMD_ICON_XFER;
buf[1] = button_id & 0x07;
for (i = 0; i < 4; i++) {
buf[2] = i;
memcpy(buf + 3, img + i * 256, 256);
retval = wacom_set_report(wacom->intf, 0x03, WAC_CMD_ICON_XFER,
buf, 259, WAC_CMD_RETRIES);
if (retval < 0)
break;
}
/* Send 'stop' */
buf[0] = WAC_CMD_ICON_START;
buf[1] = 0;
wacom_set_report(wacom->intf, 0x03, WAC_CMD_ICON_START,
buf, 2, WAC_CMD_RETRIES);
out:
kfree(buf);
return retval;
}
static ssize_t wacom_led_select_store(struct device *dev, int set_id,
const char *buf, size_t count)
{
struct wacom *wacom = dev_get_drvdata(dev);
unsigned int id;
int err;
err = kstrtouint(buf, 10, &id);
if (err)
return err;
mutex_lock(&wacom->lock);
wacom->led.select[set_id] = id & 0x3;
err = wacom_led_control(wacom);
mutex_unlock(&wacom->lock);
return err < 0 ? err : count;
}
#define DEVICE_LED_SELECT_ATTR(SET_ID) \
static ssize_t wacom_led##SET_ID##_select_store(struct device *dev, \
struct device_attribute *attr, const char *buf, size_t count) \
{ \
return wacom_led_select_store(dev, SET_ID, buf, count); \
} \
static ssize_t wacom_led##SET_ID##_select_show(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct wacom *wacom = dev_get_drvdata(dev); \
return snprintf(buf, 2, "%d\n", wacom->led.select[SET_ID]); \
} \
static DEVICE_ATTR(status_led##SET_ID##_select, S_IWUSR | S_IRUSR, \
wacom_led##SET_ID##_select_show, \
wacom_led##SET_ID##_select_store)
DEVICE_LED_SELECT_ATTR(0);
DEVICE_LED_SELECT_ATTR(1);
static ssize_t wacom_luminance_store(struct wacom *wacom, u8 *dest,
const char *buf, size_t count)
{
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
mutex_lock(&wacom->lock);
*dest = value & 0x7f;
err = wacom_led_control(wacom);
mutex_unlock(&wacom->lock);
return err < 0 ? err : count;
}
#define DEVICE_LUMINANCE_ATTR(name, field) \
static ssize_t wacom_##name##_luminance_store(struct device *dev, \
struct device_attribute *attr, const char *buf, size_t count) \
{ \
struct wacom *wacom = dev_get_drvdata(dev); \
\
return wacom_luminance_store(wacom, &wacom->led.field, \
buf, count); \
} \
static DEVICE_ATTR(name##_luminance, S_IWUSR, \
NULL, wacom_##name##_luminance_store)
DEVICE_LUMINANCE_ATTR(status0, llv);
DEVICE_LUMINANCE_ATTR(status1, hlv);
DEVICE_LUMINANCE_ATTR(buttons, img_lum);
static ssize_t wacom_button_image_store(struct device *dev, int button_id,
const char *buf, size_t count)
{
struct wacom *wacom = dev_get_drvdata(dev);
int err;
if (count != 1024)
return -EINVAL;
mutex_lock(&wacom->lock);
err = wacom_led_putimage(wacom, button_id, buf);
mutex_unlock(&wacom->lock);
return err < 0 ? err : count;
}
#define DEVICE_BTNIMG_ATTR(BUTTON_ID) \
static ssize_t wacom_btnimg##BUTTON_ID##_store(struct device *dev, \
struct device_attribute *attr, const char *buf, size_t count) \
{ \
return wacom_button_image_store(dev, BUTTON_ID, buf, count); \
} \
static DEVICE_ATTR(button##BUTTON_ID##_rawimg, S_IWUSR, \
NULL, wacom_btnimg##BUTTON_ID##_store)
DEVICE_BTNIMG_ATTR(0);
DEVICE_BTNIMG_ATTR(1);
DEVICE_BTNIMG_ATTR(2);
DEVICE_BTNIMG_ATTR(3);
DEVICE_BTNIMG_ATTR(4);
DEVICE_BTNIMG_ATTR(5);
DEVICE_BTNIMG_ATTR(6);
DEVICE_BTNIMG_ATTR(7);
static struct attribute *cintiq_led_attrs[] = {
&dev_attr_status_led0_select.attr,
&dev_attr_status_led1_select.attr,
NULL
};
static struct attribute_group cintiq_led_attr_group = {
.name = "wacom_led",
.attrs = cintiq_led_attrs,
};
static struct attribute *intuos4_led_attrs[] = {
&dev_attr_status0_luminance.attr,
&dev_attr_status1_luminance.attr,
&dev_attr_status_led0_select.attr,
&dev_attr_buttons_luminance.attr,
&dev_attr_button0_rawimg.attr,
&dev_attr_button1_rawimg.attr,
&dev_attr_button2_rawimg.attr,
&dev_attr_button3_rawimg.attr,
&dev_attr_button4_rawimg.attr,
&dev_attr_button5_rawimg.attr,
&dev_attr_button6_rawimg.attr,
&dev_attr_button7_rawimg.attr,
NULL
};
static struct attribute_group intuos4_led_attr_group = {
.name = "wacom_led",
.attrs = intuos4_led_attrs,
};
static int wacom_initialize_leds(struct wacom *wacom)
{
int error;
/* Initialize default values */
switch (wacom->wacom_wac.features.type) {
case INTUOS4:
case INTUOS4L:
wacom->led.select[0] = 0;
wacom->led.select[1] = 0;
wacom->led.llv = 10;
wacom->led.hlv = 20;
wacom->led.img_lum = 10;
error = sysfs_create_group(&wacom->intf->dev.kobj,
&intuos4_led_attr_group);
break;
case WACOM_24HD:
case WACOM_21UX2:
wacom->led.select[0] = 0;
wacom->led.select[1] = 0;
wacom->led.llv = 0;
wacom->led.hlv = 0;
wacom->led.img_lum = 0;
error = sysfs_create_group(&wacom->intf->dev.kobj,
&cintiq_led_attr_group);
break;
default:
return 0;
}
if (error) {
dev_err(&wacom->intf->dev,
"cannot create sysfs group err: %d\n", error);
return error;
}
wacom_led_control(wacom);
return 0;
}
static void wacom_destroy_leds(struct wacom *wacom)
{
switch (wacom->wacom_wac.features.type) {
case INTUOS4:
case INTUOS4L:
sysfs_remove_group(&wacom->intf->dev.kobj,
&intuos4_led_attr_group);
break;
case WACOM_24HD:
case WACOM_21UX2:
sysfs_remove_group(&wacom->intf->dev.kobj,
&cintiq_led_attr_group);
break;
}
}
static enum power_supply_property wacom_battery_props[] = {
POWER_SUPPLY_PROP_CAPACITY
};
static int wacom_battery_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct wacom *wacom = container_of(psy, struct wacom, battery);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_CAPACITY:
val->intval =
wacom->wacom_wac.battery_capacity * 100 / 31;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int wacom_initialize_battery(struct wacom *wacom)
{
int error = 0;
if (wacom->wacom_wac.features.quirks & WACOM_QUIRK_MONITOR) {
wacom->battery.properties = wacom_battery_props;
wacom->battery.num_properties = ARRAY_SIZE(wacom_battery_props);
wacom->battery.get_property = wacom_battery_get_property;
wacom->battery.name = "wacom_battery";
wacom->battery.type = POWER_SUPPLY_TYPE_BATTERY;
wacom->battery.use_for_apm = 0;
error = power_supply_register(&wacom->usbdev->dev,
&wacom->battery);
}
return error;
}
static void wacom_destroy_battery(struct wacom *wacom)
{
if (wacom->wacom_wac.features.quirks & WACOM_QUIRK_MONITOR)
power_supply_unregister(&wacom->battery);
}
static int wacom_register_input(struct wacom *wacom)
{
struct input_dev *input_dev;
struct usb_interface *intf = wacom->intf;
struct usb_device *dev = interface_to_usbdev(intf);
struct wacom_wac *wacom_wac = &(wacom->wacom_wac);
int error;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->name = wacom_wac->name;
input_dev->dev.parent = &intf->dev;
input_dev->open = wacom_open;
input_dev->close = wacom_close;
usb_to_input_id(dev, &input_dev->id);
input_set_drvdata(input_dev, wacom);
wacom_wac->input = input_dev;
wacom_setup_input_capabilities(input_dev, wacom_wac);
error = input_register_device(input_dev);
if (error) {
input_free_device(input_dev);
wacom_wac->input = NULL;
}
return error;
}
static void wacom_wireless_work(struct work_struct *work)
{
struct wacom *wacom = container_of(work, struct wacom, work);
struct usb_device *usbdev = wacom->usbdev;
struct wacom_wac *wacom_wac = &wacom->wacom_wac;
/*
* Regardless if this is a disconnect or a new tablet,
* remove any existing input devices.
*/
/* Stylus interface */
wacom = usb_get_intfdata(usbdev->config->interface[1]);
if (wacom->wacom_wac.input)
input_unregister_device(wacom->wacom_wac.input);
wacom->wacom_wac.input = 0;
/* Touch interface */
wacom = usb_get_intfdata(usbdev->config->interface[2]);
if (wacom->wacom_wac.input)
input_unregister_device(wacom->wacom_wac.input);
wacom->wacom_wac.input = 0;
if (wacom_wac->pid == 0) {
printk(KERN_INFO "wacom: wireless tablet disconnected\n");
} else {
const struct usb_device_id *id = wacom_ids;
printk(KERN_INFO
"wacom: wireless tablet connected with PID %x\n",
wacom_wac->pid);
while (id->match_flags) {
if (id->idVendor == USB_VENDOR_ID_WACOM &&
id->idProduct == wacom_wac->pid)
break;
id++;
}
if (!id->match_flags) {
printk(KERN_INFO
"wacom: ignorning unknown PID.\n");
return;
}
/* Stylus interface */
wacom = usb_get_intfdata(usbdev->config->interface[1]);
wacom_wac = &wacom->wacom_wac;
wacom_wac->features =
*((struct wacom_features *)id->driver_info);
wacom_wac->features.device_type = BTN_TOOL_PEN;
wacom_register_input(wacom);
/* Touch interface */
wacom = usb_get_intfdata(usbdev->config->interface[2]);
wacom_wac = &wacom->wacom_wac;
wacom_wac->features =
*((struct wacom_features *)id->driver_info);
wacom_wac->features.pktlen = WACOM_PKGLEN_BBTOUCH3;
wacom_wac->features.device_type = BTN_TOOL_FINGER;
wacom_set_phy_from_res(&wacom_wac->features);
wacom_wac->features.x_max = wacom_wac->features.y_max = 4096;
wacom_register_input(wacom);
}
}
static int wacom_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_endpoint_descriptor *endpoint;
struct wacom *wacom;
struct wacom_wac *wacom_wac;
struct wacom_features *features;
int error;
if (!id->driver_info)
return -EINVAL;
wacom = kzalloc(sizeof(struct wacom), GFP_KERNEL);
if (!wacom)
return -ENOMEM;
wacom_wac = &wacom->wacom_wac;
wacom_wac->features = *((struct wacom_features *)id->driver_info);
features = &wacom_wac->features;
if (features->pktlen > WACOM_PKGLEN_MAX) {
error = -EINVAL;
goto fail1;
}
wacom_wac->data = usb_alloc_coherent(dev, WACOM_PKGLEN_MAX,
GFP_KERNEL, &wacom->data_dma);
if (!wacom_wac->data) {
error = -ENOMEM;
goto fail1;
}
wacom->irq = usb_alloc_urb(0, GFP_KERNEL);
if (!wacom->irq) {
error = -ENOMEM;
goto fail2;
}
wacom->usbdev = dev;
wacom->intf = intf;
mutex_init(&wacom->lock);
INIT_WORK(&wacom->work, wacom_wireless_work);
usb_make_path(dev, wacom->phys, sizeof(wacom->phys));
strlcat(wacom->phys, "/input0", sizeof(wacom->phys));
endpoint = &intf->cur_altsetting->endpoint[0].desc;
/* Retrieve the physical and logical size for OEM devices */
error = wacom_retrieve_hid_descriptor(intf, features);
if (error)
goto fail3;
wacom_setup_device_quirks(features);
strlcpy(wacom_wac->name, features->name, sizeof(wacom_wac->name));
if (features->quirks & WACOM_QUIRK_MULTI_INPUT) {
/* Append the device type to the name */
strlcat(wacom_wac->name,
features->device_type == BTN_TOOL_PEN ?
" Pen" : " Finger",
sizeof(wacom_wac->name));
error = wacom_add_shared_data(wacom_wac, dev);
if (error)
goto fail3;
}
usb_fill_int_urb(wacom->irq, dev,
usb_rcvintpipe(dev, endpoint->bEndpointAddress),
wacom_wac->data, features->pktlen,
wacom_sys_irq, wacom, endpoint->bInterval);
wacom->irq->transfer_dma = wacom->data_dma;
wacom->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = wacom_initialize_leds(wacom);
if (error)
goto fail4;
error = wacom_initialize_battery(wacom);
if (error)
goto fail5;
if (!(features->quirks & WACOM_QUIRK_NO_INPUT)) {
error = wacom_register_input(wacom);
if (error)
goto fail6;
}
/* Note that if query fails it is not a hard failure */
wacom_query_tablet_data(intf, features);
usb_set_intfdata(intf, wacom);
if (features->quirks & WACOM_QUIRK_MONITOR) {
if (usb_submit_urb(wacom->irq, GFP_KERNEL))
goto fail5;
}
return 0;
fail6: wacom_destroy_battery(wacom);
fail5: wacom_destroy_leds(wacom);
fail4: wacom_remove_shared_data(wacom_wac);
fail3: usb_free_urb(wacom->irq);
fail2: usb_free_coherent(dev, WACOM_PKGLEN_MAX, wacom_wac->data, wacom->data_dma);
fail1: kfree(wacom);
return error;
}
static void wacom_disconnect(struct usb_interface *intf)
{
struct wacom *wacom = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
usb_kill_urb(wacom->irq);
cancel_work_sync(&wacom->work);
if (wacom->wacom_wac.input)
input_unregister_device(wacom->wacom_wac.input);
wacom_destroy_battery(wacom);
wacom_destroy_leds(wacom);
usb_free_urb(wacom->irq);
usb_free_coherent(interface_to_usbdev(intf), WACOM_PKGLEN_MAX,
wacom->wacom_wac.data, wacom->data_dma);
wacom_remove_shared_data(&wacom->wacom_wac);
kfree(wacom);
}
static int wacom_suspend(struct usb_interface *intf, pm_message_t message)
{
struct wacom *wacom = usb_get_intfdata(intf);
mutex_lock(&wacom->lock);
usb_kill_urb(wacom->irq);
mutex_unlock(&wacom->lock);
return 0;
}
static int wacom_resume(struct usb_interface *intf)
{
struct wacom *wacom = usb_get_intfdata(intf);
struct wacom_features *features = &wacom->wacom_wac.features;
int rv = 0;
mutex_lock(&wacom->lock);
/* switch to wacom mode first */
wacom_query_tablet_data(intf, features);
wacom_led_control(wacom);
if ((wacom->open || features->quirks & WACOM_QUIRK_MONITOR)
&& usb_submit_urb(wacom->irq, GFP_NOIO) < 0)
rv = -EIO;
mutex_unlock(&wacom->lock);
return rv;
}
static int wacom_reset_resume(struct usb_interface *intf)
{
return wacom_resume(intf);
}
static struct usb_driver wacom_driver = {
.name = "wacom",
.id_table = wacom_ids,
.probe = wacom_probe,
.disconnect = wacom_disconnect,
.suspend = wacom_suspend,
.resume = wacom_resume,
.reset_resume = wacom_reset_resume,
.supports_autosuspend = 1,
};
module_usb_driver(wacom_driver);
| gpl-2.0 |
hsr0/android_kernel_sony_msm7x27a | arch/powerpc/sysdev/ppc4xx_soc.c | 7081 | 6102 | /*
* IBM/AMCC PPC4xx SoC setup code
*
* Copyright 2008 DENX Software Engineering, Stefan Roese <sr@denx.de>
*
* L2 cache routines cloned from arch/ppc/syslib/ibm440gx_common.c which is:
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
* Copyright (c) 2003 - 2006 Zultys Technologies
*
* 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/stddef.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/of_platform.h>
#include <asm/dcr.h>
#include <asm/dcr-regs.h>
#include <asm/reg.h>
static u32 dcrbase_l2c;
/*
* L2-cache
*/
/* Issue L2C diagnostic command */
static inline u32 l2c_diag(u32 addr)
{
mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, addr);
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_DIAG);
while (!(mfdcr(dcrbase_l2c + DCRN_L2C0_SR) & L2C_SR_CC))
;
return mfdcr(dcrbase_l2c + DCRN_L2C0_DATA);
}
static irqreturn_t l2c_error_handler(int irq, void *dev)
{
u32 sr = mfdcr(dcrbase_l2c + DCRN_L2C0_SR);
if (sr & L2C_SR_CPE) {
/* Read cache trapped address */
u32 addr = l2c_diag(0x42000000);
printk(KERN_EMERG "L2C: Cache Parity Error, addr[16:26] = 0x%08x\n",
addr);
}
if (sr & L2C_SR_TPE) {
/* Read tag trapped address */
u32 addr = l2c_diag(0x82000000) >> 16;
printk(KERN_EMERG "L2C: Tag Parity Error, addr[16:26] = 0x%08x\n",
addr);
}
/* Clear parity errors */
if (sr & (L2C_SR_CPE | L2C_SR_TPE)){
mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, 0);
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_CCP | L2C_CMD_CTE);
} else {
printk(KERN_EMERG "L2C: LRU error\n");
}
return IRQ_HANDLED;
}
static int __init ppc4xx_l2c_probe(void)
{
struct device_node *np;
u32 r;
unsigned long flags;
int irq;
const u32 *dcrreg;
u32 dcrbase_isram;
int len;
const u32 *prop;
u32 l2_size;
np = of_find_compatible_node(NULL, NULL, "ibm,l2-cache");
if (!np)
return 0;
/* Get l2 cache size */
prop = of_get_property(np, "cache-size", NULL);
if (prop == NULL) {
printk(KERN_ERR "%s: Can't get cache-size!\n", np->full_name);
of_node_put(np);
return -ENODEV;
}
l2_size = prop[0];
/* Map DCRs */
dcrreg = of_get_property(np, "dcr-reg", &len);
if (!dcrreg || (len != 4 * sizeof(u32))) {
printk(KERN_ERR "%s: Can't get DCR register base !",
np->full_name);
of_node_put(np);
return -ENODEV;
}
dcrbase_isram = dcrreg[0];
dcrbase_l2c = dcrreg[2];
/* Get and map irq number from device tree */
irq = irq_of_parse_and_map(np, 0);
if (irq == NO_IRQ) {
printk(KERN_ERR "irq_of_parse_and_map failed\n");
of_node_put(np);
return -ENODEV;
}
/* Install error handler */
if (request_irq(irq, l2c_error_handler, 0, "L2C", 0) < 0) {
printk(KERN_ERR "Cannot install L2C error handler"
", cache is not enabled\n");
of_node_put(np);
return -ENODEV;
}
local_irq_save(flags);
asm volatile ("sync" ::: "memory");
/* Disable SRAM */
mtdcr(dcrbase_isram + DCRN_SRAM0_DPC,
mfdcr(dcrbase_isram + DCRN_SRAM0_DPC) & ~SRAM_DPC_ENABLE);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB0CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB0CR) & ~SRAM_SBCR_BU_MASK);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB1CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB1CR) & ~SRAM_SBCR_BU_MASK);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB2CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB2CR) & ~SRAM_SBCR_BU_MASK);
mtdcr(dcrbase_isram + DCRN_SRAM0_SB3CR,
mfdcr(dcrbase_isram + DCRN_SRAM0_SB3CR) & ~SRAM_SBCR_BU_MASK);
/* Enable L2_MODE without ICU/DCU */
r = mfdcr(dcrbase_l2c + DCRN_L2C0_CFG) &
~(L2C_CFG_ICU | L2C_CFG_DCU | L2C_CFG_SS_MASK);
r |= L2C_CFG_L2M | L2C_CFG_SS_256;
mtdcr(dcrbase_l2c + DCRN_L2C0_CFG, r);
mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, 0);
/* Hardware Clear Command */
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_HCC);
while (!(mfdcr(dcrbase_l2c + DCRN_L2C0_SR) & L2C_SR_CC))
;
/* Clear Cache Parity and Tag Errors */
mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_CCP | L2C_CMD_CTE);
/* Enable 64G snoop region starting at 0 */
r = mfdcr(dcrbase_l2c + DCRN_L2C0_SNP0) &
~(L2C_SNP_BA_MASK | L2C_SNP_SSR_MASK);
r |= L2C_SNP_SSR_32G | L2C_SNP_ESR;
mtdcr(dcrbase_l2c + DCRN_L2C0_SNP0, r);
r = mfdcr(dcrbase_l2c + DCRN_L2C0_SNP1) &
~(L2C_SNP_BA_MASK | L2C_SNP_SSR_MASK);
r |= 0x80000000 | L2C_SNP_SSR_32G | L2C_SNP_ESR;
mtdcr(dcrbase_l2c + DCRN_L2C0_SNP1, r);
asm volatile ("sync" ::: "memory");
/* Enable ICU/DCU ports */
r = mfdcr(dcrbase_l2c + DCRN_L2C0_CFG);
r &= ~(L2C_CFG_DCW_MASK | L2C_CFG_PMUX_MASK | L2C_CFG_PMIM
| L2C_CFG_TPEI | L2C_CFG_CPEI | L2C_CFG_NAM | L2C_CFG_NBRM);
r |= L2C_CFG_ICU | L2C_CFG_DCU | L2C_CFG_TPC | L2C_CFG_CPC | L2C_CFG_FRAN
| L2C_CFG_CPIM | L2C_CFG_TPIM | L2C_CFG_LIM | L2C_CFG_SMCM;
/* Check for 460EX/GT special handling */
if (of_device_is_compatible(np, "ibm,l2-cache-460ex") ||
of_device_is_compatible(np, "ibm,l2-cache-460gt"))
r |= L2C_CFG_RDBW;
mtdcr(dcrbase_l2c + DCRN_L2C0_CFG, r);
asm volatile ("sync; isync" ::: "memory");
local_irq_restore(flags);
printk(KERN_INFO "%dk L2-cache enabled\n", l2_size >> 10);
of_node_put(np);
return 0;
}
arch_initcall(ppc4xx_l2c_probe);
/*
* Apply a system reset. Alternatively a board specific value may be
* provided via the "reset-type" property in the cpu node.
*/
void ppc4xx_reset_system(char *cmd)
{
struct device_node *np;
u32 reset_type = DBCR0_RST_SYSTEM;
const u32 *prop;
np = of_find_node_by_type(NULL, "cpu");
if (np) {
prop = of_get_property(np, "reset-type", NULL);
/*
* Check if property exists and if it is in range:
* 1 - PPC4xx core reset
* 2 - PPC4xx chip reset
* 3 - PPC4xx system reset (default)
*/
if ((prop) && ((prop[0] >= 1) && (prop[0] <= 3)))
reset_type = prop[0] << 28;
}
mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) | reset_type);
while (1)
; /* Just in case the reset doesn't work */
}
| gpl-2.0 |
Evervolv/android_kernel_htc_msm7x30 | drivers/serial/8250_acorn.c | 10153 | 3194 | /*
* linux/drivers/serial/acorn.c
*
* Copyright (C) 1996-2003 Russell King.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/tty.h>
#include <linux/serial_core.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/ecard.h>
#include <asm/string.h>
#include "8250.h"
#define MAX_PORTS 3
struct serial_card_type {
unsigned int num_ports;
unsigned int uartclk;
unsigned int type;
unsigned int offset[MAX_PORTS];
};
struct serial_card_info {
unsigned int num_ports;
int ports[MAX_PORTS];
void __iomem *vaddr;
};
static int __devinit
serial_card_probe(struct expansion_card *ec, const struct ecard_id *id)
{
struct serial_card_info *info;
struct serial_card_type *type = id->data;
struct uart_port port;
unsigned long bus_addr;
unsigned int i;
info = kzalloc(sizeof(struct serial_card_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->num_ports = type->num_ports;
bus_addr = ecard_resource_start(ec, type->type);
info->vaddr = ecardm_iomap(ec, type->type, 0, 0);
if (!info->vaddr) {
kfree(info);
return -ENOMEM;
}
ecard_set_drvdata(ec, info);
memset(&port, 0, sizeof(struct uart_port));
port.irq = ec->irq;
port.flags = UPF_BOOT_AUTOCONF | UPF_SHARE_IRQ;
port.uartclk = type->uartclk;
port.iotype = UPIO_MEM;
port.regshift = 2;
port.dev = &ec->dev;
for (i = 0; i < info->num_ports; i ++) {
port.membase = info->vaddr + type->offset[i];
port.mapbase = bus_addr + type->offset[i];
info->ports[i] = serial8250_register_port(&port);
}
return 0;
}
static void __devexit serial_card_remove(struct expansion_card *ec)
{
struct serial_card_info *info = ecard_get_drvdata(ec);
int i;
ecard_set_drvdata(ec, NULL);
for (i = 0; i < info->num_ports; i++)
if (info->ports[i] > 0)
serial8250_unregister_port(info->ports[i]);
kfree(info);
}
static struct serial_card_type atomwide_type = {
.num_ports = 3,
.uartclk = 7372800,
.type = ECARD_RES_IOCSLOW,
.offset = { 0x2800, 0x2400, 0x2000 },
};
static struct serial_card_type serport_type = {
.num_ports = 2,
.uartclk = 3686400,
.type = ECARD_RES_IOCSLOW,
.offset = { 0x2000, 0x2020 },
};
static const struct ecard_id serial_cids[] = {
{ MANU_ATOMWIDE, PROD_ATOMWIDE_3PSERIAL, &atomwide_type },
{ MANU_SERPORT, PROD_SERPORT_DSPORT, &serport_type },
{ 0xffff, 0xffff }
};
static struct ecard_driver serial_card_driver = {
.probe = serial_card_probe,
.remove = __devexit_p(serial_card_remove),
.id_table = serial_cids,
.drv = {
.name = "8250_acorn",
},
};
static int __init serial_card_init(void)
{
return ecard_register_driver(&serial_card_driver);
}
static void __exit serial_card_exit(void)
{
ecard_remove_driver(&serial_card_driver);
}
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("Acorn 8250-compatible serial port expansion card driver");
MODULE_LICENSE("GPL");
module_init(serial_card_init);
module_exit(serial_card_exit);
| gpl-2.0 |
ubuntu-touchCAF/android_kernel_motorola_msm8226 | fs/ntfs/logfile.c | 12457 | 28894 | /*
* logfile.c - NTFS kernel journal handling. Part of the Linux-NTFS project.
*
* Copyright (c) 2002-2007 Anton Altaparmakov
*
* This program/include file 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/include file 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 Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef NTFS_RW
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/highmem.h>
#include <linux/buffer_head.h>
#include <linux/bitops.h>
#include <linux/log2.h>
#include "attrib.h"
#include "aops.h"
#include "debug.h"
#include "logfile.h"
#include "malloc.h"
#include "volume.h"
#include "ntfs.h"
/**
* ntfs_check_restart_page_header - check the page header for consistency
* @vi: $LogFile inode to which the restart page header belongs
* @rp: restart page header to check
* @pos: position in @vi at which the restart page header resides
*
* Check the restart page header @rp for consistency and return 'true' if it is
* consistent and 'false' otherwise.
*
* This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
* require the full restart page.
*/
static bool ntfs_check_restart_page_header(struct inode *vi,
RESTART_PAGE_HEADER *rp, s64 pos)
{
u32 logfile_system_page_size, logfile_log_page_size;
u16 ra_ofs, usa_count, usa_ofs, usa_end = 0;
bool have_usa = true;
ntfs_debug("Entering.");
/*
* If the system or log page sizes are smaller than the ntfs block size
* or either is not a power of 2 we cannot handle this log file.
*/
logfile_system_page_size = le32_to_cpu(rp->system_page_size);
logfile_log_page_size = le32_to_cpu(rp->log_page_size);
if (logfile_system_page_size < NTFS_BLOCK_SIZE ||
logfile_log_page_size < NTFS_BLOCK_SIZE ||
logfile_system_page_size &
(logfile_system_page_size - 1) ||
!is_power_of_2(logfile_log_page_size)) {
ntfs_error(vi->i_sb, "$LogFile uses unsupported page size.");
return false;
}
/*
* We must be either at !pos (1st restart page) or at pos = system page
* size (2nd restart page).
*/
if (pos && pos != logfile_system_page_size) {
ntfs_error(vi->i_sb, "Found restart area in incorrect "
"position in $LogFile.");
return false;
}
/* We only know how to handle version 1.1. */
if (sle16_to_cpu(rp->major_ver) != 1 ||
sle16_to_cpu(rp->minor_ver) != 1) {
ntfs_error(vi->i_sb, "$LogFile version %i.%i is not "
"supported. (This driver supports version "
"1.1 only.)", (int)sle16_to_cpu(rp->major_ver),
(int)sle16_to_cpu(rp->minor_ver));
return false;
}
/*
* If chkdsk has been run the restart page may not be protected by an
* update sequence array.
*/
if (ntfs_is_chkd_record(rp->magic) && !le16_to_cpu(rp->usa_count)) {
have_usa = false;
goto skip_usa_checks;
}
/* Verify the size of the update sequence array. */
usa_count = 1 + (logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS);
if (usa_count != le16_to_cpu(rp->usa_count)) {
ntfs_error(vi->i_sb, "$LogFile restart page specifies "
"inconsistent update sequence array count.");
return false;
}
/* Verify the position of the update sequence array. */
usa_ofs = le16_to_cpu(rp->usa_ofs);
usa_end = usa_ofs + usa_count * sizeof(u16);
if (usa_ofs < sizeof(RESTART_PAGE_HEADER) ||
usa_end > NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "$LogFile restart page specifies "
"inconsistent update sequence array offset.");
return false;
}
skip_usa_checks:
/*
* Verify the position of the restart area. It must be:
* - aligned to 8-byte boundary,
* - after the update sequence array, and
* - within the system page size.
*/
ra_ofs = le16_to_cpu(rp->restart_area_offset);
if (ra_ofs & 7 || (have_usa ? ra_ofs < usa_end :
ra_ofs < sizeof(RESTART_PAGE_HEADER)) ||
ra_ofs > logfile_system_page_size) {
ntfs_error(vi->i_sb, "$LogFile restart page specifies "
"inconsistent restart area offset.");
return false;
}
/*
* Only restart pages modified by chkdsk are allowed to have chkdsk_lsn
* set.
*/
if (!ntfs_is_chkd_record(rp->magic) && sle64_to_cpu(rp->chkdsk_lsn)) {
ntfs_error(vi->i_sb, "$LogFile restart page is not modified "
"by chkdsk but a chkdsk LSN is specified.");
return false;
}
ntfs_debug("Done.");
return true;
}
/**
* ntfs_check_restart_area - check the restart area for consistency
* @vi: $LogFile inode to which the restart page belongs
* @rp: restart page whose restart area to check
*
* Check the restart area of the restart page @rp for consistency and return
* 'true' if it is consistent and 'false' otherwise.
*
* This function assumes that the restart page header has already been
* consistency checked.
*
* This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
* require the full restart page.
*/
static bool ntfs_check_restart_area(struct inode *vi, RESTART_PAGE_HEADER *rp)
{
u64 file_size;
RESTART_AREA *ra;
u16 ra_ofs, ra_len, ca_ofs;
u8 fs_bits;
ntfs_debug("Entering.");
ra_ofs = le16_to_cpu(rp->restart_area_offset);
ra = (RESTART_AREA*)((u8*)rp + ra_ofs);
/*
* Everything before ra->file_size must be before the first word
* protected by an update sequence number. This ensures that it is
* safe to access ra->client_array_offset.
*/
if (ra_ofs + offsetof(RESTART_AREA, file_size) >
NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent file offset.");
return false;
}
/*
* Now that we can access ra->client_array_offset, make sure everything
* up to the log client array is before the first word protected by an
* update sequence number. This ensures we can access all of the
* restart area elements safely. Also, the client array offset must be
* aligned to an 8-byte boundary.
*/
ca_ofs = le16_to_cpu(ra->client_array_offset);
if (((ca_ofs + 7) & ~7) != ca_ofs ||
ra_ofs + ca_ofs > NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent client array offset.");
return false;
}
/*
* The restart area must end within the system page size both when
* calculated manually and as specified by ra->restart_area_length.
* Also, the calculated length must not exceed the specified length.
*/
ra_len = ca_ofs + le16_to_cpu(ra->log_clients) *
sizeof(LOG_CLIENT_RECORD);
if (ra_ofs + ra_len > le32_to_cpu(rp->system_page_size) ||
ra_ofs + le16_to_cpu(ra->restart_area_length) >
le32_to_cpu(rp->system_page_size) ||
ra_len > le16_to_cpu(ra->restart_area_length)) {
ntfs_error(vi->i_sb, "$LogFile restart area is out of bounds "
"of the system page size specified by the "
"restart page header and/or the specified "
"restart area length is inconsistent.");
return false;
}
/*
* The ra->client_free_list and ra->client_in_use_list must be either
* LOGFILE_NO_CLIENT or less than ra->log_clients or they are
* overflowing the client array.
*/
if ((ra->client_free_list != LOGFILE_NO_CLIENT &&
le16_to_cpu(ra->client_free_list) >=
le16_to_cpu(ra->log_clients)) ||
(ra->client_in_use_list != LOGFILE_NO_CLIENT &&
le16_to_cpu(ra->client_in_use_list) >=
le16_to_cpu(ra->log_clients))) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"overflowing client free and/or in use lists.");
return false;
}
/*
* Check ra->seq_number_bits against ra->file_size for consistency.
* We cannot just use ffs() because the file size is not a power of 2.
*/
file_size = (u64)sle64_to_cpu(ra->file_size);
fs_bits = 0;
while (file_size) {
file_size >>= 1;
fs_bits++;
}
if (le32_to_cpu(ra->seq_number_bits) != 67 - fs_bits) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent sequence number bits.");
return false;
}
/* The log record header length must be a multiple of 8. */
if (((le16_to_cpu(ra->log_record_header_length) + 7) & ~7) !=
le16_to_cpu(ra->log_record_header_length)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent log record header length.");
return false;
}
/* Dito for the log page data offset. */
if (((le16_to_cpu(ra->log_page_data_offset) + 7) & ~7) !=
le16_to_cpu(ra->log_page_data_offset)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent log page data offset.");
return false;
}
ntfs_debug("Done.");
return true;
}
/**
* ntfs_check_log_client_array - check the log client array for consistency
* @vi: $LogFile inode to which the restart page belongs
* @rp: restart page whose log client array to check
*
* Check the log client array of the restart page @rp for consistency and
* return 'true' if it is consistent and 'false' otherwise.
*
* This function assumes that the restart page header and the restart area have
* already been consistency checked.
*
* Unlike ntfs_check_restart_page_header() and ntfs_check_restart_area(), this
* function needs @rp->system_page_size bytes in @rp, i.e. it requires the full
* restart page and the page must be multi sector transfer deprotected.
*/
static bool ntfs_check_log_client_array(struct inode *vi,
RESTART_PAGE_HEADER *rp)
{
RESTART_AREA *ra;
LOG_CLIENT_RECORD *ca, *cr;
u16 nr_clients, idx;
bool in_free_list, idx_is_first;
ntfs_debug("Entering.");
ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset));
ca = (LOG_CLIENT_RECORD*)((u8*)ra +
le16_to_cpu(ra->client_array_offset));
/*
* Check the ra->client_free_list first and then check the
* ra->client_in_use_list. Check each of the log client records in
* each of the lists and check that the array does not overflow the
* ra->log_clients value. Also keep track of the number of records
* visited as there cannot be more than ra->log_clients records and
* that way we detect eventual loops in within a list.
*/
nr_clients = le16_to_cpu(ra->log_clients);
idx = le16_to_cpu(ra->client_free_list);
in_free_list = true;
check_list:
for (idx_is_first = true; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--,
idx = le16_to_cpu(cr->next_client)) {
if (!nr_clients || idx >= le16_to_cpu(ra->log_clients))
goto err_out;
/* Set @cr to the current log client record. */
cr = ca + idx;
/* The first log client record must not have a prev_client. */
if (idx_is_first) {
if (cr->prev_client != LOGFILE_NO_CLIENT)
goto err_out;
idx_is_first = false;
}
}
/* Switch to and check the in use list if we just did the free list. */
if (in_free_list) {
in_free_list = false;
idx = le16_to_cpu(ra->client_in_use_list);
goto check_list;
}
ntfs_debug("Done.");
return true;
err_out:
ntfs_error(vi->i_sb, "$LogFile log client array is corrupt.");
return false;
}
/**
* ntfs_check_and_load_restart_page - check the restart page for consistency
* @vi: $LogFile inode to which the restart page belongs
* @rp: restart page to check
* @pos: position in @vi at which the restart page resides
* @wrp: [OUT] copy of the multi sector transfer deprotected restart page
* @lsn: [OUT] set to the current logfile lsn on success
*
* Check the restart page @rp for consistency and return 0 if it is consistent
* and -errno otherwise. The restart page may have been modified by chkdsk in
* which case its magic is CHKD instead of RSTR.
*
* This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
* require the full restart page.
*
* If @wrp is not NULL, on success, *@wrp will point to a buffer containing a
* copy of the complete multi sector transfer deprotected page. On failure,
* *@wrp is undefined.
*
* Simillarly, if @lsn is not NULL, on success *@lsn will be set to the current
* logfile lsn according to this restart page. On failure, *@lsn is undefined.
*
* The following error codes are defined:
* -EINVAL - The restart page is inconsistent.
* -ENOMEM - Not enough memory to load the restart page.
* -EIO - Failed to reading from $LogFile.
*/
static int ntfs_check_and_load_restart_page(struct inode *vi,
RESTART_PAGE_HEADER *rp, s64 pos, RESTART_PAGE_HEADER **wrp,
LSN *lsn)
{
RESTART_AREA *ra;
RESTART_PAGE_HEADER *trp;
int size, err;
ntfs_debug("Entering.");
/* Check the restart page header for consistency. */
if (!ntfs_check_restart_page_header(vi, rp, pos)) {
/* Error output already done inside the function. */
return -EINVAL;
}
/* Check the restart area for consistency. */
if (!ntfs_check_restart_area(vi, rp)) {
/* Error output already done inside the function. */
return -EINVAL;
}
ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset));
/*
* Allocate a buffer to store the whole restart page so we can multi
* sector transfer deprotect it.
*/
trp = ntfs_malloc_nofs(le32_to_cpu(rp->system_page_size));
if (!trp) {
ntfs_error(vi->i_sb, "Failed to allocate memory for $LogFile "
"restart page buffer.");
return -ENOMEM;
}
/*
* Read the whole of the restart page into the buffer. If it fits
* completely inside @rp, just copy it from there. Otherwise map all
* the required pages and copy the data from them.
*/
size = PAGE_CACHE_SIZE - (pos & ~PAGE_CACHE_MASK);
if (size >= le32_to_cpu(rp->system_page_size)) {
memcpy(trp, rp, le32_to_cpu(rp->system_page_size));
} else {
pgoff_t idx;
struct page *page;
int have_read, to_read;
/* First copy what we already have in @rp. */
memcpy(trp, rp, size);
/* Copy the remaining data one page at a time. */
have_read = size;
to_read = le32_to_cpu(rp->system_page_size) - size;
idx = (pos + size) >> PAGE_CACHE_SHIFT;
BUG_ON((pos + size) & ~PAGE_CACHE_MASK);
do {
page = ntfs_map_page(vi->i_mapping, idx);
if (IS_ERR(page)) {
ntfs_error(vi->i_sb, "Error mapping $LogFile "
"page (index %lu).", idx);
err = PTR_ERR(page);
if (err != -EIO && err != -ENOMEM)
err = -EIO;
goto err_out;
}
size = min_t(int, to_read, PAGE_CACHE_SIZE);
memcpy((u8*)trp + have_read, page_address(page), size);
ntfs_unmap_page(page);
have_read += size;
to_read -= size;
idx++;
} while (to_read > 0);
}
/*
* Perform the multi sector transfer deprotection on the buffer if the
* restart page is protected.
*/
if ((!ntfs_is_chkd_record(trp->magic) || le16_to_cpu(trp->usa_count))
&& post_read_mst_fixup((NTFS_RECORD*)trp,
le32_to_cpu(rp->system_page_size))) {
/*
* A multi sector tranfer error was detected. We only need to
* abort if the restart page contents exceed the multi sector
* transfer fixup of the first sector.
*/
if (le16_to_cpu(rp->restart_area_offset) +
le16_to_cpu(ra->restart_area_length) >
NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "Multi sector transfer error "
"detected in $LogFile restart page.");
err = -EINVAL;
goto err_out;
}
}
/*
* If the restart page is modified by chkdsk or there are no active
* logfile clients, the logfile is consistent. Otherwise, need to
* check the log client records for consistency, too.
*/
err = 0;
if (ntfs_is_rstr_record(rp->magic) &&
ra->client_in_use_list != LOGFILE_NO_CLIENT) {
if (!ntfs_check_log_client_array(vi, trp)) {
err = -EINVAL;
goto err_out;
}
}
if (lsn) {
if (ntfs_is_rstr_record(rp->magic))
*lsn = sle64_to_cpu(ra->current_lsn);
else /* if (ntfs_is_chkd_record(rp->magic)) */
*lsn = sle64_to_cpu(rp->chkdsk_lsn);
}
ntfs_debug("Done.");
if (wrp)
*wrp = trp;
else {
err_out:
ntfs_free(trp);
}
return err;
}
/**
* ntfs_check_logfile - check the journal for consistency
* @log_vi: struct inode of loaded journal $LogFile to check
* @rp: [OUT] on success this is a copy of the current restart page
*
* Check the $LogFile journal for consistency and return 'true' if it is
* consistent and 'false' if not. On success, the current restart page is
* returned in *@rp. Caller must call ntfs_free(*@rp) when finished with it.
*
* At present we only check the two restart pages and ignore the log record
* pages.
*
* Note that the MstProtected flag is not set on the $LogFile inode and hence
* when reading pages they are not deprotected. This is because we do not know
* if the $LogFile was created on a system with a different page size to ours
* yet and mst deprotection would fail if our page size is smaller.
*/
bool ntfs_check_logfile(struct inode *log_vi, RESTART_PAGE_HEADER **rp)
{
s64 size, pos;
LSN rstr1_lsn, rstr2_lsn;
ntfs_volume *vol = NTFS_SB(log_vi->i_sb);
struct address_space *mapping = log_vi->i_mapping;
struct page *page = NULL;
u8 *kaddr = NULL;
RESTART_PAGE_HEADER *rstr1_ph = NULL;
RESTART_PAGE_HEADER *rstr2_ph = NULL;
int log_page_size, log_page_mask, err;
bool logfile_is_empty = true;
u8 log_page_bits;
ntfs_debug("Entering.");
/* An empty $LogFile must have been clean before it got emptied. */
if (NVolLogFileEmpty(vol))
goto is_empty;
size = i_size_read(log_vi);
/* Make sure the file doesn't exceed the maximum allowed size. */
if (size > MaxLogFileSize)
size = MaxLogFileSize;
/*
* Truncate size to a multiple of the page cache size or the default
* log page size if the page cache size is between the default log page
* log page size if the page cache size is between the default log page
* size and twice that.
*/
if (PAGE_CACHE_SIZE >= DefaultLogPageSize && PAGE_CACHE_SIZE <=
DefaultLogPageSize * 2)
log_page_size = DefaultLogPageSize;
else
log_page_size = PAGE_CACHE_SIZE;
log_page_mask = log_page_size - 1;
/*
* Use ntfs_ffs() instead of ffs() to enable the compiler to
* optimize log_page_size and log_page_bits into constants.
*/
log_page_bits = ntfs_ffs(log_page_size) - 1;
size &= ~(s64)(log_page_size - 1);
/*
* Ensure the log file is big enough to store at least the two restart
* pages and the minimum number of log record pages.
*/
if (size < log_page_size * 2 || (size - log_page_size * 2) >>
log_page_bits < MinLogRecordPages) {
ntfs_error(vol->sb, "$LogFile is too small.");
return false;
}
/*
* Read through the file looking for a restart page. Since the restart
* page header is at the beginning of a page we only need to search at
* what could be the beginning of a page (for each page size) rather
* than scanning the whole file byte by byte. If all potential places
* contain empty and uninitialzed records, the log file can be assumed
* to be empty.
*/
for (pos = 0; pos < size; pos <<= 1) {
pgoff_t idx = pos >> PAGE_CACHE_SHIFT;
if (!page || page->index != idx) {
if (page)
ntfs_unmap_page(page);
page = ntfs_map_page(mapping, idx);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Error mapping $LogFile "
"page (index %lu).", idx);
goto err_out;
}
}
kaddr = (u8*)page_address(page) + (pos & ~PAGE_CACHE_MASK);
/*
* A non-empty block means the logfile is not empty while an
* empty block after a non-empty block has been encountered
* means we are done.
*/
if (!ntfs_is_empty_recordp((le32*)kaddr))
logfile_is_empty = false;
else if (!logfile_is_empty)
break;
/*
* A log record page means there cannot be a restart page after
* this so no need to continue searching.
*/
if (ntfs_is_rcrd_recordp((le32*)kaddr))
break;
/* If not a (modified by chkdsk) restart page, continue. */
if (!ntfs_is_rstr_recordp((le32*)kaddr) &&
!ntfs_is_chkd_recordp((le32*)kaddr)) {
if (!pos)
pos = NTFS_BLOCK_SIZE >> 1;
continue;
}
/*
* Check the (modified by chkdsk) restart page for consistency
* and get a copy of the complete multi sector transfer
* deprotected restart page.
*/
err = ntfs_check_and_load_restart_page(log_vi,
(RESTART_PAGE_HEADER*)kaddr, pos,
!rstr1_ph ? &rstr1_ph : &rstr2_ph,
!rstr1_ph ? &rstr1_lsn : &rstr2_lsn);
if (!err) {
/*
* If we have now found the first (modified by chkdsk)
* restart page, continue looking for the second one.
*/
if (!pos) {
pos = NTFS_BLOCK_SIZE >> 1;
continue;
}
/*
* We have now found the second (modified by chkdsk)
* restart page, so we can stop looking.
*/
break;
}
/*
* Error output already done inside the function. Note, we do
* not abort if the restart page was invalid as we might still
* find a valid one further in the file.
*/
if (err != -EINVAL) {
ntfs_unmap_page(page);
goto err_out;
}
/* Continue looking. */
if (!pos)
pos = NTFS_BLOCK_SIZE >> 1;
}
if (page)
ntfs_unmap_page(page);
if (logfile_is_empty) {
NVolSetLogFileEmpty(vol);
is_empty:
ntfs_debug("Done. ($LogFile is empty.)");
return true;
}
if (!rstr1_ph) {
BUG_ON(rstr2_ph);
ntfs_error(vol->sb, "Did not find any restart pages in "
"$LogFile and it was not empty.");
return false;
}
/* If both restart pages were found, use the more recent one. */
if (rstr2_ph) {
/*
* If the second restart area is more recent, switch to it.
* Otherwise just throw it away.
*/
if (rstr2_lsn > rstr1_lsn) {
ntfs_debug("Using second restart page as it is more "
"recent.");
ntfs_free(rstr1_ph);
rstr1_ph = rstr2_ph;
/* rstr1_lsn = rstr2_lsn; */
} else {
ntfs_debug("Using first restart page as it is more "
"recent.");
ntfs_free(rstr2_ph);
}
rstr2_ph = NULL;
}
/* All consistency checks passed. */
if (rp)
*rp = rstr1_ph;
else
ntfs_free(rstr1_ph);
ntfs_debug("Done.");
return true;
err_out:
if (rstr1_ph)
ntfs_free(rstr1_ph);
return false;
}
/**
* ntfs_is_logfile_clean - check in the journal if the volume is clean
* @log_vi: struct inode of loaded journal $LogFile to check
* @rp: copy of the current restart page
*
* Analyze the $LogFile journal and return 'true' if it indicates the volume was
* shutdown cleanly and 'false' if not.
*
* At present we only look at the two restart pages and ignore the log record
* pages. This is a little bit crude in that there will be a very small number
* of cases where we think that a volume is dirty when in fact it is clean.
* This should only affect volumes that have not been shutdown cleanly but did
* not have any pending, non-check-pointed i/o, i.e. they were completely idle
* at least for the five seconds preceding the unclean shutdown.
*
* This function assumes that the $LogFile journal has already been consistency
* checked by a call to ntfs_check_logfile() and in particular if the $LogFile
* is empty this function requires that NVolLogFileEmpty() is true otherwise an
* empty volume will be reported as dirty.
*/
bool ntfs_is_logfile_clean(struct inode *log_vi, const RESTART_PAGE_HEADER *rp)
{
ntfs_volume *vol = NTFS_SB(log_vi->i_sb);
RESTART_AREA *ra;
ntfs_debug("Entering.");
/* An empty $LogFile must have been clean before it got emptied. */
if (NVolLogFileEmpty(vol)) {
ntfs_debug("Done. ($LogFile is empty.)");
return true;
}
BUG_ON(!rp);
if (!ntfs_is_rstr_record(rp->magic) &&
!ntfs_is_chkd_record(rp->magic)) {
ntfs_error(vol->sb, "Restart page buffer is invalid. This is "
"probably a bug in that the $LogFile should "
"have been consistency checked before calling "
"this function.");
return false;
}
ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset));
/*
* If the $LogFile has active clients, i.e. it is open, and we do not
* have the RESTART_VOLUME_IS_CLEAN bit set in the restart area flags,
* we assume there was an unclean shutdown.
*/
if (ra->client_in_use_list != LOGFILE_NO_CLIENT &&
!(ra->flags & RESTART_VOLUME_IS_CLEAN)) {
ntfs_debug("Done. $LogFile indicates a dirty shutdown.");
return false;
}
/* $LogFile indicates a clean shutdown. */
ntfs_debug("Done. $LogFile indicates a clean shutdown.");
return true;
}
/**
* ntfs_empty_logfile - empty the contents of the $LogFile journal
* @log_vi: struct inode of loaded journal $LogFile to empty
*
* Empty the contents of the $LogFile journal @log_vi and return 'true' on
* success and 'false' on error.
*
* This function assumes that the $LogFile journal has already been consistency
* checked by a call to ntfs_check_logfile() and that ntfs_is_logfile_clean()
* has been used to ensure that the $LogFile is clean.
*/
bool ntfs_empty_logfile(struct inode *log_vi)
{
VCN vcn, end_vcn;
ntfs_inode *log_ni = NTFS_I(log_vi);
ntfs_volume *vol = log_ni->vol;
struct super_block *sb = vol->sb;
runlist_element *rl;
unsigned long flags;
unsigned block_size, block_size_bits;
int err;
bool should_wait = true;
ntfs_debug("Entering.");
if (NVolLogFileEmpty(vol)) {
ntfs_debug("Done.");
return true;
}
/*
* We cannot use ntfs_attr_set() because we may be still in the middle
* of a mount operation. Thus we do the emptying by hand by first
* zapping the page cache pages for the $LogFile/$DATA attribute and
* then emptying each of the buffers in each of the clusters specified
* by the runlist by hand.
*/
block_size = sb->s_blocksize;
block_size_bits = sb->s_blocksize_bits;
vcn = 0;
read_lock_irqsave(&log_ni->size_lock, flags);
end_vcn = (log_ni->initialized_size + vol->cluster_size_mask) >>
vol->cluster_size_bits;
read_unlock_irqrestore(&log_ni->size_lock, flags);
truncate_inode_pages(log_vi->i_mapping, 0);
down_write(&log_ni->runlist.lock);
rl = log_ni->runlist.rl;
if (unlikely(!rl || vcn < rl->vcn || !rl->length)) {
map_vcn:
err = ntfs_map_runlist_nolock(log_ni, vcn, NULL);
if (err) {
ntfs_error(sb, "Failed to map runlist fragment (error "
"%d).", -err);
goto err;
}
rl = log_ni->runlist.rl;
BUG_ON(!rl || vcn < rl->vcn || !rl->length);
}
/* Seek to the runlist element containing @vcn. */
while (rl->length && vcn >= rl[1].vcn)
rl++;
do {
LCN lcn;
sector_t block, end_block;
s64 len;
/*
* If this run is not mapped map it now and start again as the
* runlist will have been updated.
*/
lcn = rl->lcn;
if (unlikely(lcn == LCN_RL_NOT_MAPPED)) {
vcn = rl->vcn;
goto map_vcn;
}
/* If this run is not valid abort with an error. */
if (unlikely(!rl->length || lcn < LCN_HOLE))
goto rl_err;
/* Skip holes. */
if (lcn == LCN_HOLE)
continue;
block = lcn << vol->cluster_size_bits >> block_size_bits;
len = rl->length;
if (rl[1].vcn > end_vcn)
len = end_vcn - rl->vcn;
end_block = (lcn + len) << vol->cluster_size_bits >>
block_size_bits;
/* Iterate over the blocks in the run and empty them. */
do {
struct buffer_head *bh;
/* Obtain the buffer, possibly not uptodate. */
bh = sb_getblk(sb, block);
BUG_ON(!bh);
/* Setup buffer i/o submission. */
lock_buffer(bh);
bh->b_end_io = end_buffer_write_sync;
get_bh(bh);
/* Set the entire contents of the buffer to 0xff. */
memset(bh->b_data, -1, block_size);
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
if (buffer_dirty(bh))
clear_buffer_dirty(bh);
/*
* Submit the buffer and wait for i/o to complete but
* only for the first buffer so we do not miss really
* serious i/o errors. Once the first buffer has
* completed ignore errors afterwards as we can assume
* that if one buffer worked all of them will work.
*/
submit_bh(WRITE, bh);
if (should_wait) {
should_wait = false;
wait_on_buffer(bh);
if (unlikely(!buffer_uptodate(bh)))
goto io_err;
}
brelse(bh);
} while (++block < end_block);
} while ((++rl)->vcn < end_vcn);
up_write(&log_ni->runlist.lock);
/*
* Zap the pages again just in case any got instantiated whilst we were
* emptying the blocks by hand. FIXME: We may not have completed
* writing to all the buffer heads yet so this may happen too early.
* We really should use a kernel thread to do the emptying
* asynchronously and then we can also set the volume dirty and output
* an error message if emptying should fail.
*/
truncate_inode_pages(log_vi->i_mapping, 0);
/* Set the flag so we do not have to do it again on remount. */
NVolSetLogFileEmpty(vol);
ntfs_debug("Done.");
return true;
io_err:
ntfs_error(sb, "Failed to write buffer. Unmount and run chkdsk.");
goto dirty_err;
rl_err:
ntfs_error(sb, "Runlist is corrupt. Unmount and run chkdsk.");
dirty_err:
NVolSetErrors(vol);
err = -EIO;
err:
up_write(&log_ni->runlist.lock);
ntfs_error(sb, "Failed to fill $LogFile with 0xff bytes (error %d).",
-err);
return false;
}
#endif /* NTFS_RW */
| gpl-2.0 |
IllusionRom-deprecated/android_kernel_samsung_msm8660-common | fs/ntfs/logfile.c | 12457 | 28894 | /*
* logfile.c - NTFS kernel journal handling. Part of the Linux-NTFS project.
*
* Copyright (c) 2002-2007 Anton Altaparmakov
*
* This program/include file 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/include file 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 Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef NTFS_RW
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/highmem.h>
#include <linux/buffer_head.h>
#include <linux/bitops.h>
#include <linux/log2.h>
#include "attrib.h"
#include "aops.h"
#include "debug.h"
#include "logfile.h"
#include "malloc.h"
#include "volume.h"
#include "ntfs.h"
/**
* ntfs_check_restart_page_header - check the page header for consistency
* @vi: $LogFile inode to which the restart page header belongs
* @rp: restart page header to check
* @pos: position in @vi at which the restart page header resides
*
* Check the restart page header @rp for consistency and return 'true' if it is
* consistent and 'false' otherwise.
*
* This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
* require the full restart page.
*/
static bool ntfs_check_restart_page_header(struct inode *vi,
RESTART_PAGE_HEADER *rp, s64 pos)
{
u32 logfile_system_page_size, logfile_log_page_size;
u16 ra_ofs, usa_count, usa_ofs, usa_end = 0;
bool have_usa = true;
ntfs_debug("Entering.");
/*
* If the system or log page sizes are smaller than the ntfs block size
* or either is not a power of 2 we cannot handle this log file.
*/
logfile_system_page_size = le32_to_cpu(rp->system_page_size);
logfile_log_page_size = le32_to_cpu(rp->log_page_size);
if (logfile_system_page_size < NTFS_BLOCK_SIZE ||
logfile_log_page_size < NTFS_BLOCK_SIZE ||
logfile_system_page_size &
(logfile_system_page_size - 1) ||
!is_power_of_2(logfile_log_page_size)) {
ntfs_error(vi->i_sb, "$LogFile uses unsupported page size.");
return false;
}
/*
* We must be either at !pos (1st restart page) or at pos = system page
* size (2nd restart page).
*/
if (pos && pos != logfile_system_page_size) {
ntfs_error(vi->i_sb, "Found restart area in incorrect "
"position in $LogFile.");
return false;
}
/* We only know how to handle version 1.1. */
if (sle16_to_cpu(rp->major_ver) != 1 ||
sle16_to_cpu(rp->minor_ver) != 1) {
ntfs_error(vi->i_sb, "$LogFile version %i.%i is not "
"supported. (This driver supports version "
"1.1 only.)", (int)sle16_to_cpu(rp->major_ver),
(int)sle16_to_cpu(rp->minor_ver));
return false;
}
/*
* If chkdsk has been run the restart page may not be protected by an
* update sequence array.
*/
if (ntfs_is_chkd_record(rp->magic) && !le16_to_cpu(rp->usa_count)) {
have_usa = false;
goto skip_usa_checks;
}
/* Verify the size of the update sequence array. */
usa_count = 1 + (logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS);
if (usa_count != le16_to_cpu(rp->usa_count)) {
ntfs_error(vi->i_sb, "$LogFile restart page specifies "
"inconsistent update sequence array count.");
return false;
}
/* Verify the position of the update sequence array. */
usa_ofs = le16_to_cpu(rp->usa_ofs);
usa_end = usa_ofs + usa_count * sizeof(u16);
if (usa_ofs < sizeof(RESTART_PAGE_HEADER) ||
usa_end > NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "$LogFile restart page specifies "
"inconsistent update sequence array offset.");
return false;
}
skip_usa_checks:
/*
* Verify the position of the restart area. It must be:
* - aligned to 8-byte boundary,
* - after the update sequence array, and
* - within the system page size.
*/
ra_ofs = le16_to_cpu(rp->restart_area_offset);
if (ra_ofs & 7 || (have_usa ? ra_ofs < usa_end :
ra_ofs < sizeof(RESTART_PAGE_HEADER)) ||
ra_ofs > logfile_system_page_size) {
ntfs_error(vi->i_sb, "$LogFile restart page specifies "
"inconsistent restart area offset.");
return false;
}
/*
* Only restart pages modified by chkdsk are allowed to have chkdsk_lsn
* set.
*/
if (!ntfs_is_chkd_record(rp->magic) && sle64_to_cpu(rp->chkdsk_lsn)) {
ntfs_error(vi->i_sb, "$LogFile restart page is not modified "
"by chkdsk but a chkdsk LSN is specified.");
return false;
}
ntfs_debug("Done.");
return true;
}
/**
* ntfs_check_restart_area - check the restart area for consistency
* @vi: $LogFile inode to which the restart page belongs
* @rp: restart page whose restart area to check
*
* Check the restart area of the restart page @rp for consistency and return
* 'true' if it is consistent and 'false' otherwise.
*
* This function assumes that the restart page header has already been
* consistency checked.
*
* This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
* require the full restart page.
*/
static bool ntfs_check_restart_area(struct inode *vi, RESTART_PAGE_HEADER *rp)
{
u64 file_size;
RESTART_AREA *ra;
u16 ra_ofs, ra_len, ca_ofs;
u8 fs_bits;
ntfs_debug("Entering.");
ra_ofs = le16_to_cpu(rp->restart_area_offset);
ra = (RESTART_AREA*)((u8*)rp + ra_ofs);
/*
* Everything before ra->file_size must be before the first word
* protected by an update sequence number. This ensures that it is
* safe to access ra->client_array_offset.
*/
if (ra_ofs + offsetof(RESTART_AREA, file_size) >
NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent file offset.");
return false;
}
/*
* Now that we can access ra->client_array_offset, make sure everything
* up to the log client array is before the first word protected by an
* update sequence number. This ensures we can access all of the
* restart area elements safely. Also, the client array offset must be
* aligned to an 8-byte boundary.
*/
ca_ofs = le16_to_cpu(ra->client_array_offset);
if (((ca_ofs + 7) & ~7) != ca_ofs ||
ra_ofs + ca_ofs > NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent client array offset.");
return false;
}
/*
* The restart area must end within the system page size both when
* calculated manually and as specified by ra->restart_area_length.
* Also, the calculated length must not exceed the specified length.
*/
ra_len = ca_ofs + le16_to_cpu(ra->log_clients) *
sizeof(LOG_CLIENT_RECORD);
if (ra_ofs + ra_len > le32_to_cpu(rp->system_page_size) ||
ra_ofs + le16_to_cpu(ra->restart_area_length) >
le32_to_cpu(rp->system_page_size) ||
ra_len > le16_to_cpu(ra->restart_area_length)) {
ntfs_error(vi->i_sb, "$LogFile restart area is out of bounds "
"of the system page size specified by the "
"restart page header and/or the specified "
"restart area length is inconsistent.");
return false;
}
/*
* The ra->client_free_list and ra->client_in_use_list must be either
* LOGFILE_NO_CLIENT or less than ra->log_clients or they are
* overflowing the client array.
*/
if ((ra->client_free_list != LOGFILE_NO_CLIENT &&
le16_to_cpu(ra->client_free_list) >=
le16_to_cpu(ra->log_clients)) ||
(ra->client_in_use_list != LOGFILE_NO_CLIENT &&
le16_to_cpu(ra->client_in_use_list) >=
le16_to_cpu(ra->log_clients))) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"overflowing client free and/or in use lists.");
return false;
}
/*
* Check ra->seq_number_bits against ra->file_size for consistency.
* We cannot just use ffs() because the file size is not a power of 2.
*/
file_size = (u64)sle64_to_cpu(ra->file_size);
fs_bits = 0;
while (file_size) {
file_size >>= 1;
fs_bits++;
}
if (le32_to_cpu(ra->seq_number_bits) != 67 - fs_bits) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent sequence number bits.");
return false;
}
/* The log record header length must be a multiple of 8. */
if (((le16_to_cpu(ra->log_record_header_length) + 7) & ~7) !=
le16_to_cpu(ra->log_record_header_length)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent log record header length.");
return false;
}
/* Dito for the log page data offset. */
if (((le16_to_cpu(ra->log_page_data_offset) + 7) & ~7) !=
le16_to_cpu(ra->log_page_data_offset)) {
ntfs_error(vi->i_sb, "$LogFile restart area specifies "
"inconsistent log page data offset.");
return false;
}
ntfs_debug("Done.");
return true;
}
/**
* ntfs_check_log_client_array - check the log client array for consistency
* @vi: $LogFile inode to which the restart page belongs
* @rp: restart page whose log client array to check
*
* Check the log client array of the restart page @rp for consistency and
* return 'true' if it is consistent and 'false' otherwise.
*
* This function assumes that the restart page header and the restart area have
* already been consistency checked.
*
* Unlike ntfs_check_restart_page_header() and ntfs_check_restart_area(), this
* function needs @rp->system_page_size bytes in @rp, i.e. it requires the full
* restart page and the page must be multi sector transfer deprotected.
*/
static bool ntfs_check_log_client_array(struct inode *vi,
RESTART_PAGE_HEADER *rp)
{
RESTART_AREA *ra;
LOG_CLIENT_RECORD *ca, *cr;
u16 nr_clients, idx;
bool in_free_list, idx_is_first;
ntfs_debug("Entering.");
ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset));
ca = (LOG_CLIENT_RECORD*)((u8*)ra +
le16_to_cpu(ra->client_array_offset));
/*
* Check the ra->client_free_list first and then check the
* ra->client_in_use_list. Check each of the log client records in
* each of the lists and check that the array does not overflow the
* ra->log_clients value. Also keep track of the number of records
* visited as there cannot be more than ra->log_clients records and
* that way we detect eventual loops in within a list.
*/
nr_clients = le16_to_cpu(ra->log_clients);
idx = le16_to_cpu(ra->client_free_list);
in_free_list = true;
check_list:
for (idx_is_first = true; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--,
idx = le16_to_cpu(cr->next_client)) {
if (!nr_clients || idx >= le16_to_cpu(ra->log_clients))
goto err_out;
/* Set @cr to the current log client record. */
cr = ca + idx;
/* The first log client record must not have a prev_client. */
if (idx_is_first) {
if (cr->prev_client != LOGFILE_NO_CLIENT)
goto err_out;
idx_is_first = false;
}
}
/* Switch to and check the in use list if we just did the free list. */
if (in_free_list) {
in_free_list = false;
idx = le16_to_cpu(ra->client_in_use_list);
goto check_list;
}
ntfs_debug("Done.");
return true;
err_out:
ntfs_error(vi->i_sb, "$LogFile log client array is corrupt.");
return false;
}
/**
* ntfs_check_and_load_restart_page - check the restart page for consistency
* @vi: $LogFile inode to which the restart page belongs
* @rp: restart page to check
* @pos: position in @vi at which the restart page resides
* @wrp: [OUT] copy of the multi sector transfer deprotected restart page
* @lsn: [OUT] set to the current logfile lsn on success
*
* Check the restart page @rp for consistency and return 0 if it is consistent
* and -errno otherwise. The restart page may have been modified by chkdsk in
* which case its magic is CHKD instead of RSTR.
*
* This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
* require the full restart page.
*
* If @wrp is not NULL, on success, *@wrp will point to a buffer containing a
* copy of the complete multi sector transfer deprotected page. On failure,
* *@wrp is undefined.
*
* Simillarly, if @lsn is not NULL, on success *@lsn will be set to the current
* logfile lsn according to this restart page. On failure, *@lsn is undefined.
*
* The following error codes are defined:
* -EINVAL - The restart page is inconsistent.
* -ENOMEM - Not enough memory to load the restart page.
* -EIO - Failed to reading from $LogFile.
*/
static int ntfs_check_and_load_restart_page(struct inode *vi,
RESTART_PAGE_HEADER *rp, s64 pos, RESTART_PAGE_HEADER **wrp,
LSN *lsn)
{
RESTART_AREA *ra;
RESTART_PAGE_HEADER *trp;
int size, err;
ntfs_debug("Entering.");
/* Check the restart page header for consistency. */
if (!ntfs_check_restart_page_header(vi, rp, pos)) {
/* Error output already done inside the function. */
return -EINVAL;
}
/* Check the restart area for consistency. */
if (!ntfs_check_restart_area(vi, rp)) {
/* Error output already done inside the function. */
return -EINVAL;
}
ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset));
/*
* Allocate a buffer to store the whole restart page so we can multi
* sector transfer deprotect it.
*/
trp = ntfs_malloc_nofs(le32_to_cpu(rp->system_page_size));
if (!trp) {
ntfs_error(vi->i_sb, "Failed to allocate memory for $LogFile "
"restart page buffer.");
return -ENOMEM;
}
/*
* Read the whole of the restart page into the buffer. If it fits
* completely inside @rp, just copy it from there. Otherwise map all
* the required pages and copy the data from them.
*/
size = PAGE_CACHE_SIZE - (pos & ~PAGE_CACHE_MASK);
if (size >= le32_to_cpu(rp->system_page_size)) {
memcpy(trp, rp, le32_to_cpu(rp->system_page_size));
} else {
pgoff_t idx;
struct page *page;
int have_read, to_read;
/* First copy what we already have in @rp. */
memcpy(trp, rp, size);
/* Copy the remaining data one page at a time. */
have_read = size;
to_read = le32_to_cpu(rp->system_page_size) - size;
idx = (pos + size) >> PAGE_CACHE_SHIFT;
BUG_ON((pos + size) & ~PAGE_CACHE_MASK);
do {
page = ntfs_map_page(vi->i_mapping, idx);
if (IS_ERR(page)) {
ntfs_error(vi->i_sb, "Error mapping $LogFile "
"page (index %lu).", idx);
err = PTR_ERR(page);
if (err != -EIO && err != -ENOMEM)
err = -EIO;
goto err_out;
}
size = min_t(int, to_read, PAGE_CACHE_SIZE);
memcpy((u8*)trp + have_read, page_address(page), size);
ntfs_unmap_page(page);
have_read += size;
to_read -= size;
idx++;
} while (to_read > 0);
}
/*
* Perform the multi sector transfer deprotection on the buffer if the
* restart page is protected.
*/
if ((!ntfs_is_chkd_record(trp->magic) || le16_to_cpu(trp->usa_count))
&& post_read_mst_fixup((NTFS_RECORD*)trp,
le32_to_cpu(rp->system_page_size))) {
/*
* A multi sector tranfer error was detected. We only need to
* abort if the restart page contents exceed the multi sector
* transfer fixup of the first sector.
*/
if (le16_to_cpu(rp->restart_area_offset) +
le16_to_cpu(ra->restart_area_length) >
NTFS_BLOCK_SIZE - sizeof(u16)) {
ntfs_error(vi->i_sb, "Multi sector transfer error "
"detected in $LogFile restart page.");
err = -EINVAL;
goto err_out;
}
}
/*
* If the restart page is modified by chkdsk or there are no active
* logfile clients, the logfile is consistent. Otherwise, need to
* check the log client records for consistency, too.
*/
err = 0;
if (ntfs_is_rstr_record(rp->magic) &&
ra->client_in_use_list != LOGFILE_NO_CLIENT) {
if (!ntfs_check_log_client_array(vi, trp)) {
err = -EINVAL;
goto err_out;
}
}
if (lsn) {
if (ntfs_is_rstr_record(rp->magic))
*lsn = sle64_to_cpu(ra->current_lsn);
else /* if (ntfs_is_chkd_record(rp->magic)) */
*lsn = sle64_to_cpu(rp->chkdsk_lsn);
}
ntfs_debug("Done.");
if (wrp)
*wrp = trp;
else {
err_out:
ntfs_free(trp);
}
return err;
}
/**
* ntfs_check_logfile - check the journal for consistency
* @log_vi: struct inode of loaded journal $LogFile to check
* @rp: [OUT] on success this is a copy of the current restart page
*
* Check the $LogFile journal for consistency and return 'true' if it is
* consistent and 'false' if not. On success, the current restart page is
* returned in *@rp. Caller must call ntfs_free(*@rp) when finished with it.
*
* At present we only check the two restart pages and ignore the log record
* pages.
*
* Note that the MstProtected flag is not set on the $LogFile inode and hence
* when reading pages they are not deprotected. This is because we do not know
* if the $LogFile was created on a system with a different page size to ours
* yet and mst deprotection would fail if our page size is smaller.
*/
bool ntfs_check_logfile(struct inode *log_vi, RESTART_PAGE_HEADER **rp)
{
s64 size, pos;
LSN rstr1_lsn, rstr2_lsn;
ntfs_volume *vol = NTFS_SB(log_vi->i_sb);
struct address_space *mapping = log_vi->i_mapping;
struct page *page = NULL;
u8 *kaddr = NULL;
RESTART_PAGE_HEADER *rstr1_ph = NULL;
RESTART_PAGE_HEADER *rstr2_ph = NULL;
int log_page_size, log_page_mask, err;
bool logfile_is_empty = true;
u8 log_page_bits;
ntfs_debug("Entering.");
/* An empty $LogFile must have been clean before it got emptied. */
if (NVolLogFileEmpty(vol))
goto is_empty;
size = i_size_read(log_vi);
/* Make sure the file doesn't exceed the maximum allowed size. */
if (size > MaxLogFileSize)
size = MaxLogFileSize;
/*
* Truncate size to a multiple of the page cache size or the default
* log page size if the page cache size is between the default log page
* log page size if the page cache size is between the default log page
* size and twice that.
*/
if (PAGE_CACHE_SIZE >= DefaultLogPageSize && PAGE_CACHE_SIZE <=
DefaultLogPageSize * 2)
log_page_size = DefaultLogPageSize;
else
log_page_size = PAGE_CACHE_SIZE;
log_page_mask = log_page_size - 1;
/*
* Use ntfs_ffs() instead of ffs() to enable the compiler to
* optimize log_page_size and log_page_bits into constants.
*/
log_page_bits = ntfs_ffs(log_page_size) - 1;
size &= ~(s64)(log_page_size - 1);
/*
* Ensure the log file is big enough to store at least the two restart
* pages and the minimum number of log record pages.
*/
if (size < log_page_size * 2 || (size - log_page_size * 2) >>
log_page_bits < MinLogRecordPages) {
ntfs_error(vol->sb, "$LogFile is too small.");
return false;
}
/*
* Read through the file looking for a restart page. Since the restart
* page header is at the beginning of a page we only need to search at
* what could be the beginning of a page (for each page size) rather
* than scanning the whole file byte by byte. If all potential places
* contain empty and uninitialzed records, the log file can be assumed
* to be empty.
*/
for (pos = 0; pos < size; pos <<= 1) {
pgoff_t idx = pos >> PAGE_CACHE_SHIFT;
if (!page || page->index != idx) {
if (page)
ntfs_unmap_page(page);
page = ntfs_map_page(mapping, idx);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Error mapping $LogFile "
"page (index %lu).", idx);
goto err_out;
}
}
kaddr = (u8*)page_address(page) + (pos & ~PAGE_CACHE_MASK);
/*
* A non-empty block means the logfile is not empty while an
* empty block after a non-empty block has been encountered
* means we are done.
*/
if (!ntfs_is_empty_recordp((le32*)kaddr))
logfile_is_empty = false;
else if (!logfile_is_empty)
break;
/*
* A log record page means there cannot be a restart page after
* this so no need to continue searching.
*/
if (ntfs_is_rcrd_recordp((le32*)kaddr))
break;
/* If not a (modified by chkdsk) restart page, continue. */
if (!ntfs_is_rstr_recordp((le32*)kaddr) &&
!ntfs_is_chkd_recordp((le32*)kaddr)) {
if (!pos)
pos = NTFS_BLOCK_SIZE >> 1;
continue;
}
/*
* Check the (modified by chkdsk) restart page for consistency
* and get a copy of the complete multi sector transfer
* deprotected restart page.
*/
err = ntfs_check_and_load_restart_page(log_vi,
(RESTART_PAGE_HEADER*)kaddr, pos,
!rstr1_ph ? &rstr1_ph : &rstr2_ph,
!rstr1_ph ? &rstr1_lsn : &rstr2_lsn);
if (!err) {
/*
* If we have now found the first (modified by chkdsk)
* restart page, continue looking for the second one.
*/
if (!pos) {
pos = NTFS_BLOCK_SIZE >> 1;
continue;
}
/*
* We have now found the second (modified by chkdsk)
* restart page, so we can stop looking.
*/
break;
}
/*
* Error output already done inside the function. Note, we do
* not abort if the restart page was invalid as we might still
* find a valid one further in the file.
*/
if (err != -EINVAL) {
ntfs_unmap_page(page);
goto err_out;
}
/* Continue looking. */
if (!pos)
pos = NTFS_BLOCK_SIZE >> 1;
}
if (page)
ntfs_unmap_page(page);
if (logfile_is_empty) {
NVolSetLogFileEmpty(vol);
is_empty:
ntfs_debug("Done. ($LogFile is empty.)");
return true;
}
if (!rstr1_ph) {
BUG_ON(rstr2_ph);
ntfs_error(vol->sb, "Did not find any restart pages in "
"$LogFile and it was not empty.");
return false;
}
/* If both restart pages were found, use the more recent one. */
if (rstr2_ph) {
/*
* If the second restart area is more recent, switch to it.
* Otherwise just throw it away.
*/
if (rstr2_lsn > rstr1_lsn) {
ntfs_debug("Using second restart page as it is more "
"recent.");
ntfs_free(rstr1_ph);
rstr1_ph = rstr2_ph;
/* rstr1_lsn = rstr2_lsn; */
} else {
ntfs_debug("Using first restart page as it is more "
"recent.");
ntfs_free(rstr2_ph);
}
rstr2_ph = NULL;
}
/* All consistency checks passed. */
if (rp)
*rp = rstr1_ph;
else
ntfs_free(rstr1_ph);
ntfs_debug("Done.");
return true;
err_out:
if (rstr1_ph)
ntfs_free(rstr1_ph);
return false;
}
/**
* ntfs_is_logfile_clean - check in the journal if the volume is clean
* @log_vi: struct inode of loaded journal $LogFile to check
* @rp: copy of the current restart page
*
* Analyze the $LogFile journal and return 'true' if it indicates the volume was
* shutdown cleanly and 'false' if not.
*
* At present we only look at the two restart pages and ignore the log record
* pages. This is a little bit crude in that there will be a very small number
* of cases where we think that a volume is dirty when in fact it is clean.
* This should only affect volumes that have not been shutdown cleanly but did
* not have any pending, non-check-pointed i/o, i.e. they were completely idle
* at least for the five seconds preceding the unclean shutdown.
*
* This function assumes that the $LogFile journal has already been consistency
* checked by a call to ntfs_check_logfile() and in particular if the $LogFile
* is empty this function requires that NVolLogFileEmpty() is true otherwise an
* empty volume will be reported as dirty.
*/
bool ntfs_is_logfile_clean(struct inode *log_vi, const RESTART_PAGE_HEADER *rp)
{
ntfs_volume *vol = NTFS_SB(log_vi->i_sb);
RESTART_AREA *ra;
ntfs_debug("Entering.");
/* An empty $LogFile must have been clean before it got emptied. */
if (NVolLogFileEmpty(vol)) {
ntfs_debug("Done. ($LogFile is empty.)");
return true;
}
BUG_ON(!rp);
if (!ntfs_is_rstr_record(rp->magic) &&
!ntfs_is_chkd_record(rp->magic)) {
ntfs_error(vol->sb, "Restart page buffer is invalid. This is "
"probably a bug in that the $LogFile should "
"have been consistency checked before calling "
"this function.");
return false;
}
ra = (RESTART_AREA*)((u8*)rp + le16_to_cpu(rp->restart_area_offset));
/*
* If the $LogFile has active clients, i.e. it is open, and we do not
* have the RESTART_VOLUME_IS_CLEAN bit set in the restart area flags,
* we assume there was an unclean shutdown.
*/
if (ra->client_in_use_list != LOGFILE_NO_CLIENT &&
!(ra->flags & RESTART_VOLUME_IS_CLEAN)) {
ntfs_debug("Done. $LogFile indicates a dirty shutdown.");
return false;
}
/* $LogFile indicates a clean shutdown. */
ntfs_debug("Done. $LogFile indicates a clean shutdown.");
return true;
}
/**
* ntfs_empty_logfile - empty the contents of the $LogFile journal
* @log_vi: struct inode of loaded journal $LogFile to empty
*
* Empty the contents of the $LogFile journal @log_vi and return 'true' on
* success and 'false' on error.
*
* This function assumes that the $LogFile journal has already been consistency
* checked by a call to ntfs_check_logfile() and that ntfs_is_logfile_clean()
* has been used to ensure that the $LogFile is clean.
*/
bool ntfs_empty_logfile(struct inode *log_vi)
{
VCN vcn, end_vcn;
ntfs_inode *log_ni = NTFS_I(log_vi);
ntfs_volume *vol = log_ni->vol;
struct super_block *sb = vol->sb;
runlist_element *rl;
unsigned long flags;
unsigned block_size, block_size_bits;
int err;
bool should_wait = true;
ntfs_debug("Entering.");
if (NVolLogFileEmpty(vol)) {
ntfs_debug("Done.");
return true;
}
/*
* We cannot use ntfs_attr_set() because we may be still in the middle
* of a mount operation. Thus we do the emptying by hand by first
* zapping the page cache pages for the $LogFile/$DATA attribute and
* then emptying each of the buffers in each of the clusters specified
* by the runlist by hand.
*/
block_size = sb->s_blocksize;
block_size_bits = sb->s_blocksize_bits;
vcn = 0;
read_lock_irqsave(&log_ni->size_lock, flags);
end_vcn = (log_ni->initialized_size + vol->cluster_size_mask) >>
vol->cluster_size_bits;
read_unlock_irqrestore(&log_ni->size_lock, flags);
truncate_inode_pages(log_vi->i_mapping, 0);
down_write(&log_ni->runlist.lock);
rl = log_ni->runlist.rl;
if (unlikely(!rl || vcn < rl->vcn || !rl->length)) {
map_vcn:
err = ntfs_map_runlist_nolock(log_ni, vcn, NULL);
if (err) {
ntfs_error(sb, "Failed to map runlist fragment (error "
"%d).", -err);
goto err;
}
rl = log_ni->runlist.rl;
BUG_ON(!rl || vcn < rl->vcn || !rl->length);
}
/* Seek to the runlist element containing @vcn. */
while (rl->length && vcn >= rl[1].vcn)
rl++;
do {
LCN lcn;
sector_t block, end_block;
s64 len;
/*
* If this run is not mapped map it now and start again as the
* runlist will have been updated.
*/
lcn = rl->lcn;
if (unlikely(lcn == LCN_RL_NOT_MAPPED)) {
vcn = rl->vcn;
goto map_vcn;
}
/* If this run is not valid abort with an error. */
if (unlikely(!rl->length || lcn < LCN_HOLE))
goto rl_err;
/* Skip holes. */
if (lcn == LCN_HOLE)
continue;
block = lcn << vol->cluster_size_bits >> block_size_bits;
len = rl->length;
if (rl[1].vcn > end_vcn)
len = end_vcn - rl->vcn;
end_block = (lcn + len) << vol->cluster_size_bits >>
block_size_bits;
/* Iterate over the blocks in the run and empty them. */
do {
struct buffer_head *bh;
/* Obtain the buffer, possibly not uptodate. */
bh = sb_getblk(sb, block);
BUG_ON(!bh);
/* Setup buffer i/o submission. */
lock_buffer(bh);
bh->b_end_io = end_buffer_write_sync;
get_bh(bh);
/* Set the entire contents of the buffer to 0xff. */
memset(bh->b_data, -1, block_size);
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
if (buffer_dirty(bh))
clear_buffer_dirty(bh);
/*
* Submit the buffer and wait for i/o to complete but
* only for the first buffer so we do not miss really
* serious i/o errors. Once the first buffer has
* completed ignore errors afterwards as we can assume
* that if one buffer worked all of them will work.
*/
submit_bh(WRITE, bh);
if (should_wait) {
should_wait = false;
wait_on_buffer(bh);
if (unlikely(!buffer_uptodate(bh)))
goto io_err;
}
brelse(bh);
} while (++block < end_block);
} while ((++rl)->vcn < end_vcn);
up_write(&log_ni->runlist.lock);
/*
* Zap the pages again just in case any got instantiated whilst we were
* emptying the blocks by hand. FIXME: We may not have completed
* writing to all the buffer heads yet so this may happen too early.
* We really should use a kernel thread to do the emptying
* asynchronously and then we can also set the volume dirty and output
* an error message if emptying should fail.
*/
truncate_inode_pages(log_vi->i_mapping, 0);
/* Set the flag so we do not have to do it again on remount. */
NVolSetLogFileEmpty(vol);
ntfs_debug("Done.");
return true;
io_err:
ntfs_error(sb, "Failed to write buffer. Unmount and run chkdsk.");
goto dirty_err;
rl_err:
ntfs_error(sb, "Runlist is corrupt. Unmount and run chkdsk.");
dirty_err:
NVolSetErrors(vol);
err = -EIO;
err:
up_write(&log_ni->runlist.lock);
ntfs_error(sb, "Failed to fill $LogFile with 0xff bytes (error %d).",
-err);
return false;
}
#endif /* NTFS_RW */
| gpl-2.0 |
marlontoe/MAD-LEGACY | fs/adfs/map.c | 12969 | 7075 | /*
* linux/fs/adfs/map.c
*
* Copyright (C) 1997-2002 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/buffer_head.h>
#include <asm/unaligned.h>
#include "adfs.h"
/*
* The ADFS map is basically a set of sectors. Each sector is called a
* zone which contains a bitstream made up of variable sized fragments.
* Each bit refers to a set of bytes in the filesystem, defined by
* log2bpmb. This may be larger or smaller than the sector size, but
* the overall size it describes will always be a round number of
* sectors. A fragment id is always idlen bits long.
*
* < idlen > < n > <1>
* +---------+-------//---------+---+
* | frag id | 0000....000000 | 1 |
* +---------+-------//---------+---+
*
* The physical disk space used by a fragment is taken from the start of
* the fragment id up to and including the '1' bit - ie, idlen + n + 1
* bits.
*
* A fragment id can be repeated multiple times in the whole map for
* large or fragmented files. The first map zone a fragment starts in
* is given by fragment id / ids_per_zone - this allows objects to start
* from any zone on the disk.
*
* Free space is described by a linked list of fragments. Each free
* fragment describes free space in the same way as the other fragments,
* however, the frag id specifies an offset (in map bits) from the end
* of this fragment to the start of the next free fragment.
*
* Objects stored on the disk are allocated object ids (we use these as
* our inode numbers.) Object ids contain a fragment id and an optional
* offset. This allows a directory fragment to contain small files
* associated with that directory.
*/
/*
* For the future...
*/
static DEFINE_RWLOCK(adfs_map_lock);
/*
* This is fun. We need to load up to 19 bits from the map at an
* arbitrary bit alignment. (We're limited to 19 bits by F+ version 2).
*/
#define GET_FRAG_ID(_map,_start,_idmask) \
({ \
unsigned char *_m = _map + (_start >> 3); \
u32 _frag = get_unaligned_le32(_m); \
_frag >>= (_start & 7); \
_frag & _idmask; \
})
/*
* return the map bit offset of the fragment frag_id in the zone dm.
* Note that the loop is optimised for best asm code - look at the
* output of:
* gcc -D__KERNEL__ -O2 -I../../include -o - -S map.c
*/
static int
lookup_zone(const struct adfs_discmap *dm, const unsigned int idlen,
const unsigned int frag_id, unsigned int *offset)
{
const unsigned int mapsize = dm->dm_endbit;
const u32 idmask = (1 << idlen) - 1;
unsigned char *map = dm->dm_bh->b_data + 4;
unsigned int start = dm->dm_startbit;
unsigned int mapptr;
u32 frag;
do {
frag = GET_FRAG_ID(map, start, idmask);
mapptr = start + idlen;
/*
* find end of fragment
*/
{
__le32 *_map = (__le32 *)map;
u32 v = le32_to_cpu(_map[mapptr >> 5]) >> (mapptr & 31);
while (v == 0) {
mapptr = (mapptr & ~31) + 32;
if (mapptr >= mapsize)
goto error;
v = le32_to_cpu(_map[mapptr >> 5]);
}
mapptr += 1 + ffz(~v);
}
if (frag == frag_id)
goto found;
again:
start = mapptr;
} while (mapptr < mapsize);
return -1;
error:
printk(KERN_ERR "adfs: oversized fragment 0x%x at 0x%x-0x%x\n",
frag, start, mapptr);
return -1;
found:
{
int length = mapptr - start;
if (*offset >= length) {
*offset -= length;
goto again;
}
}
return start + *offset;
}
/*
* Scan the free space map, for this zone, calculating the total
* number of map bits in each free space fragment.
*
* Note: idmask is limited to 15 bits [3.2]
*/
static unsigned int
scan_free_map(struct adfs_sb_info *asb, struct adfs_discmap *dm)
{
const unsigned int mapsize = dm->dm_endbit + 32;
const unsigned int idlen = asb->s_idlen;
const unsigned int frag_idlen = idlen <= 15 ? idlen : 15;
const u32 idmask = (1 << frag_idlen) - 1;
unsigned char *map = dm->dm_bh->b_data;
unsigned int start = 8, mapptr;
u32 frag;
unsigned long total = 0;
/*
* get fragment id
*/
frag = GET_FRAG_ID(map, start, idmask);
/*
* If the freelink is null, then no free fragments
* exist in this zone.
*/
if (frag == 0)
return 0;
do {
start += frag;
/*
* get fragment id
*/
frag = GET_FRAG_ID(map, start, idmask);
mapptr = start + idlen;
/*
* find end of fragment
*/
{
__le32 *_map = (__le32 *)map;
u32 v = le32_to_cpu(_map[mapptr >> 5]) >> (mapptr & 31);
while (v == 0) {
mapptr = (mapptr & ~31) + 32;
if (mapptr >= mapsize)
goto error;
v = le32_to_cpu(_map[mapptr >> 5]);
}
mapptr += 1 + ffz(~v);
}
total += mapptr - start;
} while (frag >= idlen + 1);
if (frag != 0)
printk(KERN_ERR "adfs: undersized free fragment\n");
return total;
error:
printk(KERN_ERR "adfs: oversized free fragment\n");
return 0;
}
static int
scan_map(struct adfs_sb_info *asb, unsigned int zone,
const unsigned int frag_id, unsigned int mapoff)
{
const unsigned int idlen = asb->s_idlen;
struct adfs_discmap *dm, *dm_end;
int result;
dm = asb->s_map + zone;
zone = asb->s_map_size;
dm_end = asb->s_map + zone;
do {
result = lookup_zone(dm, idlen, frag_id, &mapoff);
if (result != -1)
goto found;
dm ++;
if (dm == dm_end)
dm = asb->s_map;
} while (--zone > 0);
return -1;
found:
result -= dm->dm_startbit;
result += dm->dm_startblk;
return result;
}
/*
* calculate the amount of free blocks in the map.
*
* n=1
* total_free = E(free_in_zone_n)
* nzones
*/
unsigned int
adfs_map_free(struct super_block *sb)
{
struct adfs_sb_info *asb = ADFS_SB(sb);
struct adfs_discmap *dm;
unsigned int total = 0;
unsigned int zone;
dm = asb->s_map;
zone = asb->s_map_size;
do {
total += scan_free_map(asb, dm++);
} while (--zone > 0);
return signed_asl(total, asb->s_map2blk);
}
int
adfs_map_lookup(struct super_block *sb, unsigned int frag_id,
unsigned int offset)
{
struct adfs_sb_info *asb = ADFS_SB(sb);
unsigned int zone, mapoff;
int result;
/*
* map & root fragment is special - it starts in the center of the
* disk. The other fragments start at zone (frag / ids_per_zone)
*/
if (frag_id == ADFS_ROOT_FRAG)
zone = asb->s_map_size >> 1;
else
zone = frag_id / asb->s_ids_per_zone;
if (zone >= asb->s_map_size)
goto bad_fragment;
/* Convert sector offset to map offset */
mapoff = signed_asl(offset, -asb->s_map2blk);
read_lock(&adfs_map_lock);
result = scan_map(asb, zone, frag_id, mapoff);
read_unlock(&adfs_map_lock);
if (result > 0) {
unsigned int secoff;
/* Calculate sector offset into map block */
secoff = offset - signed_asl(mapoff, asb->s_map2blk);
return secoff + signed_asl(result, asb->s_map2blk);
}
adfs_error(sb, "fragment 0x%04x at offset %d not found in map",
frag_id, offset);
return 0;
bad_fragment:
adfs_error(sb, "invalid fragment 0x%04x (zone = %d, max = %d)",
frag_id, zone, asb->s_map_size);
return 0;
}
| gpl-2.0 |
Senthil360/android_kernel_samsung_trlte | drivers/video/via/via_utility.c | 12969 | 6019 | /*
* 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 <linux/via-core.h>
#include "global.h"
void viafb_get_device_support_state(u32 *support_state)
{
*support_state = CRT_Device;
if (viaparinfo->chip_info->tmds_chip_info.tmds_chip_name == VT1632_TMDS)
*support_state |= DVI_Device;
if (viaparinfo->chip_info->lvds_chip_info.lvds_chip_name == VT1631_LVDS)
*support_state |= LCD_Device;
}
void viafb_get_device_connect_state(u32 *connect_state)
{
bool mobile = false;
*connect_state = CRT_Device;
if (viafb_dvi_sense())
*connect_state |= DVI_Device;
viafb_lcd_get_mobile_state(&mobile);
if (mobile)
*connect_state |= LCD_Device;
}
bool viafb_lcd_get_support_expand_state(u32 xres, u32 yres)
{
unsigned int support_state = 0;
switch (viafb_lcd_panel_id) {
case LCD_PANEL_ID0_640X480:
if ((xres < 640) && (yres < 480))
support_state = true;
break;
case LCD_PANEL_ID1_800X600:
if ((xres < 800) && (yres < 600))
support_state = true;
break;
case LCD_PANEL_ID2_1024X768:
if ((xres < 1024) && (yres < 768))
support_state = true;
break;
case LCD_PANEL_ID3_1280X768:
if ((xres < 1280) && (yres < 768))
support_state = true;
break;
case LCD_PANEL_ID4_1280X1024:
if ((xres < 1280) && (yres < 1024))
support_state = true;
break;
case LCD_PANEL_ID5_1400X1050:
if ((xres < 1400) && (yres < 1050))
support_state = true;
break;
case LCD_PANEL_ID6_1600X1200:
if ((xres < 1600) && (yres < 1200))
support_state = true;
break;
case LCD_PANEL_ID7_1366X768:
if ((xres < 1366) && (yres < 768))
support_state = true;
break;
case LCD_PANEL_ID8_1024X600:
if ((xres < 1024) && (yres < 600))
support_state = true;
break;
case LCD_PANEL_ID9_1280X800:
if ((xres < 1280) && (yres < 800))
support_state = true;
break;
case LCD_PANEL_IDA_800X480:
if ((xres < 800) && (yres < 480))
support_state = true;
break;
case LCD_PANEL_IDB_1360X768:
if ((xres < 1360) && (yres < 768))
support_state = true;
break;
case LCD_PANEL_IDC_480X640:
if ((xres < 480) && (yres < 640))
support_state = true;
break;
default:
support_state = false;
break;
}
return support_state;
}
/*====================================================================*/
/* Gamma Function Implementation*/
/*====================================================================*/
void viafb_set_gamma_table(int bpp, unsigned int *gamma_table)
{
int i, sr1a;
int active_device_amount = 0;
int device_status = viafb_DeviceStatus;
for (i = 0; i < sizeof(viafb_DeviceStatus) * 8; i++) {
if (device_status & 1)
active_device_amount++;
device_status >>= 1;
}
/* 8 bpp mode can't adjust gamma */
if (bpp == 8)
return ;
/* Enable Gamma */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
viafb_write_reg_mask(SR16, VIASR, 0x80, BIT7);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
case UNICHROME_CX700:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
viafb_write_reg_mask(CR33, VIACR, 0x80, BIT7);
break;
}
sr1a = (unsigned int)viafb_read_reg(VIASR, SR1A);
viafb_write_reg_mask(SR1A, VIASR, 0x0, BIT0);
/* Fill IGA1 Gamma Table */
outb(0, LUT_INDEX_WRITE);
for (i = 0; i < 256; i++) {
outb(gamma_table[i] >> 16, LUT_DATA);
outb(gamma_table[i] >> 8 & 0xFF, LUT_DATA);
outb(gamma_table[i] & 0xFF, LUT_DATA);
}
/* If adjust Gamma value in SAMM, fill IGA1,
IGA2 Gamma table simultaneous. */
/* Switch to IGA2 Gamma Table */
if ((active_device_amount > 1) &&
!((viaparinfo->chip_info->gfx_chip_name ==
UNICHROME_CLE266) &&
(viaparinfo->chip_info->gfx_chip_revision < 15))) {
viafb_write_reg_mask(SR1A, VIASR, 0x01, BIT0);
viafb_write_reg_mask(CR6A, VIACR, 0x02, BIT1);
/* Fill IGA2 Gamma Table */
outb(0, LUT_INDEX_WRITE);
for (i = 0; i < 256; i++) {
outb(gamma_table[i] >> 16, LUT_DATA);
outb(gamma_table[i] >> 8 & 0xFF, LUT_DATA);
outb(gamma_table[i] & 0xFF, LUT_DATA);
}
}
viafb_write_reg(SR1A, VIASR, sr1a);
}
void viafb_get_gamma_table(unsigned int *gamma_table)
{
unsigned char color_r, color_g, color_b;
unsigned char sr1a = 0;
int i;
/* Enable Gamma */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
viafb_write_reg_mask(SR16, VIASR, 0x80, BIT7);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
case UNICHROME_CX700:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
viafb_write_reg_mask(CR33, VIACR, 0x80, BIT7);
break;
}
sr1a = viafb_read_reg(VIASR, SR1A);
viafb_write_reg_mask(SR1A, VIASR, 0x0, BIT0);
/* Reading gamma table to get color value */
outb(0, LUT_INDEX_READ);
for (i = 0; i < 256; i++) {
color_r = inb(LUT_DATA);
color_g = inb(LUT_DATA);
color_b = inb(LUT_DATA);
gamma_table[i] =
((((u32) color_r) << 16) |
(((u16) color_g) << 8)) | color_b;
}
viafb_write_reg(SR1A, VIASR, sr1a);
}
void viafb_get_gamma_support_state(int bpp, unsigned int *support_state)
{
if (bpp == 8)
*support_state = None_Device;
else
*support_state = CRT_Device | DVI_Device | LCD_Device;
}
| gpl-2.0 |
zzpu/linux-stack | arch/um/kernel/trap.c | 170 | 8232 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/hardirq.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <asm/current.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include <arch.h>
#include <as-layout.h>
#include <kern_util.h>
#include <os.h>
#include <skas.h>
/*
* Note this is constrained to return 0, -EFAULT, -EACCESS, -ENOMEM by
* segv().
*/
int handle_page_fault(unsigned long address, unsigned long ip,
int is_write, int is_user, int *code_out)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int err = -EFAULT;
unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
*code_out = SEGV_MAPERR;
/*
* If the fault was with pagefaults disabled, don't take the fault, just
* fail.
*/
if (faulthandler_disabled())
goto out_nosemaphore;
if (is_user)
flags |= FAULT_FLAG_USER;
retry:
down_read(&mm->mmap_sem);
vma = find_vma(mm, address);
if (!vma)
goto out;
else if (vma->vm_start <= address)
goto good_area;
else if (!(vma->vm_flags & VM_GROWSDOWN))
goto out;
else if (is_user && !ARCH_IS_STACKGROW(address))
goto out;
else if (expand_stack(vma, address))
goto out;
good_area:
*code_out = SEGV_ACCERR;
if (is_write) {
if (!(vma->vm_flags & VM_WRITE))
goto out;
flags |= FAULT_FLAG_WRITE;
} else {
/* Don't require VM_READ|VM_EXEC for write faults! */
if (!(vma->vm_flags & (VM_READ | VM_EXEC)))
goto out;
}
do {
int fault;
fault = handle_mm_fault(vma, address, flags);
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
goto out_nosemaphore;
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM) {
goto out_of_memory;
} else if (fault & VM_FAULT_SIGSEGV) {
goto out;
} else if (fault & VM_FAULT_SIGBUS) {
err = -EACCES;
goto out;
}
BUG();
}
if (flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR)
current->maj_flt++;
else
current->min_flt++;
if (fault & VM_FAULT_RETRY) {
flags &= ~FAULT_FLAG_ALLOW_RETRY;
flags |= FAULT_FLAG_TRIED;
goto retry;
}
}
pgd = pgd_offset(mm, address);
pud = pud_offset(pgd, address);
pmd = pmd_offset(pud, address);
pte = pte_offset_kernel(pmd, address);
} while (!pte_present(*pte));
err = 0;
/*
* The below warning was added in place of
* pte_mkyoung(); if (is_write) pte_mkdirty();
* If it's triggered, we'd see normally a hang here (a clean pte is
* marked read-only to emulate the dirty bit).
* However, the generic code can mark a PTE writable but clean on a
* concurrent read fault, triggering this harmlessly. So comment it out.
*/
#if 0
WARN_ON(!pte_young(*pte) || (is_write && !pte_dirty(*pte)));
#endif
flush_tlb_page(vma, address);
out:
up_read(&mm->mmap_sem);
out_nosemaphore:
return err;
out_of_memory:
/*
* We ran out of memory, call the OOM killer, and return the userspace
* (which will retry the fault, or kill us if we got oom-killed).
*/
up_read(&mm->mmap_sem);
if (!is_user)
goto out_nosemaphore;
pagefault_out_of_memory();
return 0;
}
EXPORT_SYMBOL(handle_page_fault);
static void show_segv_info(struct uml_pt_regs *regs)
{
struct task_struct *tsk = current;
struct faultinfo *fi = UPT_FAULTINFO(regs);
if (!unhandled_signal(tsk, SIGSEGV))
return;
if (!printk_ratelimit())
return;
printk("%s%s[%d]: segfault at %lx ip %p sp %p error %x",
task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG,
tsk->comm, task_pid_nr(tsk), FAULT_ADDRESS(*fi),
(void *)UPT_IP(regs), (void *)UPT_SP(regs),
fi->error_code);
print_vma_addr(KERN_CONT " in ", UPT_IP(regs));
printk(KERN_CONT "\n");
}
static void bad_segv(struct faultinfo fi, unsigned long ip)
{
struct siginfo si;
si.si_signo = SIGSEGV;
si.si_code = SEGV_ACCERR;
si.si_addr = (void __user *) FAULT_ADDRESS(fi);
current->thread.arch.faultinfo = fi;
force_sig_info(SIGSEGV, &si, current);
}
void fatal_sigsegv(void)
{
force_sigsegv(SIGSEGV, current);
do_signal(¤t->thread.regs);
/*
* This is to tell gcc that we're not returning - do_signal
* can, in general, return, but in this case, it's not, since
* we just got a fatal SIGSEGV queued.
*/
os_dump_core();
}
void segv_handler(int sig, struct siginfo *unused_si, struct uml_pt_regs *regs)
{
struct faultinfo * fi = UPT_FAULTINFO(regs);
if (UPT_IS_USER(regs) && !SEGV_IS_FIXABLE(fi)) {
show_segv_info(regs);
bad_segv(*fi, UPT_IP(regs));
return;
}
segv(*fi, UPT_IP(regs), UPT_IS_USER(regs), regs);
}
/*
* We give a *copy* of the faultinfo in the regs to segv.
* This must be done, since nesting SEGVs could overwrite
* the info in the regs. A pointer to the info then would
* give us bad data!
*/
unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user,
struct uml_pt_regs *regs)
{
struct siginfo si;
jmp_buf *catcher;
int err;
int is_write = FAULT_WRITE(fi);
unsigned long address = FAULT_ADDRESS(fi);
if (!is_user && regs)
current->thread.segv_regs = container_of(regs, struct pt_regs, regs);
if (!is_user && (address >= start_vm) && (address < end_vm)) {
flush_tlb_kernel_vm();
goto out;
}
else if (current->mm == NULL) {
show_regs(container_of(regs, struct pt_regs, regs));
panic("Segfault with no mm");
}
else if (!is_user && address > PAGE_SIZE && address < TASK_SIZE) {
show_regs(container_of(regs, struct pt_regs, regs));
panic("Kernel tried to access user memory at addr 0x%lx, ip 0x%lx",
address, ip);
}
if (SEGV_IS_FIXABLE(&fi))
err = handle_page_fault(address, ip, is_write, is_user,
&si.si_code);
else {
err = -EFAULT;
/*
* A thread accessed NULL, we get a fault, but CR2 is invalid.
* This code is used in __do_copy_from_user() of TT mode.
* XXX tt mode is gone, so maybe this isn't needed any more
*/
address = 0;
}
catcher = current->thread.fault_catcher;
if (!err)
goto out;
else if (catcher != NULL) {
current->thread.fault_addr = (void *) address;
UML_LONGJMP(catcher, 1);
}
else if (current->thread.fault_addr != NULL)
panic("fault_addr set but no fault catcher");
else if (!is_user && arch_fixup(ip, regs))
goto out;
if (!is_user) {
show_regs(container_of(regs, struct pt_regs, regs));
panic("Kernel mode fault at addr 0x%lx, ip 0x%lx",
address, ip);
}
show_segv_info(regs);
if (err == -EACCES) {
si.si_signo = SIGBUS;
si.si_errno = 0;
si.si_code = BUS_ADRERR;
si.si_addr = (void __user *)address;
current->thread.arch.faultinfo = fi;
force_sig_info(SIGBUS, &si, current);
} else {
BUG_ON(err != -EFAULT);
si.si_signo = SIGSEGV;
si.si_addr = (void __user *) address;
current->thread.arch.faultinfo = fi;
force_sig_info(SIGSEGV, &si, current);
}
out:
if (regs)
current->thread.segv_regs = NULL;
return 0;
}
void relay_signal(int sig, struct siginfo *si, struct uml_pt_regs *regs)
{
struct faultinfo *fi;
struct siginfo clean_si;
if (!UPT_IS_USER(regs)) {
if (sig == SIGBUS)
printk(KERN_ERR "Bus error - the host /dev/shm or /tmp "
"mount likely just ran out of space\n");
panic("Kernel mode signal %d", sig);
}
arch_examine_signal(sig, regs);
memset(&clean_si, 0, sizeof(clean_si));
clean_si.si_signo = si->si_signo;
clean_si.si_errno = si->si_errno;
clean_si.si_code = si->si_code;
switch (sig) {
case SIGILL:
case SIGFPE:
case SIGSEGV:
case SIGBUS:
case SIGTRAP:
fi = UPT_FAULTINFO(regs);
clean_si.si_addr = (void __user *) FAULT_ADDRESS(*fi);
current->thread.arch.faultinfo = *fi;
#ifdef __ARCH_SI_TRAPNO
clean_si.si_trapno = si->si_trapno;
#endif
break;
default:
printk(KERN_ERR "Attempted to relay unknown signal %d (si_code = %d)\n",
sig, si->si_code);
}
force_sig_info(sig, &clean_si, current);
}
void bus_handler(int sig, struct siginfo *si, struct uml_pt_regs *regs)
{
if (current->thread.fault_catcher != NULL)
UML_LONGJMP(current->thread.fault_catcher, 1);
else
relay_signal(sig, si, regs);
}
void winch(int sig, struct siginfo *unused_si, struct uml_pt_regs *regs)
{
do_IRQ(WINCH_IRQ, regs);
}
void trap_init(void)
{
}
| gpl-2.0 |
BORETS24/Zenfone-2-500CL | linux/kernel/drivers/external_drivers/camera/drivers/media/pci/atomisp2/css2401a0_v21_build/css/isp/kernels/crop/crop_1.0/ia_css_crop.host.c | 170 | 1817 | /*
* Support for Intel Camera Imaging ISP subsystem.
*
* Copyright (c) 2010 - 2014 Intel Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#include <assert_support.h>
#include <ia_css_frame_public.h>
#include <ia_css_frame.h>
#include <ia_css_binary.h>
#define IA_CSS_INCLUDE_CONFIGURATIONS
#include "ia_css_isp_configs.h"
#include "isp.h"
#include "ia_css_crop.host.h"
void
ia_css_crop_encode(
struct sh_css_isp_crop_isp_params *to,
const struct ia_css_crop_config *from,
unsigned size)
{
(void)size;
to->crop_pos = from->crop_pos;
}
void
ia_css_crop_config(
struct sh_css_isp_crop_isp_config *to,
const struct ia_css_crop_configuration *from,
unsigned size)
{
unsigned elems_a = ISP_VEC_NELEMS;
(void)size;
ia_css_dma_configure_from_info(&to->port_b, from->info);
to->width_a_over_b = elems_a / to->port_b.elems;
/* Assume divisiblity here, may need to generalize to fixed point. */
assert (elems_a % to->port_b.elems == 0);
}
void
ia_css_crop_configure(
const struct ia_css_binary *binary,
const struct ia_css_frame_info *info)
{
const struct ia_css_crop_configuration config =
{ info };
ia_css_configure_crop(binary, &config);
}
| gpl-2.0 |
pkirchhofer/nsa325-linux-upstream | arch/powerpc/kvm/e500_mmu.c | 1450 | 25047 | /*
* Copyright (C) 2008-2013 Freescale Semiconductor, Inc. All rights reserved.
*
* Author: Yu Liu, yu.liu@freescale.com
* Scott Wood, scottwood@freescale.com
* Ashish Kalra, ashish.kalra@freescale.com
* Varun Sethi, varun.sethi@freescale.com
* Alexander Graf, agraf@suse.de
*
* Description:
* This file is based on arch/powerpc/kvm/44x_tlb.c,
* by Hollis Blanchard <hollisb@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, version 2, as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/highmem.h>
#include <linux/log2.h>
#include <linux/uaccess.h>
#include <linux/sched.h>
#include <linux/rwsem.h>
#include <linux/vmalloc.h>
#include <linux/hugetlb.h>
#include <asm/kvm_ppc.h>
#include "e500.h"
#include "trace_booke.h"
#include "timing.h"
#include "e500_mmu_host.h"
static inline unsigned int gtlb0_get_next_victim(
struct kvmppc_vcpu_e500 *vcpu_e500)
{
unsigned int victim;
victim = vcpu_e500->gtlb_nv[0]++;
if (unlikely(vcpu_e500->gtlb_nv[0] >= vcpu_e500->gtlb_params[0].ways))
vcpu_e500->gtlb_nv[0] = 0;
return victim;
}
static int tlb0_set_base(gva_t addr, int sets, int ways)
{
int set_base;
set_base = (addr >> PAGE_SHIFT) & (sets - 1);
set_base *= ways;
return set_base;
}
static int gtlb0_set_base(struct kvmppc_vcpu_e500 *vcpu_e500, gva_t addr)
{
return tlb0_set_base(addr, vcpu_e500->gtlb_params[0].sets,
vcpu_e500->gtlb_params[0].ways);
}
static unsigned int get_tlb_esel(struct kvm_vcpu *vcpu, int tlbsel)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int esel = get_tlb_esel_bit(vcpu);
if (tlbsel == 0) {
esel &= vcpu_e500->gtlb_params[0].ways - 1;
esel += gtlb0_set_base(vcpu_e500, vcpu->arch.shared->mas2);
} else {
esel &= vcpu_e500->gtlb_params[tlbsel].entries - 1;
}
return esel;
}
/* Search the guest TLB for a matching entry. */
static int kvmppc_e500_tlb_index(struct kvmppc_vcpu_e500 *vcpu_e500,
gva_t eaddr, int tlbsel, unsigned int pid, int as)
{
int size = vcpu_e500->gtlb_params[tlbsel].entries;
unsigned int set_base, offset;
int i;
if (tlbsel == 0) {
set_base = gtlb0_set_base(vcpu_e500, eaddr);
size = vcpu_e500->gtlb_params[0].ways;
} else {
if (eaddr < vcpu_e500->tlb1_min_eaddr ||
eaddr > vcpu_e500->tlb1_max_eaddr)
return -1;
set_base = 0;
}
offset = vcpu_e500->gtlb_offset[tlbsel];
for (i = 0; i < size; i++) {
struct kvm_book3e_206_tlb_entry *tlbe =
&vcpu_e500->gtlb_arch[offset + set_base + i];
unsigned int tid;
if (eaddr < get_tlb_eaddr(tlbe))
continue;
if (eaddr > get_tlb_end(tlbe))
continue;
tid = get_tlb_tid(tlbe);
if (tid && (tid != pid))
continue;
if (!get_tlb_v(tlbe))
continue;
if (get_tlb_ts(tlbe) != as && as != -1)
continue;
return set_base + i;
}
return -1;
}
static inline void kvmppc_e500_deliver_tlb_miss(struct kvm_vcpu *vcpu,
gva_t eaddr, int as)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
unsigned int victim, tsized;
int tlbsel;
/* since we only have two TLBs, only lower bit is used. */
tlbsel = (vcpu->arch.shared->mas4 >> 28) & 0x1;
victim = (tlbsel == 0) ? gtlb0_get_next_victim(vcpu_e500) : 0;
tsized = (vcpu->arch.shared->mas4 >> 7) & 0x1f;
vcpu->arch.shared->mas0 = MAS0_TLBSEL(tlbsel) | MAS0_ESEL(victim)
| MAS0_NV(vcpu_e500->gtlb_nv[tlbsel]);
vcpu->arch.shared->mas1 = MAS1_VALID | (as ? MAS1_TS : 0)
| MAS1_TID(get_tlbmiss_tid(vcpu))
| MAS1_TSIZE(tsized);
vcpu->arch.shared->mas2 = (eaddr & MAS2_EPN)
| (vcpu->arch.shared->mas4 & MAS2_ATTRIB_MASK);
vcpu->arch.shared->mas7_3 &= MAS3_U0 | MAS3_U1 | MAS3_U2 | MAS3_U3;
vcpu->arch.shared->mas6 = (vcpu->arch.shared->mas6 & MAS6_SPID1)
| (get_cur_pid(vcpu) << 16)
| (as ? MAS6_SAS : 0);
}
static void kvmppc_recalc_tlb1map_range(struct kvmppc_vcpu_e500 *vcpu_e500)
{
int size = vcpu_e500->gtlb_params[1].entries;
unsigned int offset;
gva_t eaddr;
int i;
vcpu_e500->tlb1_min_eaddr = ~0UL;
vcpu_e500->tlb1_max_eaddr = 0;
offset = vcpu_e500->gtlb_offset[1];
for (i = 0; i < size; i++) {
struct kvm_book3e_206_tlb_entry *tlbe =
&vcpu_e500->gtlb_arch[offset + i];
if (!get_tlb_v(tlbe))
continue;
eaddr = get_tlb_eaddr(tlbe);
vcpu_e500->tlb1_min_eaddr =
min(vcpu_e500->tlb1_min_eaddr, eaddr);
eaddr = get_tlb_end(tlbe);
vcpu_e500->tlb1_max_eaddr =
max(vcpu_e500->tlb1_max_eaddr, eaddr);
}
}
static int kvmppc_need_recalc_tlb1map_range(struct kvmppc_vcpu_e500 *vcpu_e500,
struct kvm_book3e_206_tlb_entry *gtlbe)
{
unsigned long start, end, size;
size = get_tlb_bytes(gtlbe);
start = get_tlb_eaddr(gtlbe) & ~(size - 1);
end = start + size - 1;
return vcpu_e500->tlb1_min_eaddr == start ||
vcpu_e500->tlb1_max_eaddr == end;
}
/* This function is supposed to be called for a adding a new valid tlb entry */
static void kvmppc_set_tlb1map_range(struct kvm_vcpu *vcpu,
struct kvm_book3e_206_tlb_entry *gtlbe)
{
unsigned long start, end, size;
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
if (!get_tlb_v(gtlbe))
return;
size = get_tlb_bytes(gtlbe);
start = get_tlb_eaddr(gtlbe) & ~(size - 1);
end = start + size - 1;
vcpu_e500->tlb1_min_eaddr = min(vcpu_e500->tlb1_min_eaddr, start);
vcpu_e500->tlb1_max_eaddr = max(vcpu_e500->tlb1_max_eaddr, end);
}
static inline int kvmppc_e500_gtlbe_invalidate(
struct kvmppc_vcpu_e500 *vcpu_e500,
int tlbsel, int esel)
{
struct kvm_book3e_206_tlb_entry *gtlbe =
get_entry(vcpu_e500, tlbsel, esel);
if (unlikely(get_tlb_iprot(gtlbe)))
return -1;
if (tlbsel == 1 && kvmppc_need_recalc_tlb1map_range(vcpu_e500, gtlbe))
kvmppc_recalc_tlb1map_range(vcpu_e500);
gtlbe->mas1 = 0;
return 0;
}
int kvmppc_e500_emul_mt_mmucsr0(struct kvmppc_vcpu_e500 *vcpu_e500, ulong value)
{
int esel;
if (value & MMUCSR0_TLB0FI)
for (esel = 0; esel < vcpu_e500->gtlb_params[0].entries; esel++)
kvmppc_e500_gtlbe_invalidate(vcpu_e500, 0, esel);
if (value & MMUCSR0_TLB1FI)
for (esel = 0; esel < vcpu_e500->gtlb_params[1].entries; esel++)
kvmppc_e500_gtlbe_invalidate(vcpu_e500, 1, esel);
/* Invalidate all host shadow mappings */
kvmppc_core_flush_tlb(&vcpu_e500->vcpu);
return EMULATE_DONE;
}
int kvmppc_e500_emul_tlbivax(struct kvm_vcpu *vcpu, gva_t ea)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
unsigned int ia;
int esel, tlbsel;
ia = (ea >> 2) & 0x1;
/* since we only have two TLBs, only lower bit is used. */
tlbsel = (ea >> 3) & 0x1;
if (ia) {
/* invalidate all entries */
for (esel = 0; esel < vcpu_e500->gtlb_params[tlbsel].entries;
esel++)
kvmppc_e500_gtlbe_invalidate(vcpu_e500, tlbsel, esel);
} else {
ea &= 0xfffff000;
esel = kvmppc_e500_tlb_index(vcpu_e500, ea, tlbsel,
get_cur_pid(vcpu), -1);
if (esel >= 0)
kvmppc_e500_gtlbe_invalidate(vcpu_e500, tlbsel, esel);
}
/* Invalidate all host shadow mappings */
kvmppc_core_flush_tlb(&vcpu_e500->vcpu);
return EMULATE_DONE;
}
static void tlbilx_all(struct kvmppc_vcpu_e500 *vcpu_e500, int tlbsel,
int pid, int type)
{
struct kvm_book3e_206_tlb_entry *tlbe;
int tid, esel;
/* invalidate all entries */
for (esel = 0; esel < vcpu_e500->gtlb_params[tlbsel].entries; esel++) {
tlbe = get_entry(vcpu_e500, tlbsel, esel);
tid = get_tlb_tid(tlbe);
if (type == 0 || tid == pid) {
inval_gtlbe_on_host(vcpu_e500, tlbsel, esel);
kvmppc_e500_gtlbe_invalidate(vcpu_e500, tlbsel, esel);
}
}
}
static void tlbilx_one(struct kvmppc_vcpu_e500 *vcpu_e500, int pid,
gva_t ea)
{
int tlbsel, esel;
for (tlbsel = 0; tlbsel < 2; tlbsel++) {
esel = kvmppc_e500_tlb_index(vcpu_e500, ea, tlbsel, pid, -1);
if (esel >= 0) {
inval_gtlbe_on_host(vcpu_e500, tlbsel, esel);
kvmppc_e500_gtlbe_invalidate(vcpu_e500, tlbsel, esel);
break;
}
}
}
int kvmppc_e500_emul_tlbilx(struct kvm_vcpu *vcpu, int type, gva_t ea)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int pid = get_cur_spid(vcpu);
if (type == 0 || type == 1) {
tlbilx_all(vcpu_e500, 0, pid, type);
tlbilx_all(vcpu_e500, 1, pid, type);
} else if (type == 3) {
tlbilx_one(vcpu_e500, pid, ea);
}
return EMULATE_DONE;
}
int kvmppc_e500_emul_tlbre(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int tlbsel, esel;
struct kvm_book3e_206_tlb_entry *gtlbe;
tlbsel = get_tlb_tlbsel(vcpu);
esel = get_tlb_esel(vcpu, tlbsel);
gtlbe = get_entry(vcpu_e500, tlbsel, esel);
vcpu->arch.shared->mas0 &= ~MAS0_NV(~0);
vcpu->arch.shared->mas0 |= MAS0_NV(vcpu_e500->gtlb_nv[tlbsel]);
vcpu->arch.shared->mas1 = gtlbe->mas1;
vcpu->arch.shared->mas2 = gtlbe->mas2;
vcpu->arch.shared->mas7_3 = gtlbe->mas7_3;
return EMULATE_DONE;
}
int kvmppc_e500_emul_tlbsx(struct kvm_vcpu *vcpu, gva_t ea)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int as = !!get_cur_sas(vcpu);
unsigned int pid = get_cur_spid(vcpu);
int esel, tlbsel;
struct kvm_book3e_206_tlb_entry *gtlbe = NULL;
for (tlbsel = 0; tlbsel < 2; tlbsel++) {
esel = kvmppc_e500_tlb_index(vcpu_e500, ea, tlbsel, pid, as);
if (esel >= 0) {
gtlbe = get_entry(vcpu_e500, tlbsel, esel);
break;
}
}
if (gtlbe) {
esel &= vcpu_e500->gtlb_params[tlbsel].ways - 1;
vcpu->arch.shared->mas0 = MAS0_TLBSEL(tlbsel) | MAS0_ESEL(esel)
| MAS0_NV(vcpu_e500->gtlb_nv[tlbsel]);
vcpu->arch.shared->mas1 = gtlbe->mas1;
vcpu->arch.shared->mas2 = gtlbe->mas2;
vcpu->arch.shared->mas7_3 = gtlbe->mas7_3;
} else {
int victim;
/* since we only have two TLBs, only lower bit is used. */
tlbsel = vcpu->arch.shared->mas4 >> 28 & 0x1;
victim = (tlbsel == 0) ? gtlb0_get_next_victim(vcpu_e500) : 0;
vcpu->arch.shared->mas0 = MAS0_TLBSEL(tlbsel)
| MAS0_ESEL(victim)
| MAS0_NV(vcpu_e500->gtlb_nv[tlbsel]);
vcpu->arch.shared->mas1 =
(vcpu->arch.shared->mas6 & MAS6_SPID0)
| (vcpu->arch.shared->mas6 & (MAS6_SAS ? MAS1_TS : 0))
| (vcpu->arch.shared->mas4 & MAS4_TSIZED(~0));
vcpu->arch.shared->mas2 &= MAS2_EPN;
vcpu->arch.shared->mas2 |= vcpu->arch.shared->mas4 &
MAS2_ATTRIB_MASK;
vcpu->arch.shared->mas7_3 &= MAS3_U0 | MAS3_U1 |
MAS3_U2 | MAS3_U3;
}
kvmppc_set_exit_type(vcpu, EMULATED_TLBSX_EXITS);
return EMULATE_DONE;
}
int kvmppc_e500_emul_tlbwe(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
struct kvm_book3e_206_tlb_entry *gtlbe;
int tlbsel, esel;
int recal = 0;
int idx;
tlbsel = get_tlb_tlbsel(vcpu);
esel = get_tlb_esel(vcpu, tlbsel);
gtlbe = get_entry(vcpu_e500, tlbsel, esel);
if (get_tlb_v(gtlbe)) {
inval_gtlbe_on_host(vcpu_e500, tlbsel, esel);
if ((tlbsel == 1) &&
kvmppc_need_recalc_tlb1map_range(vcpu_e500, gtlbe))
recal = 1;
}
gtlbe->mas1 = vcpu->arch.shared->mas1;
gtlbe->mas2 = vcpu->arch.shared->mas2;
if (!(vcpu->arch.shared->msr & MSR_CM))
gtlbe->mas2 &= 0xffffffffUL;
gtlbe->mas7_3 = vcpu->arch.shared->mas7_3;
trace_kvm_booke206_gtlb_write(vcpu->arch.shared->mas0, gtlbe->mas1,
gtlbe->mas2, gtlbe->mas7_3);
if (tlbsel == 1) {
/*
* If a valid tlb1 entry is overwritten then recalculate the
* min/max TLB1 map address range otherwise no need to look
* in tlb1 array.
*/
if (recal)
kvmppc_recalc_tlb1map_range(vcpu_e500);
else
kvmppc_set_tlb1map_range(vcpu, gtlbe);
}
idx = srcu_read_lock(&vcpu->kvm->srcu);
/* Invalidate shadow mappings for the about-to-be-clobbered TLBE. */
if (tlbe_is_host_safe(vcpu, gtlbe)) {
u64 eaddr = get_tlb_eaddr(gtlbe);
u64 raddr = get_tlb_raddr(gtlbe);
if (tlbsel == 0) {
gtlbe->mas1 &= ~MAS1_TSIZE(~0);
gtlbe->mas1 |= MAS1_TSIZE(BOOK3E_PAGESZ_4K);
}
/* Premap the faulting page */
kvmppc_mmu_map(vcpu, eaddr, raddr, index_of(tlbsel, esel));
}
srcu_read_unlock(&vcpu->kvm->srcu, idx);
kvmppc_set_exit_type(vcpu, EMULATED_TLBWE_EXITS);
return EMULATE_DONE;
}
static int kvmppc_e500_tlb_search(struct kvm_vcpu *vcpu,
gva_t eaddr, unsigned int pid, int as)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int esel, tlbsel;
for (tlbsel = 0; tlbsel < 2; tlbsel++) {
esel = kvmppc_e500_tlb_index(vcpu_e500, eaddr, tlbsel, pid, as);
if (esel >= 0)
return index_of(tlbsel, esel);
}
return -1;
}
/* 'linear_address' is actually an encoding of AS|PID|EADDR . */
int kvmppc_core_vcpu_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
int index;
gva_t eaddr;
u8 pid;
u8 as;
eaddr = tr->linear_address;
pid = (tr->linear_address >> 32) & 0xff;
as = (tr->linear_address >> 40) & 0x1;
index = kvmppc_e500_tlb_search(vcpu, eaddr, pid, as);
if (index < 0) {
tr->valid = 0;
return 0;
}
tr->physical_address = kvmppc_mmu_xlate(vcpu, index, eaddr);
/* XXX what does "writeable" and "usermode" even mean? */
tr->valid = 1;
return 0;
}
int kvmppc_mmu_itlb_index(struct kvm_vcpu *vcpu, gva_t eaddr)
{
unsigned int as = !!(vcpu->arch.shared->msr & MSR_IS);
return kvmppc_e500_tlb_search(vcpu, eaddr, get_cur_pid(vcpu), as);
}
int kvmppc_mmu_dtlb_index(struct kvm_vcpu *vcpu, gva_t eaddr)
{
unsigned int as = !!(vcpu->arch.shared->msr & MSR_DS);
return kvmppc_e500_tlb_search(vcpu, eaddr, get_cur_pid(vcpu), as);
}
void kvmppc_mmu_itlb_miss(struct kvm_vcpu *vcpu)
{
unsigned int as = !!(vcpu->arch.shared->msr & MSR_IS);
kvmppc_e500_deliver_tlb_miss(vcpu, vcpu->arch.pc, as);
}
void kvmppc_mmu_dtlb_miss(struct kvm_vcpu *vcpu)
{
unsigned int as = !!(vcpu->arch.shared->msr & MSR_DS);
kvmppc_e500_deliver_tlb_miss(vcpu, vcpu->arch.fault_dear, as);
}
gpa_t kvmppc_mmu_xlate(struct kvm_vcpu *vcpu, unsigned int index,
gva_t eaddr)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
struct kvm_book3e_206_tlb_entry *gtlbe;
u64 pgmask;
gtlbe = get_entry(vcpu_e500, tlbsel_of(index), esel_of(index));
pgmask = get_tlb_bytes(gtlbe) - 1;
return get_tlb_raddr(gtlbe) | (eaddr & pgmask);
}
void kvmppc_mmu_destroy_e500(struct kvm_vcpu *vcpu)
{
}
/*****************************************/
static void free_gtlb(struct kvmppc_vcpu_e500 *vcpu_e500)
{
int i;
kvmppc_core_flush_tlb(&vcpu_e500->vcpu);
kfree(vcpu_e500->g2h_tlb1_map);
kfree(vcpu_e500->gtlb_priv[0]);
kfree(vcpu_e500->gtlb_priv[1]);
if (vcpu_e500->shared_tlb_pages) {
vfree((void *)(round_down((uintptr_t)vcpu_e500->gtlb_arch,
PAGE_SIZE)));
for (i = 0; i < vcpu_e500->num_shared_tlb_pages; i++) {
set_page_dirty_lock(vcpu_e500->shared_tlb_pages[i]);
put_page(vcpu_e500->shared_tlb_pages[i]);
}
vcpu_e500->num_shared_tlb_pages = 0;
kfree(vcpu_e500->shared_tlb_pages);
vcpu_e500->shared_tlb_pages = NULL;
} else {
kfree(vcpu_e500->gtlb_arch);
}
vcpu_e500->gtlb_arch = NULL;
}
void kvmppc_get_sregs_e500_tlb(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
{
sregs->u.e.mas0 = vcpu->arch.shared->mas0;
sregs->u.e.mas1 = vcpu->arch.shared->mas1;
sregs->u.e.mas2 = vcpu->arch.shared->mas2;
sregs->u.e.mas7_3 = vcpu->arch.shared->mas7_3;
sregs->u.e.mas4 = vcpu->arch.shared->mas4;
sregs->u.e.mas6 = vcpu->arch.shared->mas6;
sregs->u.e.mmucfg = vcpu->arch.mmucfg;
sregs->u.e.tlbcfg[0] = vcpu->arch.tlbcfg[0];
sregs->u.e.tlbcfg[1] = vcpu->arch.tlbcfg[1];
sregs->u.e.tlbcfg[2] = 0;
sregs->u.e.tlbcfg[3] = 0;
}
int kvmppc_set_sregs_e500_tlb(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
{
if (sregs->u.e.features & KVM_SREGS_E_ARCH206_MMU) {
vcpu->arch.shared->mas0 = sregs->u.e.mas0;
vcpu->arch.shared->mas1 = sregs->u.e.mas1;
vcpu->arch.shared->mas2 = sregs->u.e.mas2;
vcpu->arch.shared->mas7_3 = sregs->u.e.mas7_3;
vcpu->arch.shared->mas4 = sregs->u.e.mas4;
vcpu->arch.shared->mas6 = sregs->u.e.mas6;
}
return 0;
}
int kvmppc_get_one_reg_e500_tlb(struct kvm_vcpu *vcpu, u64 id,
union kvmppc_one_reg *val)
{
int r = 0;
long int i;
switch (id) {
case KVM_REG_PPC_MAS0:
*val = get_reg_val(id, vcpu->arch.shared->mas0);
break;
case KVM_REG_PPC_MAS1:
*val = get_reg_val(id, vcpu->arch.shared->mas1);
break;
case KVM_REG_PPC_MAS2:
*val = get_reg_val(id, vcpu->arch.shared->mas2);
break;
case KVM_REG_PPC_MAS7_3:
*val = get_reg_val(id, vcpu->arch.shared->mas7_3);
break;
case KVM_REG_PPC_MAS4:
*val = get_reg_val(id, vcpu->arch.shared->mas4);
break;
case KVM_REG_PPC_MAS6:
*val = get_reg_val(id, vcpu->arch.shared->mas6);
break;
case KVM_REG_PPC_MMUCFG:
*val = get_reg_val(id, vcpu->arch.mmucfg);
break;
case KVM_REG_PPC_EPTCFG:
*val = get_reg_val(id, vcpu->arch.eptcfg);
break;
case KVM_REG_PPC_TLB0CFG:
case KVM_REG_PPC_TLB1CFG:
case KVM_REG_PPC_TLB2CFG:
case KVM_REG_PPC_TLB3CFG:
i = id - KVM_REG_PPC_TLB0CFG;
*val = get_reg_val(id, vcpu->arch.tlbcfg[i]);
break;
case KVM_REG_PPC_TLB0PS:
case KVM_REG_PPC_TLB1PS:
case KVM_REG_PPC_TLB2PS:
case KVM_REG_PPC_TLB3PS:
i = id - KVM_REG_PPC_TLB0PS;
*val = get_reg_val(id, vcpu->arch.tlbps[i]);
break;
default:
r = -EINVAL;
break;
}
return r;
}
int kvmppc_set_one_reg_e500_tlb(struct kvm_vcpu *vcpu, u64 id,
union kvmppc_one_reg *val)
{
int r = 0;
long int i;
switch (id) {
case KVM_REG_PPC_MAS0:
vcpu->arch.shared->mas0 = set_reg_val(id, *val);
break;
case KVM_REG_PPC_MAS1:
vcpu->arch.shared->mas1 = set_reg_val(id, *val);
break;
case KVM_REG_PPC_MAS2:
vcpu->arch.shared->mas2 = set_reg_val(id, *val);
break;
case KVM_REG_PPC_MAS7_3:
vcpu->arch.shared->mas7_3 = set_reg_val(id, *val);
break;
case KVM_REG_PPC_MAS4:
vcpu->arch.shared->mas4 = set_reg_val(id, *val);
break;
case KVM_REG_PPC_MAS6:
vcpu->arch.shared->mas6 = set_reg_val(id, *val);
break;
/* Only allow MMU registers to be set to the config supported by KVM */
case KVM_REG_PPC_MMUCFG: {
u32 reg = set_reg_val(id, *val);
if (reg != vcpu->arch.mmucfg)
r = -EINVAL;
break;
}
case KVM_REG_PPC_EPTCFG: {
u32 reg = set_reg_val(id, *val);
if (reg != vcpu->arch.eptcfg)
r = -EINVAL;
break;
}
case KVM_REG_PPC_TLB0CFG:
case KVM_REG_PPC_TLB1CFG:
case KVM_REG_PPC_TLB2CFG:
case KVM_REG_PPC_TLB3CFG: {
/* MMU geometry (N_ENTRY/ASSOC) can be set only using SW_TLB */
u32 reg = set_reg_val(id, *val);
i = id - KVM_REG_PPC_TLB0CFG;
if (reg != vcpu->arch.tlbcfg[i])
r = -EINVAL;
break;
}
case KVM_REG_PPC_TLB0PS:
case KVM_REG_PPC_TLB1PS:
case KVM_REG_PPC_TLB2PS:
case KVM_REG_PPC_TLB3PS: {
u32 reg = set_reg_val(id, *val);
i = id - KVM_REG_PPC_TLB0PS;
if (reg != vcpu->arch.tlbps[i])
r = -EINVAL;
break;
}
default:
r = -EINVAL;
break;
}
return r;
}
static int vcpu_mmu_geometry_update(struct kvm_vcpu *vcpu,
struct kvm_book3e_206_tlb_params *params)
{
vcpu->arch.tlbcfg[0] &= ~(TLBnCFG_N_ENTRY | TLBnCFG_ASSOC);
if (params->tlb_sizes[0] <= 2048)
vcpu->arch.tlbcfg[0] |= params->tlb_sizes[0];
vcpu->arch.tlbcfg[0] |= params->tlb_ways[0] << TLBnCFG_ASSOC_SHIFT;
vcpu->arch.tlbcfg[1] &= ~(TLBnCFG_N_ENTRY | TLBnCFG_ASSOC);
vcpu->arch.tlbcfg[1] |= params->tlb_sizes[1];
vcpu->arch.tlbcfg[1] |= params->tlb_ways[1] << TLBnCFG_ASSOC_SHIFT;
return 0;
}
int kvm_vcpu_ioctl_config_tlb(struct kvm_vcpu *vcpu,
struct kvm_config_tlb *cfg)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
struct kvm_book3e_206_tlb_params params;
char *virt;
struct page **pages;
struct tlbe_priv *privs[2] = {};
u64 *g2h_bitmap = NULL;
size_t array_len;
u32 sets;
int num_pages, ret, i;
if (cfg->mmu_type != KVM_MMU_FSL_BOOKE_NOHV)
return -EINVAL;
if (copy_from_user(¶ms, (void __user *)(uintptr_t)cfg->params,
sizeof(params)))
return -EFAULT;
if (params.tlb_sizes[1] > 64)
return -EINVAL;
if (params.tlb_ways[1] != params.tlb_sizes[1])
return -EINVAL;
if (params.tlb_sizes[2] != 0 || params.tlb_sizes[3] != 0)
return -EINVAL;
if (params.tlb_ways[2] != 0 || params.tlb_ways[3] != 0)
return -EINVAL;
if (!is_power_of_2(params.tlb_ways[0]))
return -EINVAL;
sets = params.tlb_sizes[0] >> ilog2(params.tlb_ways[0]);
if (!is_power_of_2(sets))
return -EINVAL;
array_len = params.tlb_sizes[0] + params.tlb_sizes[1];
array_len *= sizeof(struct kvm_book3e_206_tlb_entry);
if (cfg->array_len < array_len)
return -EINVAL;
num_pages = DIV_ROUND_UP(cfg->array + array_len - 1, PAGE_SIZE) -
cfg->array / PAGE_SIZE;
pages = kmalloc(sizeof(struct page *) * num_pages, GFP_KERNEL);
if (!pages)
return -ENOMEM;
ret = get_user_pages_fast(cfg->array, num_pages, 1, pages);
if (ret < 0)
goto err_pages;
if (ret != num_pages) {
num_pages = ret;
ret = -EFAULT;
goto err_put_page;
}
virt = vmap(pages, num_pages, VM_MAP, PAGE_KERNEL);
if (!virt) {
ret = -ENOMEM;
goto err_put_page;
}
privs[0] = kzalloc(sizeof(struct tlbe_priv) * params.tlb_sizes[0],
GFP_KERNEL);
privs[1] = kzalloc(sizeof(struct tlbe_priv) * params.tlb_sizes[1],
GFP_KERNEL);
if (!privs[0] || !privs[1]) {
ret = -ENOMEM;
goto err_privs;
}
g2h_bitmap = kzalloc(sizeof(u64) * params.tlb_sizes[1],
GFP_KERNEL);
if (!g2h_bitmap) {
ret = -ENOMEM;
goto err_privs;
}
free_gtlb(vcpu_e500);
vcpu_e500->gtlb_priv[0] = privs[0];
vcpu_e500->gtlb_priv[1] = privs[1];
vcpu_e500->g2h_tlb1_map = g2h_bitmap;
vcpu_e500->gtlb_arch = (struct kvm_book3e_206_tlb_entry *)
(virt + (cfg->array & (PAGE_SIZE - 1)));
vcpu_e500->gtlb_params[0].entries = params.tlb_sizes[0];
vcpu_e500->gtlb_params[1].entries = params.tlb_sizes[1];
vcpu_e500->gtlb_offset[0] = 0;
vcpu_e500->gtlb_offset[1] = params.tlb_sizes[0];
/* Update vcpu's MMU geometry based on SW_TLB input */
vcpu_mmu_geometry_update(vcpu, ¶ms);
vcpu_e500->shared_tlb_pages = pages;
vcpu_e500->num_shared_tlb_pages = num_pages;
vcpu_e500->gtlb_params[0].ways = params.tlb_ways[0];
vcpu_e500->gtlb_params[0].sets = sets;
vcpu_e500->gtlb_params[1].ways = params.tlb_sizes[1];
vcpu_e500->gtlb_params[1].sets = 1;
kvmppc_recalc_tlb1map_range(vcpu_e500);
return 0;
err_privs:
kfree(privs[0]);
kfree(privs[1]);
err_put_page:
for (i = 0; i < num_pages; i++)
put_page(pages[i]);
err_pages:
kfree(pages);
return ret;
}
int kvm_vcpu_ioctl_dirty_tlb(struct kvm_vcpu *vcpu,
struct kvm_dirty_tlb *dirty)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
kvmppc_recalc_tlb1map_range(vcpu_e500);
kvmppc_core_flush_tlb(vcpu);
return 0;
}
/* Vcpu's MMU default configuration */
static int vcpu_mmu_init(struct kvm_vcpu *vcpu,
struct kvmppc_e500_tlb_params *params)
{
/* Initialize RASIZE, PIDSIZE, NTLBS and MAVN fields with host values*/
vcpu->arch.mmucfg = mfspr(SPRN_MMUCFG) & ~MMUCFG_LPIDSIZE;
/* Initialize TLBnCFG fields with host values and SW_TLB geometry*/
vcpu->arch.tlbcfg[0] = mfspr(SPRN_TLB0CFG) &
~(TLBnCFG_N_ENTRY | TLBnCFG_ASSOC);
vcpu->arch.tlbcfg[0] |= params[0].entries;
vcpu->arch.tlbcfg[0] |= params[0].ways << TLBnCFG_ASSOC_SHIFT;
vcpu->arch.tlbcfg[1] = mfspr(SPRN_TLB1CFG) &
~(TLBnCFG_N_ENTRY | TLBnCFG_ASSOC);
vcpu->arch.tlbcfg[1] |= params[1].entries;
vcpu->arch.tlbcfg[1] |= params[1].ways << TLBnCFG_ASSOC_SHIFT;
if (has_feature(vcpu, VCPU_FTR_MMU_V2)) {
vcpu->arch.tlbps[0] = mfspr(SPRN_TLB0PS);
vcpu->arch.tlbps[1] = mfspr(SPRN_TLB1PS);
vcpu->arch.mmucfg &= ~MMUCFG_LRAT;
/* Guest mmu emulation currently doesn't handle E.PT */
vcpu->arch.eptcfg = 0;
vcpu->arch.tlbcfg[0] &= ~TLBnCFG_PT;
vcpu->arch.tlbcfg[1] &= ~TLBnCFG_IND;
}
return 0;
}
int kvmppc_e500_tlb_init(struct kvmppc_vcpu_e500 *vcpu_e500)
{
struct kvm_vcpu *vcpu = &vcpu_e500->vcpu;
int entry_size = sizeof(struct kvm_book3e_206_tlb_entry);
int entries = KVM_E500_TLB0_SIZE + KVM_E500_TLB1_SIZE;
if (e500_mmu_host_init(vcpu_e500))
goto err;
vcpu_e500->gtlb_params[0].entries = KVM_E500_TLB0_SIZE;
vcpu_e500->gtlb_params[1].entries = KVM_E500_TLB1_SIZE;
vcpu_e500->gtlb_params[0].ways = KVM_E500_TLB0_WAY_NUM;
vcpu_e500->gtlb_params[0].sets =
KVM_E500_TLB0_SIZE / KVM_E500_TLB0_WAY_NUM;
vcpu_e500->gtlb_params[1].ways = KVM_E500_TLB1_SIZE;
vcpu_e500->gtlb_params[1].sets = 1;
vcpu_e500->gtlb_arch = kmalloc(entries * entry_size, GFP_KERNEL);
if (!vcpu_e500->gtlb_arch)
return -ENOMEM;
vcpu_e500->gtlb_offset[0] = 0;
vcpu_e500->gtlb_offset[1] = KVM_E500_TLB0_SIZE;
vcpu_e500->gtlb_priv[0] = kzalloc(sizeof(struct tlbe_ref) *
vcpu_e500->gtlb_params[0].entries,
GFP_KERNEL);
if (!vcpu_e500->gtlb_priv[0])
goto err;
vcpu_e500->gtlb_priv[1] = kzalloc(sizeof(struct tlbe_ref) *
vcpu_e500->gtlb_params[1].entries,
GFP_KERNEL);
if (!vcpu_e500->gtlb_priv[1])
goto err;
vcpu_e500->g2h_tlb1_map = kzalloc(sizeof(u64) *
vcpu_e500->gtlb_params[1].entries,
GFP_KERNEL);
if (!vcpu_e500->g2h_tlb1_map)
goto err;
vcpu_mmu_init(vcpu, vcpu_e500->gtlb_params);
kvmppc_recalc_tlb1map_range(vcpu_e500);
return 0;
err:
free_gtlb(vcpu_e500);
return -1;
}
void kvmppc_e500_tlb_uninit(struct kvmppc_vcpu_e500 *vcpu_e500)
{
free_gtlb(vcpu_e500);
e500_mmu_host_uninit(vcpu_e500);
}
| gpl-2.0 |
zanezam/boeffla-kernel-omnirom-s3 | arch/mips/kernel/irq-rm7000.c | 2986 | 1319 | /*
* Copyright (C) 2003 Ralf Baechle
*
* 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.
*
* Handler for RM7000 extended interrupts. These are a non-standard
* feature so we handle them separately from standard interrupts.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <asm/irq_cpu.h>
#include <asm/mipsregs.h>
#include <asm/system.h>
static inline void unmask_rm7k_irq(struct irq_data *d)
{
set_c0_intcontrol(0x100 << (d->irq - RM7K_CPU_IRQ_BASE));
}
static inline void mask_rm7k_irq(struct irq_data *d)
{
clear_c0_intcontrol(0x100 << (d->irq - RM7K_CPU_IRQ_BASE));
}
static struct irq_chip rm7k_irq_controller = {
.name = "RM7000",
.irq_ack = mask_rm7k_irq,
.irq_mask = mask_rm7k_irq,
.irq_mask_ack = mask_rm7k_irq,
.irq_unmask = unmask_rm7k_irq,
.irq_eoi = unmask_rm7k_irq
};
void __init rm7k_cpu_irq_init(void)
{
int base = RM7K_CPU_IRQ_BASE;
int i;
clear_c0_intcontrol(0x00000f00); /* Mask all */
for (i = base; i < base + 4; i++)
irq_set_chip_and_handler(i, &rm7k_irq_controller,
handle_percpu_irq);
}
| gpl-2.0 |
varunchitre15/linux | drivers/scsi/bnx2fc/bnx2fc_debug.c | 2986 | 1346 | #include "bnx2fc.h"
void BNX2FC_IO_DBG(const struct bnx2fc_cmd *io_req, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (likely(!(bnx2fc_debug_level & LOG_IO)))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (io_req && io_req->port && io_req->port->lport &&
io_req->port->lport->host)
shost_printk(KERN_INFO, io_req->port->lport->host,
PFX "xid:0x%x %pV",
io_req->xid, &vaf);
else
pr_info("NULL %pV", &vaf);
va_end(args);
}
void BNX2FC_TGT_DBG(const struct bnx2fc_rport *tgt, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (likely(!(bnx2fc_debug_level & LOG_TGT)))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (tgt && tgt->port && tgt->port->lport && tgt->port->lport->host &&
tgt->rport)
shost_printk(KERN_INFO, tgt->port->lport->host,
PFX "port:%x %pV",
tgt->rport->port_id, &vaf);
else
pr_info("NULL %pV", &vaf);
va_end(args);
}
void BNX2FC_HBA_DBG(const struct fc_lport *lport, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (likely(!(bnx2fc_debug_level & LOG_HBA)))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (lport && lport->host)
shost_printk(KERN_INFO, lport->host, PFX "%pV", &vaf);
else
pr_info("NULL %pV", &vaf);
va_end(args);
}
| gpl-2.0 |
arjen75/lg_p700_kernel | arch/unicore32/mm/flush.c | 2986 | 2495 | /*
* linux/arch/unicore32/mm/flush.c
*
* Code specific to PKUnity SoC and UniCore ISA
*
* Copyright (C) 2001-2010 GUAN Xue-tao
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <asm/cacheflush.h>
#include <asm/system.h>
#include <asm/tlbflush.h>
void flush_cache_mm(struct mm_struct *mm)
{
}
void flush_cache_range(struct vm_area_struct *vma, unsigned long start,
unsigned long end)
{
if (vma->vm_flags & VM_EXEC)
__flush_icache_all();
}
void flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr,
unsigned long pfn)
{
}
static void flush_ptrace_access(struct vm_area_struct *vma, struct page *page,
unsigned long uaddr, void *kaddr, unsigned long len)
{
/* VIPT non-aliasing D-cache */
if (vma->vm_flags & VM_EXEC) {
unsigned long addr = (unsigned long)kaddr;
__cpuc_coherent_kern_range(addr, addr + len);
}
}
/*
* Copy user data from/to a page which is mapped into a different
* processes address space. Really, we want to allow our "user
* space" model to handle this.
*
* Note that this code needs to run on the current CPU.
*/
void copy_to_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long uaddr, void *dst, const void *src,
unsigned long len)
{
memcpy(dst, src, len);
flush_ptrace_access(vma, page, uaddr, dst, len);
}
void __flush_dcache_page(struct address_space *mapping, struct page *page)
{
/*
* Writeback any data associated with the kernel mapping of this
* page. This ensures that data in the physical page is mutually
* coherent with the kernels mapping.
*/
__cpuc_flush_kern_dcache_area(page_address(page), PAGE_SIZE);
}
/*
* Ensure cache coherency between kernel mapping and userspace mapping
* of this page.
*/
void flush_dcache_page(struct page *page)
{
struct address_space *mapping;
/*
* The zero page is never written to, so never has any dirty
* cache lines, and therefore never needs to be flushed.
*/
if (page == ZERO_PAGE(0))
return;
mapping = page_mapping(page);
if (mapping && !mapping_mapped(mapping))
clear_bit(PG_dcache_clean, &page->flags);
else {
__flush_dcache_page(mapping, page);
if (mapping)
__flush_icache_all();
set_bit(PG_dcache_clean, &page->flags);
}
}
EXPORT_SYMBOL(flush_dcache_page);
| gpl-2.0 |
xcstacy/kernel-N8000 | net/netfilter/xt_quota.c | 3242 | 1919 | /*
* netfilter module to enforce network quotas
*
* Sam Johnston <samj@samj.net>
*/
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_quota.h>
struct xt_quota_priv {
spinlock_t lock;
uint64_t quota;
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sam Johnston <samj@samj.net>");
MODULE_DESCRIPTION("Xtables: countdown quota match");
MODULE_ALIAS("ipt_quota");
MODULE_ALIAS("ip6t_quota");
static bool
quota_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct xt_quota_info *q = (void *)par->matchinfo;
struct xt_quota_priv *priv = q->master;
bool ret = q->flags & XT_QUOTA_INVERT;
spin_lock_bh(&priv->lock);
if (priv->quota >= skb->len) {
priv->quota -= skb->len;
ret = !ret;
} else {
/* we do not allow even small packets from now on */
priv->quota = 0;
}
spin_unlock_bh(&priv->lock);
return ret;
}
static int quota_mt_check(const struct xt_mtchk_param *par)
{
struct xt_quota_info *q = par->matchinfo;
if (q->flags & ~XT_QUOTA_MASK)
return -EINVAL;
q->master = kmalloc(sizeof(*q->master), GFP_KERNEL);
if (q->master == NULL)
return -ENOMEM;
spin_lock_init(&q->master->lock);
q->master->quota = q->quota;
return 0;
}
static void quota_mt_destroy(const struct xt_mtdtor_param *par)
{
const struct xt_quota_info *q = par->matchinfo;
kfree(q->master);
}
static struct xt_match quota_mt_reg __read_mostly = {
.name = "quota",
.revision = 0,
.family = NFPROTO_UNSPEC,
.match = quota_mt,
.checkentry = quota_mt_check,
.destroy = quota_mt_destroy,
.matchsize = sizeof(struct xt_quota_info),
.me = THIS_MODULE,
};
static int __init quota_mt_init(void)
{
return xt_register_match("a_mt_reg);
}
static void __exit quota_mt_exit(void)
{
xt_unregister_match("a_mt_reg);
}
module_init(quota_mt_init);
module_exit(quota_mt_exit);
| gpl-2.0 |
fatezero/android_kernel_samsung_smdk4210-tab | net/netfilter/xt_quota.c | 3242 | 1919 | /*
* netfilter module to enforce network quotas
*
* Sam Johnston <samj@samj.net>
*/
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_quota.h>
struct xt_quota_priv {
spinlock_t lock;
uint64_t quota;
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sam Johnston <samj@samj.net>");
MODULE_DESCRIPTION("Xtables: countdown quota match");
MODULE_ALIAS("ipt_quota");
MODULE_ALIAS("ip6t_quota");
static bool
quota_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct xt_quota_info *q = (void *)par->matchinfo;
struct xt_quota_priv *priv = q->master;
bool ret = q->flags & XT_QUOTA_INVERT;
spin_lock_bh(&priv->lock);
if (priv->quota >= skb->len) {
priv->quota -= skb->len;
ret = !ret;
} else {
/* we do not allow even small packets from now on */
priv->quota = 0;
}
spin_unlock_bh(&priv->lock);
return ret;
}
static int quota_mt_check(const struct xt_mtchk_param *par)
{
struct xt_quota_info *q = par->matchinfo;
if (q->flags & ~XT_QUOTA_MASK)
return -EINVAL;
q->master = kmalloc(sizeof(*q->master), GFP_KERNEL);
if (q->master == NULL)
return -ENOMEM;
spin_lock_init(&q->master->lock);
q->master->quota = q->quota;
return 0;
}
static void quota_mt_destroy(const struct xt_mtdtor_param *par)
{
const struct xt_quota_info *q = par->matchinfo;
kfree(q->master);
}
static struct xt_match quota_mt_reg __read_mostly = {
.name = "quota",
.revision = 0,
.family = NFPROTO_UNSPEC,
.match = quota_mt,
.checkentry = quota_mt_check,
.destroy = quota_mt_destroy,
.matchsize = sizeof(struct xt_quota_info),
.me = THIS_MODULE,
};
static int __init quota_mt_init(void)
{
return xt_register_match("a_mt_reg);
}
static void __exit quota_mt_exit(void)
{
xt_unregister_match("a_mt_reg);
}
module_init(quota_mt_init);
module_exit(quota_mt_exit);
| gpl-2.0 |
n-aizu/linux-linaro-stable-mx6 | arch/mips/ath79/dev-usb.c | 4522 | 6162 | /*
* Atheros AR7XXX/AR9XXX USB Host Controller device
*
* Copyright (C) 2008-2011 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* Parts of this file are based on Atheros' 2.6.15 BSP
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/usb/ehci_pdriver.h>
#include <linux/usb/ohci_pdriver.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-usb.h"
static u64 ath79_usb_dmamask = DMA_BIT_MASK(32);
static struct usb_ohci_pdata ath79_ohci_pdata = {
};
static struct usb_ehci_pdata ath79_ehci_pdata_v1 = {
.has_synopsys_hc_bug = 1,
};
static struct usb_ehci_pdata ath79_ehci_pdata_v2 = {
.caps_offset = 0x100,
.has_tt = 1,
};
static void __init ath79_usb_register(const char *name, int id,
unsigned long base, unsigned long size,
int irq, const void *data,
size_t data_size)
{
struct resource res[2];
struct platform_device *pdev;
memset(res, 0, sizeof(res));
res[0].flags = IORESOURCE_MEM;
res[0].start = base;
res[0].end = base + size - 1;
res[1].flags = IORESOURCE_IRQ;
res[1].start = irq;
res[1].end = irq;
pdev = platform_device_register_resndata(NULL, name, id,
res, ARRAY_SIZE(res),
data, data_size);
if (IS_ERR(pdev)) {
pr_err("ath79: unable to register USB at %08lx, err=%d\n",
base, (int) PTR_ERR(pdev));
return;
}
pdev->dev.dma_mask = &ath79_usb_dmamask;
pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32);
}
#define AR71XX_USB_RESET_MASK (AR71XX_RESET_USB_HOST | \
AR71XX_RESET_USB_PHY | \
AR71XX_RESET_USB_OHCI_DLL)
static void __init ath79_usb_setup(void)
{
void __iomem *usb_ctrl_base;
ath79_device_reset_set(AR71XX_USB_RESET_MASK);
mdelay(1000);
ath79_device_reset_clear(AR71XX_USB_RESET_MASK);
usb_ctrl_base = ioremap(AR71XX_USB_CTRL_BASE, AR71XX_USB_CTRL_SIZE);
/* Turning on the Buff and Desc swap bits */
__raw_writel(0xf0000, usb_ctrl_base + AR71XX_USB_CTRL_REG_CONFIG);
/* WAR for HW bug. Here it adjusts the duration between two SOFS */
__raw_writel(0x20c00, usb_ctrl_base + AR71XX_USB_CTRL_REG_FLADJ);
iounmap(usb_ctrl_base);
mdelay(900);
ath79_usb_register("ohci-platform", -1,
AR71XX_OHCI_BASE, AR71XX_OHCI_SIZE,
ATH79_MISC_IRQ(6),
&ath79_ohci_pdata, sizeof(ath79_ohci_pdata));
ath79_usb_register("ehci-platform", -1,
AR71XX_EHCI_BASE, AR71XX_EHCI_SIZE,
ATH79_CPU_IRQ(3),
&ath79_ehci_pdata_v1, sizeof(ath79_ehci_pdata_v1));
}
static void __init ar7240_usb_setup(void)
{
void __iomem *usb_ctrl_base;
ath79_device_reset_clear(AR7240_RESET_OHCI_DLL);
ath79_device_reset_set(AR7240_RESET_USB_HOST);
mdelay(1000);
ath79_device_reset_set(AR7240_RESET_OHCI_DLL);
ath79_device_reset_clear(AR7240_RESET_USB_HOST);
usb_ctrl_base = ioremap(AR7240_USB_CTRL_BASE, AR7240_USB_CTRL_SIZE);
/* WAR for HW bug. Here it adjusts the duration between two SOFS */
__raw_writel(0x3, usb_ctrl_base + AR71XX_USB_CTRL_REG_FLADJ);
iounmap(usb_ctrl_base);
ath79_usb_register("ohci-platform", -1,
AR7240_OHCI_BASE, AR7240_OHCI_SIZE,
ATH79_CPU_IRQ(3),
&ath79_ohci_pdata, sizeof(ath79_ohci_pdata));
}
static void __init ar724x_usb_setup(void)
{
ath79_device_reset_set(AR724X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR724X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR724X_RESET_USB_PHY);
mdelay(10);
ath79_usb_register("ehci-platform", -1,
AR724X_EHCI_BASE, AR724X_EHCI_SIZE,
ATH79_CPU_IRQ(3),
&ath79_ehci_pdata_v2, sizeof(ath79_ehci_pdata_v2));
}
static void __init ar913x_usb_setup(void)
{
ath79_device_reset_set(AR913X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR913X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR913X_RESET_USB_PHY);
mdelay(10);
ath79_usb_register("ehci-platform", -1,
AR913X_EHCI_BASE, AR913X_EHCI_SIZE,
ATH79_CPU_IRQ(3),
&ath79_ehci_pdata_v2, sizeof(ath79_ehci_pdata_v2));
}
static void __init ar933x_usb_setup(void)
{
ath79_device_reset_set(AR933X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR933X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR933X_RESET_USB_PHY);
mdelay(10);
ath79_usb_register("ehci-platform", -1,
AR933X_EHCI_BASE, AR933X_EHCI_SIZE,
ATH79_CPU_IRQ(3),
&ath79_ehci_pdata_v2, sizeof(ath79_ehci_pdata_v2));
}
static void __init ar934x_usb_setup(void)
{
u32 bootstrap;
bootstrap = ath79_reset_rr(AR934X_RESET_REG_BOOTSTRAP);
if (bootstrap & AR934X_BOOTSTRAP_USB_MODE_DEVICE)
return;
ath79_device_reset_set(AR934X_RESET_USBSUS_OVERRIDE);
udelay(1000);
ath79_device_reset_clear(AR934X_RESET_USB_PHY);
udelay(1000);
ath79_device_reset_clear(AR934X_RESET_USB_PHY_ANALOG);
udelay(1000);
ath79_device_reset_clear(AR934X_RESET_USB_HOST);
udelay(1000);
ath79_usb_register("ehci-platform", -1,
AR934X_EHCI_BASE, AR934X_EHCI_SIZE,
ATH79_CPU_IRQ(3),
&ath79_ehci_pdata_v2, sizeof(ath79_ehci_pdata_v2));
}
static void __init qca955x_usb_setup(void)
{
ath79_usb_register("ehci-platform", 0,
QCA955X_EHCI0_BASE, QCA955X_EHCI_SIZE,
ATH79_IP3_IRQ(0),
&ath79_ehci_pdata_v2, sizeof(ath79_ehci_pdata_v2));
ath79_usb_register("ehci-platform", 1,
QCA955X_EHCI1_BASE, QCA955X_EHCI_SIZE,
ATH79_IP3_IRQ(1),
&ath79_ehci_pdata_v2, sizeof(ath79_ehci_pdata_v2));
}
void __init ath79_register_usb(void)
{
if (soc_is_ar71xx())
ath79_usb_setup();
else if (soc_is_ar7240())
ar7240_usb_setup();
else if (soc_is_ar7241() || soc_is_ar7242())
ar724x_usb_setup();
else if (soc_is_ar913x())
ar913x_usb_setup();
else if (soc_is_ar933x())
ar933x_usb_setup();
else if (soc_is_ar934x())
ar934x_usb_setup();
else if (soc_is_qca955x())
qca955x_usb_setup();
else
BUG();
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.